id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
41,500
kevinkhill/php-duration
src/Duration.php
Duration.formatted
public function formatted($duration = null, $zeroFill = false) { if (null !== $duration) { $this->parse($duration); } $hours = $this->hours + ($this->days * $this->hoursPerDay); if ($this->seconds > 0) { if ($this->seconds < 10 && ($this->minutes > 0 || $hours > 0 || $zeroFill)) { $this->output .= '0' . $this->seconds; } else { $this->output .= $this->seconds; } } else { if ($this->minutes > 0 || $hours > 0 || $zeroFill) { $this->output = '00'; } else { $this->output = '0'; } } if ($this->minutes > 0) { if ($this->minutes <= 9 && ($hours > 0 || $zeroFill)) { $this->output = '0' . $this->minutes . ':' . $this->output; } else { $this->output = $this->minutes . ':' . $this->output; } } else { if ($hours > 0 || $zeroFill) { $this->output = '00' . ':' . $this->output; } } if ($hours > 0) { $this->output = $hours . ':' . $this->output; } else { if ($zeroFill) { $this->output = '0' . ':' . $this->output; } } return $this->output(); }
php
public function formatted($duration = null, $zeroFill = false) { if (null !== $duration) { $this->parse($duration); } $hours = $this->hours + ($this->days * $this->hoursPerDay); if ($this->seconds > 0) { if ($this->seconds < 10 && ($this->minutes > 0 || $hours > 0 || $zeroFill)) { $this->output .= '0' . $this->seconds; } else { $this->output .= $this->seconds; } } else { if ($this->minutes > 0 || $hours > 0 || $zeroFill) { $this->output = '00'; } else { $this->output = '0'; } } if ($this->minutes > 0) { if ($this->minutes <= 9 && ($hours > 0 || $zeroFill)) { $this->output = '0' . $this->minutes . ':' . $this->output; } else { $this->output = $this->minutes . ':' . $this->output; } } else { if ($hours > 0 || $zeroFill) { $this->output = '00' . ':' . $this->output; } } if ($hours > 0) { $this->output = $hours . ':' . $this->output; } else { if ($zeroFill) { $this->output = '0' . ':' . $this->output; } } return $this->output(); }
[ "public", "function", "formatted", "(", "$", "duration", "=", "null", ",", "$", "zeroFill", "=", "false", ")", "{", "if", "(", "null", "!==", "$", "duration", ")", "{", "$", "this", "->", "parse", "(", "$", "duration", ")", ";", "}", "$", "hours", ...
Returns the duration as a colon formatted string For example, one hour and 42 minutes would be "1:43" With $zeroFill to true : - 42 minutes would be "0:42:00" - 28 seconds would be "0:00:28" @param int|float|string|null $duration A string or number, representing a duration @param bool $zeroFill A boolean, to force zero-fill result or not (see example) @return string
[ "Returns", "the", "duration", "as", "a", "colon", "formatted", "string" ]
2118a067359ffc96784b02fcd26f312e2bd886db
https://github.com/kevinkhill/php-duration/blob/2118a067359ffc96784b02fcd26f312e2bd886db/src/Duration.php#L187-L230
41,501
kevinkhill/php-duration
src/Duration.php
Duration.humanize
public function humanize($duration = null) { if (null !== $duration) { $this->parse($duration); } if ($this->seconds > 0 || ($this->seconds === 0.0 && $this->minutes === 0 && $this->hours === 0 && $this->days === 0)) { $this->output .= $this->seconds . 's'; } if ($this->minutes > 0) { $this->output = $this->minutes . 'm ' . $this->output; } if ($this->hours > 0) { $this->output = $this->hours . 'h ' . $this->output; } if ($this->days > 0) { $this->output = $this->days . 'd ' . $this->output; } return trim($this->output()); }
php
public function humanize($duration = null) { if (null !== $duration) { $this->parse($duration); } if ($this->seconds > 0 || ($this->seconds === 0.0 && $this->minutes === 0 && $this->hours === 0 && $this->days === 0)) { $this->output .= $this->seconds . 's'; } if ($this->minutes > 0) { $this->output = $this->minutes . 'm ' . $this->output; } if ($this->hours > 0) { $this->output = $this->hours . 'h ' . $this->output; } if ($this->days > 0) { $this->output = $this->days . 'd ' . $this->output; } return trim($this->output()); }
[ "public", "function", "humanize", "(", "$", "duration", "=", "null", ")", "{", "if", "(", "null", "!==", "$", "duration", ")", "{", "$", "this", "->", "parse", "(", "$", "duration", ")", ";", "}", "if", "(", "$", "this", "->", "seconds", ">", "0"...
Returns the duration as a human-readable string. For example, one hour and 42 minutes would be "1h 42m" @param int|float|string $duration A string or number, representing a duration @return string
[ "Returns", "the", "duration", "as", "a", "human", "-", "readable", "string", "." ]
2118a067359ffc96784b02fcd26f312e2bd886db
https://github.com/kevinkhill/php-duration/blob/2118a067359ffc96784b02fcd26f312e2bd886db/src/Duration.php#L240-L263
41,502
kevinkhill/php-duration
src/Duration.php
Duration.reset
private function reset() { $this->output = ''; $this->seconds = 0.0; $this->minutes = 0; $this->hours = 0; $this->days = 0; }
php
private function reset() { $this->output = ''; $this->seconds = 0.0; $this->minutes = 0; $this->hours = 0; $this->days = 0; }
[ "private", "function", "reset", "(", ")", "{", "$", "this", "->", "output", "=", "''", ";", "$", "this", "->", "seconds", "=", "0.0", ";", "$", "this", "->", "minutes", "=", "0", ";", "$", "this", "->", "hours", "=", "0", ";", "$", "this", "->"...
Resets the Duration object by clearing the output and values. @access private @return void
[ "Resets", "the", "Duration", "object", "by", "clearing", "the", "output", "and", "values", "." ]
2118a067359ffc96784b02fcd26f312e2bd886db
https://github.com/kevinkhill/php-duration/blob/2118a067359ffc96784b02fcd26f312e2bd886db/src/Duration.php#L295-L302
41,503
j0k3r/php-imgur-api-client
lib/Imgur/HttpClient/HttpClient.php
HttpClient.addAuthMiddleware
public function addAuthMiddleware($token, $clientId) { $this->stack->push(Middleware::mapRequest(function (RequestInterface $request) use ($token, $clientId) { return (new AuthMiddleware($token, $clientId))->addAuthHeader($request); })); }
php
public function addAuthMiddleware($token, $clientId) { $this->stack->push(Middleware::mapRequest(function (RequestInterface $request) use ($token, $clientId) { return (new AuthMiddleware($token, $clientId))->addAuthHeader($request); })); }
[ "public", "function", "addAuthMiddleware", "(", "$", "token", ",", "$", "clientId", ")", "{", "$", "this", "->", "stack", "->", "push", "(", "Middleware", "::", "mapRequest", "(", "function", "(", "RequestInterface", "$", "request", ")", "use", "(", "$", ...
Push authorization middleware. @param array $token @param string $clientId
[ "Push", "authorization", "middleware", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/HttpClient/HttpClient.php#L138-L143
41,504
j0k3r/php-imgur-api-client
lib/Imgur/Api/AlbumOrImage.php
AlbumOrImage.find
public function find($imageIdOrAlbumId) { try { return $this->get('image/' . $imageIdOrAlbumId); } catch (ExceptionInterface $e) { if (404 !== $e->getCode()) { throw $e; } } try { return $this->get('album/' . $imageIdOrAlbumId); } catch (ExceptionInterface $e) { if (404 !== $e->getCode()) { throw $e; } } throw new ErrorException('Unable to find an album OR an image with the id, ' . $imageIdOrAlbumId); }
php
public function find($imageIdOrAlbumId) { try { return $this->get('image/' . $imageIdOrAlbumId); } catch (ExceptionInterface $e) { if (404 !== $e->getCode()) { throw $e; } } try { return $this->get('album/' . $imageIdOrAlbumId); } catch (ExceptionInterface $e) { if (404 !== $e->getCode()) { throw $e; } } throw new ErrorException('Unable to find an album OR an image with the id, ' . $imageIdOrAlbumId); }
[ "public", "function", "find", "(", "$", "imageIdOrAlbumId", ")", "{", "try", "{", "return", "$", "this", "->", "get", "(", "'image/'", ".", "$", "imageIdOrAlbumId", ")", ";", "}", "catch", "(", "ExceptionInterface", "$", "e", ")", "{", "if", "(", "404"...
Try to find an image or an album using the given parameter. @param string $imageIdOrAlbumId @return array Album (@see https://api.imgur.com/models/album) OR Image (@see https://api.imgur.com/models/image)
[ "Try", "to", "find", "an", "image", "or", "an", "album", "using", "the", "given", "parameter", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/AlbumOrImage.php#L22-L41
41,505
j0k3r/php-imgur-api-client
lib/Imgur/Api/Comment.php
Comment.createReply
public function createReply($commentId, $data) { if (!isset($data['image_id'], $data['comment'])) { throw new MissingArgumentException(['image_id', 'comment']); } return $this->post('comment/' . $commentId, $data); }
php
public function createReply($commentId, $data) { if (!isset($data['image_id'], $data['comment'])) { throw new MissingArgumentException(['image_id', 'comment']); } return $this->post('comment/' . $commentId, $data); }
[ "public", "function", "createReply", "(", "$", "commentId", ",", "$", "data", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'image_id'", "]", ",", "$", "data", "[", "'comment'", "]", ")", ")", "{", "throw", "new", "MissingArgumentException...
Create a reply for the given comment. @param string $commentId @param array $data @see https://api.imgur.com/endpoints/comment#comment-reply-create @return bool
[ "Create", "a", "reply", "for", "the", "given", "comment", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Comment.php#L86-L93
41,506
j0k3r/php-imgur-api-client
lib/Imgur/Api/Topic.php
Topic.galleryTopic
public function galleryTopic($topicId, $sort = 'viral', $page = 0, $window = 'week') { $this->validateSortArgument($sort, ['viral', 'top', 'time', 'rising']); $this->validateWindowArgument($window, ['day', 'week', 'month', 'year', 'all']); return $this->get('topics/' . $topicId . '/' . $sort . '/' . $window . '/' . $page); }
php
public function galleryTopic($topicId, $sort = 'viral', $page = 0, $window = 'week') { $this->validateSortArgument($sort, ['viral', 'top', 'time', 'rising']); $this->validateWindowArgument($window, ['day', 'week', 'month', 'year', 'all']); return $this->get('topics/' . $topicId . '/' . $sort . '/' . $window . '/' . $page); }
[ "public", "function", "galleryTopic", "(", "$", "topicId", ",", "$", "sort", "=", "'viral'", ",", "$", "page", "=", "0", ",", "$", "window", "=", "'week'", ")", "{", "$", "this", "->", "validateSortArgument", "(", "$", "sort", ",", "[", "'viral'", ",...
View gallery items for a topic. @param string $topicId The ID or URL-formatted name of the topic. If using a topic's name, replace its spaces with underscores (Mother's_Day) @param string $sort (viral | top | time) @param int $page @param string $window (day | week | month | year | all) @see https://api.imgur.com/endpoints/topic#gallery-topic @return array Gallery Image (@see https://api.imgur.com/models/gallery_image) OR Gallery Album (@see https://api.imgur.com/models/gallery_album)
[ "View", "gallery", "items", "for", "a", "topic", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Topic.php#L36-L42
41,507
j0k3r/php-imgur-api-client
lib/Imgur/Api/CustomGallery.php
CustomGallery.filtered
public function filtered($sort = 'viral', $page = 0, $window = 'week') { $this->validateSortArgument($sort, ['viral', 'top', 'time']); $this->validateWindowArgument($window, ['day', 'week', 'month', 'year', 'all']); return $this->get('g/filtered/' . $sort . '/' . $window . '/' . (int) $page); }
php
public function filtered($sort = 'viral', $page = 0, $window = 'week') { $this->validateSortArgument($sort, ['viral', 'top', 'time']); $this->validateWindowArgument($window, ['day', 'week', 'month', 'year', 'all']); return $this->get('g/filtered/' . $sort . '/' . $window . '/' . (int) $page); }
[ "public", "function", "filtered", "(", "$", "sort", "=", "'viral'", ",", "$", "page", "=", "0", ",", "$", "window", "=", "'week'", ")", "{", "$", "this", "->", "validateSortArgument", "(", "$", "sort", ",", "[", "'viral'", ",", "'top'", ",", "'time'"...
Retrieve user's filtered out gallery. @param string $sort (viral | top | time) @param int $page @param string $window (day | week | month | year | all) @see https://api.imgur.com/endpoints/custom_gallery#filtered-out-gallery @return array Custom Gallery (@see https://api.imgur.com/models/custom_gallery)
[ "Retrieve", "user", "s", "filtered", "out", "gallery", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/CustomGallery.php#L42-L48
41,508
j0k3r/php-imgur-api-client
lib/Imgur/Middleware/ErrorMiddleware.php
ErrorMiddleware.checkUserRateLimit
private function checkUserRateLimit(ResponseInterface $response) { $userRemaining = $response->getHeaderLine('X-RateLimit-UserRemaining'); $userLimit = $response->getHeaderLine('X-RateLimit-UserLimit'); if ('' !== $userRemaining && $userRemaining < 1) { throw new RateLimitException('No user credits available. The limit is ' . $userLimit); } }
php
private function checkUserRateLimit(ResponseInterface $response) { $userRemaining = $response->getHeaderLine('X-RateLimit-UserRemaining'); $userLimit = $response->getHeaderLine('X-RateLimit-UserLimit'); if ('' !== $userRemaining && $userRemaining < 1) { throw new RateLimitException('No user credits available. The limit is ' . $userLimit); } }
[ "private", "function", "checkUserRateLimit", "(", "ResponseInterface", "$", "response", ")", "{", "$", "userRemaining", "=", "$", "response", "->", "getHeaderLine", "(", "'X-RateLimit-UserRemaining'", ")", ";", "$", "userLimit", "=", "$", "response", "->", "getHea...
Check if user hit limit. @param ResponseInterface $response
[ "Check", "if", "user", "hit", "limit", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Middleware/ErrorMiddleware.php#L102-L110
41,509
j0k3r/php-imgur-api-client
lib/Imgur/Middleware/ErrorMiddleware.php
ErrorMiddleware.checkClientRateLimit
private function checkClientRateLimit(ResponseInterface $response) { $clientRemaining = $response->getHeaderLine('X-RateLimit-ClientRemaining'); $clientLimit = $response->getHeaderLine('X-RateLimit-ClientLimit'); if ('' !== $clientRemaining && $clientRemaining < 1) { // X-RateLimit-UserReset: Timestamp (unix epoch) for when the credits will be reset. $resetTime = date('Y-m-d H:i:s', $response->getHeaderLine('X-RateLimit-UserReset')); throw new RateLimitException('No application credits available. The limit is ' . $clientLimit . ' and will be reset at ' . $resetTime); } }
php
private function checkClientRateLimit(ResponseInterface $response) { $clientRemaining = $response->getHeaderLine('X-RateLimit-ClientRemaining'); $clientLimit = $response->getHeaderLine('X-RateLimit-ClientLimit'); if ('' !== $clientRemaining && $clientRemaining < 1) { // X-RateLimit-UserReset: Timestamp (unix epoch) for when the credits will be reset. $resetTime = date('Y-m-d H:i:s', $response->getHeaderLine('X-RateLimit-UserReset')); throw new RateLimitException('No application credits available. The limit is ' . $clientLimit . ' and will be reset at ' . $resetTime); } }
[ "private", "function", "checkClientRateLimit", "(", "ResponseInterface", "$", "response", ")", "{", "$", "clientRemaining", "=", "$", "response", "->", "getHeaderLine", "(", "'X-RateLimit-ClientRemaining'", ")", ";", "$", "clientLimit", "=", "$", "response", "->", ...
Check if client hit limit. @param ResponseInterface $response
[ "Check", "if", "client", "hit", "limit", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Middleware/ErrorMiddleware.php#L117-L128
41,510
j0k3r/php-imgur-api-client
lib/Imgur/Middleware/ErrorMiddleware.php
ErrorMiddleware.checkPostRateLimit
private function checkPostRateLimit(ResponseInterface $response) { $postRemaining = $response->getHeaderLine('X-Post-Rate-Limit-Remaining'); $postLimit = $response->getHeaderLine('X-Post-Rate-Limit-Limit'); if ('' !== $postRemaining && $postRemaining < 1) { // X-Post-Rate-Limit-Reset: Time in seconds until your POST ratelimit is reset $resetTime = date('Y-m-d H:i:s', $response->getHeaderLine('X-Post-Rate-Limit-Reset')); throw new RateLimitException('No post credits available. The limit is ' . $postLimit . ' and will be reset at ' . $resetTime); } }
php
private function checkPostRateLimit(ResponseInterface $response) { $postRemaining = $response->getHeaderLine('X-Post-Rate-Limit-Remaining'); $postLimit = $response->getHeaderLine('X-Post-Rate-Limit-Limit'); if ('' !== $postRemaining && $postRemaining < 1) { // X-Post-Rate-Limit-Reset: Time in seconds until your POST ratelimit is reset $resetTime = date('Y-m-d H:i:s', $response->getHeaderLine('X-Post-Rate-Limit-Reset')); throw new RateLimitException('No post credits available. The limit is ' . $postLimit . ' and will be reset at ' . $resetTime); } }
[ "private", "function", "checkPostRateLimit", "(", "ResponseInterface", "$", "response", ")", "{", "$", "postRemaining", "=", "$", "response", "->", "getHeaderLine", "(", "'X-Post-Rate-Limit-Remaining'", ")", ";", "$", "postLimit", "=", "$", "response", "->", "getH...
Check if client hit post limit. @param ResponseInterface $response
[ "Check", "if", "client", "hit", "post", "limit", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Middleware/ErrorMiddleware.php#L135-L146
41,511
j0k3r/php-imgur-api-client
lib/Imgur/Client.php
Client.getAuthenticationClient
public function getAuthenticationClient() { if (null === $this->authenticationClient) { $this->authenticationClient = new Auth\OAuth2( $this->getHttpClient(), $this->getOption('client_id'), $this->getOption('client_secret') ); } return $this->authenticationClient; }
php
public function getAuthenticationClient() { if (null === $this->authenticationClient) { $this->authenticationClient = new Auth\OAuth2( $this->getHttpClient(), $this->getOption('client_id'), $this->getOption('client_secret') ); } return $this->authenticationClient; }
[ "public", "function", "getAuthenticationClient", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "authenticationClient", ")", "{", "$", "this", "->", "authenticationClient", "=", "new", "Auth", "\\", "OAuth2", "(", "$", "this", "->", "getHttpClie...
Retrieves the Auth object and also instantiates it if not already present. @return Auth\AuthInterface
[ "Retrieves", "the", "Auth", "object", "and", "also", "instantiates", "it", "if", "not", "already", "present", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Client.php#L128-L139
41,512
j0k3r/php-imgur-api-client
lib/Imgur/Auth/OAuth2.php
OAuth2.getAuthenticationURL
public function getAuthenticationURL($responseType = 'code', $state = null) { $httpQueryParameters = [ 'client_id' => $this->clientId, 'response_type' => $responseType, 'state' => $state, ]; $httpQueryParameters = http_build_query($httpQueryParameters); return self::AUTHORIZATION_ENDPOINT . '?' . $httpQueryParameters; }
php
public function getAuthenticationURL($responseType = 'code', $state = null) { $httpQueryParameters = [ 'client_id' => $this->clientId, 'response_type' => $responseType, 'state' => $state, ]; $httpQueryParameters = http_build_query($httpQueryParameters); return self::AUTHORIZATION_ENDPOINT . '?' . $httpQueryParameters; }
[ "public", "function", "getAuthenticationURL", "(", "$", "responseType", "=", "'code'", ",", "$", "state", "=", "null", ")", "{", "$", "httpQueryParameters", "=", "[", "'client_id'", "=>", "$", "this", "->", "clientId", ",", "'response_type'", "=>", "$", "res...
Generates the authentication URL to which a user should be pointed at in order to start the OAuth2 process. @param string $responseType @param string|null $state @return string
[ "Generates", "the", "authentication", "URL", "to", "which", "a", "user", "should", "be", "pointed", "at", "in", "order", "to", "start", "the", "OAuth2", "process", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Auth/OAuth2.php#L84-L95
41,513
j0k3r/php-imgur-api-client
lib/Imgur/Auth/OAuth2.php
OAuth2.refreshToken
public function refreshToken() { $token = $this->getAccessToken(); try { $response = $this->httpClient->post( self::ACCESS_TOKEN_ENDPOINT, [ 'refresh_token' => $token['refresh_token'], 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'grant_type' => 'refresh_token', ] ); $responseBody = json_decode($response->getBody(), true); } catch (\Exception $e) { throw new AuthException('Request for refresh access token failed: ' . $e->getMessage(), $e->getCode()); } $this->setAccessToken($responseBody); $this->sign(); return $responseBody; }
php
public function refreshToken() { $token = $this->getAccessToken(); try { $response = $this->httpClient->post( self::ACCESS_TOKEN_ENDPOINT, [ 'refresh_token' => $token['refresh_token'], 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'grant_type' => 'refresh_token', ] ); $responseBody = json_decode($response->getBody(), true); } catch (\Exception $e) { throw new AuthException('Request for refresh access token failed: ' . $e->getMessage(), $e->getCode()); } $this->setAccessToken($responseBody); $this->sign(); return $responseBody; }
[ "public", "function", "refreshToken", "(", ")", "{", "$", "token", "=", "$", "this", "->", "getAccessToken", "(", ")", ";", "try", "{", "$", "response", "=", "$", "this", "->", "httpClient", "->", "post", "(", "self", "::", "ACCESS_TOKEN_ENDPOINT", ",", ...
If a user has authorized their account but you no longer have a valid access_token for them, then a new one can be generated by using the refresh_token. When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, you will have to prompt the user for their login information again. @throws AuthException @return array
[ "If", "a", "user", "has", "authorized", "their", "account", "but", "you", "no", "longer", "have", "a", "valid", "access_token", "for", "them", "then", "a", "new", "one", "can", "be", "generated", "by", "using", "the", "refresh_token", ".", "When", "your", ...
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Auth/OAuth2.php#L153-L178
41,514
j0k3r/php-imgur-api-client
lib/Imgur/Auth/OAuth2.php
OAuth2.setAccessToken
public function setAccessToken($token) { if (!\is_array($token)) { throw new AuthException('Token is not a valid json string.'); } if (isset($token['data']['access_token'])) { $token = $token['data']; } if (!isset($token['access_token'])) { throw new AuthException('Access token could not be retrieved from the decoded json response.'); } $this->token = $token; $this->sign(); }
php
public function setAccessToken($token) { if (!\is_array($token)) { throw new AuthException('Token is not a valid json string.'); } if (isset($token['data']['access_token'])) { $token = $token['data']; } if (!isset($token['access_token'])) { throw new AuthException('Access token could not be retrieved from the decoded json response.'); } $this->token = $token; $this->sign(); }
[ "public", "function", "setAccessToken", "(", "$", "token", ")", "{", "if", "(", "!", "\\", "is_array", "(", "$", "token", ")", ")", "{", "throw", "new", "AuthException", "(", "'Token is not a valid json string.'", ")", ";", "}", "if", "(", "isset", "(", ...
Stores the access token, refresh token and expiration date. @param array $token @throws AuthException @return array
[ "Stores", "the", "access", "token", "refresh", "token", "and", "expiration", "date", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Auth/OAuth2.php#L189-L206
41,515
j0k3r/php-imgur-api-client
lib/Imgur/Api/Account.php
Account.galleryFavorites
public function galleryFavorites($username = 'me', $page = 0, $sort = 'newest') { $this->validateSortArgument($sort, ['oldest', 'newest']); return $this->get('account/' . $username . '/gallery_favorites/' . (int) $page . '/' . $sort); }
php
public function galleryFavorites($username = 'me', $page = 0, $sort = 'newest') { $this->validateSortArgument($sort, ['oldest', 'newest']); return $this->get('account/' . $username . '/gallery_favorites/' . (int) $page . '/' . $sort); }
[ "public", "function", "galleryFavorites", "(", "$", "username", "=", "'me'", ",", "$", "page", "=", "0", ",", "$", "sort", "=", "'newest'", ")", "{", "$", "this", "->", "validateSortArgument", "(", "$", "sort", ",", "[", "'oldest'", ",", "'newest'", "]...
Return the images the user has favorited in the gallery. @param string $username @param int $page @param string $sort 'oldest', or 'newest'. Defaults to 'newest' @see https://api.imgur.com/endpoints/account#account-gallery-favorites @return array Gallery Image (@see https://api.imgur.com/models/gallery_image) OR Gallery Album (@see https://api.imgur.com/models/gallery_album)
[ "Return", "the", "images", "the", "user", "has", "favorited", "in", "the", "gallery", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Account.php#L52-L57
41,516
j0k3r/php-imgur-api-client
lib/Imgur/Api/Account.php
Account.comments
public function comments($username = 'me', $page = 0, $sort = 'newest') { $this->validateSortArgument($sort, ['best', 'worst', 'oldest', 'newest']); return $this->get('account/' . $username . '/comments/' . $sort . '/' . (int) $page); }
php
public function comments($username = 'me', $page = 0, $sort = 'newest') { $this->validateSortArgument($sort, ['best', 'worst', 'oldest', 'newest']); return $this->get('account/' . $username . '/comments/' . $sort . '/' . (int) $page); }
[ "public", "function", "comments", "(", "$", "username", "=", "'me'", ",", "$", "page", "=", "0", ",", "$", "sort", "=", "'newest'", ")", "{", "$", "this", "->", "validateSortArgument", "(", "$", "sort", ",", "[", "'best'", ",", "'worst'", ",", "'olde...
Return the comments the user has created. @param string $username @param int $page @param string $sort 'best', 'worst', 'oldest', or 'newest'. Defaults to 'newest' @see https://api.imgur.com/endpoints/account#comments @return array Array of Comment (@see https://api.imgur.com/models/comment)
[ "Return", "the", "comments", "the", "user", "has", "created", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Account.php#L257-L262
41,517
j0k3r/php-imgur-api-client
lib/Imgur/Api/Account.php
Account.commentIds
public function commentIds($username = 'me', $page = 0, $sort = 'newest') { $this->validateSortArgument($sort, ['best', 'worst', 'oldest', 'newest']); return $this->get('account/' . $username . '/comments/ids/' . $sort . '/' . (int) $page); }
php
public function commentIds($username = 'me', $page = 0, $sort = 'newest') { $this->validateSortArgument($sort, ['best', 'worst', 'oldest', 'newest']); return $this->get('account/' . $username . '/comments/ids/' . $sort . '/' . (int) $page); }
[ "public", "function", "commentIds", "(", "$", "username", "=", "'me'", ",", "$", "page", "=", "0", ",", "$", "sort", "=", "'newest'", ")", "{", "$", "this", "->", "validateSortArgument", "(", "$", "sort", ",", "[", "'best'", ",", "'worst'", ",", "'ol...
Return an array of all of the comment IDs. @param string $username @param int $page @param string $sort 'best', 'worst', 'oldest', or 'newest'. Defaults to 'newest' @see https://api.imgur.com/endpoints/account#comment-ids @return array<int>
[ "Return", "an", "array", "of", "all", "of", "the", "comment", "IDs", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Account.php#L291-L296
41,518
j0k3r/php-imgur-api-client
lib/Imgur/Api/Account.php
Account.replies
public function replies($username = 'me', $onlyNew = false) { $onlyNew = $onlyNew ? 'true' : 'false'; return $this->get('account/' . $username . '/notifications/replies', ['new' => $onlyNew]); }
php
public function replies($username = 'me', $onlyNew = false) { $onlyNew = $onlyNew ? 'true' : 'false'; return $this->get('account/' . $username . '/notifications/replies', ['new' => $onlyNew]); }
[ "public", "function", "replies", "(", "$", "username", "=", "'me'", ",", "$", "onlyNew", "=", "false", ")", "{", "$", "onlyNew", "=", "$", "onlyNew", "?", "'true'", ":", "'false'", ";", "return", "$", "this", "->", "get", "(", "'account/'", ".", "$",...
Returns all of the reply notifications for the user. Required to be logged in as that user. @param string $username @param bool $onlyNew @see https://api.imgur.com/endpoints/account#replies @return array Array of Notification (@see https://api.imgur.com/models/notification)
[ "Returns", "all", "of", "the", "reply", "notifications", "for", "the", "user", ".", "Required", "to", "be", "logged", "in", "as", "that", "user", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Account.php#L413-L418
41,519
j0k3r/php-imgur-api-client
lib/Imgur/Api/Gallery.php
Gallery.subredditGalleries
public function subredditGalleries($subreddit, $sort = 'time', $page = 0, $window = 'day') { $this->validateSortArgument($sort, ['top', 'time']); $this->validateWindowArgument($window, ['day', 'week', 'month', 'year', 'all']); return $this->get('gallery/r/' . $subreddit . '/' . $sort . '/' . $window . '/' . (int) $page); }
php
public function subredditGalleries($subreddit, $sort = 'time', $page = 0, $window = 'day') { $this->validateSortArgument($sort, ['top', 'time']); $this->validateWindowArgument($window, ['day', 'week', 'month', 'year', 'all']); return $this->get('gallery/r/' . $subreddit . '/' . $sort . '/' . $window . '/' . (int) $page); }
[ "public", "function", "subredditGalleries", "(", "$", "subreddit", ",", "$", "sort", "=", "'time'", ",", "$", "page", "=", "0", ",", "$", "window", "=", "'day'", ")", "{", "$", "this", "->", "validateSortArgument", "(", "$", "sort", ",", "[", "'top'", ...
View gallery images for a sub-reddit. @param string $subreddit (e.g pics - A valid sub-reddit name) @param string $sort (top | time) @param int $page @param string $window (day | week | month | year | all) @see https://api.imgur.com/endpoints/gallery#subreddit @return array Gallery Image (@see https://api.imgur.com/models/gallery_image)
[ "View", "gallery", "images", "for", "a", "sub", "-", "reddit", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Gallery.php#L91-L97
41,520
j0k3r/php-imgur-api-client
lib/Imgur/Api/Gallery.php
Gallery.galleryTag
public function galleryTag($name, $sort = 'viral', $page = 0, $window = 'week') { $this->validateSortArgument($sort, ['top', 'time', 'viral']); $this->validateWindowArgument($window, ['day', 'week', 'month', 'year', 'all']); return $this->get('gallery/t/' . $name . '/' . $sort . '/' . $window . '/' . (int) $page); }
php
public function galleryTag($name, $sort = 'viral', $page = 0, $window = 'week') { $this->validateSortArgument($sort, ['top', 'time', 'viral']); $this->validateWindowArgument($window, ['day', 'week', 'month', 'year', 'all']); return $this->get('gallery/t/' . $name . '/' . $sort . '/' . $window . '/' . (int) $page); }
[ "public", "function", "galleryTag", "(", "$", "name", ",", "$", "sort", "=", "'viral'", ",", "$", "page", "=", "0", ",", "$", "window", "=", "'week'", ")", "{", "$", "this", "->", "validateSortArgument", "(", "$", "sort", ",", "[", "'top'", ",", "'...
View images for a gallery tag. @param string $name The name of the tag @param string $sort (top | time | viral) @param int $page @param string $window (day | week | month | year | all) @see https://api.imgur.com/endpoints/gallery#gallery-tag @return array Tag (@see https://api.imgur.com/models/tag)
[ "View", "images", "for", "a", "gallery", "tag", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Gallery.php#L126-L132
41,521
j0k3r/php-imgur-api-client
lib/Imgur/Api/Gallery.php
Gallery.galleryVoteTag
public function galleryVoteTag($id, $name, $vote) { $this->validateVoteArgument($vote, ['up', 'down']); return $this->post('gallery/' . $id . '/vote/tag/' . $name . '/' . $vote); }
php
public function galleryVoteTag($id, $name, $vote) { $this->validateVoteArgument($vote, ['up', 'down']); return $this->post('gallery/' . $id . '/vote/tag/' . $name . '/' . $vote); }
[ "public", "function", "galleryVoteTag", "(", "$", "id", ",", "$", "name", ",", "$", "vote", ")", "{", "$", "this", "->", "validateVoteArgument", "(", "$", "vote", ",", "[", "'up'", ",", "'down'", "]", ")", ";", "return", "$", "this", "->", "post", ...
Vote for a tag, 'up' or 'down' vote. Send the same value again to undo a vote. @param string $id ID of the gallery item @param string $name Name of the tag (implicitly created, if doesn't exist) @param string $vote 'up' or 'down' @see https://api.imgur.com/endpoints/gallery#gallery-tag-vote @return bool
[ "Vote", "for", "a", "tag", "up", "or", "down", "vote", ".", "Send", "the", "same", "value", "again", "to", "undo", "a", "vote", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Gallery.php#L174-L179
41,522
j0k3r/php-imgur-api-client
lib/Imgur/Api/Gallery.php
Gallery.search
public function search($query, $sort = 'time', $page = 0) { $this->validateSortArgument($sort, ['viral', 'top', 'time']); return $this->get('gallery/search/' . $sort . '/' . (int) $page, ['q' => $query]); }
php
public function search($query, $sort = 'time', $page = 0) { $this->validateSortArgument($sort, ['viral', 'top', 'time']); return $this->get('gallery/search/' . $sort . '/' . (int) $page, ['q' => $query]); }
[ "public", "function", "search", "(", "$", "query", ",", "$", "sort", "=", "'time'", ",", "$", "page", "=", "0", ")", "{", "$", "this", "->", "validateSortArgument", "(", "$", "sort", ",", "[", "'viral'", ",", "'top'", ",", "'time'", "]", ")", ";", ...
Search the gallery with a given query string. @param string $query Query string (note: if advanced search parameters are set, this query string is ignored). This parameter also supports boolean operators (AND, OR, NOT) and indices (tag: user: title: ext: subreddit: album: meme:). An example compound query would be 'title: cats AND dogs ext: gif' @param string $sort (time | viral | top) @param int $page @see https://api.imgur.com/endpoints/gallery#gallery-search @return array Gallery Image (@see https://api.imgur.com/models/gallery_image) OR Gallery Album (@see https://api.imgur.com/models/gallery_album)
[ "Search", "the", "gallery", "with", "a", "given", "query", "string", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Gallery.php#L194-L199
41,523
j0k3r/php-imgur-api-client
lib/Imgur/Api/Gallery.php
Gallery.submitToGallery
public function submitToGallery($imageOrAlbumId, $data) { if (!isset($data['title'])) { throw new MissingArgumentException('title'); } return $this->post('gallery/' . $imageOrAlbumId, $data); }
php
public function submitToGallery($imageOrAlbumId, $data) { if (!isset($data['title'])) { throw new MissingArgumentException('title'); } return $this->post('gallery/' . $imageOrAlbumId, $data); }
[ "public", "function", "submitToGallery", "(", "$", "imageOrAlbumId", ",", "$", "data", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'title'", "]", ")", ")", "{", "throw", "new", "MissingArgumentException", "(", "'title'", ")", ";", "}", "...
Share an Album or Image to the Gallery. @param string $imageOrAlbumId @param array $data @see https://api.imgur.com/endpoints/gallery#to-gallery @return bool
[ "Share", "an", "Album", "or", "Image", "to", "the", "Gallery", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Gallery.php#L225-L232
41,524
j0k3r/php-imgur-api-client
lib/Imgur/Api/Gallery.php
Gallery.vote
public function vote($imageOrAlbumId, $vote) { $this->validateVoteArgument($vote, ['up', 'down', 'veto']); return $this->post('gallery/' . $imageOrAlbumId . '/vote/' . $vote); }
php
public function vote($imageOrAlbumId, $vote) { $this->validateVoteArgument($vote, ['up', 'down', 'veto']); return $this->post('gallery/' . $imageOrAlbumId . '/vote/' . $vote); }
[ "public", "function", "vote", "(", "$", "imageOrAlbumId", ",", "$", "vote", ")", "{", "$", "this", "->", "validateVoteArgument", "(", "$", "vote", ",", "[", "'up'", ",", "'down'", ",", "'veto'", "]", ")", ";", "return", "$", "this", "->", "post", "("...
Vote for an image, 'up' or 'down' vote. Send 'veto' to undo a vote. @param string $imageOrAlbumId @param string $vote (up | down | veto) @see https://api.imgur.com/endpoints/gallery#gallery-voting @return bool
[ "Vote", "for", "an", "image", "up", "or", "down", "vote", ".", "Send", "veto", "to", "undo", "a", "vote", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Gallery.php#L314-L319
41,525
j0k3r/php-imgur-api-client
lib/Imgur/Api/Gallery.php
Gallery.comments
public function comments($imageOrAlbumId, $sort = 'best') { $this->validateSortArgument($sort, ['best', 'top', 'new']); return $this->get('gallery/' . $imageOrAlbumId . '/comments/' . $sort); }
php
public function comments($imageOrAlbumId, $sort = 'best') { $this->validateSortArgument($sort, ['best', 'top', 'new']); return $this->get('gallery/' . $imageOrAlbumId . '/comments/' . $sort); }
[ "public", "function", "comments", "(", "$", "imageOrAlbumId", ",", "$", "sort", "=", "'best'", ")", "{", "$", "this", "->", "validateSortArgument", "(", "$", "sort", ",", "[", "'best'", ",", "'top'", ",", "'new'", "]", ")", ";", "return", "$", "this", ...
Retrieve comments on an image or album in the gallery. @param string $imageOrAlbumId @param string $sort (best | top | new) @see https://api.imgur.com/endpoints/gallery#gallery-comments @return array Array of Comment (@see https://api.imgur.com/endpoints/gallery#gallery-comments)
[ "Retrieve", "comments", "on", "an", "image", "or", "album", "in", "the", "gallery", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/Gallery.php#L331-L336
41,526
j0k3r/php-imgur-api-client
lib/Imgur/Api/AbstractApi.php
AbstractApi.get
public function get($url, $parameters = []) { $httpClient = $this->client->getHttpClient(); if (!empty($this->pager)) { $parameters['page'] = $this->pager->getPage(); $parameters['perPage'] = $this->pager->getResultsPerPage(); } $response = $httpClient->get($url, ['query' => $parameters]); return $httpClient->parseResponse($response); }
php
public function get($url, $parameters = []) { $httpClient = $this->client->getHttpClient(); if (!empty($this->pager)) { $parameters['page'] = $this->pager->getPage(); $parameters['perPage'] = $this->pager->getResultsPerPage(); } $response = $httpClient->get($url, ['query' => $parameters]); return $httpClient->parseResponse($response); }
[ "public", "function", "get", "(", "$", "url", ",", "$", "parameters", "=", "[", "]", ")", "{", "$", "httpClient", "=", "$", "this", "->", "client", "->", "getHttpClient", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "pager", ")...
Perform a GET request and return the parsed response. @param string $url @return array
[ "Perform", "a", "GET", "request", "and", "return", "the", "parsed", "response", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/AbstractApi.php#L39-L51
41,527
j0k3r/php-imgur-api-client
lib/Imgur/Api/AbstractApi.php
AbstractApi.put
public function put($url, $parameters = []) { $httpClient = $this->client->getHttpClient(); $response = $httpClient->put($url, $parameters); return $httpClient->parseResponse($response); }
php
public function put($url, $parameters = []) { $httpClient = $this->client->getHttpClient(); $response = $httpClient->put($url, $parameters); return $httpClient->parseResponse($response); }
[ "public", "function", "put", "(", "$", "url", ",", "$", "parameters", "=", "[", "]", ")", "{", "$", "httpClient", "=", "$", "this", "->", "client", "->", "getHttpClient", "(", ")", ";", "$", "response", "=", "$", "httpClient", "->", "put", "(", "$"...
Perform a PUT request and return the parsed response. @param string $url @return array
[ "Perform", "a", "PUT", "request", "and", "return", "the", "parsed", "response", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/AbstractApi.php#L76-L83
41,528
j0k3r/php-imgur-api-client
lib/Imgur/Api/AbstractApi.php
AbstractApi.validateArgument
private function validateArgument($type, $input, $possibleValues) { if (!\in_array($input, $possibleValues, true)) { throw new InvalidArgumentException($type . ' parameter "' . $input . '" is wrong. Possible values are: ' . implode(', ', $possibleValues)); } }
php
private function validateArgument($type, $input, $possibleValues) { if (!\in_array($input, $possibleValues, true)) { throw new InvalidArgumentException($type . ' parameter "' . $input . '" is wrong. Possible values are: ' . implode(', ', $possibleValues)); } }
[ "private", "function", "validateArgument", "(", "$", "type", ",", "$", "input", ",", "$", "possibleValues", ")", "{", "if", "(", "!", "\\", "in_array", "(", "$", "input", ",", "$", "possibleValues", ",", "true", ")", ")", "{", "throw", "new", "InvalidA...
Global method to validate an argument. @param string $type The required parameter (used for the error message) @param string $input Input value @param array $possibleValues Possible values for this argument
[ "Global", "method", "to", "validate", "an", "argument", "." ]
30455a44248b6933fc33f3a01022cf2869c3557b
https://github.com/j0k3r/php-imgur-api-client/blob/30455a44248b6933fc33f3a01022cf2869c3557b/lib/Imgur/Api/AbstractApi.php#L141-L146
41,529
maxhelias/php-nominatim
src/Reverse.php
Reverse.latlon
public function latlon(float $lat, float $lon): self { $this->query['lat'] = $lat; $this->query['lon'] = $lon; return $this; }
php
public function latlon(float $lat, float $lon): self { $this->query['lat'] = $lat; $this->query['lon'] = $lon; return $this; }
[ "public", "function", "latlon", "(", "float", "$", "lat", ",", "float", "$", "lon", ")", ":", "self", "{", "$", "this", "->", "query", "[", "'lat'", "]", "=", "$", "lat", ";", "$", "this", "->", "query", "[", "'lon'", "]", "=", "$", "lon", ";",...
The location to generate an address for. @param float $lat The latitude @param float $lon The longitude @return \maxh\Nominatim\Reverse
[ "The", "location", "to", "generate", "an", "address", "for", "." ]
7bd5fd76fb87625dd52bb459cb89df2b06937dd7
https://github.com/maxhelias/php-nominatim/blob/7bd5fd76fb87625dd52bb459cb89df2b06937dd7/src/Reverse.php#L86-L93
41,530
maxhelias/php-nominatim
src/Nominatim.php
Nominatim.decodeResponse
private function decodeResponse(string $format, Request $request, ResponseInterface $response) { if ('json' === $format || 'jsonv2' === $format || 'geojson' === $format || 'geocodejson' === $format) { return \json_decode($response->getBody()->getContents(), true); } if ('xml' === $format) { return new \SimpleXMLElement($response->getBody()->getContents()); } throw new NominatimException('Format is undefined or not supported for decode response', $request, $response); }
php
private function decodeResponse(string $format, Request $request, ResponseInterface $response) { if ('json' === $format || 'jsonv2' === $format || 'geojson' === $format || 'geocodejson' === $format) { return \json_decode($response->getBody()->getContents(), true); } if ('xml' === $format) { return new \SimpleXMLElement($response->getBody()->getContents()); } throw new NominatimException('Format is undefined or not supported for decode response', $request, $response); }
[ "private", "function", "decodeResponse", "(", "string", "$", "format", ",", "Request", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "if", "(", "'json'", "===", "$", "format", "||", "'jsonv2'", "===", "$", "format", "||", "'geojson'", ...
Decode the data returned from the request. @param string $format json or xml @param Request $request Request object from Guzzle @param ResponseInterface $response Interface response object from Guzzle @throws \RuntimeException @throws \maxh\Nominatim\Exceptions\NominatimException if no format for decode @return array|\SimpleXMLElement
[ "Decode", "the", "data", "returned", "from", "the", "request", "." ]
7bd5fd76fb87625dd52bb459cb89df2b06937dd7
https://github.com/maxhelias/php-nominatim/blob/7bd5fd76fb87625dd52bb459cb89df2b06937dd7/src/Nominatim.php#L159-L170
41,531
maxhelias/php-nominatim
src/Nominatim.php
Nominatim.find
public function find(QueryInterface $nRequest, array $headers = []) { $url = $this->application_url . '/' . $nRequest->getPath() . '?'; $request = new Request('GET', $url, \array_merge($this->defaultHeaders, $headers)); //Convert the query array to string with space replace to + $query = \GuzzleHttp\Psr7\build_query($nRequest->getQuery(), PHP_QUERY_RFC1738); $url = $request->getUri()->withQuery($query); $request = $request->withUri($url); return $this->decodeResponse( $nRequest->getFormat(), $request, $this->http_client->send($request) ); }
php
public function find(QueryInterface $nRequest, array $headers = []) { $url = $this->application_url . '/' . $nRequest->getPath() . '?'; $request = new Request('GET', $url, \array_merge($this->defaultHeaders, $headers)); //Convert the query array to string with space replace to + $query = \GuzzleHttp\Psr7\build_query($nRequest->getQuery(), PHP_QUERY_RFC1738); $url = $request->getUri()->withQuery($query); $request = $request->withUri($url); return $this->decodeResponse( $nRequest->getFormat(), $request, $this->http_client->send($request) ); }
[ "public", "function", "find", "(", "QueryInterface", "$", "nRequest", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "application_url", ".", "'/'", ".", "$", "nRequest", "->", "getPath", "(", ")", ".", "'?'...
Runs the query and returns the result set from Nominatim. @param QueryInterface $nRequest The object request to send @param array $headers Override the request header @throws NominatimException if no format for decode @throws \GuzzleHttp\Exception\GuzzleException @return array|\SimpleXMLElement The decoded data returned from Nominatim
[ "Runs", "the", "query", "and", "returns", "the", "result", "set", "from", "Nominatim", "." ]
7bd5fd76fb87625dd52bb459cb89df2b06937dd7
https://github.com/maxhelias/php-nominatim/blob/7bd5fd76fb87625dd52bb459cb89df2b06937dd7/src/Nominatim.php#L183-L199
41,532
maxhelias/php-nominatim
src/Query.php
Query.format
public function format(string $format): self { $format = \mb_strtolower($format); if (\in_array($format, $this->acceptedFormat, true)) { $this->setFormat($format); return $this; } throw new InvalidParameterException('Format is not supported'); }
php
public function format(string $format): self { $format = \mb_strtolower($format); if (\in_array($format, $this->acceptedFormat, true)) { $this->setFormat($format); return $this; } throw new InvalidParameterException('Format is not supported'); }
[ "public", "function", "format", "(", "string", "$", "format", ")", ":", "self", "{", "$", "format", "=", "\\", "mb_strtolower", "(", "$", "format", ")", ";", "if", "(", "\\", "in_array", "(", "$", "format", ",", "$", "this", "->", "acceptedFormat", "...
Format returning by the request. @param string $format The output format for the request @throws \maxh\Nominatim\Exceptions\InvalidParameterException if format is not supported @return \maxh\Nominatim\Search|\maxh\Nominatim\Reverse|\maxh\Nominatim\Lookup
[ "Format", "returning", "by", "the", "request", "." ]
7bd5fd76fb87625dd52bb459cb89df2b06937dd7
https://github.com/maxhelias/php-nominatim/blob/7bd5fd76fb87625dd52bb459cb89df2b06937dd7/src/Query.php#L83-L94
41,533
maxhelias/php-nominatim
src/Query.php
Query.polygon
public function polygon(string $polygon) { if (\in_array($polygon, $this->polygon, true)) { $this->query['polygon_' . $polygon] = '1'; return $this; } throw new InvalidParameterException('This polygon format is not supported'); }
php
public function polygon(string $polygon) { if (\in_array($polygon, $this->polygon, true)) { $this->query['polygon_' . $polygon] = '1'; return $this; } throw new InvalidParameterException('This polygon format is not supported'); }
[ "public", "function", "polygon", "(", "string", "$", "polygon", ")", "{", "if", "(", "\\", "in_array", "(", "$", "polygon", ",", "$", "this", "->", "polygon", ",", "true", ")", ")", "{", "$", "this", "->", "query", "[", "'polygon_'", ".", "$", "pol...
Output format for the geometry of results. @param string $polygon @throws \maxh\Nominatim\Exceptions\InvalidParameterException if polygon format is not supported @return \maxh\Nominatim\Search|\maxh\Nominatim\Reverse|\maxh\Nominatim\Query
[ "Output", "format", "for", "the", "geometry", "of", "results", "." ]
7bd5fd76fb87625dd52bb459cb89df2b06937dd7
https://github.com/maxhelias/php-nominatim/blob/7bd5fd76fb87625dd52bb459cb89df2b06937dd7/src/Query.php#L154-L163
41,534
maxhelias/php-nominatim
src/Search.php
Search.viewBox
public function viewBox(string $left, string $top, string $right, string $bottom): self { $this->query['viewbox'] = $left . ',' . $top . ',' . $right . ',' . $bottom; return $this; }
php
public function viewBox(string $left, string $top, string $right, string $bottom): self { $this->query['viewbox'] = $left . ',' . $top . ',' . $right . ',' . $bottom; return $this; }
[ "public", "function", "viewBox", "(", "string", "$", "left", ",", "string", "$", "top", ",", "string", "$", "right", ",", "string", "$", "bottom", ")", ":", "self", "{", "$", "this", "->", "query", "[", "'viewbox'", "]", "=", "$", "left", ".", "','...
The preferred area to find search results. @param string $left Left of the area @param string $top Top of the area @param string $right Right of the area @param string $bottom Bottom of the area @return \maxh\Nominatim\Search
[ "The", "preferred", "area", "to", "find", "search", "results", "." ]
7bd5fd76fb87625dd52bb459cb89df2b06937dd7
https://github.com/maxhelias/php-nominatim/blob/7bd5fd76fb87625dd52bb459cb89df2b06937dd7/src/Search.php#L187-L192
41,535
maxhelias/php-nominatim
src/Search.php
Search.exludePlaceIds
public function exludePlaceIds(): self { $args = \func_get_args(); if (\count($args) > 0) { $this->query['exclude_place_ids'] = \implode(', ', $args); return $this; } throw new InvalidParameterException('No place id in parameter'); }
php
public function exludePlaceIds(): self { $args = \func_get_args(); if (\count($args) > 0) { $this->query['exclude_place_ids'] = \implode(', ', $args); return $this; } throw new InvalidParameterException('No place id in parameter'); }
[ "public", "function", "exludePlaceIds", "(", ")", ":", "self", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "if", "(", "\\", "count", "(", "$", "args", ")", ">", "0", ")", "{", "$", "this", "->", "query", "[", "'exclude_place_ids'", ...
If you do not want certain OpenStreetMap objects to appear in the search results. @throws \maxh\Nominatim\Exceptions\InvalidParameterException if no place id @return \maxh\Nominatim\Search
[ "If", "you", "do", "not", "want", "certain", "OpenStreetMap", "objects", "to", "appear", "in", "the", "search", "results", "." ]
7bd5fd76fb87625dd52bb459cb89df2b06937dd7
https://github.com/maxhelias/php-nominatim/blob/7bd5fd76fb87625dd52bb459cb89df2b06937dd7/src/Search.php#L201-L212
41,536
lndj/Lcrawl
src/Traits/BuildRequest.php
BuildRequest.buildGetRequest
public function buildGetRequest($uri, $param = [], $headers = [], $isAsync = false) { $query_param = array_merge(['xh' => $this->stu_id], $param); $query = [ 'query' => $query_param, 'headers' => $headers, ]; if ($this->cacheCookie) { $query['cookies'] = $this->getCookie(); } //If use getAll(), use the Async request. return $isAsync ? $this->client->getAsync($uri, $query) : $this->client->get($uri, $query); }
php
public function buildGetRequest($uri, $param = [], $headers = [], $isAsync = false) { $query_param = array_merge(['xh' => $this->stu_id], $param); $query = [ 'query' => $query_param, 'headers' => $headers, ]; if ($this->cacheCookie) { $query['cookies'] = $this->getCookie(); } //If use getAll(), use the Async request. return $isAsync ? $this->client->getAsync($uri, $query) : $this->client->get($uri, $query); }
[ "public", "function", "buildGetRequest", "(", "$", "uri", ",", "$", "param", "=", "[", "]", ",", "$", "headers", "=", "[", "]", ",", "$", "isAsync", "=", "false", ")", "{", "$", "query_param", "=", "array_merge", "(", "[", "'xh'", "=>", "$", "this"...
Build the get request. @param type|string $uri @param type|array $param @param type|array $headers @param type|bool $isAsync @return type
[ "Build", "the", "get", "request", "." ]
61adc5d99355155099743b288ea3be52efebb852
https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Traits/BuildRequest.php#L29-L43
41,537
lndj/Lcrawl
src/Traits/BuildRequest.php
BuildRequest.buildPostRequest
public function buildPostRequest($uri, $query, $param, $headers = [], $isAsync = false) { $query_param = array_merge(['xh' => $this->stu_id], $query); $post = [ 'query' => $query_param, 'headers' => $headers, 'form_params' => $param, ]; //If opened cookie cache if ($this->cacheCookie) { $post['cookies'] = $this->getCookie(); } //If use getAll(), use the Async request. return $isAsync ? $this->client->postAsync($uri, $post) : $this->client->post($uri, $post); }
php
public function buildPostRequest($uri, $query, $param, $headers = [], $isAsync = false) { $query_param = array_merge(['xh' => $this->stu_id], $query); $post = [ 'query' => $query_param, 'headers' => $headers, 'form_params' => $param, ]; //If opened cookie cache if ($this->cacheCookie) { $post['cookies'] = $this->getCookie(); } //If use getAll(), use the Async request. return $isAsync ? $this->client->postAsync($uri, $post) : $this->client->post($uri, $post); }
[ "public", "function", "buildPostRequest", "(", "$", "uri", ",", "$", "query", ",", "$", "param", ",", "$", "headers", "=", "[", "]", ",", "$", "isAsync", "=", "false", ")", "{", "$", "query_param", "=", "array_merge", "(", "[", "'xh'", "=>", "$", "...
Build the POST request. @param $uri @param $query @param $param @param array $headers A array of headers. @param bool $isAsync If use getAll(), by Async request. @return mixed
[ "Build", "the", "POST", "request", "." ]
61adc5d99355155099743b288ea3be52efebb852
https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Traits/BuildRequest.php#L55-L73
41,538
letsdrink/ouzo
src/Ouzo/Core/Model.php
Model.inspect
public function inspect() { return get_called_class() . Objects::toString(Arrays::filter($this->attributes, Functions::notNull())); }
php
public function inspect() { return get_called_class() . Objects::toString(Arrays::filter($this->attributes, Functions::notNull())); }
[ "public", "function", "inspect", "(", ")", "{", "return", "get_called_class", "(", ")", ".", "Objects", "::", "toString", "(", "Arrays", "::", "filter", "(", "$", "this", "->", "attributes", ",", "Functions", "::", "notNull", "(", ")", ")", ")", ";", "...
Returns model object as a nicely formatted string. @return string
[ "Returns", "model", "object", "as", "a", "nicely", "formatted", "string", "." ]
4ab809ce8152dc7ef02c67bd6d42924d5d73631e
https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Model.php#L374-L377
41,539
letsdrink/ouzo
src/Ouzo/Core/Model.php
Model.findBySql
public static function findBySql($nativeSql, $params = []) { $meta = static::metaInstance(); $results = $meta->modelDefinition->db->query($nativeSql, Arrays::toArray($params))->fetchAll(); return Arrays::map($results, function ($row) use ($meta) { return $meta->newInstance($row); }); }
php
public static function findBySql($nativeSql, $params = []) { $meta = static::metaInstance(); $results = $meta->modelDefinition->db->query($nativeSql, Arrays::toArray($params))->fetchAll(); return Arrays::map($results, function ($row) use ($meta) { return $meta->newInstance($row); }); }
[ "public", "static", "function", "findBySql", "(", "$", "nativeSql", ",", "$", "params", "=", "[", "]", ")", "{", "$", "meta", "=", "static", "::", "metaInstance", "(", ")", ";", "$", "results", "=", "$", "meta", "->", "modelDefinition", "->", "db", "...
Executes a native sql and returns an array of model objects created by passing every result row to the model constructor. @param string $nativeSql - database specific sql @param array $params - bind parameters @return Model[]
[ "Executes", "a", "native", "sql", "and", "returns", "an", "array", "of", "model", "objects", "created", "by", "passing", "every", "result", "row", "to", "the", "model", "constructor", "." ]
4ab809ce8152dc7ef02c67bd6d42924d5d73631e
https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Model.php#L582-L590
41,540
letsdrink/ouzo
src/Ouzo/Core/Db/ModelQueryBuilder.php
ModelQueryBuilder.update
public function update(array $attributes) { $this->query->type = QueryType::$UPDATE; $this->query->updateAttributes = $attributes; return QueryExecutor::prepare($this->db, $this->query)->execute(); }
php
public function update(array $attributes) { $this->query->type = QueryType::$UPDATE; $this->query->updateAttributes = $attributes; return QueryExecutor::prepare($this->db, $this->query)->execute(); }
[ "public", "function", "update", "(", "array", "$", "attributes", ")", "{", "$", "this", "->", "query", "->", "type", "=", "QueryType", "::", "$", "UPDATE", ";", "$", "this", "->", "query", "->", "updateAttributes", "=", "$", "attributes", ";", "return", ...
Runs an update query against a set of models @param array $attributes @return int
[ "Runs", "an", "update", "query", "against", "a", "set", "of", "models" ]
4ab809ce8152dc7ef02c67bd6d42924d5d73631e
https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Db/ModelQueryBuilder.php#L220-L225
41,541
lndj/Lcrawl
src/Traits/Parser.php
Parser.parserSchedule
public function parserSchedule($body) { $crawler = new Crawler((string)$body); $crawler = $crawler->filter('#Table1'); $page = $crawler->children(); //delete line 1、2; $page = $page->reduce(function (Crawler $node, $i) { if ($i == 0 || $i == 1) { return false; } }); //to array $array = $page->each(function (Crawler $node, $i) { return $node->children()->each(function (Crawler $node, $j) { $span = (int)$node->attr('rowspan') ?: 0; return [$node->html(), $span]; }); }); //If there are some classes in the table is in two or more lines, //insert it into the next lines in $array. //Thanks for @CheukFung $line_count = count($array); $schedule = []; for ($i = 0; $i < $line_count; $i++) { //lines for ($j = 0; $j < 9; $j++) { //rows if (isset($array[$i][$j])) { $k = $array[$i][$j][1]; while (--$k > 0) { // insert element to next line //Set the span 0 $array[$i][$j][1] = 0; $array[$i + $k] = array_merge( array_slice($array[$i + $k], 0, $j), [$array[$i][$j]], array_splice($array[$i + $k], $j) ); } } $schedule[$i][$j] = isset($array[$i][$j][0]) ? $array[$i][$j][0] : ''; } } return $schedule; }
php
public function parserSchedule($body) { $crawler = new Crawler((string)$body); $crawler = $crawler->filter('#Table1'); $page = $crawler->children(); //delete line 1、2; $page = $page->reduce(function (Crawler $node, $i) { if ($i == 0 || $i == 1) { return false; } }); //to array $array = $page->each(function (Crawler $node, $i) { return $node->children()->each(function (Crawler $node, $j) { $span = (int)$node->attr('rowspan') ?: 0; return [$node->html(), $span]; }); }); //If there are some classes in the table is in two or more lines, //insert it into the next lines in $array. //Thanks for @CheukFung $line_count = count($array); $schedule = []; for ($i = 0; $i < $line_count; $i++) { //lines for ($j = 0; $j < 9; $j++) { //rows if (isset($array[$i][$j])) { $k = $array[$i][$j][1]; while (--$k > 0) { // insert element to next line //Set the span 0 $array[$i][$j][1] = 0; $array[$i + $k] = array_merge( array_slice($array[$i + $k], 0, $j), [$array[$i][$j]], array_splice($array[$i + $k], $j) ); } } $schedule[$i][$j] = isset($array[$i][$j][0]) ? $array[$i][$j][0] : ''; } } return $schedule; }
[ "public", "function", "parserSchedule", "(", "$", "body", ")", "{", "$", "crawler", "=", "new", "Crawler", "(", "(", "string", ")", "$", "body", ")", ";", "$", "crawler", "=", "$", "crawler", "->", "filter", "(", "'#Table1'", ")", ";", "$", "page", ...
Paser the schedule data. @param Object $body @return Array
[ "Paser", "the", "schedule", "data", "." ]
61adc5d99355155099743b288ea3be52efebb852
https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Traits/Parser.php#L27-L70
41,542
lndj/Lcrawl
src/Supports/Log.php
Log.info
public static function info($info, $context) { self::$logger->pushHandler(new StreamHandler(self::$log_file), Logger::INFO); return self::$logger->info($info, $context); }
php
public static function info($info, $context) { self::$logger->pushHandler(new StreamHandler(self::$log_file), Logger::INFO); return self::$logger->info($info, $context); }
[ "public", "static", "function", "info", "(", "$", "info", ",", "$", "context", ")", "{", "self", "::", "$", "logger", "->", "pushHandler", "(", "new", "StreamHandler", "(", "self", "::", "$", "log_file", ")", ",", "Logger", "::", "INFO", ")", ";", "r...
Info log. @param $info @param $context @return bool
[ "Info", "log", "." ]
61adc5d99355155099743b288ea3be52efebb852
https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Supports/Log.php#L41-L45
41,543
lndj/Lcrawl
src/Supports/Log.php
Log.debug
public static function debug($message, $context) { self::$logger->pushHandler(new StreamHandler(self::$log_file), Logger::DEBUG); return self::$logger->debug($message, $context); }
php
public static function debug($message, $context) { self::$logger->pushHandler(new StreamHandler(self::$log_file), Logger::DEBUG); return self::$logger->debug($message, $context); }
[ "public", "static", "function", "debug", "(", "$", "message", ",", "$", "context", ")", "{", "self", "::", "$", "logger", "->", "pushHandler", "(", "new", "StreamHandler", "(", "self", "::", "$", "log_file", ")", ",", "Logger", "::", "DEBUG", ")", ";",...
Debug message. @param $message @param $context @return bool
[ "Debug", "message", "." ]
61adc5d99355155099743b288ea3be52efebb852
https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Supports/Log.php#L53-L58
41,544
lndj/Lcrawl
src/Lcrawl.php
Lcrawl.getCookie
public function getCookie($forceRefresh = false) { $cacheKey = $this->cachePrefix . $this->stu_id; $cached = $this->getCache()->fetch($cacheKey); if ($forceRefresh || empty($cached)) { $jar = $this->login(); //Cache the cookieJar 3000 s. $this->getCache()->save($cacheKey, serialize($jar), 3000); return $jar; } return unserialize($cached); }
php
public function getCookie($forceRefresh = false) { $cacheKey = $this->cachePrefix . $this->stu_id; $cached = $this->getCache()->fetch($cacheKey); if ($forceRefresh || empty($cached)) { $jar = $this->login(); //Cache the cookieJar 3000 s. $this->getCache()->save($cacheKey, serialize($jar), 3000); return $jar; } return unserialize($cached); }
[ "public", "function", "getCookie", "(", "$", "forceRefresh", "=", "false", ")", "{", "$", "cacheKey", "=", "$", "this", "->", "cachePrefix", ".", "$", "this", "->", "stu_id", ";", "$", "cached", "=", "$", "this", "->", "getCache", "(", ")", "->", "fe...
Get cookie from cache or login. @param bool $forceRefresh @return string
[ "Get", "cookie", "from", "cache", "or", "login", "." ]
61adc5d99355155099743b288ea3be52efebb852
https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Lcrawl.php#L111-L122
41,545
lndj/Lcrawl
src/Lcrawl.php
Lcrawl.getAll
public function getAll() { $requests = [ 'schedule' => $this->buildGetRequest(self::ZF_SCHEDULE_URI, [], $this->headers, true), 'cet' => $this->buildGetRequest(self::ZF_CET_URI, [], $this->headers, true), 'exam' => $this->buildGetRequest(self::ZF_EXAM_URI, [], $this->headers, true), ]; // Wait on all of the requests to complete. Throws a ConnectException // if any of the requests fail $results = Promise\unwrap($requests); // Wait for the requests to complete, even if some of them fail // $results = Promise\settle($requests)->wait(); //Parser the data we need. $schedule = $this->parserSchedule($results['schedule']->getBody()); $cet = $this->parserCommonTable($results['cet']->getBody()); $exam = $this->parserCommonTable($results['exam']->getBody()); return compact('schedule', 'cet', 'exam'); }
php
public function getAll() { $requests = [ 'schedule' => $this->buildGetRequest(self::ZF_SCHEDULE_URI, [], $this->headers, true), 'cet' => $this->buildGetRequest(self::ZF_CET_URI, [], $this->headers, true), 'exam' => $this->buildGetRequest(self::ZF_EXAM_URI, [], $this->headers, true), ]; // Wait on all of the requests to complete. Throws a ConnectException // if any of the requests fail $results = Promise\unwrap($requests); // Wait for the requests to complete, even if some of them fail // $results = Promise\settle($requests)->wait(); //Parser the data we need. $schedule = $this->parserSchedule($results['schedule']->getBody()); $cet = $this->parserCommonTable($results['cet']->getBody()); $exam = $this->parserCommonTable($results['exam']->getBody()); return compact('schedule', 'cet', 'exam'); }
[ "public", "function", "getAll", "(", ")", "{", "$", "requests", "=", "[", "'schedule'", "=>", "$", "this", "->", "buildGetRequest", "(", "self", "::", "ZF_SCHEDULE_URI", ",", "[", "]", ",", "$", "this", "->", "headers", ",", "true", ")", ",", "'cet'", ...
By Concurrent requests, to get all the data. @return Array
[ "By", "Concurrent", "requests", "to", "get", "all", "the", "data", "." ]
61adc5d99355155099743b288ea3be52efebb852
https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Lcrawl.php#L352-L372
41,546
lndj/Lcrawl
src/Lcrawl.php
Lcrawl.getSchedule
public function getSchedule() { /** * Default: get the current term schedule data by GET * If you want to get the other term's data, use POST * TODO: use POST to get other term's data */ $response = $this->buildGetRequest(self::ZF_SCHEDULE_URI, [], $this->headers); return $this->parserSchedule($response->getBody()); }
php
public function getSchedule() { /** * Default: get the current term schedule data by GET * If you want to get the other term's data, use POST * TODO: use POST to get other term's data */ $response = $this->buildGetRequest(self::ZF_SCHEDULE_URI, [], $this->headers); return $this->parserSchedule($response->getBody()); }
[ "public", "function", "getSchedule", "(", ")", "{", "/**\n * Default: get the current term schedule data by GET\n * If you want to get the other term's data, use POST\n * TODO: use POST to get other term's data\n */", "$", "response", "=", "$", "this", "->", ...
Get the schedule data @return Array
[ "Get", "the", "schedule", "data" ]
61adc5d99355155099743b288ea3be52efebb852
https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Lcrawl.php#L404-L413
41,547
lndj/Lcrawl
src/Lcrawl.php
Lcrawl.getCet
public function getCet() { $response = $this->buildGetRequest(self::ZF_CET_URI); return $this->parserCommonTable($response->getBody()); }
php
public function getCet() { $response = $this->buildGetRequest(self::ZF_CET_URI); return $this->parserCommonTable($response->getBody()); }
[ "public", "function", "getCet", "(", ")", "{", "$", "response", "=", "$", "this", "->", "buildGetRequest", "(", "self", "::", "ZF_CET_URI", ")", ";", "return", "$", "this", "->", "parserCommonTable", "(", "$", "response", "->", "getBody", "(", ")", ")", ...
Get the CET data. @return type|Object
[ "Get", "the", "CET", "data", "." ]
61adc5d99355155099743b288ea3be52efebb852
https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Lcrawl.php#L419-L423
41,548
letsdrink/ouzo
src/Ouzo/Core/Validatable.php
Validatable.validateTrue
public function validateTrue($value, $errorMessage, $errorField = null) { if (!$value) { $this->error($errorMessage); $this->_errorFields[] = $errorField; } }
php
public function validateTrue($value, $errorMessage, $errorField = null) { if (!$value) { $this->error($errorMessage); $this->_errorFields[] = $errorField; } }
[ "public", "function", "validateTrue", "(", "$", "value", ",", "$", "errorMessage", ",", "$", "errorField", "=", "null", ")", "{", "if", "(", "!", "$", "value", ")", "{", "$", "this", "->", "error", "(", "$", "errorMessage", ")", ";", "$", "this", "...
Checks whether value is true, if not it saves error @param $value - value to check whether is true (values which are considered as TRUE or FALSE are presented here http://php.net/manual/en/types.comparisons.php ) @param $errorMessage - error message @param null $errorField
[ "Checks", "whether", "value", "is", "true", "if", "not", "it", "saves", "error" ]
4ab809ce8152dc7ef02c67bd6d42924d5d73631e
https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L88-L94
41,549
letsdrink/ouzo
src/Ouzo/Core/Validatable.php
Validatable.validateUnique
public function validateUnique(array $values, $errorMessage, $errorField = null) { if (count($values) != count(array_unique($values))) { $this->error($errorMessage); $this->_errorFields[] = $errorField; } }
php
public function validateUnique(array $values, $errorMessage, $errorField = null) { if (count($values) != count(array_unique($values))) { $this->error($errorMessage); $this->_errorFields[] = $errorField; } }
[ "public", "function", "validateUnique", "(", "array", "$", "values", ",", "$", "errorMessage", ",", "$", "errorField", "=", "null", ")", "{", "if", "(", "count", "(", "$", "values", ")", "!=", "count", "(", "array_unique", "(", "$", "values", ")", ")",...
Checks whether array does not contain duplicate values @param array $values - array to check @param $errorMessage - error message @param null $errorField
[ "Checks", "whether", "array", "does", "not", "contain", "duplicate", "values" ]
4ab809ce8152dc7ef02c67bd6d42924d5d73631e
https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L102-L108
41,550
letsdrink/ouzo
src/Ouzo/Core/Validatable.php
Validatable.validateStringMaxLength
public function validateStringMaxLength($value, $maxLength, $errorMessage, $errorField = null) { if (strlen($value) > $maxLength) { $this->error($errorMessage); $this->_errorFields[] = $errorField; } }
php
public function validateStringMaxLength($value, $maxLength, $errorMessage, $errorField = null) { if (strlen($value) > $maxLength) { $this->error($errorMessage); $this->_errorFields[] = $errorField; } }
[ "public", "function", "validateStringMaxLength", "(", "$", "value", ",", "$", "maxLength", ",", "$", "errorMessage", ",", "$", "errorField", "=", "null", ")", "{", "if", "(", "strlen", "(", "$", "value", ")", ">", "$", "maxLength", ")", "{", "$", "this...
Checks whether string does not exceed max length @param string $value - string to check @param int $maxLength - max length which doesn't cause error @param $errorMessage - error message @param null $errorField
[ "Checks", "whether", "string", "does", "not", "exceed", "max", "length" ]
4ab809ce8152dc7ef02c67bd6d42924d5d73631e
https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L131-L137
41,551
letsdrink/ouzo
src/Ouzo/Core/Validatable.php
Validatable.error
public function error($error, $code = 0) { $this->_errors[] = $error instanceof Error ? $error : new Error($code, $error); }
php
public function error($error, $code = 0) { $this->_errors[] = $error instanceof Error ? $error : new Error($code, $error); }
[ "public", "function", "error", "(", "$", "error", ",", "$", "code", "=", "0", ")", "{", "$", "this", "->", "_errors", "[", "]", "=", "$", "error", "instanceof", "Error", "?", "$", "error", ":", "new", "Error", "(", "$", "code", ",", "$", "error",...
Method for adding error manually @param string|\Ouzo\ExceptionHandling\Error $error - \Ouzo\ExceptionHandling\Error instance or new error message @param int $code - error code
[ "Method", "for", "adding", "error", "manually" ]
4ab809ce8152dc7ef02c67bd6d42924d5d73631e
https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L174-L177
41,552
letsdrink/ouzo
src/Ouzo/Core/Validatable.php
Validatable.errors
public function errors(array $errors, $code = 0) { foreach ($errors as $error) { $this->error($error, $code); } }
php
public function errors(array $errors, $code = 0) { foreach ($errors as $error) { $this->error($error, $code); } }
[ "public", "function", "errors", "(", "array", "$", "errors", ",", "$", "code", "=", "0", ")", "{", "foreach", "(", "$", "errors", "as", "$", "error", ")", "{", "$", "this", "->", "error", "(", "$", "error", ",", "$", "code", ")", ";", "}", "}" ...
Method for batch adding errors manually @param array $errors - array of \Ouzo\ExceptionHandling\Error instaces or new error messages @param int $code
[ "Method", "for", "batch", "adding", "errors", "manually" ]
4ab809ce8152dc7ef02c67bd6d42924d5d73631e
https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L184-L189
41,553
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Image.php
Image.scaleDimensions
public static function scaleDimensions(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) { $aspect = $dimensions['height'] / $dimensions['width']; // Calculate one of the dimensions from the other target dimension, // ensuring the same aspect ratio as the source dimensions. If one of the // target dimensions is missing, that is the one that is calculated. If both // are specified then the dimension calculated is the one that would not be // calculated to be bigger than its target. if (($width && !$height) || ($width && $height && $aspect < $height / $width)) { $height = (int) round($width * $aspect); } else { $width = (int) round($height / $aspect); } // Don't upscale if the option isn't enabled. if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) { return FALSE; } $dimensions['width'] = $width; $dimensions['height'] = $height; return TRUE; }
php
public static function scaleDimensions(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) { $aspect = $dimensions['height'] / $dimensions['width']; // Calculate one of the dimensions from the other target dimension, // ensuring the same aspect ratio as the source dimensions. If one of the // target dimensions is missing, that is the one that is calculated. If both // are specified then the dimension calculated is the one that would not be // calculated to be bigger than its target. if (($width && !$height) || ($width && $height && $aspect < $height / $width)) { $height = (int) round($width * $aspect); } else { $width = (int) round($height / $aspect); } // Don't upscale if the option isn't enabled. if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) { return FALSE; } $dimensions['width'] = $width; $dimensions['height'] = $height; return TRUE; }
[ "public", "static", "function", "scaleDimensions", "(", "array", "&", "$", "dimensions", ",", "$", "width", "=", "NULL", ",", "$", "height", "=", "NULL", ",", "$", "upscale", "=", "FALSE", ")", "{", "$", "aspect", "=", "$", "dimensions", "[", "'height'...
Scales image dimensions while maintaining aspect ratio. The resulting dimensions can be smaller for one or both target dimensions. @param array $dimensions Dimensions to be modified - an array with components width and height, in pixels. @param int $width (optional) The target width, in pixels. If this value is NULL then the scaling will be based only on the height value. @param int $height (optional) The target height, in pixels. If this value is NULL then the scaling will be based only on the width value. @param bool $upscale (optional) Boolean indicating that images smaller than the target dimensions will be scaled up. This generally results in a low quality image. @return bool TRUE if $dimensions was modified, FALSE otherwise. @see image_scale()
[ "Scales", "image", "dimensions", "while", "maintaining", "aspect", "ratio", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Image.php#L41-L64
41,554
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Color.php
Color.validateHex
public static function validateHex($hex) { // Must be a string. $valid = is_string($hex); // Hash prefix is optional. $hex = ltrim($hex, '#'); // Must be either RGB or RRGGBB. $length = Unicode::strlen($hex); $valid = $valid && ($length === 3 || $length === 6); // Must be a valid hex value. $valid = $valid && ctype_xdigit($hex); return $valid; }
php
public static function validateHex($hex) { // Must be a string. $valid = is_string($hex); // Hash prefix is optional. $hex = ltrim($hex, '#'); // Must be either RGB or RRGGBB. $length = Unicode::strlen($hex); $valid = $valid && ($length === 3 || $length === 6); // Must be a valid hex value. $valid = $valid && ctype_xdigit($hex); return $valid; }
[ "public", "static", "function", "validateHex", "(", "$", "hex", ")", "{", "// Must be a string.", "$", "valid", "=", "is_string", "(", "$", "hex", ")", ";", "// Hash prefix is optional.", "$", "hex", "=", "ltrim", "(", "$", "hex", ",", "'#'", ")", ";", "...
Validates whether a hexadecimal color value is syntactically correct. @param $hex The hexadecimal string to validate. May contain a leading '#'. May use the shorthand notation (e.g., '123' for '112233'). @return bool TRUE if $hex is valid or FALSE if it is not.
[ "Validates", "whether", "a", "hexadecimal", "color", "value", "is", "syntactically", "correct", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Color.php#L25-L36
41,555
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Xss.php
Xss.split
protected static function split($string, $html_tags, $class) { if (substr($string, 0, 1) != '<') { // We matched a lone ">" character. return '&gt;'; } elseif (strlen($string) == 1) { // We matched a lone "<" character. return '&lt;'; } if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)\s*([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) { // Seriously malformed. return ''; } $slash = trim($matches[1]); $elem = &$matches[2]; $attrlist = &$matches[3]; $comment = &$matches[4]; if ($comment) { $elem = '!--'; } // When in whitelist mode, an element is disallowed when not listed. if ($class::needsRemoval($html_tags, $elem)) { return ''; } if ($comment) { return $comment; } if ($slash != '') { return "</$elem>"; } // Is there a closing XHTML slash at the end of the attributes? $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count); $xhtml_slash = $count ? ' /' : ''; // Clean up attributes. $attr2 = implode(' ', $class::attributes($attrlist)); $attr2 = preg_replace('/[<>]/', '', $attr2); $attr2 = strlen($attr2) ? ' ' . $attr2 : ''; return "<$elem$attr2$xhtml_slash>"; }
php
protected static function split($string, $html_tags, $class) { if (substr($string, 0, 1) != '<') { // We matched a lone ">" character. return '&gt;'; } elseif (strlen($string) == 1) { // We matched a lone "<" character. return '&lt;'; } if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)\s*([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) { // Seriously malformed. return ''; } $slash = trim($matches[1]); $elem = &$matches[2]; $attrlist = &$matches[3]; $comment = &$matches[4]; if ($comment) { $elem = '!--'; } // When in whitelist mode, an element is disallowed when not listed. if ($class::needsRemoval($html_tags, $elem)) { return ''; } if ($comment) { return $comment; } if ($slash != '') { return "</$elem>"; } // Is there a closing XHTML slash at the end of the attributes? $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count); $xhtml_slash = $count ? ' /' : ''; // Clean up attributes. $attr2 = implode(' ', $class::attributes($attrlist)); $attr2 = preg_replace('/[<>]/', '', $attr2); $attr2 = strlen($attr2) ? ' ' . $attr2 : ''; return "<$elem$attr2$xhtml_slash>"; }
[ "protected", "static", "function", "split", "(", "$", "string", ",", "$", "html_tags", ",", "$", "class", ")", "{", "if", "(", "substr", "(", "$", "string", ",", "0", ",", "1", ")", "!=", "'<'", ")", "{", "// We matched a lone \">\" character.", "return"...
Processes an HTML tag. @param string $string The HTML tag to process. @param array $html_tags An array where the keys are the allowed tags and the values are not used. @param string $class The called class. This method is called from an anonymous function which breaks late static binding. See https://bugs.php.net/bug.php?id=66622 for more information. @return string If the element isn't allowed, an empty string. Otherwise, the cleaned up version of the HTML element.
[ "Processes", "an", "HTML", "tag", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Xss.php#L147-L193
41,556
aleksip/plugin-data-transform
src/Drupal/Core/Template/AttributeValueBase.php
AttributeValueBase.render
public function render() { $value = (string) $this; if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) { return Html::escape($this->name) . '="' . $value . '"'; } }
php
public function render() { $value = (string) $this; if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) { return Html::escape($this->name) . '="' . $value . '"'; } }
[ "public", "function", "render", "(", ")", "{", "$", "value", "=", "(", "string", ")", "$", "this", ";", "if", "(", "isset", "(", "$", "this", "->", "value", ")", "&&", "static", "::", "RENDER_EMPTY_ATTRIBUTE", "||", "!", "empty", "(", "$", "value", ...
Returns a string representation of the attribute. While __toString only returns the value in a string form, render() contains the name of the attribute as well. @return string The string representation of the attribute.
[ "Returns", "a", "string", "representation", "of", "the", "attribute", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/AttributeValueBase.php#L56-L61
41,557
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Tags.php
Tags.explode
public static function explode($tags) { // This regexp allows the following types of user input: // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x'; preg_match_all($regexp, $tags, $matches); $typed_tags = array_unique($matches[1]); $tags = array(); foreach ($typed_tags as $tag) { // If a user has escaped a term (to demonstrate that it is a group, // or includes a comma or quote character), we remove the escape // formatting so to save the term into the database as the user intends. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag))); if ($tag != "") { $tags[] = $tag; } } return $tags; }
php
public static function explode($tags) { // This regexp allows the following types of user input: // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x'; preg_match_all($regexp, $tags, $matches); $typed_tags = array_unique($matches[1]); $tags = array(); foreach ($typed_tags as $tag) { // If a user has escaped a term (to demonstrate that it is a group, // or includes a comma or quote character), we remove the escape // formatting so to save the term into the database as the user intends. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag))); if ($tag != "") { $tags[] = $tag; } } return $tags; }
[ "public", "static", "function", "explode", "(", "$", "tags", ")", "{", "// This regexp allows the following types of user input:", "// this, \"somecompany, llc\", \"and \"\"this\"\" w,o.rks\", foo bar", "$", "regexp", "=", "'%(?:^|,\\ *)(\"(?>[^\"]*)(?>\"\"[^\"]* )*\"|(?: [^\",]*))%x'", ...
Explodes a string of tags into an array. @param string $tags A string to explode. @return array An array of tags.
[ "Explodes", "a", "string", "of", "tags", "into", "an", "array", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Tags.php#L26-L45
41,558
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Tags.php
Tags.encode
public static function encode($tag) { if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) { return '"' . str_replace('"', '""', $tag) . '"'; } return $tag; }
php
public static function encode($tag) { if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) { return '"' . str_replace('"', '""', $tag) . '"'; } return $tag; }
[ "public", "static", "function", "encode", "(", "$", "tag", ")", "{", "if", "(", "strpos", "(", "$", "tag", ",", "','", ")", "!==", "FALSE", "||", "strpos", "(", "$", "tag", ",", "'\"'", ")", "!==", "FALSE", ")", "{", "return", "'\"'", ".", "str_r...
Encodes a tag string, taking care of special cases like commas and quotes. @param string $tag A tag string. @return string The encoded string.
[ "Encodes", "a", "tag", "string", "taking", "care", "of", "special", "cases", "like", "commas", "and", "quotes", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Tags.php#L56-L61
41,559
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Tags.php
Tags.implode
public static function implode($tags) { $encoded_tags = array(); foreach ($tags as $tag) { $encoded_tags[] = self::encode($tag); } return implode(', ', $encoded_tags); }
php
public static function implode($tags) { $encoded_tags = array(); foreach ($tags as $tag) { $encoded_tags[] = self::encode($tag); } return implode(', ', $encoded_tags); }
[ "public", "static", "function", "implode", "(", "$", "tags", ")", "{", "$", "encoded_tags", "=", "array", "(", ")", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "$", "encoded_tags", "[", "]", "=", "self", "::", "encode", "(", "$", ...
Implodes an array of tags into a string. @param array $tags An array of tags. @return string The imploded string.
[ "Implodes", "an", "array", "of", "tags", "into", "a", "string", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Tags.php#L72-L78
41,560
aleksip/plugin-data-transform
src/Drupal/Component/Utility/UserAgent.php
UserAgent.getBestMatchingLangcode
public static function getBestMatchingLangcode($http_accept_language, $langcodes, $mappings = array()) { // The Accept-Language header contains information about the language // preferences configured in the user's user agent / operating system. // RFC 2616 (section 14.4) defines the Accept-Language header as follows: // Accept-Language = "Accept-Language" ":" // 1#( language-range [ ";" "q" "=" qvalue ] ) // language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" ) // Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5" $ua_langcodes = array(); if (preg_match_all('@(?<=[, ]|^)([a-zA-Z-]+|\*)(?:;q=([0-9.]+))?(?:$|\s*,\s*)@', trim($http_accept_language), $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { if ($mappings) { $langcode = strtolower($match[1]); foreach ($mappings as $ua_langcode => $standard_langcode) { if ($langcode == $ua_langcode) { $match[1] = $standard_langcode; } } } // We can safely use strtolower() here, tags are ASCII. // RFC2616 mandates that the decimal part is no more than three digits, // so we multiply the qvalue by 1000 to avoid floating point // comparisons. $langcode = strtolower($match[1]); $qvalue = isset($match[2]) ? (float) $match[2] : 1; // Take the highest qvalue for this langcode. Although the request // supposedly contains unique langcodes, our mapping possibly resolves // to the same langcode for different qvalues. Keep the highest. $ua_langcodes[$langcode] = max( (int) ($qvalue * 1000), (isset($ua_langcodes[$langcode]) ? $ua_langcodes[$langcode] : 0) ); } } // We should take pristine values from the HTTP headers, but Internet // Explorer from version 7 sends only specific language tags (eg. fr-CA) // without the corresponding generic tag (fr) unless explicitly configured. // In that case, we assume that the lowest value of the specific tags is the // value of the generic language to be as close to the HTTP 1.1 spec as // possible. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and // http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx asort($ua_langcodes); foreach ($ua_langcodes as $langcode => $qvalue) { // For Chinese languages the generic tag is either zh-hans or zh-hant, so // we need to handle this separately, we can not split $langcode on the // first occurrence of '-' otherwise we get a non-existing language zh. // All other languages use a langcode without a '-', so we can safely // split on the first occurrence of it. if (strlen($langcode) > 7 && (substr($langcode, 0, 7) == 'zh-hant' || substr($langcode, 0, 7) == 'zh-hans')) { $generic_tag = substr($langcode, 0, 7); } else { $generic_tag = strtok($langcode, '-'); } if (!empty($generic_tag) && !isset($ua_langcodes[$generic_tag])) { // Add the generic langcode, but make sure it has a lower qvalue as the // more specific one, so the more specific one gets selected if it's // defined by both the user agent and us. $ua_langcodes[$generic_tag] = $qvalue - 0.1; } } // Find the added language with the greatest qvalue, following the rules // of RFC 2616 (section 14.4). If several languages have the same qvalue, // prefer the one with the greatest weight. $best_match_langcode = FALSE; $max_qvalue = 0; foreach ($langcodes as $langcode_case_sensitive) { // Language tags are case insensitive (RFC2616, sec 3.10). $langcode = strtolower($langcode_case_sensitive); // If nothing matches below, the default qvalue is the one of the wildcard // language, if set, or is 0 (which will never match). $qvalue = isset($ua_langcodes['*']) ? $ua_langcodes['*'] : 0; // Find the longest possible prefix of the user agent supplied language // ('the language-range') that matches this site language ('the language // tag'). $prefix = $langcode; do { if (isset($ua_langcodes[$prefix])) { $qvalue = $ua_langcodes[$prefix]; break; } } while ($prefix = substr($prefix, 0, strrpos($prefix, '-'))); // Find the best match. if ($qvalue > $max_qvalue) { $best_match_langcode = $langcode_case_sensitive; $max_qvalue = $qvalue; } } return $best_match_langcode; }
php
public static function getBestMatchingLangcode($http_accept_language, $langcodes, $mappings = array()) { // The Accept-Language header contains information about the language // preferences configured in the user's user agent / operating system. // RFC 2616 (section 14.4) defines the Accept-Language header as follows: // Accept-Language = "Accept-Language" ":" // 1#( language-range [ ";" "q" "=" qvalue ] ) // language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" ) // Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5" $ua_langcodes = array(); if (preg_match_all('@(?<=[, ]|^)([a-zA-Z-]+|\*)(?:;q=([0-9.]+))?(?:$|\s*,\s*)@', trim($http_accept_language), $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { if ($mappings) { $langcode = strtolower($match[1]); foreach ($mappings as $ua_langcode => $standard_langcode) { if ($langcode == $ua_langcode) { $match[1] = $standard_langcode; } } } // We can safely use strtolower() here, tags are ASCII. // RFC2616 mandates that the decimal part is no more than three digits, // so we multiply the qvalue by 1000 to avoid floating point // comparisons. $langcode = strtolower($match[1]); $qvalue = isset($match[2]) ? (float) $match[2] : 1; // Take the highest qvalue for this langcode. Although the request // supposedly contains unique langcodes, our mapping possibly resolves // to the same langcode for different qvalues. Keep the highest. $ua_langcodes[$langcode] = max( (int) ($qvalue * 1000), (isset($ua_langcodes[$langcode]) ? $ua_langcodes[$langcode] : 0) ); } } // We should take pristine values from the HTTP headers, but Internet // Explorer from version 7 sends only specific language tags (eg. fr-CA) // without the corresponding generic tag (fr) unless explicitly configured. // In that case, we assume that the lowest value of the specific tags is the // value of the generic language to be as close to the HTTP 1.1 spec as // possible. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and // http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx asort($ua_langcodes); foreach ($ua_langcodes as $langcode => $qvalue) { // For Chinese languages the generic tag is either zh-hans or zh-hant, so // we need to handle this separately, we can not split $langcode on the // first occurrence of '-' otherwise we get a non-existing language zh. // All other languages use a langcode without a '-', so we can safely // split on the first occurrence of it. if (strlen($langcode) > 7 && (substr($langcode, 0, 7) == 'zh-hant' || substr($langcode, 0, 7) == 'zh-hans')) { $generic_tag = substr($langcode, 0, 7); } else { $generic_tag = strtok($langcode, '-'); } if (!empty($generic_tag) && !isset($ua_langcodes[$generic_tag])) { // Add the generic langcode, but make sure it has a lower qvalue as the // more specific one, so the more specific one gets selected if it's // defined by both the user agent and us. $ua_langcodes[$generic_tag] = $qvalue - 0.1; } } // Find the added language with the greatest qvalue, following the rules // of RFC 2616 (section 14.4). If several languages have the same qvalue, // prefer the one with the greatest weight. $best_match_langcode = FALSE; $max_qvalue = 0; foreach ($langcodes as $langcode_case_sensitive) { // Language tags are case insensitive (RFC2616, sec 3.10). $langcode = strtolower($langcode_case_sensitive); // If nothing matches below, the default qvalue is the one of the wildcard // language, if set, or is 0 (which will never match). $qvalue = isset($ua_langcodes['*']) ? $ua_langcodes['*'] : 0; // Find the longest possible prefix of the user agent supplied language // ('the language-range') that matches this site language ('the language // tag'). $prefix = $langcode; do { if (isset($ua_langcodes[$prefix])) { $qvalue = $ua_langcodes[$prefix]; break; } } while ($prefix = substr($prefix, 0, strrpos($prefix, '-'))); // Find the best match. if ($qvalue > $max_qvalue) { $best_match_langcode = $langcode_case_sensitive; $max_qvalue = $qvalue; } } return $best_match_langcode; }
[ "public", "static", "function", "getBestMatchingLangcode", "(", "$", "http_accept_language", ",", "$", "langcodes", ",", "$", "mappings", "=", "array", "(", ")", ")", "{", "// The Accept-Language header contains information about the language", "// preferences configured in t...
Identifies user agent language from the Accept-language HTTP header. The algorithm works as follows: - map user agent language codes to available language codes. - order all user agent language codes by qvalue from high to low. - add generic user agent language codes if they aren't already specified but with a slightly lower qvalue. - find the most specific available language code with the highest qvalue. - if 2 or more languages are having the same qvalue, respect the order of them inside the $languages array. We perform user agent accept-language parsing only if page cache is disabled, otherwise we would cache a user-specific preference. @param string $http_accept_language The value of the "Accept-Language" HTTP header. @param array $langcodes An array of available language codes to pick from. @param array $mappings (optional) Custom mappings to support user agents that are sending non standard language codes. No mapping is assumed by default. @return string The selected language code or FALSE if no valid language can be identified.
[ "Identifies", "user", "agent", "language", "from", "the", "Accept", "-", "language", "HTTP", "header", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UserAgent.php#L44-L141
41,561
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Environment.php
Environment.checkMemoryLimit
public static function checkMemoryLimit($required, $memory_limit = NULL) { if (!isset($memory_limit)) { $memory_limit = ini_get('memory_limit'); } // There is sufficient memory if: // - No memory limit is set. // - The memory limit is set to unlimited (-1). // - The memory limit is greater than or equal to the memory required for // the operation. return ((!$memory_limit) || ($memory_limit == -1) || (Bytes::toInt($memory_limit) >= Bytes::toInt($required))); }
php
public static function checkMemoryLimit($required, $memory_limit = NULL) { if (!isset($memory_limit)) { $memory_limit = ini_get('memory_limit'); } // There is sufficient memory if: // - No memory limit is set. // - The memory limit is set to unlimited (-1). // - The memory limit is greater than or equal to the memory required for // the operation. return ((!$memory_limit) || ($memory_limit == -1) || (Bytes::toInt($memory_limit) >= Bytes::toInt($required))); }
[ "public", "static", "function", "checkMemoryLimit", "(", "$", "required", ",", "$", "memory_limit", "=", "NULL", ")", "{", "if", "(", "!", "isset", "(", "$", "memory_limit", ")", ")", "{", "$", "memory_limit", "=", "ini_get", "(", "'memory_limit'", ")", ...
Compares the memory required for an operation to the available memory. @param string $required The memory required for the operation, expressed as a number of bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes, 9mbytes). @param $memory_limit (optional) The memory limit for the operation, expressed as a number of bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP memory_limit will be used. Defaults to NULL. @return bool TRUE if there is sufficient memory to allow the operation, or FALSE otherwise.
[ "Compares", "the", "memory", "required", "for", "an", "operation", "to", "the", "available", "memory", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Environment.php#L32-L43
41,562
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Unicode.php
Unicode.check
public static function check() { // Check for mbstring extension. if (!function_exists('mb_strlen')) { static::$status = static::STATUS_SINGLEBYTE; return 'mb_strlen'; } // Check mbstring configuration. if (ini_get('mbstring.func_overload') != 0) { static::$status = static::STATUS_ERROR; return 'mbstring.func_overload'; } if (ini_get('mbstring.encoding_translation') != 0) { static::$status = static::STATUS_ERROR; return 'mbstring.encoding_translation'; } // mbstring.http_input and mbstring.http_output are deprecated and empty by // default in PHP 5.6. if (version_compare(PHP_VERSION, '5.6.0') == -1) { if (ini_get('mbstring.http_input') != 'pass') { static::$status = static::STATUS_ERROR; return 'mbstring.http_input'; } if (ini_get('mbstring.http_output') != 'pass') { static::$status = static::STATUS_ERROR; return 'mbstring.http_output'; } } // Set appropriate configuration. mb_internal_encoding('utf-8'); mb_language('uni'); static::$status = static::STATUS_MULTIBYTE; return ''; }
php
public static function check() { // Check for mbstring extension. if (!function_exists('mb_strlen')) { static::$status = static::STATUS_SINGLEBYTE; return 'mb_strlen'; } // Check mbstring configuration. if (ini_get('mbstring.func_overload') != 0) { static::$status = static::STATUS_ERROR; return 'mbstring.func_overload'; } if (ini_get('mbstring.encoding_translation') != 0) { static::$status = static::STATUS_ERROR; return 'mbstring.encoding_translation'; } // mbstring.http_input and mbstring.http_output are deprecated and empty by // default in PHP 5.6. if (version_compare(PHP_VERSION, '5.6.0') == -1) { if (ini_get('mbstring.http_input') != 'pass') { static::$status = static::STATUS_ERROR; return 'mbstring.http_input'; } if (ini_get('mbstring.http_output') != 'pass') { static::$status = static::STATUS_ERROR; return 'mbstring.http_output'; } } // Set appropriate configuration. mb_internal_encoding('utf-8'); mb_language('uni'); static::$status = static::STATUS_MULTIBYTE; return ''; }
[ "public", "static", "function", "check", "(", ")", "{", "// Check for mbstring extension.", "if", "(", "!", "function_exists", "(", "'mb_strlen'", ")", ")", "{", "static", "::", "$", "status", "=", "static", "::", "STATUS_SINGLEBYTE", ";", "return", "'mb_strlen'...
Checks for Unicode support in PHP and sets the proper settings if possible. Because of the need to be able to handle text in various encodings, we do not support mbstring function overloading. HTTP input/output conversion must be disabled for similar reasons. @return string A string identifier of a failed multibyte extension check, if any. Otherwise, an empty string.
[ "Checks", "for", "Unicode", "support", "in", "PHP", "and", "sets", "the", "proper", "settings", "if", "possible", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L150-L184
41,563
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Unicode.php
Unicode.convertToUtf8
public static function convertToUtf8($data, $encoding) { if (function_exists('iconv')) { return @iconv($encoding, 'utf-8', $data); } elseif (function_exists('mb_convert_encoding')) { return @mb_convert_encoding($data, 'utf-8', $encoding); } elseif (function_exists('recode_string')) { return @recode_string($encoding . '..utf-8', $data); } // Cannot convert. return FALSE; }
php
public static function convertToUtf8($data, $encoding) { if (function_exists('iconv')) { return @iconv($encoding, 'utf-8', $data); } elseif (function_exists('mb_convert_encoding')) { return @mb_convert_encoding($data, 'utf-8', $encoding); } elseif (function_exists('recode_string')) { return @recode_string($encoding . '..utf-8', $data); } // Cannot convert. return FALSE; }
[ "public", "static", "function", "convertToUtf8", "(", "$", "data", ",", "$", "encoding", ")", "{", "if", "(", "function_exists", "(", "'iconv'", ")", ")", "{", "return", "@", "iconv", "(", "$", "encoding", ",", "'utf-8'", ",", "$", "data", ")", ";", ...
Converts data to UTF-8. Requires the iconv, GNU recode or mbstring PHP extension. @param string $data The data to be converted. @param string $encoding The encoding that the data is in. @return string|bool Converted data or FALSE.
[ "Converts", "data", "to", "UTF", "-", "8", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L231-L243
41,564
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Unicode.php
Unicode.truncateBytes
public static function truncateBytes($string, $len) { if (strlen($string) <= $len) { return $string; } if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) { return substr($string, 0, $len); } // Scan backwards to beginning of the byte sequence. while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0); return substr($string, 0, $len); }
php
public static function truncateBytes($string, $len) { if (strlen($string) <= $len) { return $string; } if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) { return substr($string, 0, $len); } // Scan backwards to beginning of the byte sequence. while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0); return substr($string, 0, $len); }
[ "public", "static", "function", "truncateBytes", "(", "$", "string", ",", "$", "len", ")", "{", "if", "(", "strlen", "(", "$", "string", ")", "<=", "$", "len", ")", "{", "return", "$", "string", ";", "}", "if", "(", "(", "ord", "(", "$", "string"...
Truncates a UTF-8-encoded string safely to a number of bytes. If the end position is in the middle of a UTF-8 sequence, it scans backwards until the beginning of the byte sequence. Use this function whenever you want to chop off a string at an unsure location. On the other hand, if you're sure that you're splitting on a character boundary (e.g. after using strpos() or similar), you can safely use substr() instead. @param string $string The string to truncate. @param int $len An upper limit on the returned string length. @return string The truncated string.
[ "Truncates", "a", "UTF", "-", "8", "-", "encoded", "string", "safely", "to", "a", "number", "of", "bytes", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L264-L275
41,565
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Unicode.php
Unicode.strtoupper
public static function strtoupper($text) { if (static::getStatus() == static::STATUS_MULTIBYTE) { return mb_strtoupper($text); } else { // Use C-locale for ASCII-only uppercase. $text = strtoupper($text); // Case flip Latin-1 accented letters. $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text); return $text; } }
php
public static function strtoupper($text) { if (static::getStatus() == static::STATUS_MULTIBYTE) { return mb_strtoupper($text); } else { // Use C-locale for ASCII-only uppercase. $text = strtoupper($text); // Case flip Latin-1 accented letters. $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text); return $text; } }
[ "public", "static", "function", "strtoupper", "(", "$", "text", ")", "{", "if", "(", "static", "::", "getStatus", "(", ")", "==", "static", "::", "STATUS_MULTIBYTE", ")", "{", "return", "mb_strtoupper", "(", "$", "text", ")", ";", "}", "else", "{", "//...
Converts a UTF-8 string to uppercase. @param string $text The string to run the operation on. @return string The string in uppercase.
[ "Converts", "a", "UTF", "-", "8", "string", "to", "uppercase", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L307-L318
41,566
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Unicode.php
Unicode.strtolower
public static function strtolower($text) { if (static::getStatus() == static::STATUS_MULTIBYTE) { return mb_strtolower($text); } else { // Use C-locale for ASCII-only lowercase. $text = strtolower($text); // Case flip Latin-1 accented letters. $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text); return $text; } }
php
public static function strtolower($text) { if (static::getStatus() == static::STATUS_MULTIBYTE) { return mb_strtolower($text); } else { // Use C-locale for ASCII-only lowercase. $text = strtolower($text); // Case flip Latin-1 accented letters. $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text); return $text; } }
[ "public", "static", "function", "strtolower", "(", "$", "text", ")", "{", "if", "(", "static", "::", "getStatus", "(", ")", "==", "static", "::", "STATUS_MULTIBYTE", ")", "{", "return", "mb_strtolower", "(", "$", "text", ")", ";", "}", "else", "{", "//...
Converts a UTF-8 string to lowercase. @param string $text The string to run the operation on. @return string The string in lowercase.
[ "Converts", "a", "UTF", "-", "8", "string", "to", "lowercase", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L329-L340
41,567
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Unicode.php
Unicode.ucwords
public static function ucwords($text) { $regex = '/(^|[' . static::PREG_CLASS_WORD_BOUNDARY . '])([^' . static::PREG_CLASS_WORD_BOUNDARY . '])/u'; return preg_replace_callback($regex, function(array $matches) { return $matches[1] . Unicode::strtoupper($matches[2]); }, $text); }
php
public static function ucwords($text) { $regex = '/(^|[' . static::PREG_CLASS_WORD_BOUNDARY . '])([^' . static::PREG_CLASS_WORD_BOUNDARY . '])/u'; return preg_replace_callback($regex, function(array $matches) { return $matches[1] . Unicode::strtoupper($matches[2]); }, $text); }
[ "public", "static", "function", "ucwords", "(", "$", "text", ")", "{", "$", "regex", "=", "'/(^|['", ".", "static", "::", "PREG_CLASS_WORD_BOUNDARY", ".", "'])([^'", ".", "static", "::", "PREG_CLASS_WORD_BOUNDARY", ".", "'])/u'", ";", "return", "preg_replace_cal...
Capitalizes the first character of each word in a UTF-8 string. @param string $text The text that will be converted. @return string The input $text with each word capitalized. @ingroup php_wrappers
[ "Capitalizes", "the", "first", "character", "of", "each", "word", "in", "a", "UTF", "-", "8", "string", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L382-L387
41,568
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Unicode.php
Unicode.substr
public static function substr($text, $start, $length = NULL) { if (static::getStatus() == static::STATUS_MULTIBYTE) { return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length); } else { $strlen = strlen($text); // Find the starting byte offset. $bytes = 0; if ($start > 0) { // Count all the characters except continuation bytes from the start // until we have found $start characters or the end of the string. $bytes = -1; $chars = -1; while ($bytes < $strlen - 1 && $chars < $start) { $bytes++; $c = ord($text[$bytes]); if ($c < 0x80 || $c >= 0xC0) { $chars++; } } } elseif ($start < 0) { // Count all the characters except continuation bytes from the end // until we have found abs($start) characters. $start = abs($start); $bytes = $strlen; $chars = 0; while ($bytes > 0 && $chars < $start) { $bytes--; $c = ord($text[$bytes]); if ($c < 0x80 || $c >= 0xC0) { $chars++; } } } $istart = $bytes; // Find the ending byte offset. if ($length === NULL) { $iend = $strlen; } elseif ($length > 0) { // Count all the characters except continuation bytes from the starting // index until we have found $length characters or reached the end of // the string, then backtrace one byte. $iend = $istart - 1; $chars = -1; $last_real = FALSE; while ($iend < $strlen - 1 && $chars < $length) { $iend++; $c = ord($text[$iend]); $last_real = FALSE; if ($c < 0x80 || $c >= 0xC0) { $chars++; $last_real = TRUE; } } // Backtrace one byte if the last character we found was a real // character and we don't need it. if ($last_real && $chars >= $length) { $iend--; } } elseif ($length < 0) { // Count all the characters except continuation bytes from the end // until we have found abs($start) characters, then backtrace one byte. $length = abs($length); $iend = $strlen; $chars = 0; while ($iend > 0 && $chars < $length) { $iend--; $c = ord($text[$iend]); if ($c < 0x80 || $c >= 0xC0) { $chars++; } } // Backtrace one byte if we are not at the beginning of the string. if ($iend > 0) { $iend--; } } else { // $length == 0, return an empty string. return ''; } return substr($text, $istart, max(0, $iend - $istart + 1)); } }
php
public static function substr($text, $start, $length = NULL) { if (static::getStatus() == static::STATUS_MULTIBYTE) { return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length); } else { $strlen = strlen($text); // Find the starting byte offset. $bytes = 0; if ($start > 0) { // Count all the characters except continuation bytes from the start // until we have found $start characters or the end of the string. $bytes = -1; $chars = -1; while ($bytes < $strlen - 1 && $chars < $start) { $bytes++; $c = ord($text[$bytes]); if ($c < 0x80 || $c >= 0xC0) { $chars++; } } } elseif ($start < 0) { // Count all the characters except continuation bytes from the end // until we have found abs($start) characters. $start = abs($start); $bytes = $strlen; $chars = 0; while ($bytes > 0 && $chars < $start) { $bytes--; $c = ord($text[$bytes]); if ($c < 0x80 || $c >= 0xC0) { $chars++; } } } $istart = $bytes; // Find the ending byte offset. if ($length === NULL) { $iend = $strlen; } elseif ($length > 0) { // Count all the characters except continuation bytes from the starting // index until we have found $length characters or reached the end of // the string, then backtrace one byte. $iend = $istart - 1; $chars = -1; $last_real = FALSE; while ($iend < $strlen - 1 && $chars < $length) { $iend++; $c = ord($text[$iend]); $last_real = FALSE; if ($c < 0x80 || $c >= 0xC0) { $chars++; $last_real = TRUE; } } // Backtrace one byte if the last character we found was a real // character and we don't need it. if ($last_real && $chars >= $length) { $iend--; } } elseif ($length < 0) { // Count all the characters except continuation bytes from the end // until we have found abs($start) characters, then backtrace one byte. $length = abs($length); $iend = $strlen; $chars = 0; while ($iend > 0 && $chars < $length) { $iend--; $c = ord($text[$iend]); if ($c < 0x80 || $c >= 0xC0) { $chars++; } } // Backtrace one byte if we are not at the beginning of the string. if ($iend > 0) { $iend--; } } else { // $length == 0, return an empty string. return ''; } return substr($text, $istart, max(0, $iend - $istart + 1)); } }
[ "public", "static", "function", "substr", "(", "$", "text", ",", "$", "start", ",", "$", "length", "=", "NULL", ")", "{", "if", "(", "static", "::", "getStatus", "(", ")", "==", "static", "::", "STATUS_MULTIBYTE", ")", "{", "return", "$", "length", "...
Cuts off a piece of a string based on character indices and counts. Follows the same behavior as PHP's own substr() function. Note that for cutting off a string at a known character/substring location, the usage of PHP's normal strpos/substr is safe and much faster. @param string $text The input string. @param int $start The position at which to start reading. @param int $length The number of characters to read. @return string The shortened string.
[ "Cuts", "off", "a", "piece", "of", "a", "string", "based", "on", "character", "indices", "and", "counts", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L406-L491
41,569
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Unicode.php
Unicode.strpos
public static function strpos($haystack, $needle, $offset = 0) { if (static::getStatus() == static::STATUS_MULTIBYTE) { return mb_strpos($haystack, $needle, $offset); } else { // Remove Unicode continuation characters, to be compatible with // Unicode::strlen() and Unicode::substr(). $haystack = preg_replace("/[\x80-\xBF]/", '', $haystack); $needle = preg_replace("/[\x80-\xBF]/", '', $needle); return strpos($haystack, $needle, $offset); } }
php
public static function strpos($haystack, $needle, $offset = 0) { if (static::getStatus() == static::STATUS_MULTIBYTE) { return mb_strpos($haystack, $needle, $offset); } else { // Remove Unicode continuation characters, to be compatible with // Unicode::strlen() and Unicode::substr(). $haystack = preg_replace("/[\x80-\xBF]/", '', $haystack); $needle = preg_replace("/[\x80-\xBF]/", '', $needle); return strpos($haystack, $needle, $offset); } }
[ "public", "static", "function", "strpos", "(", "$", "haystack", ",", "$", "needle", ",", "$", "offset", "=", "0", ")", "{", "if", "(", "static", "::", "getStatus", "(", ")", "==", "static", "::", "STATUS_MULTIBYTE", ")", "{", "return", "mb_strpos", "("...
Finds the position of the first occurrence of a string in another string. @param string $haystack The string to search in. @param string $needle The string to find in $haystack. @param int $offset If specified, start the search at this number of characters from the beginning (default 0). @return int|false The position where $needle occurs in $haystack, always relative to the beginning (independent of $offset), or FALSE if not found. Note that a return value of 0 is not the same as FALSE.
[ "Finds", "the", "position", "of", "the", "first", "occurrence", "of", "a", "string", "in", "another", "string", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L716-L727
41,570
Firehed/u2f-php
src/ECPublicKeyTrait.php
ECPublicKeyTrait.getPublicKeyPem
public function getPublicKeyPem(): string { $key = $this->getPublicKeyBinary(); // Described in RFC 5480 // Just use an OID calculator to figure out *that* encoding $der = hex2bin( '3059' // SEQUENCE, length 89 .'3013' // SEQUENCE, length 19 .'0607' // OID, length 7 .'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key .'0608' // OID, length 8 .'2a8648ce3d030107' // 1.2.840.10045.3.1.7 = P-256 Curve .'0342' // BIT STRING, length 66 .'00' // prepend with NUL - pubkey will follow ); $der .= $key; $pem = "-----BEGIN PUBLIC KEY-----\r\n"; $pem .= chunk_split(base64_encode($der), 64); $pem .= "-----END PUBLIC KEY-----"; return $pem; }
php
public function getPublicKeyPem(): string { $key = $this->getPublicKeyBinary(); // Described in RFC 5480 // Just use an OID calculator to figure out *that* encoding $der = hex2bin( '3059' // SEQUENCE, length 89 .'3013' // SEQUENCE, length 19 .'0607' // OID, length 7 .'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key .'0608' // OID, length 8 .'2a8648ce3d030107' // 1.2.840.10045.3.1.7 = P-256 Curve .'0342' // BIT STRING, length 66 .'00' // prepend with NUL - pubkey will follow ); $der .= $key; $pem = "-----BEGIN PUBLIC KEY-----\r\n"; $pem .= chunk_split(base64_encode($der), 64); $pem .= "-----END PUBLIC KEY-----"; return $pem; }
[ "public", "function", "getPublicKeyPem", "(", ")", ":", "string", "{", "$", "key", "=", "$", "this", "->", "getPublicKeyBinary", "(", ")", ";", "// Described in RFC 5480", "// Just use an OID calculator to figure out *that* encoding", "$", "der", "=", "hex2bin", "(", ...
public key component
[ "public", "key", "component" ]
65bb799b1f709192ff7fed1af814ca43b03a64c7
https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/ECPublicKeyTrait.php#L34-L56
41,571
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Html.php
Html.getUniqueId
public static function getUniqueId($id) { // If this is an Ajax request, then content returned by this page request // will be merged with content already on the base page. The HTML IDs must // be unique for the fully merged content. Therefore use unique IDs. if (static::$isAjax) { return static::getId($id) . '--' . Crypt::randomBytesBase64(8); } // @todo Remove all that code once we switch over to random IDs only, // see https://www.drupal.org/node/1090592. if (!isset(static::$seenIdsInit)) { static::$seenIdsInit = array(); } if (!isset(static::$seenIds)) { static::$seenIds = static::$seenIdsInit; } $id = static::getId($id); // Ensure IDs are unique by appending a counter after the first occurrence. // The counter needs to be appended with a delimiter that does not exist in // the base ID. Requiring a unique delimiter helps ensure that we really do // return unique IDs and also helps us re-create the $seen_ids array during // Ajax requests. if (isset(static::$seenIds[$id])) { $id = $id . '--' . ++static::$seenIds[$id]; } else { static::$seenIds[$id] = 1; } return $id; }
php
public static function getUniqueId($id) { // If this is an Ajax request, then content returned by this page request // will be merged with content already on the base page. The HTML IDs must // be unique for the fully merged content. Therefore use unique IDs. if (static::$isAjax) { return static::getId($id) . '--' . Crypt::randomBytesBase64(8); } // @todo Remove all that code once we switch over to random IDs only, // see https://www.drupal.org/node/1090592. if (!isset(static::$seenIdsInit)) { static::$seenIdsInit = array(); } if (!isset(static::$seenIds)) { static::$seenIds = static::$seenIdsInit; } $id = static::getId($id); // Ensure IDs are unique by appending a counter after the first occurrence. // The counter needs to be appended with a delimiter that does not exist in // the base ID. Requiring a unique delimiter helps ensure that we really do // return unique IDs and also helps us re-create the $seen_ids array during // Ajax requests. if (isset(static::$seenIds[$id])) { $id = $id . '--' . ++static::$seenIds[$id]; } else { static::$seenIds[$id] = 1; } return $id; }
[ "public", "static", "function", "getUniqueId", "(", "$", "id", ")", "{", "// If this is an Ajax request, then content returned by this page request", "// will be merged with content already on the base page. The HTML IDs must", "// be unique for the fully merged content. Therefore use unique I...
Prepares a string for use as a valid HTML ID and guarantees uniqueness. This function ensures that each passed HTML ID value only exists once on the page. By tracking the already returned ids, this function enables forms, blocks, and other content to be output multiple times on the same page, without breaking (X)HTML validation. For already existing IDs, a counter is appended to the ID string. Therefore, JavaScript and CSS code should not rely on any value that was generated by this function and instead should rely on manually added CSS classes or similarly reliable constructs. Two consecutive hyphens separate the counter from the original ID. To manage uniqueness across multiple Ajax requests on the same page, Ajax requests POST an array of all IDs currently present on the page, which are used to prime this function's cache upon first invocation. To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive hyphens in the originally passed $id are replaced with a single hyphen. @param string $id The ID to clean. @return string The cleaned ID.
[ "Prepares", "a", "string", "for", "use", "as", "a", "valid", "HTML", "ID", "and", "guarantees", "uniqueness", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Html.php#L154-L185
41,572
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Html.php
Html.getId
public static function getId($id) { $id = str_replace([' ', '_', '[', ']'], ['-', '-', '-', ''], Unicode::strtolower($id)); // As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can // only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"), // colons (":"), and periods ("."). We strip out any character not in that // list. Note that the CSS spec doesn't allow colons or periods in identifiers // (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two // characters as well. $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id); // Removing multiple consecutive hyphens. $id = preg_replace('/\-+/', '-', $id); return $id; }
php
public static function getId($id) { $id = str_replace([' ', '_', '[', ']'], ['-', '-', '-', ''], Unicode::strtolower($id)); // As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can // only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"), // colons (":"), and periods ("."). We strip out any character not in that // list. Note that the CSS spec doesn't allow colons or periods in identifiers // (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two // characters as well. $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id); // Removing multiple consecutive hyphens. $id = preg_replace('/\-+/', '-', $id); return $id; }
[ "public", "static", "function", "getId", "(", "$", "id", ")", "{", "$", "id", "=", "str_replace", "(", "[", "' '", ",", "'_'", ",", "'['", ",", "']'", "]", ",", "[", "'-'", ",", "'-'", ",", "'-'", ",", "''", "]", ",", "Unicode", "::", "strtolow...
Prepares a string for use as a valid HTML ID. Only use this function when you want to intentionally skip the uniqueness guarantee of self::getUniqueId(). @param string $id The ID to clean. @return string The cleaned ID. @see self::getUniqueId()
[ "Prepares", "a", "string", "for", "use", "as", "a", "valid", "HTML", "ID", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Html.php#L201-L215
41,573
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Html.php
Html.serialize
public static function serialize(\DOMDocument $document) { $body_node = $document->getElementsByTagName('body')->item(0); $html = ''; if ($body_node !== NULL) { foreach ($body_node->getElementsByTagName('script') as $node) { static::escapeCdataElement($node); } foreach ($body_node->getElementsByTagName('style') as $node) { static::escapeCdataElement($node, '/*', '*/'); } foreach ($body_node->childNodes as $node) { $html .= $document->saveXML($node); } } return $html; }
php
public static function serialize(\DOMDocument $document) { $body_node = $document->getElementsByTagName('body')->item(0); $html = ''; if ($body_node !== NULL) { foreach ($body_node->getElementsByTagName('script') as $node) { static::escapeCdataElement($node); } foreach ($body_node->getElementsByTagName('style') as $node) { static::escapeCdataElement($node, '/*', '*/'); } foreach ($body_node->childNodes as $node) { $html .= $document->saveXML($node); } } return $html; }
[ "public", "static", "function", "serialize", "(", "\\", "DOMDocument", "$", "document", ")", "{", "$", "body_node", "=", "$", "document", "->", "getElementsByTagName", "(", "'body'", ")", "->", "item", "(", "0", ")", ";", "$", "html", "=", "''", ";", "...
Converts the body of a \DOMDocument back to an HTML snippet. The function serializes the body part of a \DOMDocument back to an (X)HTML snippet. The resulting (X)HTML snippet will be properly formatted to be compatible with HTML user agents. @param \DOMDocument $document A \DOMDocument object to serialize, only the tags below the first <body> node will be converted. @return string A valid (X)HTML snippet, as a string.
[ "Converts", "the", "body", "of", "a", "\\", "DOMDocument", "back", "to", "an", "HTML", "snippet", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Html.php#L291-L307
41,574
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Html.php
Html.escapeCdataElement
public static function escapeCdataElement(\DOMNode $node, $comment_start = '//', $comment_end = '') { foreach ($node->childNodes as $child_node) { if ($child_node instanceof \DOMCdataSection) { $embed_prefix = "\n<!--{$comment_start}--><![CDATA[{$comment_start} ><!--{$comment_end}\n"; $embed_suffix = "\n{$comment_start}--><!]]>{$comment_end}\n"; // Prevent invalid cdata escaping as this would throw a DOM error. // This is the same behavior as found in libxml2. // Related W3C standard: http://www.w3.org/TR/REC-xml/#dt-cdsection // Fix explanation: http://en.wikipedia.org/wiki/CDATA#Nesting $data = str_replace(']]>', ']]]]><![CDATA[>', $child_node->data); $fragment = $node->ownerDocument->createDocumentFragment(); $fragment->appendXML($embed_prefix . $data . $embed_suffix); $node->appendChild($fragment); $node->removeChild($child_node); } } }
php
public static function escapeCdataElement(\DOMNode $node, $comment_start = '//', $comment_end = '') { foreach ($node->childNodes as $child_node) { if ($child_node instanceof \DOMCdataSection) { $embed_prefix = "\n<!--{$comment_start}--><![CDATA[{$comment_start} ><!--{$comment_end}\n"; $embed_suffix = "\n{$comment_start}--><!]]>{$comment_end}\n"; // Prevent invalid cdata escaping as this would throw a DOM error. // This is the same behavior as found in libxml2. // Related W3C standard: http://www.w3.org/TR/REC-xml/#dt-cdsection // Fix explanation: http://en.wikipedia.org/wiki/CDATA#Nesting $data = str_replace(']]>', ']]]]><![CDATA[>', $child_node->data); $fragment = $node->ownerDocument->createDocumentFragment(); $fragment->appendXML($embed_prefix . $data . $embed_suffix); $node->appendChild($fragment); $node->removeChild($child_node); } } }
[ "public", "static", "function", "escapeCdataElement", "(", "\\", "DOMNode", "$", "node", ",", "$", "comment_start", "=", "'//'", ",", "$", "comment_end", "=", "''", ")", "{", "foreach", "(", "$", "node", "->", "childNodes", "as", "$", "child_node", ")", ...
Adds comments around a <!CDATA section in a \DOMNode. \DOMDocument::loadHTML() in \Drupal\Component\Utility\Html::load() makes CDATA sections from the contents of inline script and style tags. This can cause HTML4 browsers to throw exceptions. This function attempts to solve the problem by creating a \DOMDocumentFragment to comment the CDATA tag. @param \DOMNode $node The element potentially containing a CDATA node. @param string $comment_start (optional) A string to use as a comment start marker to escape the CDATA declaration. Defaults to '//'. @param string $comment_end (optional) A string to use as a comment end marker to escape the CDATA declaration. Defaults to an empty string.
[ "Adds", "comments", "around", "a", "<!CDATA", "section", "in", "a", "\\", "DOMNode", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Html.php#L328-L346
41,575
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Bytes.php
Bytes.toInt
public static function toInt($size) { // Remove the non-unit characters from the size. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-numeric characters from the size. $size = preg_replace('/[^0-9\.]/', '', $size); if ($unit) { // Find the position of the unit in the ordered string which is the power // of magnitude to multiply a kilobyte by. return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0]))); } else { return round($size); } }
php
public static function toInt($size) { // Remove the non-unit characters from the size. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-numeric characters from the size. $size = preg_replace('/[^0-9\.]/', '', $size); if ($unit) { // Find the position of the unit in the ordered string which is the power // of magnitude to multiply a kilobyte by. return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0]))); } else { return round($size); } }
[ "public", "static", "function", "toInt", "(", "$", "size", ")", "{", "// Remove the non-unit characters from the size.", "$", "unit", "=", "preg_replace", "(", "'/[^bkmgtpezy]/i'", ",", "''", ",", "$", "size", ")", ";", "// Remove the non-numeric characters from the siz...
Parses a given byte size. @param mixed $size An integer or string size expressed as a number of bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes). @return int An integer representation of the size in bytes.
[ "Parses", "a", "given", "byte", "size", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Bytes.php#L32-L45
41,576
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Random.php
Random.object
public function object($size = 4) { $object = new \stdClass(); for ($i = 0; $i < $size; $i++) { $random_key = $this->name(); $random_value = $this->string(); $object->{$random_key} = $random_value; } return $object; }
php
public function object($size = 4) { $object = new \stdClass(); for ($i = 0; $i < $size; $i++) { $random_key = $this->name(); $random_value = $this->string(); $object->{$random_key} = $random_value; } return $object; }
[ "public", "function", "object", "(", "$", "size", "=", "4", ")", "{", "$", "object", "=", "new", "\\", "stdClass", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "size", ";", "$", "i", "++", ")", "{", "$", "random_k...
Generates a random PHP object. @param int $size The number of random keys to add to the object. @return \stdClass The generated object, with the specified number of random keys. Each key has a random string value.
[ "Generates", "a", "random", "PHP", "object", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Random.php#L174-L182
41,577
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Random.php
Random.paragraphs
public function paragraphs($paragraph_count = 12) { $output = ''; for ($i = 1; $i <= $paragraph_count; $i++) { $output .= $this->sentences(mt_rand(20, 60)) ."\n\n"; } return $output; }
php
public function paragraphs($paragraph_count = 12) { $output = ''; for ($i = 1; $i <= $paragraph_count; $i++) { $output .= $this->sentences(mt_rand(20, 60)) ."\n\n"; } return $output; }
[ "public", "function", "paragraphs", "(", "$", "paragraph_count", "=", "12", ")", "{", "$", "output", "=", "''", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<=", "$", "paragraph_count", ";", "$", "i", "++", ")", "{", "$", "output", ".=", ...
Generate paragraphs separated by double new line. @param int $paragraph_count @return string
[ "Generate", "paragraphs", "separated", "by", "double", "new", "line", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Random.php#L256-L262
41,578
aleksip/plugin-data-transform
src/Drupal/Component/Utility/OpCodeCache.php
OpCodeCache.invalidate
public static function invalidate($pathname) { clearstatcache(TRUE, $pathname); // Check if the Zend OPcache is enabled and if so invalidate the file. if (function_exists('opcache_invalidate')) { opcache_invalidate($pathname, TRUE); } // If apcu extension is enabled in PHP 5.5 or greater it emulates apc. // This is to provide an easy upgrade path if you are using apc's user // caching however the emulation does not extend to opcode caching. // Therefore we need to check if the function exists as well. if (extension_loaded('apc') && function_exists('apc_delete_file')) { // apc_delete_file() throws a PHP warning in case the specified file was // not compiled yet. // @see http://php.net/manual/en/function.apc-delete-file.php @apc_delete_file($pathname); } }
php
public static function invalidate($pathname) { clearstatcache(TRUE, $pathname); // Check if the Zend OPcache is enabled and if so invalidate the file. if (function_exists('opcache_invalidate')) { opcache_invalidate($pathname, TRUE); } // If apcu extension is enabled in PHP 5.5 or greater it emulates apc. // This is to provide an easy upgrade path if you are using apc's user // caching however the emulation does not extend to opcode caching. // Therefore we need to check if the function exists as well. if (extension_loaded('apc') && function_exists('apc_delete_file')) { // apc_delete_file() throws a PHP warning in case the specified file was // not compiled yet. // @see http://php.net/manual/en/function.apc-delete-file.php @apc_delete_file($pathname); } }
[ "public", "static", "function", "invalidate", "(", "$", "pathname", ")", "{", "clearstatcache", "(", "TRUE", ",", "$", "pathname", ")", ";", "// Check if the Zend OPcache is enabled and if so invalidate the file.", "if", "(", "function_exists", "(", "'opcache_invalidate'"...
Invalidates a PHP file from a possibly active opcode cache. In case the opcode cache does not support to invalidate an individual file, the entire cache will be flushed. @param string $pathname The absolute pathname of the PHP file to invalidate.
[ "Invalidates", "a", "PHP", "file", "from", "a", "possibly", "active", "opcode", "cache", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/OpCodeCache.php#L26-L43
41,579
aleksip/plugin-data-transform
src/Drupal/Core/Template/Attribute.php
Attribute.createAttributeValue
protected function createAttributeValue($name, $value) { // If the value is already an AttributeValueBase object, // return a new instance of the same class, but with the new name. if ($value instanceof AttributeValueBase) { $class = get_class($value); return new $class($name, $value->value()); } // An array value or 'class' attribute name are forced to always be an // AttributeArray value for consistency. if ($name == 'class' && !is_array($value)) { // Cast the value to string in case it implements MarkupInterface. $value = [(string) $value]; } if (is_array($value)) { // Cast the value to an array if the value was passed in as a string. // @todo Decide to fix all the broken instances of class as a string // in core or cast them. $value = new AttributeArray($name, $value); } elseif (is_bool($value)) { $value = new AttributeBoolean($name, $value); } // As a development aid, we allow the value to be a safe string object. elseif (SafeMarkup::isSafe($value)) { // Attributes are not supposed to display HTML markup, so we just convert // the value to plain text. $value = PlainTextOutput::renderFromHtml($value); $value = new AttributeString($name, $value); } elseif (!is_object($value)) { $value = new AttributeString($name, $value); } return $value; }
php
protected function createAttributeValue($name, $value) { // If the value is already an AttributeValueBase object, // return a new instance of the same class, but with the new name. if ($value instanceof AttributeValueBase) { $class = get_class($value); return new $class($name, $value->value()); } // An array value or 'class' attribute name are forced to always be an // AttributeArray value for consistency. if ($name == 'class' && !is_array($value)) { // Cast the value to string in case it implements MarkupInterface. $value = [(string) $value]; } if (is_array($value)) { // Cast the value to an array if the value was passed in as a string. // @todo Decide to fix all the broken instances of class as a string // in core or cast them. $value = new AttributeArray($name, $value); } elseif (is_bool($value)) { $value = new AttributeBoolean($name, $value); } // As a development aid, we allow the value to be a safe string object. elseif (SafeMarkup::isSafe($value)) { // Attributes are not supposed to display HTML markup, so we just convert // the value to plain text. $value = PlainTextOutput::renderFromHtml($value); $value = new AttributeString($name, $value); } elseif (!is_object($value)) { $value = new AttributeString($name, $value); } return $value; }
[ "protected", "function", "createAttributeValue", "(", "$", "name", ",", "$", "value", ")", "{", "// If the value is already an AttributeValueBase object,", "// return a new instance of the same class, but with the new name.", "if", "(", "$", "value", "instanceof", "AttributeValue...
Creates the different types of attribute values. @param string $name The attribute name. @param mixed $value The attribute value. @return \Drupal\Core\Template\AttributeValueBase An AttributeValueBase representation of the attribute's value.
[ "Creates", "the", "different", "types", "of", "attribute", "values", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L119-L152
41,580
aleksip/plugin-data-transform
src/Drupal/Core/Template/Attribute.php
Attribute.addClass
public function addClass() { $args = func_get_args(); if ($args) { $classes = array(); foreach ($args as $arg) { // Merge the values passed in from the classes array. // The argument is cast to an array to support comma separated single // values or one or more array arguments. $classes = array_merge($classes, (array) $arg); } // Merge if there are values, just add them otherwise. if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { // Merge the values passed in from the class value array. $classes = array_merge($this->storage['class']->value(), $classes); $this->storage['class']->exchangeArray($classes); } else { $this->offsetSet('class', $classes); } } return $this; }
php
public function addClass() { $args = func_get_args(); if ($args) { $classes = array(); foreach ($args as $arg) { // Merge the values passed in from the classes array. // The argument is cast to an array to support comma separated single // values or one or more array arguments. $classes = array_merge($classes, (array) $arg); } // Merge if there are values, just add them otherwise. if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { // Merge the values passed in from the class value array. $classes = array_merge($this->storage['class']->value(), $classes); $this->storage['class']->exchangeArray($classes); } else { $this->offsetSet('class', $classes); } } return $this; }
[ "public", "function", "addClass", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "if", "(", "$", "args", ")", "{", "$", "classes", "=", "array", "(", ")", ";", "foreach", "(", "$", "args", "as", "$", "arg", ")", "{", "// Merge t...
Adds classes or merges them on to array of existing CSS classes. @param string|array ... CSS classes to add to the class attribute array. @return $this
[ "Adds", "classes", "or", "merges", "them", "on", "to", "array", "of", "existing", "CSS", "classes", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L176-L199
41,581
aleksip/plugin-data-transform
src/Drupal/Core/Template/Attribute.php
Attribute.removeAttribute
public function removeAttribute() { $args = func_get_args(); foreach ($args as $arg) { // Support arrays or multiple arguments. if (is_array($arg)) { foreach ($arg as $value) { unset($this->storage[$value]); } } else { unset($this->storage[$arg]); } } return $this; }
php
public function removeAttribute() { $args = func_get_args(); foreach ($args as $arg) { // Support arrays or multiple arguments. if (is_array($arg)) { foreach ($arg as $value) { unset($this->storage[$value]); } } else { unset($this->storage[$arg]); } } return $this; }
[ "public", "function", "removeAttribute", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "foreach", "(", "$", "args", "as", "$", "arg", ")", "{", "// Support arrays or multiple arguments.", "if", "(", "is_array", "(", "$", "arg", ")", ")",...
Removes an attribute from an Attribute object. @param string|array ... Attributes to remove from the attribute array. @return $this
[ "Removes", "an", "attribute", "from", "an", "Attribute", "object", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L225-L240
41,582
aleksip/plugin-data-transform
src/Drupal/Core/Template/Attribute.php
Attribute.removeClass
public function removeClass() { // With no class attribute, there is no need to remove. if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { $args = func_get_args(); $classes = array(); foreach ($args as $arg) { // Merge the values passed in from the classes array. // The argument is cast to an array to support comma separated single // values or one or more array arguments. $classes = array_merge($classes, (array) $arg); } // Remove the values passed in from the value array. Use array_values() to // ensure that the array index remains sequential. $classes = array_values(array_diff($this->storage['class']->value(), $classes)); $this->storage['class']->exchangeArray($classes); } return $this; }
php
public function removeClass() { // With no class attribute, there is no need to remove. if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { $args = func_get_args(); $classes = array(); foreach ($args as $arg) { // Merge the values passed in from the classes array. // The argument is cast to an array to support comma separated single // values or one or more array arguments. $classes = array_merge($classes, (array) $arg); } // Remove the values passed in from the value array. Use array_values() to // ensure that the array index remains sequential. $classes = array_values(array_diff($this->storage['class']->value(), $classes)); $this->storage['class']->exchangeArray($classes); } return $this; }
[ "public", "function", "removeClass", "(", ")", "{", "// With no class attribute, there is no need to remove.", "if", "(", "isset", "(", "$", "this", "->", "storage", "[", "'class'", "]", ")", "&&", "$", "this", "->", "storage", "[", "'class'", "]", "instanceof",...
Removes argument values from array of existing CSS classes. @param string|array ... CSS classes to remove from the class attribute array. @return $this
[ "Removes", "argument", "values", "from", "array", "of", "existing", "CSS", "classes", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L250-L268
41,583
aleksip/plugin-data-transform
src/Drupal/Core/Template/Attribute.php
Attribute.hasClass
public function hasClass($class) { if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { return in_array($class, $this->storage['class']->value()); } else { return FALSE; } }
php
public function hasClass($class) { if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { return in_array($class, $this->storage['class']->value()); } else { return FALSE; } }
[ "public", "function", "hasClass", "(", "$", "class", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "storage", "[", "'class'", "]", ")", "&&", "$", "this", "->", "storage", "[", "'class'", "]", "instanceof", "AttributeArray", ")", "{", "return",...
Checks if the class array has the given CSS class. @param string $class The CSS class to check for. @return bool Returns TRUE if the class exists, or FALSE otherwise.
[ "Checks", "if", "the", "class", "array", "has", "the", "given", "CSS", "class", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L279-L286
41,584
Firehed/u2f-php
src/Server.php
Server.register
public function register(RegisterResponse $resp): RegistrationInterface { if (!$this->registerRequest) { throw new BadMethodCallException( 'Before calling register(), provide a RegisterRequest '. 'with setRegisterRequest()' ); } $this->validateChallenge($resp->getClientData(), $this->registerRequest); // Check the Application Parameter? // https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html#registration-response-message-success $signed_data = sprintf( '%s%s%s%s%s', chr(0), $this->registerRequest->getApplicationParameter(), $resp->getClientData()->getChallengeParameter(), $resp->getKeyHandleBinary(), $resp->getPublicKeyBinary() ); $pem = $resp->getAttestationCertificatePem(); if ($this->verifyCA) { $resp->verifyIssuerAgainstTrustedCAs($this->trustedCAs); } // Signature must validate against device issuer's public key $sig_check = openssl_verify( $signed_data, $resp->getSignature(), $pem, \OPENSSL_ALGO_SHA256 ); if ($sig_check !== 1) { throw new SE(SE::SIGNATURE_INVALID); } return (new Registration()) ->setAttestationCertificate($resp->getAttestationCertificateBinary()) ->setCounter(0) // The response does not include this ->setKeyHandle($resp->getKeyHandleBinary()) ->setPublicKey($resp->getPublicKeyBinary()); }
php
public function register(RegisterResponse $resp): RegistrationInterface { if (!$this->registerRequest) { throw new BadMethodCallException( 'Before calling register(), provide a RegisterRequest '. 'with setRegisterRequest()' ); } $this->validateChallenge($resp->getClientData(), $this->registerRequest); // Check the Application Parameter? // https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html#registration-response-message-success $signed_data = sprintf( '%s%s%s%s%s', chr(0), $this->registerRequest->getApplicationParameter(), $resp->getClientData()->getChallengeParameter(), $resp->getKeyHandleBinary(), $resp->getPublicKeyBinary() ); $pem = $resp->getAttestationCertificatePem(); if ($this->verifyCA) { $resp->verifyIssuerAgainstTrustedCAs($this->trustedCAs); } // Signature must validate against device issuer's public key $sig_check = openssl_verify( $signed_data, $resp->getSignature(), $pem, \OPENSSL_ALGO_SHA256 ); if ($sig_check !== 1) { throw new SE(SE::SIGNATURE_INVALID); } return (new Registration()) ->setAttestationCertificate($resp->getAttestationCertificateBinary()) ->setCounter(0) // The response does not include this ->setKeyHandle($resp->getKeyHandleBinary()) ->setPublicKey($resp->getPublicKeyBinary()); }
[ "public", "function", "register", "(", "RegisterResponse", "$", "resp", ")", ":", "RegistrationInterface", "{", "if", "(", "!", "$", "this", "->", "registerRequest", ")", "{", "throw", "new", "BadMethodCallException", "(", "'Before calling register(), provide a Regist...
This method authenticates a RegisterResponse against its corresponding RegisterRequest by verifying the certificate and signature. If valid, it returns a registration; if not, a SE will be thrown and attempt to register the key must be aborted. @param RegisterResponse $resp The response to verify @return RegistrationInterface if the response is proven authentic @throws SE if the response cannot be proven authentic @throws BadMethodCallException if a precondition is not met
[ "This", "method", "authenticates", "a", "RegisterResponse", "against", "its", "corresponding", "RegisterRequest", "by", "verifying", "the", "certificate", "and", "signature", ".", "If", "valid", "it", "returns", "a", "registration", ";", "if", "not", "a", "SE", ...
65bb799b1f709192ff7fed1af814ca43b03a64c7
https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L190-L232
41,585
Firehed/u2f-php
src/Server.php
Server.setTrustedCAs
public function setTrustedCAs(array $CAs): self { $this->verifyCA = true; $this->trustedCAs = $CAs; return $this; }
php
public function setTrustedCAs(array $CAs): self { $this->verifyCA = true; $this->trustedCAs = $CAs; return $this; }
[ "public", "function", "setTrustedCAs", "(", "array", "$", "CAs", ")", ":", "self", "{", "$", "this", "->", "verifyCA", "=", "true", ";", "$", "this", "->", "trustedCAs", "=", "$", "CAs", ";", "return", "$", "this", ";", "}" ]
Provides a list of CA certificates for device issuer verification during registration. This method or disableCAVerification must be called before register() or a SecurityException will always be thrown. @param string[] $CAs A list of file paths to device issuer CA certs @return self
[ "Provides", "a", "list", "of", "CA", "certificates", "for", "device", "issuer", "verification", "during", "registration", "." ]
65bb799b1f709192ff7fed1af814ca43b03a64c7
https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L260-L265
41,586
Firehed/u2f-php
src/Server.php
Server.setRegistrations
public function setRegistrations(array $registrations): self { array_map(function (Registration $r) { }, $registrations); // type check $this->registrations = $registrations; return $this; }
php
public function setRegistrations(array $registrations): self { array_map(function (Registration $r) { }, $registrations); // type check $this->registrations = $registrations; return $this; }
[ "public", "function", "setRegistrations", "(", "array", "$", "registrations", ")", ":", "self", "{", "array_map", "(", "function", "(", "Registration", "$", "r", ")", "{", "}", ",", "$", "registrations", ")", ";", "// type check", "$", "this", "->", "regis...
Provide a user's existing registration to be used during authentication @param RegistrationInterface[] $registrations @return self
[ "Provide", "a", "user", "s", "existing", "registration", "to", "be", "used", "during", "authentication" ]
65bb799b1f709192ff7fed1af814ca43b03a64c7
https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L287-L293
41,587
Firehed/u2f-php
src/Server.php
Server.generateSignRequest
public function generateSignRequest(RegistrationInterface $reg): SignRequest { return (new SignRequest()) ->setAppId($this->getAppId()) ->setChallenge($this->generateChallenge()) ->setKeyHandle($reg->getKeyHandleBinary()); }
php
public function generateSignRequest(RegistrationInterface $reg): SignRequest { return (new SignRequest()) ->setAppId($this->getAppId()) ->setChallenge($this->generateChallenge()) ->setKeyHandle($reg->getKeyHandleBinary()); }
[ "public", "function", "generateSignRequest", "(", "RegistrationInterface", "$", "reg", ")", ":", "SignRequest", "{", "return", "(", "new", "SignRequest", "(", ")", ")", "->", "setAppId", "(", "$", "this", "->", "getAppId", "(", ")", ")", "->", "setChallenge"...
Creates a new SignRequest for an existing registration for an authenticating user, used by the `u2f.sign` API. @param RegistrationInterface $reg one of the user's existing Registrations @return SignRequest
[ "Creates", "a", "new", "SignRequest", "for", "an", "existing", "registration", "for", "an", "authenticating", "user", "used", "by", "the", "u2f", ".", "sign", "API", "." ]
65bb799b1f709192ff7fed1af814ca43b03a64c7
https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L331-L337
41,588
Firehed/u2f-php
src/Server.php
Server.findObjectWithKeyHandle
private function findObjectWithKeyHandle( array $objects, string $keyHandle ) { foreach ($objects as $object) { if (hash_equals($object->getKeyHandleBinary(), $keyHandle)) { return $object; } } return null; }
php
private function findObjectWithKeyHandle( array $objects, string $keyHandle ) { foreach ($objects as $object) { if (hash_equals($object->getKeyHandleBinary(), $keyHandle)) { return $object; } } return null; }
[ "private", "function", "findObjectWithKeyHandle", "(", "array", "$", "objects", ",", "string", "$", "keyHandle", ")", "{", "foreach", "(", "$", "objects", "as", "$", "object", ")", "{", "if", "(", "hash_equals", "(", "$", "object", "->", "getKeyHandleBinary"...
Searches through the provided array of objects, and looks for a matching key handle value. If one is found, it is returned; if not, this returns null. TODO: create and implement a HasKeyHandle interface of sorts to type this better @param array $objects haystack to search @param string $keyHandle key handle to find in haystack @return mixed element from haystack @return null if no element matches
[ "Searches", "through", "the", "provided", "array", "of", "objects", "and", "looks", "for", "a", "matching", "key", "handle", "value", ".", "If", "one", "is", "found", "it", "is", "returned", ";", "if", "not", "this", "returns", "null", "." ]
65bb799b1f709192ff7fed1af814ca43b03a64c7
https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L362-L372
41,589
Firehed/u2f-php
src/Server.php
Server.validateChallenge
private function validateChallenge( ChallengeProvider $from, ChallengeProvider $to ): bool { // Note: strictly speaking, this shouldn't even be targetable as // a timing attack. However, this opts to be proactive, and also // ensures that no weird PHP-isms in string handling cause mismatched // values to validate. if (!hash_equals($from->getChallenge(), $to->getChallenge())) { throw new SE(SE::CHALLENGE_MISMATCH); } // TOOD: generate and compare timestamps return true; }
php
private function validateChallenge( ChallengeProvider $from, ChallengeProvider $to ): bool { // Note: strictly speaking, this shouldn't even be targetable as // a timing attack. However, this opts to be proactive, and also // ensures that no weird PHP-isms in string handling cause mismatched // values to validate. if (!hash_equals($from->getChallenge(), $to->getChallenge())) { throw new SE(SE::CHALLENGE_MISMATCH); } // TOOD: generate and compare timestamps return true; }
[ "private", "function", "validateChallenge", "(", "ChallengeProvider", "$", "from", ",", "ChallengeProvider", "$", "to", ")", ":", "bool", "{", "// Note: strictly speaking, this shouldn't even be targetable as", "// a timing attack. However, this opts to be proactive, and also", "//...
Compares the Challenge value from a known source against the user-provided value. A mismatch will throw a SE. Future versions may also enforce a timing window. @param ChallengeProvider $from source of known challenge @param ChallengeProvider $to user-provided value @return true on success @throws SE on failure
[ "Compares", "the", "Challenge", "value", "from", "a", "known", "source", "against", "the", "user", "-", "provided", "value", ".", "A", "mismatch", "will", "throw", "a", "SE", ".", "Future", "versions", "may", "also", "enforce", "a", "timing", "window", "."...
65bb799b1f709192ff7fed1af814ca43b03a64c7
https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L395-L408
41,590
aleksip/plugin-data-transform
src/Drupal/Component/Utility/UrlHelper.php
UrlHelper.filterQueryParameters
public static function filterQueryParameters(array $query, array $exclude = array(), $parent = '') { // If $exclude is empty, there is nothing to filter. if (empty($exclude)) { return $query; } elseif (!$parent) { $exclude = array_flip($exclude); } $params = array(); foreach ($query as $key => $value) { $string_key = ($parent ? $parent . '[' . $key . ']' : $key); if (isset($exclude[$string_key])) { continue; } if (is_array($value)) { $params[$key] = static::filterQueryParameters($value, $exclude, $string_key); } else { $params[$key] = $value; } } return $params; }
php
public static function filterQueryParameters(array $query, array $exclude = array(), $parent = '') { // If $exclude is empty, there is nothing to filter. if (empty($exclude)) { return $query; } elseif (!$parent) { $exclude = array_flip($exclude); } $params = array(); foreach ($query as $key => $value) { $string_key = ($parent ? $parent . '[' . $key . ']' : $key); if (isset($exclude[$string_key])) { continue; } if (is_array($value)) { $params[$key] = static::filterQueryParameters($value, $exclude, $string_key); } else { $params[$key] = $value; } } return $params; }
[ "public", "static", "function", "filterQueryParameters", "(", "array", "$", "query", ",", "array", "$", "exclude", "=", "array", "(", ")", ",", "$", "parent", "=", "''", ")", "{", "// If $exclude is empty, there is nothing to filter.", "if", "(", "empty", "(", ...
Filters a URL query parameter array to remove unwanted elements. @param array $query An array to be processed. @param array $exclude (optional) A list of $query array keys to remove. Use "parent[child]" to exclude nested items. @param string $parent Internal use only. Used to build the $query array key for nested items. @return An array containing query parameters.
[ "Filters", "a", "URL", "query", "parameter", "array", "to", "remove", "unwanted", "elements", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L87-L112
41,591
aleksip/plugin-data-transform
src/Drupal/Component/Utility/UrlHelper.php
UrlHelper.parse
public static function parse($url) { $options = array( 'path' => NULL, 'query' => array(), 'fragment' => '', ); // External URLs: not using parse_url() here, so we do not have to rebuild // the scheme, host, and path without having any use for it. if (strpos($url, '://') !== FALSE) { // Split off everything before the query string into 'path'. $parts = explode('?', $url); // Don't support URLs without a path, like 'http://'. list(, $path) = explode('://', $parts[0], 2); if ($path != '') { $options['path'] = $parts[0]; } // If there is a query string, transform it into keyed query parameters. if (isset($parts[1])) { $query_parts = explode('#', $parts[1]); parse_str($query_parts[0], $options['query']); // Take over the fragment, if there is any. if (isset($query_parts[1])) { $options['fragment'] = $query_parts[1]; } } } // Internal URLs. else { // parse_url() does not support relative URLs, so make it absolute. E.g. the // relative URL "foo/bar:1" isn't properly parsed. $parts = parse_url('http://example.com/' . $url); // Strip the leading slash that was just added. $options['path'] = substr($parts['path'], 1); if (isset($parts['query'])) { parse_str($parts['query'], $options['query']); } if (isset($parts['fragment'])) { $options['fragment'] = $parts['fragment']; } } return $options; }
php
public static function parse($url) { $options = array( 'path' => NULL, 'query' => array(), 'fragment' => '', ); // External URLs: not using parse_url() here, so we do not have to rebuild // the scheme, host, and path without having any use for it. if (strpos($url, '://') !== FALSE) { // Split off everything before the query string into 'path'. $parts = explode('?', $url); // Don't support URLs without a path, like 'http://'. list(, $path) = explode('://', $parts[0], 2); if ($path != '') { $options['path'] = $parts[0]; } // If there is a query string, transform it into keyed query parameters. if (isset($parts[1])) { $query_parts = explode('#', $parts[1]); parse_str($query_parts[0], $options['query']); // Take over the fragment, if there is any. if (isset($query_parts[1])) { $options['fragment'] = $query_parts[1]; } } } // Internal URLs. else { // parse_url() does not support relative URLs, so make it absolute. E.g. the // relative URL "foo/bar:1" isn't properly parsed. $parts = parse_url('http://example.com/' . $url); // Strip the leading slash that was just added. $options['path'] = substr($parts['path'], 1); if (isset($parts['query'])) { parse_str($parts['query'], $options['query']); } if (isset($parts['fragment'])) { $options['fragment'] = $parts['fragment']; } } return $options; }
[ "public", "static", "function", "parse", "(", "$", "url", ")", "{", "$", "options", "=", "array", "(", "'path'", "=>", "NULL", ",", "'query'", "=>", "array", "(", ")", ",", "'fragment'", "=>", "''", ",", ")", ";", "// External URLs: not using parse_url() h...
Parses a URL string into its path, query, and fragment components. This function splits both internal paths like @code node?b=c#d @endcode and external URLs like @code https://example.com/a?b=c#d @endcode into their component parts. See @link http://tools.ietf.org/html/rfc3986#section-3 RFC 3986 @endlink for an explanation of what the component parts are. Note that, unlike the RFC, when passed an external URL, this function groups the scheme, authority, and path together into the path component. @param string $url The internal path or external URL string to parse. @return array An associative array containing: - path: The path component of $url. If $url is an external URL, this includes the scheme, authority, and path. - query: An array of query parameters from $url, if they exist. - fragment: The fragment component from $url, if it exists. @see \Drupal\Core\Utility\LinkGenerator @see http://tools.ietf.org/html/rfc3986 @ingroup php_wrappers
[ "Parses", "a", "URL", "string", "into", "its", "path", "query", "and", "fragment", "components", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L141-L185
41,592
aleksip/plugin-data-transform
src/Drupal/Component/Utility/UrlHelper.php
UrlHelper.externalIsLocal
public static function externalIsLocal($url, $base_url) { $url_parts = parse_url($url); $base_parts = parse_url($base_url); if (empty($base_parts['host']) || empty($url_parts['host'])) { throw new \InvalidArgumentException('A path was passed when a fully qualified domain was expected.'); } if (!isset($url_parts['path']) || !isset($base_parts['path'])) { return (!isset($base_parts['path']) || $base_parts['path'] == '/') && ($url_parts['host'] == $base_parts['host']); } else { // When comparing base paths, we need a trailing slash to make sure a // partial URL match isn't occurring. Since base_path() always returns // with a trailing slash, we don't need to add the trailing slash here. return ($url_parts['host'] == $base_parts['host'] && stripos($url_parts['path'], $base_parts['path']) === 0); } }
php
public static function externalIsLocal($url, $base_url) { $url_parts = parse_url($url); $base_parts = parse_url($base_url); if (empty($base_parts['host']) || empty($url_parts['host'])) { throw new \InvalidArgumentException('A path was passed when a fully qualified domain was expected.'); } if (!isset($url_parts['path']) || !isset($base_parts['path'])) { return (!isset($base_parts['path']) || $base_parts['path'] == '/') && ($url_parts['host'] == $base_parts['host']); } else { // When comparing base paths, we need a trailing slash to make sure a // partial URL match isn't occurring. Since base_path() always returns // with a trailing slash, we don't need to add the trailing slash here. return ($url_parts['host'] == $base_parts['host'] && stripos($url_parts['path'], $base_parts['path']) === 0); } }
[ "public", "static", "function", "externalIsLocal", "(", "$", "url", ",", "$", "base_url", ")", "{", "$", "url_parts", "=", "parse_url", "(", "$", "url", ")", ";", "$", "base_parts", "=", "parse_url", "(", "$", "base_url", ")", ";", "if", "(", "empty", ...
Determines if an external URL points to this installation. @param string $url A string containing an external URL, such as "http://example.com/foo". @param string $base_url The base URL string to check against, such as "http://example.com/" @return bool TRUE if the URL has the same domain and base path. @throws \InvalidArgumentException Exception thrown when a either $url or $bath_url are not fully qualified.
[ "Determines", "if", "an", "external", "URL", "points", "to", "this", "installation", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L242-L260
41,593
aleksip/plugin-data-transform
src/Drupal/Component/Utility/UrlHelper.php
UrlHelper.filterBadProtocol
public static function filterBadProtocol($string) { // Get the plain text representation of the attribute value (i.e. its // meaning). $string = Html::decodeEntities($string); return Html::escape(static::stripDangerousProtocols($string)); }
php
public static function filterBadProtocol($string) { // Get the plain text representation of the attribute value (i.e. its // meaning). $string = Html::decodeEntities($string); return Html::escape(static::stripDangerousProtocols($string)); }
[ "public", "static", "function", "filterBadProtocol", "(", "$", "string", ")", "{", "// Get the plain text representation of the attribute value (i.e. its", "// meaning).", "$", "string", "=", "Html", "::", "decodeEntities", "(", "$", "string", ")", ";", "return", "Html"...
Processes an HTML attribute value and strips dangerous protocols from URLs. @param string $string The string with the attribute value. @return string Cleaned up and HTML-escaped version of $string.
[ "Processes", "an", "HTML", "attribute", "value", "and", "strips", "dangerous", "protocols", "from", "URLs", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L271-L276
41,594
aleksip/plugin-data-transform
src/Drupal/Component/Utility/UrlHelper.php
UrlHelper.isValid
public static function isValid($url, $absolute = FALSE) { if ($absolute) { return (bool) preg_match(" /^ # Start at the beginning of the text (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes (?: # Userinfo (optional) which is typically (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination )? (?: (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address ) (?::[0-9]+)? # Server port number (optional) (?:[\/|\?] (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional) *)? $/xi", $url); } else { return (bool) preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url); } }
php
public static function isValid($url, $absolute = FALSE) { if ($absolute) { return (bool) preg_match(" /^ # Start at the beginning of the text (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes (?: # Userinfo (optional) which is typically (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination )? (?: (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address ) (?::[0-9]+)? # Server port number (optional) (?:[\/|\?] (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional) *)? $/xi", $url); } else { return (bool) preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url); } }
[ "public", "static", "function", "isValid", "(", "$", "url", ",", "$", "absolute", "=", "FALSE", ")", "{", "if", "(", "$", "absolute", ")", "{", "return", "(", "bool", ")", "preg_match", "(", "\"\n /^ # St...
Verifies the syntax of the given URL. This function should only be used on actual URLs. It should not be used for Drupal menu paths, which can contain arbitrary characters. Valid values per RFC 3986. @param string $url The URL to verify. @param bool $absolute Whether the URL is absolute (beginning with a scheme such as "http:"). @return bool TRUE if the URL is in a valid format, FALSE otherwise.
[ "Verifies", "the", "syntax", "of", "the", "given", "URL", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L380-L402
41,595
aleksip/plugin-data-transform
src/Drupal/Component/Render/MarkupTrait.php
MarkupTrait.create
public static function create($string) { if ($string instanceof MarkupInterface) { return $string; } $string = (string) $string; if ($string === '') { return ''; } $safe_string = new static(); $safe_string->string = $string; return $safe_string; }
php
public static function create($string) { if ($string instanceof MarkupInterface) { return $string; } $string = (string) $string; if ($string === '') { return ''; } $safe_string = new static(); $safe_string->string = $string; return $safe_string; }
[ "public", "static", "function", "create", "(", "$", "string", ")", "{", "if", "(", "$", "string", "instanceof", "MarkupInterface", ")", "{", "return", "$", "string", ";", "}", "$", "string", "=", "(", "string", ")", "$", "string", ";", "if", "(", "$"...
Creates a Markup object if necessary. If $string is equal to a blank string then it is not necessary to create a Markup object. If $string is an object that implements MarkupInterface it is returned unchanged. @param mixed $string The string to mark as safe. This value will be cast to a string. @return string|\Drupal\Component\Render\MarkupInterface A safe string.
[ "Creates", "a", "Markup", "object", "if", "necessary", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Render/MarkupTrait.php#L39-L50
41,596
aleksip/plugin-data-transform
src/Drupal/Component/Render/FormattableMarkup.php
FormattableMarkup.placeholderFormat
protected static function placeholderFormat($string, array $args) { // Transform arguments before inserting them. foreach ($args as $key => $value) { switch ($key[0]) { case '@': // Escape if the value is not an object from a class that implements // \Drupal\Component\Render\MarkupInterface, for example strings will // be escaped. // \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe() may // return TRUE for content that is safe within HTML fragments, but not // within other contexts, so this placeholder type must not be used // within HTML attributes, JavaScript, or CSS. $args[$key] = static::placeholderEscape($value); break; case ':': // Strip URL protocols that can be XSS vectors. $value = UrlHelper::stripDangerousProtocols($value); // Escape unconditionally, without checking // \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe(). This // forces characters that are unsafe for use in an "href" HTML // attribute to be encoded. If a caller wants to pass a value that is // extracted from HTML and therefore is already HTML encoded, it must // invoke // \Drupal\Component\Render\OutputStrategyInterface::renderFromHtml() // on it prior to passing it in as a placeholder value of this type. // @todo Add some advice and stronger warnings. // https://www.drupal.org/node/2569041. $args[$key] = Html::escape($value); break; case '%': // Similarly to @, escape non-safe values. Also, add wrapping markup // in order to render as a placeholder. Not for use within attributes, // per the warning above about // \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe() and also // due to the wrapping markup. $args[$key] = '<em class="placeholder">' . static::placeholderEscape($value) . '</em>'; break; default: // We do not trigger an error for placeholder that start with an // alphabetic character. if (!ctype_alpha($key[0])) { // We trigger an error as we may want to introduce new placeholders // in the future without breaking backward compatibility. trigger_error('Invalid placeholder (' . $key . ') in string: ' . $string, E_USER_ERROR); } break; } } return strtr($string, $args); }
php
protected static function placeholderFormat($string, array $args) { // Transform arguments before inserting them. foreach ($args as $key => $value) { switch ($key[0]) { case '@': // Escape if the value is not an object from a class that implements // \Drupal\Component\Render\MarkupInterface, for example strings will // be escaped. // \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe() may // return TRUE for content that is safe within HTML fragments, but not // within other contexts, so this placeholder type must not be used // within HTML attributes, JavaScript, or CSS. $args[$key] = static::placeholderEscape($value); break; case ':': // Strip URL protocols that can be XSS vectors. $value = UrlHelper::stripDangerousProtocols($value); // Escape unconditionally, without checking // \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe(). This // forces characters that are unsafe for use in an "href" HTML // attribute to be encoded. If a caller wants to pass a value that is // extracted from HTML and therefore is already HTML encoded, it must // invoke // \Drupal\Component\Render\OutputStrategyInterface::renderFromHtml() // on it prior to passing it in as a placeholder value of this type. // @todo Add some advice and stronger warnings. // https://www.drupal.org/node/2569041. $args[$key] = Html::escape($value); break; case '%': // Similarly to @, escape non-safe values. Also, add wrapping markup // in order to render as a placeholder. Not for use within attributes, // per the warning above about // \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe() and also // due to the wrapping markup. $args[$key] = '<em class="placeholder">' . static::placeholderEscape($value) . '</em>'; break; default: // We do not trigger an error for placeholder that start with an // alphabetic character. if (!ctype_alpha($key[0])) { // We trigger an error as we may want to introduce new placeholders // in the future without breaking backward compatibility. trigger_error('Invalid placeholder (' . $key . ') in string: ' . $string, E_USER_ERROR); } break; } } return strtr($string, $args); }
[ "protected", "static", "function", "placeholderFormat", "(", "$", "string", ",", "array", "$", "args", ")", "{", "// Transform arguments before inserting them.", "foreach", "(", "$", "args", "as", "$", "key", "=>", "$", "value", ")", "{", "switch", "(", "$", ...
Replaces placeholders in a string with values. @param string $string A string containing placeholders. The string itself is expected to be safe and correct HTML. Any unsafe content must be in $args and inserted via placeholders. @param array $args An associative array of replacements. Each array key should be the same as a placeholder in $string. The corresponding value should be a string or an object that implements \Drupal\Component\Render\MarkupInterface. The value replaces the placeholder in $string. Sanitization and formatting will be done before replacement. The type of sanitization and formatting depends on the first character of the key: - @variable: When the placeholder replacement value is: - A string, the replaced value in the returned string will be sanitized using \Drupal\Component\Utility\Html::escape(). - A MarkupInterface object, the replaced value in the returned string will not be sanitized. - A MarkupInterface object cast to a string, the replaced value in the returned string be forcibly sanitized using \Drupal\Component\Utility\Html::escape(). @code $this->placeholderFormat('This will force HTML-escaping of the replacement value: @text', ['@text' => (string) $safe_string_interface_object)); @endcode Use this placeholder as the default choice for anything displayed on the site, but not within HTML attributes, JavaScript, or CSS. Doing so is a security risk. - %variable: Use when the replacement value is to be wrapped in <em> tags. A call like: @code $string = "%output_text"; $arguments = ['output_text' => 'text output here.']; $this->placeholderFormat($string, $arguments); @endcode makes the following HTML code: @code <em class="placeholder">text output here.</em> @endcode As with @variable, do not use this within HTML attributes, JavaScript, or CSS. Doing so is a security risk. - :variable: Return value is escaped with \Drupal\Component\Utility\Html::escape() and filtered for dangerous protocols using UrlHelper::stripDangerousProtocols(). Use this when using the "href" attribute, ensuring the attribute value is always wrapped in quotes: @code // Secure (with quotes): $this->placeholderFormat('<a href=":url">@variable</a>', [':url' => $url, @variable => $variable]); // Insecure (without quotes): $this->placeholderFormat('<a href=:url>@variable</a>', [':url' => $url, @variable => $variable]); @endcode When ":variable" comes from arbitrary user input, the result is secure, but not guaranteed to be a valid URL (which means the resulting output could fail HTML validation). To guarantee a valid URL, use Url::fromUri($user_input)->toString() (which either throws an exception or returns a well-formed URL) before passing the result into a ":variable" placeholder. @return string A formatted HTML string with the placeholders replaced. @ingroup sanitization @see \Drupal\Core\StringTranslation\TranslatableMarkup @see \Drupal\Core\StringTranslation\PluralTranslatableMarkup @see \Drupal\Component\Utility\Html::escape() @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() @see \Drupal\Core\Url::fromUri()
[ "Replaces", "placeholders", "in", "a", "string", "with", "values", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Render/FormattableMarkup.php#L194-L247
41,597
aleksip/plugin-data-transform
src/Drupal/Component/Render/FormattableMarkup.php
FormattableMarkup.placeholderEscape
protected static function placeholderEscape($value) { return SafeMarkup::isSafe($value) ? (string) $value : Html::escape($value); }
php
protected static function placeholderEscape($value) { return SafeMarkup::isSafe($value) ? (string) $value : Html::escape($value); }
[ "protected", "static", "function", "placeholderEscape", "(", "$", "value", ")", "{", "return", "SafeMarkup", "::", "isSafe", "(", "$", "value", ")", "?", "(", "string", ")", "$", "value", ":", "Html", "::", "escape", "(", "$", "value", ")", ";", "}" ]
Escapes a placeholder replacement value if needed. @param string|\Drupal\Component\Render\MarkupInterface $value A placeholder replacement value. @return string The properly escaped replacement value.
[ "Escapes", "a", "placeholder", "replacement", "value", "if", "needed", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Render/FormattableMarkup.php#L258-L260
41,598
aleksip/plugin-data-transform
src/Drupal/Component/Utility/ArgumentsResolver.php
ArgumentsResolver.getArgument
protected function getArgument(\ReflectionParameter $parameter) { $parameter_type_hint = $parameter->getClass(); $parameter_name = $parameter->getName(); // If the argument exists and is NULL, return it, regardless of // parameter type hint. if (!isset($this->objects[$parameter_name]) && array_key_exists($parameter_name, $this->objects)) { return NULL; } if ($parameter_type_hint) { // If the argument exists and complies with the type hint, return it. if (isset($this->objects[$parameter_name]) && is_object($this->objects[$parameter_name]) && $parameter_type_hint->isInstance($this->objects[$parameter_name])) { return $this->objects[$parameter_name]; } // Otherwise, resolve wildcard arguments by type matching. foreach ($this->wildcards as $wildcard) { if ($parameter_type_hint->isInstance($wildcard)) { return $wildcard; } } } elseif (isset($this->scalars[$parameter_name])) { return $this->scalars[$parameter_name]; } // If the callable provides a default value, use it. if ($parameter->isDefaultValueAvailable()) { return $parameter->getDefaultValue(); } // Can't resolve it: call a method that throws an exception or can be // overridden to do something else. return $this->handleUnresolvedArgument($parameter); }
php
protected function getArgument(\ReflectionParameter $parameter) { $parameter_type_hint = $parameter->getClass(); $parameter_name = $parameter->getName(); // If the argument exists and is NULL, return it, regardless of // parameter type hint. if (!isset($this->objects[$parameter_name]) && array_key_exists($parameter_name, $this->objects)) { return NULL; } if ($parameter_type_hint) { // If the argument exists and complies with the type hint, return it. if (isset($this->objects[$parameter_name]) && is_object($this->objects[$parameter_name]) && $parameter_type_hint->isInstance($this->objects[$parameter_name])) { return $this->objects[$parameter_name]; } // Otherwise, resolve wildcard arguments by type matching. foreach ($this->wildcards as $wildcard) { if ($parameter_type_hint->isInstance($wildcard)) { return $wildcard; } } } elseif (isset($this->scalars[$parameter_name])) { return $this->scalars[$parameter_name]; } // If the callable provides a default value, use it. if ($parameter->isDefaultValueAvailable()) { return $parameter->getDefaultValue(); } // Can't resolve it: call a method that throws an exception or can be // overridden to do something else. return $this->handleUnresolvedArgument($parameter); }
[ "protected", "function", "getArgument", "(", "\\", "ReflectionParameter", "$", "parameter", ")", "{", "$", "parameter_type_hint", "=", "$", "parameter", "->", "getClass", "(", ")", ";", "$", "parameter_name", "=", "$", "parameter", "->", "getName", "(", ")", ...
Gets the argument value for a parameter. @param \ReflectionParameter $parameter The parameter of a callable to get the value for. @return mixed The value of the requested parameter value. @throws \RuntimeException Thrown when there is a missing parameter.
[ "Gets", "the", "argument", "value", "for", "a", "parameter", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/ArgumentsResolver.php#L76-L110
41,599
aleksip/plugin-data-transform
src/Drupal/Component/Utility/SortArray.php
SortArray.sortByKeyString
public static function sortByKeyString($a, $b, $key) { $a_title = (is_array($a) && isset($a[$key])) ? $a[$key] : ''; $b_title = (is_array($b) && isset($b[$key])) ? $b[$key] : ''; return strnatcasecmp($a_title, $b_title); }
php
public static function sortByKeyString($a, $b, $key) { $a_title = (is_array($a) && isset($a[$key])) ? $a[$key] : ''; $b_title = (is_array($b) && isset($b[$key])) ? $b[$key] : ''; return strnatcasecmp($a_title, $b_title); }
[ "public", "static", "function", "sortByKeyString", "(", "$", "a", ",", "$", "b", ",", "$", "key", ")", "{", "$", "a_title", "=", "(", "is_array", "(", "$", "a", ")", "&&", "isset", "(", "$", "a", "[", "$", "key", "]", ")", ")", "?", "$", "a",...
Sorts a string array item by an arbitrary key. @param array $a First item for comparison. @param array $b Second item for comparison. @param string $key The key to use in the comparison. @return int The comparison result for uasort().
[ "Sorts", "a", "string", "array", "item", "by", "an", "arbitrary", "key", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/SortArray.php#L106-L111