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
35,300
Becklyn/RadBundle
src/Model/DoctrineModel.php
DoctrineModel.getRepository
protected function getRepository ($persistentObject = null) : EntityRepository { if (null === $persistentObject) { $persistentObject = $this->getFullEntityName(); } return $this->doctrine->getRepository($persistentObject); }
php
protected function getRepository ($persistentObject = null) : EntityRepository { if (null === $persistentObject) { $persistentObject = $this->getFullEntityName(); } return $this->doctrine->getRepository($persistentObject); }
[ "protected", "function", "getRepository", "(", "$", "persistentObject", "=", "null", ")", ":", "EntityRepository", "{", "if", "(", "null", "===", "$", "persistentObject", ")", "{", "$", "persistentObject", "=", "$", "this", "->", "getFullEntityName", "(", ")", ";", "}", "return", "$", "this", "->", "doctrine", "->", "getRepository", "(", "$", "persistentObject", ")", ";", "}" ]
Returns the repository. @param string|null $persistentObject you can specify which repository you want to load. Defaults to the automatically derived one. @return EntityRepository
[ "Returns", "the", "repository", "." ]
34d5887e13f5a4018843b77dcbefc2eb2f3169f4
https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/DoctrineModel.php#L48-L56
35,301
Becklyn/RadBundle
src/Model/DoctrineModel.php
DoctrineModel.getFullEntityName
protected function getFullEntityName () : string { $entityClass = $this->classNameTransformer->transformModelToEntity(static::class); if (!\class_exists($entityClass)) { throw new AutoConfigurationFailedException(\sprintf( "Cannot automatically generate entity name for model '%s', guessed '%s'.", static::class, $entityClass )); } return $entityClass; }
php
protected function getFullEntityName () : string { $entityClass = $this->classNameTransformer->transformModelToEntity(static::class); if (!\class_exists($entityClass)) { throw new AutoConfigurationFailedException(\sprintf( "Cannot automatically generate entity name for model '%s', guessed '%s'.", static::class, $entityClass )); } return $entityClass; }
[ "protected", "function", "getFullEntityName", "(", ")", ":", "string", "{", "$", "entityClass", "=", "$", "this", "->", "classNameTransformer", "->", "transformModelToEntity", "(", "static", "::", "class", ")", ";", "if", "(", "!", "\\", "class_exists", "(", "$", "entityClass", ")", ")", "{", "throw", "new", "AutoConfigurationFailedException", "(", "\\", "sprintf", "(", "\"Cannot automatically generate entity name for model '%s', guessed '%s'.\"", ",", "static", "::", "class", ",", "$", "entityClass", ")", ")", ";", "}", "return", "$", "entityClass", ";", "}" ]
Returns the entity name. @throws AutoConfigurationFailedException @return string the entity reference string
[ "Returns", "the", "entity", "name", "." ]
34d5887e13f5a4018843b77dcbefc2eb2f3169f4
https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/DoctrineModel.php#L77-L91
35,302
Becklyn/RadBundle
src/Model/DoctrineModel.php
DoctrineModel.removeEntity
protected function removeEntity (...$entities) : void { try { $entities = \array_filter($entities); if (empty($entities)) { return; } $entityManager = $this->getEntityManager(); \array_map([$entityManager, "remove"], $entities); $entityManager->flush(); } catch (ForeignKeyConstraintViolationException $foreignKeyException) { throw new EntityRemovalBlockedException( $entities, "Can't remove entities as a foreign key constraint failed.", $foreignKeyException ); } }
php
protected function removeEntity (...$entities) : void { try { $entities = \array_filter($entities); if (empty($entities)) { return; } $entityManager = $this->getEntityManager(); \array_map([$entityManager, "remove"], $entities); $entityManager->flush(); } catch (ForeignKeyConstraintViolationException $foreignKeyException) { throw new EntityRemovalBlockedException( $entities, "Can't remove entities as a foreign key constraint failed.", $foreignKeyException ); } }
[ "protected", "function", "removeEntity", "(", "...", "$", "entities", ")", ":", "void", "{", "try", "{", "$", "entities", "=", "\\", "array_filter", "(", "$", "entities", ")", ";", "if", "(", "empty", "(", "$", "entities", ")", ")", "{", "return", ";", "}", "$", "entityManager", "=", "$", "this", "->", "getEntityManager", "(", ")", ";", "\\", "array_map", "(", "[", "$", "entityManager", ",", "\"remove\"", "]", ",", "$", "entities", ")", ";", "$", "entityManager", "->", "flush", "(", ")", ";", "}", "catch", "(", "ForeignKeyConstraintViolationException", "$", "foreignKeyException", ")", "{", "throw", "new", "EntityRemovalBlockedException", "(", "$", "entities", ",", "\"Can't remove entities as a foreign key constraint failed.\"", ",", "$", "foreignKeyException", ")", ";", "}", "}" ]
Removes the given entities. @param object[] ...$entities
[ "Removes", "the", "given", "entities", "." ]
34d5887e13f5a4018843b77dcbefc2eb2f3169f4
https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Model/DoctrineModel.php#L111-L134
35,303
systemson/collection
src/Base/ArrayFunctionsTrait.php
ArrayFunctionsTrait.filter
public function filter(Closure $callback): CollectionInterface { $array = array_filter( $this->toArray(), $callback, ARRAY_FILTER_USE_BOTH ); return static::make(array_values($array)); }
php
public function filter(Closure $callback): CollectionInterface { $array = array_filter( $this->toArray(), $callback, ARRAY_FILTER_USE_BOTH ); return static::make(array_values($array)); }
[ "public", "function", "filter", "(", "Closure", "$", "callback", ")", ":", "CollectionInterface", "{", "$", "array", "=", "array_filter", "(", "$", "this", "->", "toArray", "(", ")", ",", "$", "callback", ",", "ARRAY_FILTER_USE_BOTH", ")", ";", "return", "static", "::", "make", "(", "array_values", "(", "$", "array", ")", ")", ";", "}" ]
Returns a new filtered collection using a user-defined function. @param Closure $callback @return Collection A new collection instance.
[ "Returns", "a", "new", "filtered", "collection", "using", "a", "user", "-", "defined", "function", "." ]
fb3ae1a78806aafabc0562db96822e8b99dc2a64
https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/ArrayFunctionsTrait.php#L45-L54
35,304
systemson/collection
src/Base/ArrayFunctionsTrait.php
ArrayFunctionsTrait.sort
public function sort(Closure $callback = null): CollectionInterface { $array = $this->toArray(); if (is_null($callback)) { sort($array); } else { usort( $array, $callback ); } return static::make($array); }
php
public function sort(Closure $callback = null): CollectionInterface { $array = $this->toArray(); if (is_null($callback)) { sort($array); } else { usort( $array, $callback ); } return static::make($array); }
[ "public", "function", "sort", "(", "Closure", "$", "callback", "=", "null", ")", ":", "CollectionInterface", "{", "$", "array", "=", "$", "this", "->", "toArray", "(", ")", ";", "if", "(", "is_null", "(", "$", "callback", ")", ")", "{", "sort", "(", "$", "array", ")", ";", "}", "else", "{", "usort", "(", "$", "array", ",", "$", "callback", ")", ";", "}", "return", "static", "::", "make", "(", "$", "array", ")", ";", "}" ]
Returns a new sorted collection using a user-defined comparison function. @param Closure $callback The user-defined comparison function. @return Collection A new collection instance.
[ "Returns", "a", "new", "sorted", "collection", "using", "a", "user", "-", "defined", "comparison", "function", "." ]
fb3ae1a78806aafabc0562db96822e8b99dc2a64
https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/ArrayFunctionsTrait.php#L63-L77
35,305
systemson/collection
src/Base/ArrayFunctionsTrait.php
ArrayFunctionsTrait.chunk
public function chunk(int $size, bool $preserve_keys = false): CollectionInterface { $return = array_chunk($this->toArray(), $size, $preserve_keys); return static::make($return); }
php
public function chunk(int $size, bool $preserve_keys = false): CollectionInterface { $return = array_chunk($this->toArray(), $size, $preserve_keys); return static::make($return); }
[ "public", "function", "chunk", "(", "int", "$", "size", ",", "bool", "$", "preserve_keys", "=", "false", ")", ":", "CollectionInterface", "{", "$", "return", "=", "array_chunk", "(", "$", "this", "->", "toArray", "(", ")", ",", "$", "size", ",", "$", "preserve_keys", ")", ";", "return", "static", "::", "make", "(", "$", "return", ")", ";", "}" ]
Splits an array into chunks. @param int $size The size of each chunk. @param bool $preserve_keys Whether the keys should be preserved. @return Collection A new collection instance.
[ "Splits", "an", "array", "into", "chunks", "." ]
fb3ae1a78806aafabc0562db96822e8b99dc2a64
https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/ArrayFunctionsTrait.php#L115-L120
35,306
systemson/collection
src/Base/ArrayFunctionsTrait.php
ArrayFunctionsTrait.random
public function random(int $num = 1): CollectionInterface { if ($this->isEmpty()) { return static::make(); } $keys = array_rand($this->toArray(), $num); $return = $this->getMultiple((array) $keys); return static::make($return); }
php
public function random(int $num = 1): CollectionInterface { if ($this->isEmpty()) { return static::make(); } $keys = array_rand($this->toArray(), $num); $return = $this->getMultiple((array) $keys); return static::make($return); }
[ "public", "function", "random", "(", "int", "$", "num", "=", "1", ")", ":", "CollectionInterface", "{", "if", "(", "$", "this", "->", "isEmpty", "(", ")", ")", "{", "return", "static", "::", "make", "(", ")", ";", "}", "$", "keys", "=", "array_rand", "(", "$", "this", "->", "toArray", "(", ")", ",", "$", "num", ")", ";", "$", "return", "=", "$", "this", "->", "getMultiple", "(", "(", "array", ")", "$", "keys", ")", ";", "return", "static", "::", "make", "(", "$", "return", ")", ";", "}" ]
Pick one or more random items from the collection. @param int $num @return Collection
[ "Pick", "one", "or", "more", "random", "items", "from", "the", "collection", "." ]
fb3ae1a78806aafabc0562db96822e8b99dc2a64
https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/ArrayFunctionsTrait.php#L183-L194
35,307
Kajna/K-Core
Core/Database/Connections/MSSQLConnection.php
MSSQLConnection.connect
public function connect() { try { // Make string containing database settings $database = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->database; // Make connection. $conn = new \PDO($database, $this->username, $this->password); // Set attributes from parameters $conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, $this->fetch); $conn->setAttribute(\PDO::ATTR_ERRMODE, $this->error); return $conn; } catch (\PDOException $ex) { throw new \InvalidArgumentException('Error! Cannot connect to database ' . $ex->getMessage()); } }
php
public function connect() { try { // Make string containing database settings $database = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->database; // Make connection. $conn = new \PDO($database, $this->username, $this->password); // Set attributes from parameters $conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, $this->fetch); $conn->setAttribute(\PDO::ATTR_ERRMODE, $this->error); return $conn; } catch (\PDOException $ex) { throw new \InvalidArgumentException('Error! Cannot connect to database ' . $ex->getMessage()); } }
[ "public", "function", "connect", "(", ")", "{", "try", "{", "// Make string containing database settings", "$", "database", "=", "'sqlsrv:Server='", ".", "$", "this", "->", "host", ".", "';Database='", ".", "$", "this", "->", "database", ";", "// Make connection.", "$", "conn", "=", "new", "\\", "PDO", "(", "$", "database", ",", "$", "this", "->", "username", ",", "$", "this", "->", "password", ")", ";", "// Set attributes from parameters", "$", "conn", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_DEFAULT_FETCH_MODE", ",", "$", "this", "->", "fetch", ")", ";", "$", "conn", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_ERRMODE", ",", "$", "this", "->", "error", ")", ";", "return", "$", "conn", ";", "}", "catch", "(", "\\", "PDOException", "$", "ex", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Error! Cannot connect to database '", ".", "$", "ex", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Connect to database with using settings defined in class. @return \PDO @throws \PDOException @throws \InvalidArgumentException
[ "Connect", "to", "database", "with", "using", "settings", "defined", "in", "class", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Database/Connections/MSSQLConnection.php#L34-L51
35,308
TheBnl/silverstripe-pageslices
src/extensions/PageSlicesExtension.php
PageSlicesExtension.getSlices
public function getSlices() { $controllers = ArrayList::create(); if( $this->owner instanceof \VirtualPage && ($original = $this->owner->CopyContentFrom()) && $original->hasExtension(self::class)) { $slices = $original->PageSlices(); } else { $slices = $this->owner->PageSlices(); } if ($slices) { /** @var PageSlice $slice */ foreach ($slices as $slice) { $controller = $slice->getController(); $controller->init(); $controllers->push($controller); } return $controllers; } return $controllers; }
php
public function getSlices() { $controllers = ArrayList::create(); if( $this->owner instanceof \VirtualPage && ($original = $this->owner->CopyContentFrom()) && $original->hasExtension(self::class)) { $slices = $original->PageSlices(); } else { $slices = $this->owner->PageSlices(); } if ($slices) { /** @var PageSlice $slice */ foreach ($slices as $slice) { $controller = $slice->getController(); $controller->init(); $controllers->push($controller); } return $controllers; } return $controllers; }
[ "public", "function", "getSlices", "(", ")", "{", "$", "controllers", "=", "ArrayList", "::", "create", "(", ")", ";", "if", "(", "$", "this", "->", "owner", "instanceof", "\\", "VirtualPage", "&&", "(", "$", "original", "=", "$", "this", "->", "owner", "->", "CopyContentFrom", "(", ")", ")", "&&", "$", "original", "->", "hasExtension", "(", "self", "::", "class", ")", ")", "{", "$", "slices", "=", "$", "original", "->", "PageSlices", "(", ")", ";", "}", "else", "{", "$", "slices", "=", "$", "this", "->", "owner", "->", "PageSlices", "(", ")", ";", "}", "if", "(", "$", "slices", ")", "{", "/** @var PageSlice $slice */", "foreach", "(", "$", "slices", "as", "$", "slice", ")", "{", "$", "controller", "=", "$", "slice", "->", "getController", "(", ")", ";", "$", "controller", "->", "init", "(", ")", ";", "$", "controllers", "->", "push", "(", "$", "controller", ")", ";", "}", "return", "$", "controllers", ";", "}", "return", "$", "controllers", ";", "}" ]
Get the slice controllers @return ArrayList
[ "Get", "the", "slice", "controllers" ]
5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b
https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/extensions/PageSlicesExtension.php#L59-L84
35,309
TheBnl/silverstripe-pageslices
src/extensions/PageSlicesExtension.php
PageSlicesExtension.onAfterDuplicate
public function onAfterDuplicate(\Page $page) { foreach ($this->owner->PageSlices() as $slice) { /** @var PageSlice $slice */ $sliceCopy = $slice->duplicate(true); $page->PageSlices()->add($sliceCopy); $sliceCopy->publishRecursive(); } }
php
public function onAfterDuplicate(\Page $page) { foreach ($this->owner->PageSlices() as $slice) { /** @var PageSlice $slice */ $sliceCopy = $slice->duplicate(true); $page->PageSlices()->add($sliceCopy); $sliceCopy->publishRecursive(); } }
[ "public", "function", "onAfterDuplicate", "(", "\\", "Page", "$", "page", ")", "{", "foreach", "(", "$", "this", "->", "owner", "->", "PageSlices", "(", ")", "as", "$", "slice", ")", "{", "/** @var PageSlice $slice */", "$", "sliceCopy", "=", "$", "slice", "->", "duplicate", "(", "true", ")", ";", "$", "page", "->", "PageSlices", "(", ")", "->", "add", "(", "$", "sliceCopy", ")", ";", "$", "sliceCopy", "->", "publishRecursive", "(", ")", ";", "}", "}" ]
Loop over and copy the attached page slices @param \Page $page
[ "Loop", "over", "and", "copy", "the", "attached", "page", "slices" ]
5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b
https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/extensions/PageSlicesExtension.php#L109-L117
35,310
TheBnl/silverstripe-pageslices
src/extensions/PageSlicesExtension.php
PageSlicesExtension.isValidClass
public function isValidClass() { $invalidClassList = array_unique(PageSlice::config()->get('default_slices_exceptions')); return !in_array($this->owner->getClassName(), $invalidClassList); }
php
public function isValidClass() { $invalidClassList = array_unique(PageSlice::config()->get('default_slices_exceptions')); return !in_array($this->owner->getClassName(), $invalidClassList); }
[ "public", "function", "isValidClass", "(", ")", "{", "$", "invalidClassList", "=", "array_unique", "(", "PageSlice", "::", "config", "(", ")", "->", "get", "(", "'default_slices_exceptions'", ")", ")", ";", "return", "!", "in_array", "(", "$", "this", "->", "owner", "->", "getClassName", "(", ")", ",", "$", "invalidClassList", ")", ";", "}" ]
Check if the class is not in the exception list @return bool
[ "Check", "if", "the", "class", "is", "not", "in", "the", "exception", "list" ]
5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b
https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/extensions/PageSlicesExtension.php#L124-L128
35,311
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.getTokenByClientCredentialsGrant
protected function getTokenByClientCredentialsGrant() { $token = $this->getAuthorizationServer()->getAccessToken('client_credentials', [ 'scope' => $this->config['client_credentials']['scope'], ]); $this->getFrameworkBridge()->persistClientToken( $this->config['client_credentials']['client_id'], $token->getToken(), $token->getExpires(), $token->getValues()['role'] ); return $token; }
php
protected function getTokenByClientCredentialsGrant() { $token = $this->getAuthorizationServer()->getAccessToken('client_credentials', [ 'scope' => $this->config['client_credentials']['scope'], ]); $this->getFrameworkBridge()->persistClientToken( $this->config['client_credentials']['client_id'], $token->getToken(), $token->getExpires(), $token->getValues()['role'] ); return $token; }
[ "protected", "function", "getTokenByClientCredentialsGrant", "(", ")", "{", "$", "token", "=", "$", "this", "->", "getAuthorizationServer", "(", ")", "->", "getAccessToken", "(", "'client_credentials'", ",", "[", "'scope'", "=>", "$", "this", "->", "config", "[", "'client_credentials'", "]", "[", "'scope'", "]", ",", "]", ")", ";", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "persistClientToken", "(", "$", "this", "->", "config", "[", "'client_credentials'", "]", "[", "'client_id'", "]", ",", "$", "token", "->", "getToken", "(", ")", ",", "$", "token", "->", "getExpires", "(", ")", ",", "$", "token", "->", "getValues", "(", ")", "[", "'role'", "]", ")", ";", "return", "$", "token", ";", "}" ]
Authorize a machine based on the given client credentials. @return mixed
[ "Authorize", "a", "machine", "based", "on", "the", "given", "client", "credentials", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L83-L97
35,312
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.getTokenByAuthorizationCodeGrant
protected function getTokenByAuthorizationCodeGrant($code) { try { $token = $this->getAuthorizationServer()->getAccessToken('authorization_code', [ 'code' => $code, ]); $this->getFrameworkBridge()->persistUserToken($token); return $token; } catch (IdentityProviderException $e) { return null; } }
php
protected function getTokenByAuthorizationCodeGrant($code) { try { $token = $this->getAuthorizationServer()->getAccessToken('authorization_code', [ 'code' => $code, ]); $this->getFrameworkBridge()->persistUserToken($token); return $token; } catch (IdentityProviderException $e) { return null; } }
[ "protected", "function", "getTokenByAuthorizationCodeGrant", "(", "$", "code", ")", "{", "try", "{", "$", "token", "=", "$", "this", "->", "getAuthorizationServer", "(", ")", "->", "getAccessToken", "(", "'authorization_code'", ",", "[", "'code'", "=>", "$", "code", ",", "]", ")", ";", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "persistUserToken", "(", "$", "token", ")", ";", "return", "$", "token", ";", "}", "catch", "(", "IdentityProviderException", "$", "e", ")", "{", "return", "null", ";", "}", "}" ]
Authorize a user by redirecting to Northstar's single sign-on page. @param string $code @return \League\OAuth2\Client\Token\AccessToken
[ "Authorize", "a", "user", "by", "redirecting", "to", "Northstar", "s", "single", "sign", "-", "on", "page", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L105-L118
35,313
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.authorize
public function authorize(ServerRequestInterface $request, ResponseInterface $response, $url = '/', $destination = null, $options = []) { // Make sure we're making request with the authorization_code grant. $this->asUser(); $url = $this->getFrameworkBridge()->prepareUrl($url); $query = $request->getQueryParams(); // If we don't have an authorization code then make one and redirect. if (! isset($query['code'])) { $params = array_merge($options, [ 'scope' => $this->config['authorization_code']['scope'], 'destination' => ! empty($destination) ? $destination : null, ]); $authorizationUrl = $this->getAuthorizationServer()->getAuthorizationUrl($params); // Get the state generated for you and store it to the session. $state = $this->getAuthorizationServer()->getState(); $this->getFrameworkBridge()->saveStateToken($state); // Redirect the user to the authorization URL. return $response->withStatus(302)->withHeader('Location', $authorizationUrl); } // Check given state against previously stored one to mitigate CSRF attack if (! (isset($query['state']) && $query['state'] === $this->getFrameworkBridge()->getStateToken())) { throw new InternalException('[authorization_code]', 500, 'The OAuth state field did not match.'); } $token = $this->getTokenByAuthorizationCodeGrant($query['code']); if (! $token) { throw new InternalException('[authorization_code]', 500, 'The authorization server did not return a valid access token.'); } // Find or create a local user account, and create a session for them. $user = $this->getFrameworkBridge()->getOrCreateUser($token->getResourceOwnerId()); $this->getFrameworkBridge()->login($user, $token); return $response->withStatus(302)->withHeader('Location', $url); }
php
public function authorize(ServerRequestInterface $request, ResponseInterface $response, $url = '/', $destination = null, $options = []) { // Make sure we're making request with the authorization_code grant. $this->asUser(); $url = $this->getFrameworkBridge()->prepareUrl($url); $query = $request->getQueryParams(); // If we don't have an authorization code then make one and redirect. if (! isset($query['code'])) { $params = array_merge($options, [ 'scope' => $this->config['authorization_code']['scope'], 'destination' => ! empty($destination) ? $destination : null, ]); $authorizationUrl = $this->getAuthorizationServer()->getAuthorizationUrl($params); // Get the state generated for you and store it to the session. $state = $this->getAuthorizationServer()->getState(); $this->getFrameworkBridge()->saveStateToken($state); // Redirect the user to the authorization URL. return $response->withStatus(302)->withHeader('Location', $authorizationUrl); } // Check given state against previously stored one to mitigate CSRF attack if (! (isset($query['state']) && $query['state'] === $this->getFrameworkBridge()->getStateToken())) { throw new InternalException('[authorization_code]', 500, 'The OAuth state field did not match.'); } $token = $this->getTokenByAuthorizationCodeGrant($query['code']); if (! $token) { throw new InternalException('[authorization_code]', 500, 'The authorization server did not return a valid access token.'); } // Find or create a local user account, and create a session for them. $user = $this->getFrameworkBridge()->getOrCreateUser($token->getResourceOwnerId()); $this->getFrameworkBridge()->login($user, $token); return $response->withStatus(302)->withHeader('Location', $url); }
[ "public", "function", "authorize", "(", "ServerRequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ",", "$", "url", "=", "'/'", ",", "$", "destination", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "// Make sure we're making request with the authorization_code grant.", "$", "this", "->", "asUser", "(", ")", ";", "$", "url", "=", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "prepareUrl", "(", "$", "url", ")", ";", "$", "query", "=", "$", "request", "->", "getQueryParams", "(", ")", ";", "// If we don't have an authorization code then make one and redirect.", "if", "(", "!", "isset", "(", "$", "query", "[", "'code'", "]", ")", ")", "{", "$", "params", "=", "array_merge", "(", "$", "options", ",", "[", "'scope'", "=>", "$", "this", "->", "config", "[", "'authorization_code'", "]", "[", "'scope'", "]", ",", "'destination'", "=>", "!", "empty", "(", "$", "destination", ")", "?", "$", "destination", ":", "null", ",", "]", ")", ";", "$", "authorizationUrl", "=", "$", "this", "->", "getAuthorizationServer", "(", ")", "->", "getAuthorizationUrl", "(", "$", "params", ")", ";", "// Get the state generated for you and store it to the session.", "$", "state", "=", "$", "this", "->", "getAuthorizationServer", "(", ")", "->", "getState", "(", ")", ";", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "saveStateToken", "(", "$", "state", ")", ";", "// Redirect the user to the authorization URL.", "return", "$", "response", "->", "withStatus", "(", "302", ")", "->", "withHeader", "(", "'Location'", ",", "$", "authorizationUrl", ")", ";", "}", "// Check given state against previously stored one to mitigate CSRF attack", "if", "(", "!", "(", "isset", "(", "$", "query", "[", "'state'", "]", ")", "&&", "$", "query", "[", "'state'", "]", "===", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "getStateToken", "(", ")", ")", ")", "{", "throw", "new", "InternalException", "(", "'[authorization_code]'", ",", "500", ",", "'The OAuth state field did not match.'", ")", ";", "}", "$", "token", "=", "$", "this", "->", "getTokenByAuthorizationCodeGrant", "(", "$", "query", "[", "'code'", "]", ")", ";", "if", "(", "!", "$", "token", ")", "{", "throw", "new", "InternalException", "(", "'[authorization_code]'", ",", "500", ",", "'The authorization server did not return a valid access token.'", ")", ";", "}", "// Find or create a local user account, and create a session for them.", "$", "user", "=", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "getOrCreateUser", "(", "$", "token", "->", "getResourceOwnerId", "(", ")", ")", ";", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "login", "(", "$", "user", ",", "$", "token", ")", ";", "return", "$", "response", "->", "withStatus", "(", "302", ")", "->", "withHeader", "(", "'Location'", ",", "$", "url", ")", ";", "}" ]
Handle the OpenID Connect authorization flow. @TODO: Merge $url & $destination into $options @param ServerRequestInterface $request @param ResponseInterface $response @param string $url - The destination URL to redirect to on a successful login. @param string $destination - the title for the post-login destination @param array $options - Array of options to apply @return ResponseInterface @throws InternalException
[ "Handle", "the", "OpenID", "Connect", "authorization", "flow", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L133-L172
35,314
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.logout
public function logout(ResponseInterface $response, $destination = '/') { // Make sure we're making request with the authorization_code grant. $this->asUser(); $this->getFrameworkBridge()->logout(); $destination = $this->getFrameworkBridge()->prepareUrl($destination); $ssoLogoutUrl = config('services.northstar.url').'/logout?redirect='.$destination; return $response->withStatus(302)->withHeader('Location', $ssoLogoutUrl); }
php
public function logout(ResponseInterface $response, $destination = '/') { // Make sure we're making request with the authorization_code grant. $this->asUser(); $this->getFrameworkBridge()->logout(); $destination = $this->getFrameworkBridge()->prepareUrl($destination); $ssoLogoutUrl = config('services.northstar.url').'/logout?redirect='.$destination; return $response->withStatus(302)->withHeader('Location', $ssoLogoutUrl); }
[ "public", "function", "logout", "(", "ResponseInterface", "$", "response", ",", "$", "destination", "=", "'/'", ")", "{", "// Make sure we're making request with the authorization_code grant.", "$", "this", "->", "asUser", "(", ")", ";", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "logout", "(", ")", ";", "$", "destination", "=", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "prepareUrl", "(", "$", "destination", ")", ";", "$", "ssoLogoutUrl", "=", "config", "(", "'services.northstar.url'", ")", ".", "'/logout?redirect='", ".", "$", "destination", ";", "return", "$", "response", "->", "withStatus", "(", "302", ")", "->", "withHeader", "(", "'Location'", ",", "$", "ssoLogoutUrl", ")", ";", "}" ]
Log a user out of the application and SSO service. @param ResponseInterface $response @param string $destination @return ResponseInterface
[ "Log", "a", "user", "out", "of", "the", "application", "and", "SSO", "service", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L181-L192
35,315
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.getTokenByRefreshTokenGrant
public function getTokenByRefreshTokenGrant(AccessToken $oldToken) { try { $token = $this->getAuthorizationServer()->getAccessToken('refresh_token', [ 'refresh_token' => $oldToken->getRefreshToken(), 'scope' => $this->config[$this->grant]['scope'], ]); $this->getFrameworkBridge()->persistUserToken($token); return $token; } catch (IdentityProviderException $e) { $this->getFrameworkBridge()->requestUserCredentials(); return null; } }
php
public function getTokenByRefreshTokenGrant(AccessToken $oldToken) { try { $token = $this->getAuthorizationServer()->getAccessToken('refresh_token', [ 'refresh_token' => $oldToken->getRefreshToken(), 'scope' => $this->config[$this->grant]['scope'], ]); $this->getFrameworkBridge()->persistUserToken($token); return $token; } catch (IdentityProviderException $e) { $this->getFrameworkBridge()->requestUserCredentials(); return null; } }
[ "public", "function", "getTokenByRefreshTokenGrant", "(", "AccessToken", "$", "oldToken", ")", "{", "try", "{", "$", "token", "=", "$", "this", "->", "getAuthorizationServer", "(", ")", "->", "getAccessToken", "(", "'refresh_token'", ",", "[", "'refresh_token'", "=>", "$", "oldToken", "->", "getRefreshToken", "(", ")", ",", "'scope'", "=>", "$", "this", "->", "config", "[", "$", "this", "->", "grant", "]", "[", "'scope'", "]", ",", "]", ")", ";", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "persistUserToken", "(", "$", "token", ")", ";", "return", "$", "token", ";", "}", "catch", "(", "IdentityProviderException", "$", "e", ")", "{", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "requestUserCredentials", "(", ")", ";", "return", "null", ";", "}", "}" ]
Re-authorize a user based on their stored refresh token. @param AccessToken $oldToken @return AccessToken
[ "Re", "-", "authorize", "a", "user", "based", "on", "their", "stored", "refresh", "token", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L200-L216
35,316
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.invalidateCurrentRefreshToken
public function invalidateCurrentRefreshToken() { if ($this->grant === 'client_credentials') { return; } $token = $this->getAccessToken(); if ($token) { $this->invalidateRefreshToken($token); } }
php
public function invalidateCurrentRefreshToken() { if ($this->grant === 'client_credentials') { return; } $token = $this->getAccessToken(); if ($token) { $this->invalidateRefreshToken($token); } }
[ "public", "function", "invalidateCurrentRefreshToken", "(", ")", "{", "if", "(", "$", "this", "->", "grant", "===", "'client_credentials'", ")", "{", "return", ";", "}", "$", "token", "=", "$", "this", "->", "getAccessToken", "(", ")", ";", "if", "(", "$", "token", ")", "{", "$", "this", "->", "invalidateRefreshToken", "(", "$", "token", ")", ";", "}", "}" ]
Invalidate the authenticated user's refresh token.
[ "Invalidate", "the", "authenticated", "user", "s", "refresh", "token", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L221-L231
35,317
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.invalidateRefreshToken
public function invalidateRefreshToken(AccessToken $token) { $this->getAuthorizationServer()->getAuthenticatedRequest('DELETE', $this->authorizationServerUri . '/v2/auth/token', $token, [ 'json' => [ 'token' => $token->getRefreshToken(), ], ]); $user = $this->getFrameworkBridge()->getUser($token->getResourceOwnerId()); $user->clearOAuthToken(); }
php
public function invalidateRefreshToken(AccessToken $token) { $this->getAuthorizationServer()->getAuthenticatedRequest('DELETE', $this->authorizationServerUri . '/v2/auth/token', $token, [ 'json' => [ 'token' => $token->getRefreshToken(), ], ]); $user = $this->getFrameworkBridge()->getUser($token->getResourceOwnerId()); $user->clearOAuthToken(); }
[ "public", "function", "invalidateRefreshToken", "(", "AccessToken", "$", "token", ")", "{", "$", "this", "->", "getAuthorizationServer", "(", ")", "->", "getAuthenticatedRequest", "(", "'DELETE'", ",", "$", "this", "->", "authorizationServerUri", ".", "'/v2/auth/token'", ",", "$", "token", ",", "[", "'json'", "=>", "[", "'token'", "=>", "$", "token", "->", "getRefreshToken", "(", ")", ",", "]", ",", "]", ")", ";", "$", "user", "=", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "getUser", "(", "$", "token", "->", "getResourceOwnerId", "(", ")", ")", ";", "$", "user", "->", "clearOAuthToken", "(", ")", ";", "}" ]
Invalidate the refresh token for the given access token. @param AccessToken $token
[ "Invalidate", "the", "refresh", "token", "for", "the", "given", "access", "token", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L238-L249
35,318
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.getAccessToken
protected function getAccessToken() { switch ($this->grant) { case 'provided_token': return $this->token; case 'client_credentials': return $this->getFrameworkBridge()->getClientToken(); case 'authorization_code': $user = $this->getFrameworkBridge()->getCurrentUser(); if (! $user) { return null; } return $user->getOAuthToken(); default: throw new \Exception('Unsupported grant type. Check $this->grant.'); } }
php
protected function getAccessToken() { switch ($this->grant) { case 'provided_token': return $this->token; case 'client_credentials': return $this->getFrameworkBridge()->getClientToken(); case 'authorization_code': $user = $this->getFrameworkBridge()->getCurrentUser(); if (! $user) { return null; } return $user->getOAuthToken(); default: throw new \Exception('Unsupported grant type. Check $this->grant.'); } }
[ "protected", "function", "getAccessToken", "(", ")", "{", "switch", "(", "$", "this", "->", "grant", ")", "{", "case", "'provided_token'", ":", "return", "$", "this", "->", "token", ";", "case", "'client_credentials'", ":", "return", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "getClientToken", "(", ")", ";", "case", "'authorization_code'", ":", "$", "user", "=", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "getCurrentUser", "(", ")", ";", "if", "(", "!", "$", "user", ")", "{", "return", "null", ";", "}", "return", "$", "user", "->", "getOAuthToken", "(", ")", ";", "default", ":", "throw", "new", "\\", "Exception", "(", "'Unsupported grant type. Check $this->grant.'", ")", ";", "}", "}" ]
Get the access token from the repository based on the chosen grant. @return AccessToken|null @throws \Exception
[ "Get", "the", "access", "token", "from", "the", "repository", "based", "on", "the", "chosen", "grant", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L308-L329
35,319
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.refreshIfExpired
public function refreshIfExpired() { $user = $this->getFrameworkBridge()->getCurrentUser(); if (! $user) { return null; } $token = $user->getOAuthToken(); if ($token && $token->hasExpired()) { $this->refreshAccessToken($token); } }
php
public function refreshIfExpired() { $user = $this->getFrameworkBridge()->getCurrentUser(); if (! $user) { return null; } $token = $user->getOAuthToken(); if ($token && $token->hasExpired()) { $this->refreshAccessToken($token); } }
[ "public", "function", "refreshIfExpired", "(", ")", "{", "$", "user", "=", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "getCurrentUser", "(", ")", ";", "if", "(", "!", "$", "user", ")", "{", "return", "null", ";", "}", "$", "token", "=", "$", "user", "->", "getOAuthToken", "(", ")", ";", "if", "(", "$", "token", "&&", "$", "token", "->", "hasExpired", "(", ")", ")", "{", "$", "this", "->", "refreshAccessToken", "(", "$", "token", ")", ";", "}", "}" ]
If a user is logged in & has an expired access token, fetch a new one using their refresh token. @return void
[ "If", "a", "user", "is", "logged", "in", "&", "has", "an", "expired", "access", "token", "fetch", "a", "new", "one", "using", "their", "refresh", "token", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L337-L349
35,320
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.refreshAccessToken
protected function refreshAccessToken($token) { switch ($this->grant) { case 'provided_token': throw new UnauthorizedException('[internal]', 'The provided token expired.'); case 'client_credentials': return $this->getTokenByClientCredentialsGrant(); case 'authorization_code': return $this->getTokenByRefreshTokenGrant($token); default: throw new \Exception('Unsupported grant type. Check $this->grant.'); } }
php
protected function refreshAccessToken($token) { switch ($this->grant) { case 'provided_token': throw new UnauthorizedException('[internal]', 'The provided token expired.'); case 'client_credentials': return $this->getTokenByClientCredentialsGrant(); case 'authorization_code': return $this->getTokenByRefreshTokenGrant($token); default: throw new \Exception('Unsupported grant type. Check $this->grant.'); } }
[ "protected", "function", "refreshAccessToken", "(", "$", "token", ")", "{", "switch", "(", "$", "this", "->", "grant", ")", "{", "case", "'provided_token'", ":", "throw", "new", "UnauthorizedException", "(", "'[internal]'", ",", "'The provided token expired.'", ")", ";", "case", "'client_credentials'", ":", "return", "$", "this", "->", "getTokenByClientCredentialsGrant", "(", ")", ";", "case", "'authorization_code'", ":", "return", "$", "this", "->", "getTokenByRefreshTokenGrant", "(", "$", "token", ")", ";", "default", ":", "throw", "new", "\\", "Exception", "(", "'Unsupported grant type. Check $this->grant.'", ")", ";", "}", "}" ]
Get a new access token based on the chosen grant. @param $token @return mixed @throws \Exception
[ "Get", "a", "new", "access", "token", "based", "on", "the", "chosen", "grant", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L358-L373
35,321
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.getAuthorizationHeader
protected function getAuthorizationHeader($forceRefresh = false) { $token = $this->getAccessToken(); // If we're using a token provided with the request, return it. if ($this->grant === 'provided_token') { return ['Authorization' => 'Bearer ' . $token->getToken()]; } // Don't attempt to refresh token if there isn't a logged-in user. $user = $this->getFrameworkBridge()->getCurrentUser(); if ($this->grant === 'authorization_code' && ! $user) { return []; } // If the token is expired, fetch a new one before making the request. if (! $token || ($token && $token->hasExpired()) || $forceRefresh) { $token = $this->refreshAccessToken($token); } return $this->getAuthorizationServer()->getHeaders($token); }
php
protected function getAuthorizationHeader($forceRefresh = false) { $token = $this->getAccessToken(); // If we're using a token provided with the request, return it. if ($this->grant === 'provided_token') { return ['Authorization' => 'Bearer ' . $token->getToken()]; } // Don't attempt to refresh token if there isn't a logged-in user. $user = $this->getFrameworkBridge()->getCurrentUser(); if ($this->grant === 'authorization_code' && ! $user) { return []; } // If the token is expired, fetch a new one before making the request. if (! $token || ($token && $token->hasExpired()) || $forceRefresh) { $token = $this->refreshAccessToken($token); } return $this->getAuthorizationServer()->getHeaders($token); }
[ "protected", "function", "getAuthorizationHeader", "(", "$", "forceRefresh", "=", "false", ")", "{", "$", "token", "=", "$", "this", "->", "getAccessToken", "(", ")", ";", "// If we're using a token provided with the request, return it.", "if", "(", "$", "this", "->", "grant", "===", "'provided_token'", ")", "{", "return", "[", "'Authorization'", "=>", "'Bearer '", ".", "$", "token", "->", "getToken", "(", ")", "]", ";", "}", "// Don't attempt to refresh token if there isn't a logged-in user.", "$", "user", "=", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "getCurrentUser", "(", ")", ";", "if", "(", "$", "this", "->", "grant", "===", "'authorization_code'", "&&", "!", "$", "user", ")", "{", "return", "[", "]", ";", "}", "// If the token is expired, fetch a new one before making the request.", "if", "(", "!", "$", "token", "||", "(", "$", "token", "&&", "$", "token", "->", "hasExpired", "(", ")", ")", "||", "$", "forceRefresh", ")", "{", "$", "token", "=", "$", "this", "->", "refreshAccessToken", "(", "$", "token", ")", ";", "}", "return", "$", "this", "->", "getAuthorizationServer", "(", ")", "->", "getHeaders", "(", "$", "token", ")", ";", "}" ]
Get the authorization header for a request, if needed. Overrides this empty method in RestApiClient. @param bool $forceRefresh - Should the token be refreshed, even if expiration timestamp hasn't passed? @return array @throws \Exception
[ "Get", "the", "authorization", "header", "for", "a", "request", "if", "needed", ".", "Overrides", "this", "empty", "method", "in", "RestApiClient", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L383-L404
35,322
DoSomething/gateway
src/AuthorizesWithOAuth2.php
AuthorizesWithOAuth2.getAuthorizationServer
protected function getAuthorizationServer() { if (! $this->authorizationServer) { $config = $this->config[$this->grant]; $options = [ 'url' => $this->authorizationServerUri, 'clientId' => $config['client_id'], 'clientSecret' => $config['client_secret'], ]; if (! empty($config['redirect_uri'])) { $options['redirectUri'] = $this->getFrameworkBridge()->prepareUrl($config['redirect_uri']); } // Allow setting a custom handler (for mocking requests in tests). if (! empty($this->config['handler'])) { $options['handler'] = $this->config['handler']; } $this->authorizationServer = new NorthstarOAuthProvider($options); } return $this->authorizationServer; }
php
protected function getAuthorizationServer() { if (! $this->authorizationServer) { $config = $this->config[$this->grant]; $options = [ 'url' => $this->authorizationServerUri, 'clientId' => $config['client_id'], 'clientSecret' => $config['client_secret'], ]; if (! empty($config['redirect_uri'])) { $options['redirectUri'] = $this->getFrameworkBridge()->prepareUrl($config['redirect_uri']); } // Allow setting a custom handler (for mocking requests in tests). if (! empty($this->config['handler'])) { $options['handler'] = $this->config['handler']; } $this->authorizationServer = new NorthstarOAuthProvider($options); } return $this->authorizationServer; }
[ "protected", "function", "getAuthorizationServer", "(", ")", "{", "if", "(", "!", "$", "this", "->", "authorizationServer", ")", "{", "$", "config", "=", "$", "this", "->", "config", "[", "$", "this", "->", "grant", "]", ";", "$", "options", "=", "[", "'url'", "=>", "$", "this", "->", "authorizationServerUri", ",", "'clientId'", "=>", "$", "config", "[", "'client_id'", "]", ",", "'clientSecret'", "=>", "$", "config", "[", "'client_secret'", "]", ",", "]", ";", "if", "(", "!", "empty", "(", "$", "config", "[", "'redirect_uri'", "]", ")", ")", "{", "$", "options", "[", "'redirectUri'", "]", "=", "$", "this", "->", "getFrameworkBridge", "(", ")", "->", "prepareUrl", "(", "$", "config", "[", "'redirect_uri'", "]", ")", ";", "}", "// Allow setting a custom handler (for mocking requests in tests).", "if", "(", "!", "empty", "(", "$", "this", "->", "config", "[", "'handler'", "]", ")", ")", "{", "$", "options", "[", "'handler'", "]", "=", "$", "this", "->", "config", "[", "'handler'", "]", ";", "}", "$", "this", "->", "authorizationServer", "=", "new", "NorthstarOAuthProvider", "(", "$", "options", ")", ";", "}", "return", "$", "this", "->", "authorizationServer", ";", "}" ]
Get the authorization server.
[ "Get", "the", "authorization", "server", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithOAuth2.php#L432-L456
35,323
Kajna/K-Core
Core/Pagination/Pagination.php
Pagination.create
public function create() { $r = '';// Variable to hold result // Calculate the total number of pages $num_pages = ceil($this->totalRows / $this->perPage); // If there is only one page make no links if ($num_pages === 1 || $this->totalRows === 0) { return ''; } $display_offset = (int)($this->numLinks / 2);//precalculate display offset according to numLinks $r .= '<div class="" id="pagination"><ul class="pagination">';//set opening tags $r .= '<li class="' . $this->liClass . '" id="1"><a href="' . $this->baseUrl . '/0/' . $this->perPage . $this->extraParams . '">&laquo</a></li>';//set go to first tag $start = 0; $end = $num_pages; if (!($num_pages <= $this->numLinks)) {//if total pages is less than numLinks display all pages at once $cur_link_number = ($this->curOffset / $this->perPage); if (($cur_link_number) <= $display_offset) {//if current link in first set of links $start = 0; $end = $this->numLinks; } elseif ($num_pages - $cur_link_number <= $display_offset) {//if current link in last set of links $start = $num_pages - $this->numLinks; $end = $num_pages; } else {//if current link in middle set of links $start = $cur_link_number - $display_offset; $end = $cur_link_number + $display_offset + 1; } } // Create links according to parameters for ($i = $start; $i < $end; ++$i) {// Create links tags $offset = $i * $this->perPage;// Set offset to pass to jquery function if ($offset != $this->curOffset) $class = ''; else $class = ' active';// Set current link active // Add link to result variable $r .= '<li class="' . $this->liClass . $class . '" id="' . ($i + 1) . '"> <a href="' . $this->baseUrl . '/' . ($i * $this->perPage) . '/' . $this->perPage . $this->extraParams . '">' . ($i + 1) . '</a></li>'; } $r .= '<li class="' . $this->liClass . '" id="' . $num_pages . '"><a href="' . $this->baseUrl . '/' . (($num_pages - 1) * $this->perPage) . '/' . $this->perPage . $this->extraParams . '">»</a></li>';//set go to last tag $r .= '</div><ul>';// Set closing tags return $r;// Return final result }
php
public function create() { $r = '';// Variable to hold result // Calculate the total number of pages $num_pages = ceil($this->totalRows / $this->perPage); // If there is only one page make no links if ($num_pages === 1 || $this->totalRows === 0) { return ''; } $display_offset = (int)($this->numLinks / 2);//precalculate display offset according to numLinks $r .= '<div class="" id="pagination"><ul class="pagination">';//set opening tags $r .= '<li class="' . $this->liClass . '" id="1"><a href="' . $this->baseUrl . '/0/' . $this->perPage . $this->extraParams . '">&laquo</a></li>';//set go to first tag $start = 0; $end = $num_pages; if (!($num_pages <= $this->numLinks)) {//if total pages is less than numLinks display all pages at once $cur_link_number = ($this->curOffset / $this->perPage); if (($cur_link_number) <= $display_offset) {//if current link in first set of links $start = 0; $end = $this->numLinks; } elseif ($num_pages - $cur_link_number <= $display_offset) {//if current link in last set of links $start = $num_pages - $this->numLinks; $end = $num_pages; } else {//if current link in middle set of links $start = $cur_link_number - $display_offset; $end = $cur_link_number + $display_offset + 1; } } // Create links according to parameters for ($i = $start; $i < $end; ++$i) {// Create links tags $offset = $i * $this->perPage;// Set offset to pass to jquery function if ($offset != $this->curOffset) $class = ''; else $class = ' active';// Set current link active // Add link to result variable $r .= '<li class="' . $this->liClass . $class . '" id="' . ($i + 1) . '"> <a href="' . $this->baseUrl . '/' . ($i * $this->perPage) . '/' . $this->perPage . $this->extraParams . '">' . ($i + 1) . '</a></li>'; } $r .= '<li class="' . $this->liClass . '" id="' . $num_pages . '"><a href="' . $this->baseUrl . '/' . (($num_pages - 1) * $this->perPage) . '/' . $this->perPage . $this->extraParams . '">»</a></li>';//set go to last tag $r .= '</div><ul>';// Set closing tags return $r;// Return final result }
[ "public", "function", "create", "(", ")", "{", "$", "r", "=", "''", ";", "// Variable to hold result", "// Calculate the total number of pages", "$", "num_pages", "=", "ceil", "(", "$", "this", "->", "totalRows", "/", "$", "this", "->", "perPage", ")", ";", "// If there is only one page make no links", "if", "(", "$", "num_pages", "===", "1", "||", "$", "this", "->", "totalRows", "===", "0", ")", "{", "return", "''", ";", "}", "$", "display_offset", "=", "(", "int", ")", "(", "$", "this", "->", "numLinks", "/", "2", ")", ";", "//precalculate display offset according to numLinks", "$", "r", ".=", "'<div class=\"\" id=\"pagination\"><ul class=\"pagination\">'", ";", "//set opening tags", "$", "r", ".=", "'<li class=\"'", ".", "$", "this", "->", "liClass", ".", "'\" id=\"1\"><a href=\"'", ".", "$", "this", "->", "baseUrl", ".", "'/0/'", ".", "$", "this", "->", "perPage", ".", "$", "this", "->", "extraParams", ".", "'\">&laquo</a></li>'", ";", "//set go to first tag", "$", "start", "=", "0", ";", "$", "end", "=", "$", "num_pages", ";", "if", "(", "!", "(", "$", "num_pages", "<=", "$", "this", "->", "numLinks", ")", ")", "{", "//if total pages is less than numLinks display all pages at once", "$", "cur_link_number", "=", "(", "$", "this", "->", "curOffset", "/", "$", "this", "->", "perPage", ")", ";", "if", "(", "(", "$", "cur_link_number", ")", "<=", "$", "display_offset", ")", "{", "//if current link in first set of links", "$", "start", "=", "0", ";", "$", "end", "=", "$", "this", "->", "numLinks", ";", "}", "elseif", "(", "$", "num_pages", "-", "$", "cur_link_number", "<=", "$", "display_offset", ")", "{", "//if current link in last set of links", "$", "start", "=", "$", "num_pages", "-", "$", "this", "->", "numLinks", ";", "$", "end", "=", "$", "num_pages", ";", "}", "else", "{", "//if current link in middle set of links", "$", "start", "=", "$", "cur_link_number", "-", "$", "display_offset", ";", "$", "end", "=", "$", "cur_link_number", "+", "$", "display_offset", "+", "1", ";", "}", "}", "// Create links according to parameters", "for", "(", "$", "i", "=", "$", "start", ";", "$", "i", "<", "$", "end", ";", "++", "$", "i", ")", "{", "// Create links tags", "$", "offset", "=", "$", "i", "*", "$", "this", "->", "perPage", ";", "// Set offset to pass to jquery function", "if", "(", "$", "offset", "!=", "$", "this", "->", "curOffset", ")", "$", "class", "=", "''", ";", "else", "$", "class", "=", "' active'", ";", "// Set current link active", "// Add link to result variable", "$", "r", ".=", "'<li class=\"'", ".", "$", "this", "->", "liClass", ".", "$", "class", ".", "'\" id=\"'", ".", "(", "$", "i", "+", "1", ")", ".", "'\">\n <a href=\"'", ".", "$", "this", "->", "baseUrl", ".", "'/'", ".", "(", "$", "i", "*", "$", "this", "->", "perPage", ")", ".", "'/'", ".", "$", "this", "->", "perPage", ".", "$", "this", "->", "extraParams", ".", "'\">'", ".", "(", "$", "i", "+", "1", ")", ".", "'</a></li>'", ";", "}", "$", "r", ".=", "'<li class=\"'", ".", "$", "this", "->", "liClass", ".", "'\" id=\"'", ".", "$", "num_pages", ".", "'\"><a href=\"'", ".", "$", "this", "->", "baseUrl", ".", "'/'", ".", "(", "(", "$", "num_pages", "-", "1", ")", "*", "$", "this", "->", "perPage", ")", ".", "'/'", ".", "$", "this", "->", "perPage", ".", "$", "this", "->", "extraParams", ".", "'\">»</a></li>';", "/", "/set go to last tag", "$", "r", ".=", "'</div><ul>'", ";", "// Set closing tags", "return", "$", "r", ";", "// Return final result", "}" ]
Generate the pagination links. @return string (HTML of pagination menu)
[ "Generate", "the", "pagination", "links", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Pagination/Pagination.php#L115-L159
35,324
htmlburger/wpemerge-cli
src/Commands/Install.php
Install.shouldRemoveComposerAuthorInformation
protected function shouldRemoveComposerAuthorInformation( InputInterface $input, OutputInterface $output ) { $helper = $this->getHelper( 'question' ); $question = new ConfirmationQuestion( 'Would you like to remove author information from composer.json? <info>[y/N]</info> ', false ); $install = $helper->ask( $input, $output, $question ); $output->writeln( '' ); return $install; }
php
protected function shouldRemoveComposerAuthorInformation( InputInterface $input, OutputInterface $output ) { $helper = $this->getHelper( 'question' ); $question = new ConfirmationQuestion( 'Would you like to remove author information from composer.json? <info>[y/N]</info> ', false ); $install = $helper->ask( $input, $output, $question ); $output->writeln( '' ); return $install; }
[ "protected", "function", "shouldRemoveComposerAuthorInformation", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "helper", "=", "$", "this", "->", "getHelper", "(", "'question'", ")", ";", "$", "question", "=", "new", "ConfirmationQuestion", "(", "'Would you like to remove author information from composer.json? <info>[y/N]</info> '", ",", "false", ")", ";", "$", "install", "=", "$", "helper", "->", "ask", "(", "$", "input", ",", "$", "output", ",", "$", "question", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "return", "$", "install", ";", "}" ]
Check whether composer.json should be cleaned of author information @param InputInterface $input @param OutputInterface $output @return boolean
[ "Check", "whether", "composer", ".", "json", "should", "be", "cleaned", "of", "author", "information" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L72-L84
35,325
htmlburger/wpemerge-cli
src/Commands/Install.php
Install.removeComposerAuthorInformation
protected function removeComposerAuthorInformation( InputInterface $input, OutputInterface $output ) { $command = $this->getApplication()->find( 'install:clean-composer' ); $output->write( '<comment>Cleaning <info>composer.json</info> ...</comment>' ); $command->run( new ArrayInput( [ 'command' => 'install:carbon-fields', ] ), new NullOutput() ); $output->writeln( ' <info>Done</info>' ); }
php
protected function removeComposerAuthorInformation( InputInterface $input, OutputInterface $output ) { $command = $this->getApplication()->find( 'install:clean-composer' ); $output->write( '<comment>Cleaning <info>composer.json</info> ...</comment>' ); $command->run( new ArrayInput( [ 'command' => 'install:carbon-fields', ] ), new NullOutput() ); $output->writeln( ' <info>Done</info>' ); }
[ "protected", "function", "removeComposerAuthorInformation", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "command", "=", "$", "this", "->", "getApplication", "(", ")", "->", "find", "(", "'install:clean-composer'", ")", ";", "$", "output", "->", "write", "(", "'<comment>Cleaning <info>composer.json</info> ...</comment>'", ")", ";", "$", "command", "->", "run", "(", "new", "ArrayInput", "(", "[", "'command'", "=>", "'install:carbon-fields'", ",", "]", ")", ",", "new", "NullOutput", "(", ")", ")", ";", "$", "output", "->", "writeln", "(", "' <info>Done</info>'", ")", ";", "}" ]
Remove author information from composer.json @param InputInterface $input @param OutputInterface $output @return void
[ "Remove", "author", "information", "from", "composer", ".", "json" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L93-L103
35,326
htmlburger/wpemerge-cli
src/Commands/Install.php
Install.shouldInstallCssFramework
protected function shouldInstallCssFramework( InputInterface $input, OutputInterface $output ) { $helper = $this->getHelper( 'question' ); $question = new ChoiceQuestion( 'Please select a CSS framework:', ['None', 'Normalize.css', 'Bootstrap', 'Bulma', 'Foundation', 'Tachyons', 'Tailwind CSS', 'Spectre.css'], 0 ); $css_framework = $helper->ask( $input, $output, $question ); $output->writeln( '' ); return $css_framework; }
php
protected function shouldInstallCssFramework( InputInterface $input, OutputInterface $output ) { $helper = $this->getHelper( 'question' ); $question = new ChoiceQuestion( 'Please select a CSS framework:', ['None', 'Normalize.css', 'Bootstrap', 'Bulma', 'Foundation', 'Tachyons', 'Tailwind CSS', 'Spectre.css'], 0 ); $css_framework = $helper->ask( $input, $output, $question ); $output->writeln( '' ); return $css_framework; }
[ "protected", "function", "shouldInstallCssFramework", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "helper", "=", "$", "this", "->", "getHelper", "(", "'question'", ")", ";", "$", "question", "=", "new", "ChoiceQuestion", "(", "'Please select a CSS framework:'", ",", "[", "'None'", ",", "'Normalize.css'", ",", "'Bootstrap'", ",", "'Bulma'", ",", "'Foundation'", ",", "'Tachyons'", ",", "'Tailwind CSS'", ",", "'Spectre.css'", "]", ",", "0", ")", ";", "$", "css_framework", "=", "$", "helper", "->", "ask", "(", "$", "input", ",", "$", "output", ",", "$", "question", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "return", "$", "css_framework", ";", "}" ]
Check whether any CSS framework should be installed @param InputInterface $input @param OutputInterface $output @return string
[ "Check", "whether", "any", "CSS", "framework", "should", "be", "installed" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L148-L161
35,327
htmlburger/wpemerge-cli
src/Commands/Install.php
Install.installCssFramework
protected function installCssFramework( InputInterface $input, OutputInterface $output, $css_framework ) { $command = $this->getApplication()->find( 'install:css-framework' ); $this->runInstallCommand( $css_framework, $command, new ArrayInput( [ 'command' => 'install:css-framework', 'css-framework' => $css_framework, ] ), $output ); }
php
protected function installCssFramework( InputInterface $input, OutputInterface $output, $css_framework ) { $command = $this->getApplication()->find( 'install:css-framework' ); $this->runInstallCommand( $css_framework, $command, new ArrayInput( [ 'command' => 'install:css-framework', 'css-framework' => $css_framework, ] ), $output ); }
[ "protected", "function", "installCssFramework", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ",", "$", "css_framework", ")", "{", "$", "command", "=", "$", "this", "->", "getApplication", "(", ")", "->", "find", "(", "'install:css-framework'", ")", ";", "$", "this", "->", "runInstallCommand", "(", "$", "css_framework", ",", "$", "command", ",", "new", "ArrayInput", "(", "[", "'command'", "=>", "'install:css-framework'", ",", "'css-framework'", "=>", "$", "css_framework", ",", "]", ")", ",", "$", "output", ")", ";", "}" ]
Install any CSS framework @param InputInterface $input @param OutputInterface $output @param string $css_framework @return void
[ "Install", "any", "CSS", "framework" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L171-L178
35,328
htmlburger/wpemerge-cli
src/Commands/Install.php
Install.installFontAwesome
protected function installFontAwesome( InputInterface $input, OutputInterface $output ) { $command = $this->getApplication()->find( 'install:font-awesome' ); $this->runInstallCommand( 'Font Awesome', $command, new ArrayInput( [ 'command' => 'install:font-awesome', ] ), $output ); }
php
protected function installFontAwesome( InputInterface $input, OutputInterface $output ) { $command = $this->getApplication()->find( 'install:font-awesome' ); $this->runInstallCommand( 'Font Awesome', $command, new ArrayInput( [ 'command' => 'install:font-awesome', ] ), $output ); }
[ "protected", "function", "installFontAwesome", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "command", "=", "$", "this", "->", "getApplication", "(", ")", "->", "find", "(", "'install:font-awesome'", ")", ";", "$", "this", "->", "runInstallCommand", "(", "'Font Awesome'", ",", "$", "command", ",", "new", "ArrayInput", "(", "[", "'command'", "=>", "'install:font-awesome'", ",", "]", ")", ",", "$", "output", ")", ";", "}" ]
Install Font Awesome @param InputInterface $input @param OutputInterface $output @return void
[ "Install", "Font", "Awesome" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L208-L214
35,329
htmlburger/wpemerge-cli
src/Commands/Install.php
Install.shouldProceedWithInstall
protected function shouldProceedWithInstall( InputInterface $input, OutputInterface $output, $config ) { $helper = $this->getHelper( 'question' ); $output->writeln( 'Configuration:' ); $output->writeln( str_pad( 'Clean composer.json: ', 25 ) . ( $config['remove_composer_author_information'] ? '<info>Yes</info>' : '<comment>No</comment>' ) ); $output->writeln( str_pad( 'Install Carbon Fields: ', 25 ) . ( $config['install_carbon_fields'] ? '<info>Yes</info>' : '<comment>No</comment>' ) ); $output->writeln( str_pad( 'Install CSS Framework: ', 25 ) . '<info>' . $config['install_css_framework'] . '</info>' ); $output->writeln( str_pad( 'Install Font Awesome: ', 25 ) . ( $config['install_font_awesome'] ? '<info>Yes</info>' : '<comment>No</comment>' ) ); $output->writeln( '' ); $question = new ConfirmationQuestion( 'Proceed with installation? <info>[Y/n]</info> ', true ); $proceed = $helper->ask( $input, $output, $question ); $output->writeln( '' ); return $proceed; }
php
protected function shouldProceedWithInstall( InputInterface $input, OutputInterface $output, $config ) { $helper = $this->getHelper( 'question' ); $output->writeln( 'Configuration:' ); $output->writeln( str_pad( 'Clean composer.json: ', 25 ) . ( $config['remove_composer_author_information'] ? '<info>Yes</info>' : '<comment>No</comment>' ) ); $output->writeln( str_pad( 'Install Carbon Fields: ', 25 ) . ( $config['install_carbon_fields'] ? '<info>Yes</info>' : '<comment>No</comment>' ) ); $output->writeln( str_pad( 'Install CSS Framework: ', 25 ) . '<info>' . $config['install_css_framework'] . '</info>' ); $output->writeln( str_pad( 'Install Font Awesome: ', 25 ) . ( $config['install_font_awesome'] ? '<info>Yes</info>' : '<comment>No</comment>' ) ); $output->writeln( '' ); $question = new ConfirmationQuestion( 'Proceed with installation? <info>[Y/n]</info> ', true ); $proceed = $helper->ask( $input, $output, $question ); $output->writeln( '' ); return $proceed; }
[ "protected", "function", "shouldProceedWithInstall", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ",", "$", "config", ")", "{", "$", "helper", "=", "$", "this", "->", "getHelper", "(", "'question'", ")", ";", "$", "output", "->", "writeln", "(", "'Configuration:'", ")", ";", "$", "output", "->", "writeln", "(", "str_pad", "(", "'Clean composer.json: '", ",", "25", ")", ".", "(", "$", "config", "[", "'remove_composer_author_information'", "]", "?", "'<info>Yes</info>'", ":", "'<comment>No</comment>'", ")", ")", ";", "$", "output", "->", "writeln", "(", "str_pad", "(", "'Install Carbon Fields: '", ",", "25", ")", ".", "(", "$", "config", "[", "'install_carbon_fields'", "]", "?", "'<info>Yes</info>'", ":", "'<comment>No</comment>'", ")", ")", ";", "$", "output", "->", "writeln", "(", "str_pad", "(", "'Install CSS Framework: '", ",", "25", ")", ".", "'<info>'", ".", "$", "config", "[", "'install_css_framework'", "]", ".", "'</info>'", ")", ";", "$", "output", "->", "writeln", "(", "str_pad", "(", "'Install Font Awesome: '", ",", "25", ")", ".", "(", "$", "config", "[", "'install_font_awesome'", "]", "?", "'<info>Yes</info>'", ":", "'<comment>No</comment>'", ")", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "$", "question", "=", "new", "ConfirmationQuestion", "(", "'Proceed with installation? <info>[Y/n]</info> '", ",", "true", ")", ";", "$", "proceed", "=", "$", "helper", "->", "ask", "(", "$", "input", ",", "$", "output", ",", "$", "question", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "return", "$", "proceed", ";", "}" ]
Check whether we should proceed with installation @param InputInterface $input @param OutputInterface $output @param array $config @return boolean
[ "Check", "whether", "we", "should", "proceed", "with", "installation" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L224-L260
35,330
htmlburger/wpemerge-cli
src/Commands/Install.php
Install.runInstallCommand
protected function runInstallCommand( $label, Command $command, InputInterface $input, OutputInterface $output ) { $buffered_output = new BufferedOutput(); $buffered_output->setVerbosity( $output->getVerbosity() ); $output->write( '<comment>Installing <info>' . $label . '</info> ...</comment>' ); $command->run( $input, $buffered_output ); $output->writeln( ' <info>Done</info>' ); $buffered_output_value = $buffered_output->fetch(); if ( ! empty( $buffered_output_value ) ) { $output->writeln( '---' ); $output->writeln( trim( $buffered_output_value ) ); $output->writeln( '---' ); } }
php
protected function runInstallCommand( $label, Command $command, InputInterface $input, OutputInterface $output ) { $buffered_output = new BufferedOutput(); $buffered_output->setVerbosity( $output->getVerbosity() ); $output->write( '<comment>Installing <info>' . $label . '</info> ...</comment>' ); $command->run( $input, $buffered_output ); $output->writeln( ' <info>Done</info>' ); $buffered_output_value = $buffered_output->fetch(); if ( ! empty( $buffered_output_value ) ) { $output->writeln( '---' ); $output->writeln( trim( $buffered_output_value ) ); $output->writeln( '---' ); } }
[ "protected", "function", "runInstallCommand", "(", "$", "label", ",", "Command", "$", "command", ",", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "buffered_output", "=", "new", "BufferedOutput", "(", ")", ";", "$", "buffered_output", "->", "setVerbosity", "(", "$", "output", "->", "getVerbosity", "(", ")", ")", ";", "$", "output", "->", "write", "(", "'<comment>Installing <info>'", ".", "$", "label", ".", "'</info> ...</comment>'", ")", ";", "$", "command", "->", "run", "(", "$", "input", ",", "$", "buffered_output", ")", ";", "$", "output", "->", "writeln", "(", "' <info>Done</info>'", ")", ";", "$", "buffered_output_value", "=", "$", "buffered_output", "->", "fetch", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "buffered_output_value", ")", ")", "{", "$", "output", "->", "writeln", "(", "'---'", ")", ";", "$", "output", "->", "writeln", "(", "trim", "(", "$", "buffered_output_value", ")", ")", ";", "$", "output", "->", "writeln", "(", "'---'", ")", ";", "}", "}" ]
Install a preset @param string $label @param Command $command @param InputInterface $input @param OutputInterface $output @return void
[ "Install", "a", "preset" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Commands/Install.php#L271-L285
35,331
mirko-pagliai/php-tools
src/BodyParser.php
BodyParser.extractLinks
public function extractLinks() { if ($this->extractedLinks) { return $this->extractedLinks; } if (!is_html($this->body)) { return []; } $libxmlPreviousState = libxml_use_internal_errors(true); $dom = new DOMDocument; $dom->loadHTML($this->body); libxml_clear_errors(); libxml_use_internal_errors($libxmlPreviousState); $links = []; foreach ($this->tags as $tag => $attribute) { foreach ($dom->getElementsByTagName($tag) as $element) { $link = $element->getAttribute($attribute); if (!$link) { continue; } $links[] = clean_url(url_to_absolute($this->url, $link), true, true); } } return $this->extractedLinks = array_unique($links); }
php
public function extractLinks() { if ($this->extractedLinks) { return $this->extractedLinks; } if (!is_html($this->body)) { return []; } $libxmlPreviousState = libxml_use_internal_errors(true); $dom = new DOMDocument; $dom->loadHTML($this->body); libxml_clear_errors(); libxml_use_internal_errors($libxmlPreviousState); $links = []; foreach ($this->tags as $tag => $attribute) { foreach ($dom->getElementsByTagName($tag) as $element) { $link = $element->getAttribute($attribute); if (!$link) { continue; } $links[] = clean_url(url_to_absolute($this->url, $link), true, true); } } return $this->extractedLinks = array_unique($links); }
[ "public", "function", "extractLinks", "(", ")", "{", "if", "(", "$", "this", "->", "extractedLinks", ")", "{", "return", "$", "this", "->", "extractedLinks", ";", "}", "if", "(", "!", "is_html", "(", "$", "this", "->", "body", ")", ")", "{", "return", "[", "]", ";", "}", "$", "libxmlPreviousState", "=", "libxml_use_internal_errors", "(", "true", ")", ";", "$", "dom", "=", "new", "DOMDocument", ";", "$", "dom", "->", "loadHTML", "(", "$", "this", "->", "body", ")", ";", "libxml_clear_errors", "(", ")", ";", "libxml_use_internal_errors", "(", "$", "libxmlPreviousState", ")", ";", "$", "links", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "tags", "as", "$", "tag", "=>", "$", "attribute", ")", "{", "foreach", "(", "$", "dom", "->", "getElementsByTagName", "(", "$", "tag", ")", "as", "$", "element", ")", "{", "$", "link", "=", "$", "element", "->", "getAttribute", "(", "$", "attribute", ")", ";", "if", "(", "!", "$", "link", ")", "{", "continue", ";", "}", "$", "links", "[", "]", "=", "clean_url", "(", "url_to_absolute", "(", "$", "this", "->", "url", ",", "$", "link", ")", ",", "true", ",", "true", ")", ";", "}", "}", "return", "$", "this", "->", "extractedLinks", "=", "array_unique", "(", "$", "links", ")", ";", "}" ]
Extracs links from body @return array @uses $body @uses $extractedLinks @uses $tags @uses $url
[ "Extracs", "links", "from", "body" ]
46003b05490de4b570b46c6377f1e09139ffe43b
https://github.com/mirko-pagliai/php-tools/blob/46003b05490de4b570b46c6377f1e09139ffe43b/src/BodyParser.php#L87-L120
35,332
mcrumm/pecan
src/Console/Output/PecanOutput.php
PecanOutput.initializePipes
protected function initializePipes() { $this->pipes = [ fopen($this->hasStdoutSupport() ? 'php://stdout' : 'php://output', 'w'), fopen('php://stderr', 'w'), ]; foreach ($this->pipes as $pipe) { stream_set_blocking($pipe, 0); } }
php
protected function initializePipes() { $this->pipes = [ fopen($this->hasStdoutSupport() ? 'php://stdout' : 'php://output', 'w'), fopen('php://stderr', 'w'), ]; foreach ($this->pipes as $pipe) { stream_set_blocking($pipe, 0); } }
[ "protected", "function", "initializePipes", "(", ")", "{", "$", "this", "->", "pipes", "=", "[", "fopen", "(", "$", "this", "->", "hasStdoutSupport", "(", ")", "?", "'php://stdout'", ":", "'php://output'", ",", "'w'", ")", ",", "fopen", "(", "'php://stderr'", ",", "'w'", ")", ",", "]", ";", "foreach", "(", "$", "this", "->", "pipes", "as", "$", "pipe", ")", "{", "stream_set_blocking", "(", "$", "pipe", ",", "0", ")", ";", "}", "}" ]
Initialize the STDOUT and STDERR pipes.
[ "Initialize", "the", "STDOUT", "and", "STDERR", "pipes", "." ]
f35f01249587a4df45c7d3ab78f3e51919471177
https://github.com/mcrumm/pecan/blob/f35f01249587a4df45c7d3ab78f3e51919471177/src/Console/Output/PecanOutput.php#L66-L76
35,333
railken/amethyst-template
src/Managers/TemplateManager.php
TemplateManager.getGeneratorOrFail
public function getGeneratorOrFail(string $filetype) { $generators = config('amethyst.template.generators', []); $generator = isset($generators[$filetype]) ? $generators[$filetype] : null; if (!$generator) { throw new Exceptions\GeneratorNotFoundException(sprintf('No generator found for: %s', $filetype)); } return $generator; }
php
public function getGeneratorOrFail(string $filetype) { $generators = config('amethyst.template.generators', []); $generator = isset($generators[$filetype]) ? $generators[$filetype] : null; if (!$generator) { throw new Exceptions\GeneratorNotFoundException(sprintf('No generator found for: %s', $filetype)); } return $generator; }
[ "public", "function", "getGeneratorOrFail", "(", "string", "$", "filetype", ")", "{", "$", "generators", "=", "config", "(", "'amethyst.template.generators'", ",", "[", "]", ")", ";", "$", "generator", "=", "isset", "(", "$", "generators", "[", "$", "filetype", "]", ")", "?", "$", "generators", "[", "$", "filetype", "]", ":", "null", ";", "if", "(", "!", "$", "generator", ")", "{", "throw", "new", "Exceptions", "\\", "GeneratorNotFoundException", "(", "sprintf", "(", "'No generator found for: %s'", ",", "$", "filetype", ")", ")", ";", "}", "return", "$", "generator", ";", "}" ]
Retrieve the generator given the template or throw exception. @param string $filetype @return \Railken\Template\Generators\GeneratorContract
[ "Retrieve", "the", "generator", "given", "the", "template", "or", "throw", "exception", "." ]
211d696dd5636b85e44ab27061f72a4f792b128c
https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L33-L44
35,334
railken/amethyst-template
src/Managers/TemplateManager.php
TemplateManager.render
public function render(DataBuilder $data_builder, string $filetype, $parameters, array $data = []) { $result = new Result(); try { $bag = new Bag($parameters); $bag->set('content', $this->renderRaw($filetype, strval($bag->get('content')), $data)); $result->setResources(new Collection([$bag->toArray()])); } catch (\Twig_Error $e) { $e = new Exceptions\TemplateRenderException($e->getRawMessage().' on line '.$e->getTemplateLine()); $result->addErrors(new Collection([$e])); } return $result; }
php
public function render(DataBuilder $data_builder, string $filetype, $parameters, array $data = []) { $result = new Result(); try { $bag = new Bag($parameters); $bag->set('content', $this->renderRaw($filetype, strval($bag->get('content')), $data)); $result->setResources(new Collection([$bag->toArray()])); } catch (\Twig_Error $e) { $e = new Exceptions\TemplateRenderException($e->getRawMessage().' on line '.$e->getTemplateLine()); $result->addErrors(new Collection([$e])); } return $result; }
[ "public", "function", "render", "(", "DataBuilder", "$", "data_builder", ",", "string", "$", "filetype", ",", "$", "parameters", ",", "array", "$", "data", "=", "[", "]", ")", "{", "$", "result", "=", "new", "Result", "(", ")", ";", "try", "{", "$", "bag", "=", "new", "Bag", "(", "$", "parameters", ")", ";", "$", "bag", "->", "set", "(", "'content'", ",", "$", "this", "->", "renderRaw", "(", "$", "filetype", ",", "strval", "(", "$", "bag", "->", "get", "(", "'content'", ")", ")", ",", "$", "data", ")", ")", ";", "$", "result", "->", "setResources", "(", "new", "Collection", "(", "[", "$", "bag", "->", "toArray", "(", ")", "]", ")", ")", ";", "}", "catch", "(", "\\", "Twig_Error", "$", "e", ")", "{", "$", "e", "=", "new", "Exceptions", "\\", "TemplateRenderException", "(", "$", "e", "->", "getRawMessage", "(", ")", ".", "' on line '", ".", "$", "e", "->", "getTemplateLine", "(", ")", ")", ";", "$", "result", "->", "addErrors", "(", "new", "Collection", "(", "[", "$", "e", "]", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Render an email. @param DataBuilder $data_builder @param string $filetype @param array $parameters @param array $data @return \Railken\Lem\Contracts\ResultContract
[ "Render", "an", "email", "." ]
211d696dd5636b85e44ab27061f72a4f792b128c
https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L56-L73
35,335
railken/amethyst-template
src/Managers/TemplateManager.php
TemplateManager.renderRaw
public function renderRaw(string $filetype, string $content, array $data) { $generator = $this->getGeneratorOrFail($filetype); $generator = new $generator(); return $generator->generateAndRender($content, $data); }
php
public function renderRaw(string $filetype, string $content, array $data) { $generator = $this->getGeneratorOrFail($filetype); $generator = new $generator(); return $generator->generateAndRender($content, $data); }
[ "public", "function", "renderRaw", "(", "string", "$", "filetype", ",", "string", "$", "content", ",", "array", "$", "data", ")", "{", "$", "generator", "=", "$", "this", "->", "getGeneratorOrFail", "(", "$", "filetype", ")", ";", "$", "generator", "=", "new", "$", "generator", "(", ")", ";", "return", "$", "generator", "->", "generateAndRender", "(", "$", "content", ",", "$", "data", ")", ";", "}" ]
Render given template with data. @param string $filetype @param string $content @param array $data @return mixed
[ "Render", "given", "template", "with", "data", "." ]
211d696dd5636b85e44ab27061f72a4f792b128c
https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L84-L90
35,336
railken/amethyst-template
src/Managers/TemplateManager.php
TemplateManager.renderMock
public function renderMock(Template $template) { return $this->render($template->data_builder, $template->filetype, ['content' => $template->content], Yaml::parse((string) $template->data_builder->mock_data)); }
php
public function renderMock(Template $template) { return $this->render($template->data_builder, $template->filetype, ['content' => $template->content], Yaml::parse((string) $template->data_builder->mock_data)); }
[ "public", "function", "renderMock", "(", "Template", "$", "template", ")", "{", "return", "$", "this", "->", "render", "(", "$", "template", "->", "data_builder", ",", "$", "template", "->", "filetype", ",", "[", "'content'", "=>", "$", "template", "->", "content", "]", ",", "Yaml", "::", "parse", "(", "(", "string", ")", "$", "template", "->", "data_builder", "->", "mock_data", ")", ")", ";", "}" ]
Render mock template. @param Template $template @return mixed
[ "Render", "mock", "template", "." ]
211d696dd5636b85e44ab27061f72a4f792b128c
https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L99-L102
35,337
railken/amethyst-template
src/Managers/TemplateManager.php
TemplateManager.checksumByPath
public function checksumByPath(string $path) { return file_exists($path) ? $this->checksum((string) file_get_contents($path)) : null; }
php
public function checksumByPath(string $path) { return file_exists($path) ? $this->checksum((string) file_get_contents($path)) : null; }
[ "public", "function", "checksumByPath", "(", "string", "$", "path", ")", "{", "return", "file_exists", "(", "$", "path", ")", "?", "$", "this", "->", "checksum", "(", "(", "string", ")", "file_get_contents", "(", "$", "path", ")", ")", ":", "null", ";", "}" ]
Calculate checksum by path file. @param string $path @return string|null
[ "Calculate", "checksum", "by", "path", "file", "." ]
211d696dd5636b85e44ab27061f72a4f792b128c
https://github.com/railken/amethyst-template/blob/211d696dd5636b85e44ab27061f72a4f792b128c/src/Managers/TemplateManager.php#L121-L124
35,338
TheBnl/silverstripe-pageslices
src/controller/PageSliceControllerExtension.php
PageSliceControllerExtension.handleSlice
public function handleSlice() { if (!$id = $this->owner->getRequest()->param('ID')) { return false; } $sliceRelations = array(); if (!$hasManyRelations = $this->owner->data()->hasMany()) { return false; } foreach ($hasManyRelations as $relationName => $relationClass) { if ($relationClass == PageSlice::class || is_subclass_of($relationClass, PageSlice::class)) { $sliceRelations[] = $relationName; } } $slice = null; foreach ($sliceRelations as $sliceRelation) { if ($slice) { break; } /** @var PageSlice $slice */ $slice = $this->owner->data()->$sliceRelation()->find('ID', $id); } if (!$slice) { user_error('No slice found', E_USER_ERROR); } return $slice->getController(); }
php
public function handleSlice() { if (!$id = $this->owner->getRequest()->param('ID')) { return false; } $sliceRelations = array(); if (!$hasManyRelations = $this->owner->data()->hasMany()) { return false; } foreach ($hasManyRelations as $relationName => $relationClass) { if ($relationClass == PageSlice::class || is_subclass_of($relationClass, PageSlice::class)) { $sliceRelations[] = $relationName; } } $slice = null; foreach ($sliceRelations as $sliceRelation) { if ($slice) { break; } /** @var PageSlice $slice */ $slice = $this->owner->data()->$sliceRelation()->find('ID', $id); } if (!$slice) { user_error('No slice found', E_USER_ERROR); } return $slice->getController(); }
[ "public", "function", "handleSlice", "(", ")", "{", "if", "(", "!", "$", "id", "=", "$", "this", "->", "owner", "->", "getRequest", "(", ")", "->", "param", "(", "'ID'", ")", ")", "{", "return", "false", ";", "}", "$", "sliceRelations", "=", "array", "(", ")", ";", "if", "(", "!", "$", "hasManyRelations", "=", "$", "this", "->", "owner", "->", "data", "(", ")", "->", "hasMany", "(", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "hasManyRelations", "as", "$", "relationName", "=>", "$", "relationClass", ")", "{", "if", "(", "$", "relationClass", "==", "PageSlice", "::", "class", "||", "is_subclass_of", "(", "$", "relationClass", ",", "PageSlice", "::", "class", ")", ")", "{", "$", "sliceRelations", "[", "]", "=", "$", "relationName", ";", "}", "}", "$", "slice", "=", "null", ";", "foreach", "(", "$", "sliceRelations", "as", "$", "sliceRelation", ")", "{", "if", "(", "$", "slice", ")", "{", "break", ";", "}", "/** @var PageSlice $slice */", "$", "slice", "=", "$", "this", "->", "owner", "->", "data", "(", ")", "->", "$", "sliceRelation", "(", ")", "->", "find", "(", "'ID'", ",", "$", "id", ")", ";", "}", "if", "(", "!", "$", "slice", ")", "{", "user_error", "(", "'No slice found'", ",", "E_USER_ERROR", ")", ";", "}", "return", "$", "slice", "->", "getController", "(", ")", ";", "}" ]
Handle the slice @return bool|PageSliceController
[ "Handle", "the", "slice" ]
5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b
https://github.com/TheBnl/silverstripe-pageslices/blob/5ac2f2a7b6d43e9e5b1852bbe47b0aaf98de168b/src/controller/PageSliceControllerExtension.php#L27-L58
35,339
railken/amethyst-common
src/ConfigurableModel.php
ConfigurableModel.ini
public function ini($config) { $this->table = Config::get($config.'.table'); $classSchema = Config::get($config.'.schema'); $schema = new $classSchema(); $attributes = collect(($schema)->getAttributes()); $this->internalAttributes = new Bag(); $this->iniFillable($attributes); $this->iniDates($attributes); $this->iniCasts($attributes); }
php
public function ini($config) { $this->table = Config::get($config.'.table'); $classSchema = Config::get($config.'.schema'); $schema = new $classSchema(); $attributes = collect(($schema)->getAttributes()); $this->internalAttributes = new Bag(); $this->iniFillable($attributes); $this->iniDates($attributes); $this->iniCasts($attributes); }
[ "public", "function", "ini", "(", "$", "config", ")", "{", "$", "this", "->", "table", "=", "Config", "::", "get", "(", "$", "config", ".", "'.table'", ")", ";", "$", "classSchema", "=", "Config", "::", "get", "(", "$", "config", ".", "'.schema'", ")", ";", "$", "schema", "=", "new", "$", "classSchema", "(", ")", ";", "$", "attributes", "=", "collect", "(", "(", "$", "schema", ")", "->", "getAttributes", "(", ")", ")", ";", "$", "this", "->", "internalAttributes", "=", "new", "Bag", "(", ")", ";", "$", "this", "->", "iniFillable", "(", "$", "attributes", ")", ";", "$", "this", "->", "iniDates", "(", "$", "attributes", ")", ";", "$", "this", "->", "iniCasts", "(", "$", "attributes", ")", ";", "}" ]
Initialize the model by the configuration. @param string $config
[ "Initialize", "the", "model", "by", "the", "configuration", "." ]
ee89a31531e267d454352e2caf02fd73be5babfe
https://github.com/railken/amethyst-common/blob/ee89a31531e267d454352e2caf02fd73be5babfe/src/ConfigurableModel.php#L20-L34
35,340
railken/amethyst-common
src/ConfigurableModel.php
ConfigurableModel.iniFillable
public function iniFillable(Collection $attributes) { $this->fillable = $attributes->filter(function ($attribute) { return $attribute->getFillable(); })->map(function ($attribute) { return $attribute->getName(); })->toArray(); }
php
public function iniFillable(Collection $attributes) { $this->fillable = $attributes->filter(function ($attribute) { return $attribute->getFillable(); })->map(function ($attribute) { return $attribute->getName(); })->toArray(); }
[ "public", "function", "iniFillable", "(", "Collection", "$", "attributes", ")", "{", "$", "this", "->", "fillable", "=", "$", "attributes", "->", "filter", "(", "function", "(", "$", "attribute", ")", "{", "return", "$", "attribute", "->", "getFillable", "(", ")", ";", "}", ")", "->", "map", "(", "function", "(", "$", "attribute", ")", "{", "return", "$", "attribute", "->", "getName", "(", ")", ";", "}", ")", "->", "toArray", "(", ")", ";", "}" ]
Initialize fillable by attributes. @param Collection $attributes
[ "Initialize", "fillable", "by", "attributes", "." ]
ee89a31531e267d454352e2caf02fd73be5babfe
https://github.com/railken/amethyst-common/blob/ee89a31531e267d454352e2caf02fd73be5babfe/src/ConfigurableModel.php#L41-L48
35,341
hail-framework/framework
src/Debugger/Bar.php
Bar.addPanel
public function addPanel(Bar\PanelInterface $panel, string $id = null): self { if ($id === null) { $c = 0; do { $id = \get_class($panel) . ($c++ ? "-$c" : ''); } while (isset($this->panels[$id])); } $this->panels[$id] = $panel; return $this; }
php
public function addPanel(Bar\PanelInterface $panel, string $id = null): self { if ($id === null) { $c = 0; do { $id = \get_class($panel) . ($c++ ? "-$c" : ''); } while (isset($this->panels[$id])); } $this->panels[$id] = $panel; return $this; }
[ "public", "function", "addPanel", "(", "Bar", "\\", "PanelInterface", "$", "panel", ",", "string", "$", "id", "=", "null", ")", ":", "self", "{", "if", "(", "$", "id", "===", "null", ")", "{", "$", "c", "=", "0", ";", "do", "{", "$", "id", "=", "\\", "get_class", "(", "$", "panel", ")", ".", "(", "$", "c", "++", "?", "\"-$c\"", ":", "''", ")", ";", "}", "while", "(", "isset", "(", "$", "this", "->", "panels", "[", "$", "id", "]", ")", ")", ";", "}", "$", "this", "->", "panels", "[", "$", "id", "]", "=", "$", "panel", ";", "return", "$", "this", ";", "}" ]
Add custom panel. @param Bar\PanelInterface $panel @param string $id @return static
[ "Add", "custom", "panel", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Bar.php#L35-L46
35,342
hail-framework/framework
src/Debugger/Bar.php
Bar.render
public function render(): void { $useSession = $this->useSession && \session_status() === PHP_SESSION_ACTIVE; $redirectQueue = &$_SESSION['_tracy']['redirect']; foreach (['bar', 'redirect', 'bluescreen'] as $key) { $queue = &$_SESSION['_tracy'][$key]; $queue = \array_slice((array) $queue, -10, null, true); $queue = \array_filter($queue, function ($item) { return isset($item['time']) && $item['time'] > \time() - 60; }); } $rows = []; if (Helpers::isAjax()) { if ($useSession) { $rows[] = (object) ['type' => 'ajax', 'panels' => $this->renderPanels('-ajax')]; $contentId = $_SERVER['HTTP_X_TRACY_AJAX'] . '-ajax'; $_SESSION['_tracy']['bar'][$contentId] = ['content' => self::renderHtmlRows($rows), 'dumps' => Dumper::fetchLiveData(), 'time' => \time()]; } } elseif (Helpers::isRedirect()) { // redirect if ($useSession) { Dumper::fetchLiveData(); Dumper::$livePrefix = \count($redirectQueue) . 'p'; $redirectQueue[] = [ 'panels' => $this->renderPanels('-r' . \count($redirectQueue)), 'dumps' => Dumper::fetchLiveData(), 'time' => \time(), ]; } } elseif (Helpers::isHtmlMode()) { $rows[] = (object) ['type' => 'main', 'panels' => $this->renderPanels()]; $dumps = Dumper::fetchLiveData(); foreach (\array_reverse((array) $redirectQueue) as $info) { $rows[] = (object) ['type' => 'redirect', 'panels' => $info['panels']]; $dumps += $info['dumps']; } $redirectQueue = null; $content = self::renderHtmlRows($rows); if ($this->contentId) { $_SESSION['_tracy']['bar'][$this->contentId] = ['content' => $content, 'dumps' => $dumps, 'time' => time()]; } else { $contentId = \substr(\md5(\uniqid('', true)), 0, 10); $nonce = Helpers::getNonce(); $async = false; require __DIR__ . '/assets/Bar/loader.phtml'; } } }
php
public function render(): void { $useSession = $this->useSession && \session_status() === PHP_SESSION_ACTIVE; $redirectQueue = &$_SESSION['_tracy']['redirect']; foreach (['bar', 'redirect', 'bluescreen'] as $key) { $queue = &$_SESSION['_tracy'][$key]; $queue = \array_slice((array) $queue, -10, null, true); $queue = \array_filter($queue, function ($item) { return isset($item['time']) && $item['time'] > \time() - 60; }); } $rows = []; if (Helpers::isAjax()) { if ($useSession) { $rows[] = (object) ['type' => 'ajax', 'panels' => $this->renderPanels('-ajax')]; $contentId = $_SERVER['HTTP_X_TRACY_AJAX'] . '-ajax'; $_SESSION['_tracy']['bar'][$contentId] = ['content' => self::renderHtmlRows($rows), 'dumps' => Dumper::fetchLiveData(), 'time' => \time()]; } } elseif (Helpers::isRedirect()) { // redirect if ($useSession) { Dumper::fetchLiveData(); Dumper::$livePrefix = \count($redirectQueue) . 'p'; $redirectQueue[] = [ 'panels' => $this->renderPanels('-r' . \count($redirectQueue)), 'dumps' => Dumper::fetchLiveData(), 'time' => \time(), ]; } } elseif (Helpers::isHtmlMode()) { $rows[] = (object) ['type' => 'main', 'panels' => $this->renderPanels()]; $dumps = Dumper::fetchLiveData(); foreach (\array_reverse((array) $redirectQueue) as $info) { $rows[] = (object) ['type' => 'redirect', 'panels' => $info['panels']]; $dumps += $info['dumps']; } $redirectQueue = null; $content = self::renderHtmlRows($rows); if ($this->contentId) { $_SESSION['_tracy']['bar'][$this->contentId] = ['content' => $content, 'dumps' => $dumps, 'time' => time()]; } else { $contentId = \substr(\md5(\uniqid('', true)), 0, 10); $nonce = Helpers::getNonce(); $async = false; require __DIR__ . '/assets/Bar/loader.phtml'; } } }
[ "public", "function", "render", "(", ")", ":", "void", "{", "$", "useSession", "=", "$", "this", "->", "useSession", "&&", "\\", "session_status", "(", ")", "===", "PHP_SESSION_ACTIVE", ";", "$", "redirectQueue", "=", "&", "$", "_SESSION", "[", "'_tracy'", "]", "[", "'redirect'", "]", ";", "foreach", "(", "[", "'bar'", ",", "'redirect'", ",", "'bluescreen'", "]", "as", "$", "key", ")", "{", "$", "queue", "=", "&", "$", "_SESSION", "[", "'_tracy'", "]", "[", "$", "key", "]", ";", "$", "queue", "=", "\\", "array_slice", "(", "(", "array", ")", "$", "queue", ",", "-", "10", ",", "null", ",", "true", ")", ";", "$", "queue", "=", "\\", "array_filter", "(", "$", "queue", ",", "function", "(", "$", "item", ")", "{", "return", "isset", "(", "$", "item", "[", "'time'", "]", ")", "&&", "$", "item", "[", "'time'", "]", ">", "\\", "time", "(", ")", "-", "60", ";", "}", ")", ";", "}", "$", "rows", "=", "[", "]", ";", "if", "(", "Helpers", "::", "isAjax", "(", ")", ")", "{", "if", "(", "$", "useSession", ")", "{", "$", "rows", "[", "]", "=", "(", "object", ")", "[", "'type'", "=>", "'ajax'", ",", "'panels'", "=>", "$", "this", "->", "renderPanels", "(", "'-ajax'", ")", "]", ";", "$", "contentId", "=", "$", "_SERVER", "[", "'HTTP_X_TRACY_AJAX'", "]", ".", "'-ajax'", ";", "$", "_SESSION", "[", "'_tracy'", "]", "[", "'bar'", "]", "[", "$", "contentId", "]", "=", "[", "'content'", "=>", "self", "::", "renderHtmlRows", "(", "$", "rows", ")", ",", "'dumps'", "=>", "Dumper", "::", "fetchLiveData", "(", ")", ",", "'time'", "=>", "\\", "time", "(", ")", "]", ";", "}", "}", "elseif", "(", "Helpers", "::", "isRedirect", "(", ")", ")", "{", "// redirect", "if", "(", "$", "useSession", ")", "{", "Dumper", "::", "fetchLiveData", "(", ")", ";", "Dumper", "::", "$", "livePrefix", "=", "\\", "count", "(", "$", "redirectQueue", ")", ".", "'p'", ";", "$", "redirectQueue", "[", "]", "=", "[", "'panels'", "=>", "$", "this", "->", "renderPanels", "(", "'-r'", ".", "\\", "count", "(", "$", "redirectQueue", ")", ")", ",", "'dumps'", "=>", "Dumper", "::", "fetchLiveData", "(", ")", ",", "'time'", "=>", "\\", "time", "(", ")", ",", "]", ";", "}", "}", "elseif", "(", "Helpers", "::", "isHtmlMode", "(", ")", ")", "{", "$", "rows", "[", "]", "=", "(", "object", ")", "[", "'type'", "=>", "'main'", ",", "'panels'", "=>", "$", "this", "->", "renderPanels", "(", ")", "]", ";", "$", "dumps", "=", "Dumper", "::", "fetchLiveData", "(", ")", ";", "foreach", "(", "\\", "array_reverse", "(", "(", "array", ")", "$", "redirectQueue", ")", "as", "$", "info", ")", "{", "$", "rows", "[", "]", "=", "(", "object", ")", "[", "'type'", "=>", "'redirect'", ",", "'panels'", "=>", "$", "info", "[", "'panels'", "]", "]", ";", "$", "dumps", "+=", "$", "info", "[", "'dumps'", "]", ";", "}", "$", "redirectQueue", "=", "null", ";", "$", "content", "=", "self", "::", "renderHtmlRows", "(", "$", "rows", ")", ";", "if", "(", "$", "this", "->", "contentId", ")", "{", "$", "_SESSION", "[", "'_tracy'", "]", "[", "'bar'", "]", "[", "$", "this", "->", "contentId", "]", "=", "[", "'content'", "=>", "$", "content", ",", "'dumps'", "=>", "$", "dumps", ",", "'time'", "=>", "time", "(", ")", "]", ";", "}", "else", "{", "$", "contentId", "=", "\\", "substr", "(", "\\", "md5", "(", "\\", "uniqid", "(", "''", ",", "true", ")", ")", ",", "0", ",", "10", ")", ";", "$", "nonce", "=", "Helpers", "::", "getNonce", "(", ")", ";", "$", "async", "=", "false", ";", "require", "__DIR__", ".", "'/assets/Bar/loader.phtml'", ";", "}", "}", "}" ]
Renders debug bar. @return void
[ "Renders", "debug", "bar", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Bar.php#L82-L132
35,343
hail-framework/framework
src/Debugger/Bar.php
Bar.dispatchAssets
public function dispatchAssets(): ?ResponseInterface { $asset = $_GET['_tracy_bar'] ?? null; if ($asset === 'js') { \ob_start(); $this->renderAssets(); $body = \ob_get_clean(); return Factory::response(200, $body, [ 'Content-Type' => 'application/javascript', 'Cache-Control' => 'max-age=864000', ]); } $this->useSession = \session_status() === PHP_SESSION_ACTIVE; $headers = []; if ($this->useSession && Helpers::isAjax()) { $headers['X-Tracy-Ajax'] = '1'; // session must be already locked } if ($this->useSession && $asset && \preg_match('#^content(-ajax)?\.(\w+)$#', $asset, $m)) { $session = &$_SESSION['_tracy']['bar'][$m[2] . $m[1]]; $headers['Content-Type'] = 'application/javascript'; $headers['Cache-Control'] = 'max-age=60'; \ob_start(); if (!$m[1]) { $this->renderAssets(); } if ($session) { $method = $m[1] ? 'loadAjax' : 'init'; echo "Tracy.Debug.$method(", \json_encode($session['content']), ', ', \json_encode($session['dumps']), ');'; $session = null; } $session = &$_SESSION['_tracy']['bluescreen'][$m[2]]; if ($session) { echo 'Tracy.BlueScreen.loadAjax(', \json_encode($session['content']), ', ', \json_encode($session['dumps']), ');'; $session = null; } $body = \ob_get_clean(); return Factory::response(200, $body, $headers); } return null; }
php
public function dispatchAssets(): ?ResponseInterface { $asset = $_GET['_tracy_bar'] ?? null; if ($asset === 'js') { \ob_start(); $this->renderAssets(); $body = \ob_get_clean(); return Factory::response(200, $body, [ 'Content-Type' => 'application/javascript', 'Cache-Control' => 'max-age=864000', ]); } $this->useSession = \session_status() === PHP_SESSION_ACTIVE; $headers = []; if ($this->useSession && Helpers::isAjax()) { $headers['X-Tracy-Ajax'] = '1'; // session must be already locked } if ($this->useSession && $asset && \preg_match('#^content(-ajax)?\.(\w+)$#', $asset, $m)) { $session = &$_SESSION['_tracy']['bar'][$m[2] . $m[1]]; $headers['Content-Type'] = 'application/javascript'; $headers['Cache-Control'] = 'max-age=60'; \ob_start(); if (!$m[1]) { $this->renderAssets(); } if ($session) { $method = $m[1] ? 'loadAjax' : 'init'; echo "Tracy.Debug.$method(", \json_encode($session['content']), ', ', \json_encode($session['dumps']), ');'; $session = null; } $session = &$_SESSION['_tracy']['bluescreen'][$m[2]]; if ($session) { echo 'Tracy.BlueScreen.loadAjax(', \json_encode($session['content']), ', ', \json_encode($session['dumps']), ');'; $session = null; } $body = \ob_get_clean(); return Factory::response(200, $body, $headers); } return null; }
[ "public", "function", "dispatchAssets", "(", ")", ":", "?", "ResponseInterface", "{", "$", "asset", "=", "$", "_GET", "[", "'_tracy_bar'", "]", "??", "null", ";", "if", "(", "$", "asset", "===", "'js'", ")", "{", "\\", "ob_start", "(", ")", ";", "$", "this", "->", "renderAssets", "(", ")", ";", "$", "body", "=", "\\", "ob_get_clean", "(", ")", ";", "return", "Factory", "::", "response", "(", "200", ",", "$", "body", ",", "[", "'Content-Type'", "=>", "'application/javascript'", ",", "'Cache-Control'", "=>", "'max-age=864000'", ",", "]", ")", ";", "}", "$", "this", "->", "useSession", "=", "\\", "session_status", "(", ")", "===", "PHP_SESSION_ACTIVE", ";", "$", "headers", "=", "[", "]", ";", "if", "(", "$", "this", "->", "useSession", "&&", "Helpers", "::", "isAjax", "(", ")", ")", "{", "$", "headers", "[", "'X-Tracy-Ajax'", "]", "=", "'1'", ";", "// session must be already locked", "}", "if", "(", "$", "this", "->", "useSession", "&&", "$", "asset", "&&", "\\", "preg_match", "(", "'#^content(-ajax)?\\.(\\w+)$#'", ",", "$", "asset", ",", "$", "m", ")", ")", "{", "$", "session", "=", "&", "$", "_SESSION", "[", "'_tracy'", "]", "[", "'bar'", "]", "[", "$", "m", "[", "2", "]", ".", "$", "m", "[", "1", "]", "]", ";", "$", "headers", "[", "'Content-Type'", "]", "=", "'application/javascript'", ";", "$", "headers", "[", "'Cache-Control'", "]", "=", "'max-age=60'", ";", "\\", "ob_start", "(", ")", ";", "if", "(", "!", "$", "m", "[", "1", "]", ")", "{", "$", "this", "->", "renderAssets", "(", ")", ";", "}", "if", "(", "$", "session", ")", "{", "$", "method", "=", "$", "m", "[", "1", "]", "?", "'loadAjax'", ":", "'init'", ";", "echo", "\"Tracy.Debug.$method(\"", ",", "\\", "json_encode", "(", "$", "session", "[", "'content'", "]", ")", ",", "', '", ",", "\\", "json_encode", "(", "$", "session", "[", "'dumps'", "]", ")", ",", "');'", ";", "$", "session", "=", "null", ";", "}", "$", "session", "=", "&", "$", "_SESSION", "[", "'_tracy'", "]", "[", "'bluescreen'", "]", "[", "$", "m", "[", "2", "]", "]", ";", "if", "(", "$", "session", ")", "{", "echo", "'Tracy.BlueScreen.loadAjax('", ",", "\\", "json_encode", "(", "$", "session", "[", "'content'", "]", ")", ",", "', '", ",", "\\", "json_encode", "(", "$", "session", "[", "'dumps'", "]", ")", ",", "');'", ";", "$", "session", "=", "null", ";", "}", "$", "body", "=", "\\", "ob_get_clean", "(", ")", ";", "return", "Factory", "::", "response", "(", "200", ",", "$", "body", ",", "$", "headers", ")", ";", "}", "return", "null", ";", "}" ]
Renders debug bar assets. @return ResponseInterface|null
[ "Renders", "debug", "bar", "assets", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Bar.php#L182-L231
35,344
hail-framework/framework
src/Cache/Simple/AbstractAdapter.php
AbstractAdapter.prefixValue
protected function prefixValue(&$key) { if (null === ($version = $this->namespaceVersion)) { $version = $this->getNamespaceVersion(); } // namespace#[version]#key $key = $this->namespace . self::SEPARATOR . $version . self::SEPARATOR . $key; }
php
protected function prefixValue(&$key) { if (null === ($version = $this->namespaceVersion)) { $version = $this->getNamespaceVersion(); } // namespace#[version]#key $key = $this->namespace . self::SEPARATOR . $version . self::SEPARATOR . $key; }
[ "protected", "function", "prefixValue", "(", "&", "$", "key", ")", "{", "if", "(", "null", "===", "(", "$", "version", "=", "$", "this", "->", "namespaceVersion", ")", ")", "{", "$", "version", "=", "$", "this", "->", "getNamespaceVersion", "(", ")", ";", "}", "// namespace#[version]#key", "$", "key", "=", "$", "this", "->", "namespace", ".", "self", "::", "SEPARATOR", ".", "$", "version", ".", "self", "::", "SEPARATOR", ".", "$", "key", ";", "}" ]
Add namespace prefix on the key. @param string $key
[ "Add", "namespace", "prefix", "on", "the", "key", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L110-L119
35,345
hail-framework/framework
src/Cache/Simple/AbstractAdapter.php
AbstractAdapter.getMultiple
public function getMultiple($keys, $default = null) { if (empty($keys)) { return []; } // note: the array_combine() is in place to keep an association between our $keys and the $namespacedKeys \array_walk($keys, [$this, 'validateKey']); $prefixed = $keys; $this->namespace && \array_walk($prefixed, [$this, 'prefixValue']); $namespacedKeys = \array_combine($keys, $prefixed); $items = $this->doGetMultiple($namespacedKeys); $return = []; // no internal array function supports this sort of mapping: needs to be iterative // this filters and combines keys in one pass foreach ($namespacedKeys as $k => $v) { [$found, $value] = $items[$v] ?? [false, null]; $return[$k] = $found === true ? $value : $default; } return $return; }
php
public function getMultiple($keys, $default = null) { if (empty($keys)) { return []; } // note: the array_combine() is in place to keep an association between our $keys and the $namespacedKeys \array_walk($keys, [$this, 'validateKey']); $prefixed = $keys; $this->namespace && \array_walk($prefixed, [$this, 'prefixValue']); $namespacedKeys = \array_combine($keys, $prefixed); $items = $this->doGetMultiple($namespacedKeys); $return = []; // no internal array function supports this sort of mapping: needs to be iterative // this filters and combines keys in one pass foreach ($namespacedKeys as $k => $v) { [$found, $value] = $items[$v] ?? [false, null]; $return[$k] = $found === true ? $value : $default; } return $return; }
[ "public", "function", "getMultiple", "(", "$", "keys", ",", "$", "default", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "keys", ")", ")", "{", "return", "[", "]", ";", "}", "// note: the array_combine() is in place to keep an association between our $keys and the $namespacedKeys", "\\", "array_walk", "(", "$", "keys", ",", "[", "$", "this", ",", "'validateKey'", "]", ")", ";", "$", "prefixed", "=", "$", "keys", ";", "$", "this", "->", "namespace", "&&", "\\", "array_walk", "(", "$", "prefixed", ",", "[", "$", "this", ",", "'prefixValue'", "]", ")", ";", "$", "namespacedKeys", "=", "\\", "array_combine", "(", "$", "keys", ",", "$", "prefixed", ")", ";", "$", "items", "=", "$", "this", "->", "doGetMultiple", "(", "$", "namespacedKeys", ")", ";", "$", "return", "=", "[", "]", ";", "// no internal array function supports this sort of mapping: needs to be iterative", "// this filters and combines keys in one pass", "foreach", "(", "$", "namespacedKeys", "as", "$", "k", "=>", "$", "v", ")", "{", "[", "$", "found", ",", "$", "value", "]", "=", "$", "items", "[", "$", "v", "]", "??", "[", "false", ",", "null", "]", ";", "$", "return", "[", "$", "k", "]", "=", "$", "found", "===", "true", "?", "$", "value", ":", "$", "default", ";", "}", "return", "$", "return", ";", "}" ]
Returns an associative array of values for keys is found in cache. @param string[] $keys Array of keys to retrieve from cache @param mixed $default @return mixed[] Array of retrieved values, indexed by the specified keys. Values that couldn't be retrieved are not contained in this array.
[ "Returns", "an", "associative", "array", "of", "values", "for", "keys", "is", "found", "in", "cache", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L199-L223
35,346
hail-framework/framework
src/Cache/Simple/AbstractAdapter.php
AbstractAdapter.setMultiple
public function setMultiple($values, $ttl = null) { [$ttl, $expireTime] = $this->ttl($ttl); $namespacedValues = []; foreach ($values as $key => $value) { $this->validateKey($key); $this->namespace && $this->prefixValue($key); $namespacedValues[$key] = [true, $value, [], $expireTime]; } return $this->doSetMultiple($namespacedValues, $ttl); }
php
public function setMultiple($values, $ttl = null) { [$ttl, $expireTime] = $this->ttl($ttl); $namespacedValues = []; foreach ($values as $key => $value) { $this->validateKey($key); $this->namespace && $this->prefixValue($key); $namespacedValues[$key] = [true, $value, [], $expireTime]; } return $this->doSetMultiple($namespacedValues, $ttl); }
[ "public", "function", "setMultiple", "(", "$", "values", ",", "$", "ttl", "=", "null", ")", "{", "[", "$", "ttl", ",", "$", "expireTime", "]", "=", "$", "this", "->", "ttl", "(", "$", "ttl", ")", ";", "$", "namespacedValues", "=", "[", "]", ";", "foreach", "(", "$", "values", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "validateKey", "(", "$", "key", ")", ";", "$", "this", "->", "namespace", "&&", "$", "this", "->", "prefixValue", "(", "$", "key", ")", ";", "$", "namespacedValues", "[", "$", "key", "]", "=", "[", "true", ",", "$", "value", ",", "[", "]", ",", "$", "expireTime", "]", ";", "}", "return", "$", "this", "->", "doSetMultiple", "(", "$", "namespacedValues", ",", "$", "ttl", ")", ";", "}" ]
Returns a boolean value indicating if the operation succeeded. @param iterable $values Array of keys and values to save in cache @param null|int|\DateInterval $ttl The lifetime. If != 0, sets a specific lifetime for these cache entries (0 => infinite lifeTime). @return bool TRUE if the operation was successful, FALSE if it wasn't.
[ "Returns", "a", "boolean", "value", "indicating", "if", "the", "operation", "succeeded", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L249-L262
35,347
hail-framework/framework
src/Cache/Simple/AbstractAdapter.php
AbstractAdapter.deleteMultiple
public function deleteMultiple($keys) { \array_walk($keys, [$this, 'validateKey']); $this->namespace && \array_walk($keys, [$this, 'prefixValue']); return $this->doDeleteMultiple($keys); }
php
public function deleteMultiple($keys) { \array_walk($keys, [$this, 'validateKey']); $this->namespace && \array_walk($keys, [$this, 'prefixValue']); return $this->doDeleteMultiple($keys); }
[ "public", "function", "deleteMultiple", "(", "$", "keys", ")", "{", "\\", "array_walk", "(", "$", "keys", ",", "[", "$", "this", ",", "'validateKey'", "]", ")", ";", "$", "this", "->", "namespace", "&&", "\\", "array_walk", "(", "$", "keys", ",", "[", "$", "this", ",", "'prefixValue'", "]", ")", ";", "return", "$", "this", "->", "doDeleteMultiple", "(", "$", "keys", ")", ";", "}" ]
Deletes several cache entries. @param string[] $keys Array of keys to delete from cache @return bool TRUE if the operation was successful, FALSE if it wasn't.
[ "Deletes", "several", "cache", "entries", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L319-L325
35,348
hail-framework/framework
src/Cache/Simple/AbstractAdapter.php
AbstractAdapter.deleteAll
public function deleteAll() { if (!$this->namespace) { return $this->clear(); } $namespaceCacheKey = $this->getNamespaceCacheKey(); $namespaceVersion = $this->getNamespaceVersion() + 1; if ($this->doSet($namespaceCacheKey, [true, $namespaceVersion, [], 0])) { $this->namespaceVersion = $namespaceVersion; return true; } return false; }
php
public function deleteAll() { if (!$this->namespace) { return $this->clear(); } $namespaceCacheKey = $this->getNamespaceCacheKey(); $namespaceVersion = $this->getNamespaceVersion() + 1; if ($this->doSet($namespaceCacheKey, [true, $namespaceVersion, [], 0])) { $this->namespaceVersion = $namespaceVersion; return true; } return false; }
[ "public", "function", "deleteAll", "(", ")", "{", "if", "(", "!", "$", "this", "->", "namespace", ")", "{", "return", "$", "this", "->", "clear", "(", ")", ";", "}", "$", "namespaceCacheKey", "=", "$", "this", "->", "getNamespaceCacheKey", "(", ")", ";", "$", "namespaceVersion", "=", "$", "this", "->", "getNamespaceVersion", "(", ")", "+", "1", ";", "if", "(", "$", "this", "->", "doSet", "(", "$", "namespaceCacheKey", ",", "[", "true", ",", "$", "namespaceVersion", ",", "[", "]", ",", "0", "]", ")", ")", "{", "$", "this", "->", "namespaceVersion", "=", "$", "namespaceVersion", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Deletes all cache entries in the current cache namespace. @return bool TRUE if the cache entries were successfully deleted, FALSE otherwise.
[ "Deletes", "all", "cache", "entries", "in", "the", "current", "cache", "namespace", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L342-L358
35,349
hail-framework/framework
src/Cache/Simple/AbstractAdapter.php
AbstractAdapter.doGetMultiple
protected function doGetMultiple(iterable $keys) { $return = []; foreach ($keys as $key) { $return[$key] = $this->doGet($key); } return $return; }
php
protected function doGetMultiple(iterable $keys) { $return = []; foreach ($keys as $key) { $return[$key] = $this->doGet($key); } return $return; }
[ "protected", "function", "doGetMultiple", "(", "iterable", "$", "keys", ")", "{", "$", "return", "=", "[", "]", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "return", "[", "$", "key", "]", "=", "$", "this", "->", "doGet", "(", "$", "key", ")", ";", "}", "return", "$", "return", ";", "}" ]
Default implementation of doGetMultiple. Each driver that supports multi-get should owerwrite it. @param array $keys Array of keys to retrieve from cache @return array Array of values retrieved for the given keys.
[ "Default", "implementation", "of", "doGetMultiple", ".", "Each", "driver", "that", "supports", "multi", "-", "get", "should", "owerwrite", "it", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L431-L440
35,350
hail-framework/framework
src/Cache/Simple/AbstractAdapter.php
AbstractAdapter.doDeleteMultiple
protected function doDeleteMultiple(iterable $keys) { $success = true; foreach ($keys as $key) { if (!$this->doDelete($key)) { $success = false; } } return $success; }
php
protected function doDeleteMultiple(iterable $keys) { $success = true; foreach ($keys as $key) { if (!$this->doDelete($key)) { $success = false; } } return $success; }
[ "protected", "function", "doDeleteMultiple", "(", "iterable", "$", "keys", ")", "{", "$", "success", "=", "true", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "!", "$", "this", "->", "doDelete", "(", "$", "key", ")", ")", "{", "$", "success", "=", "false", ";", "}", "}", "return", "$", "success", ";", "}" ]
Default implementation of doDeleteMultiple. Each driver that supports multi-delete should override it. @param array $keys Array of keys to delete from cache @return bool TRUE if the operation was successful, FALSE if it wasn't
[ "Default", "implementation", "of", "doDeleteMultiple", ".", "Each", "driver", "that", "supports", "multi", "-", "delete", "should", "override", "it", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Cache/Simple/AbstractAdapter.php#L449-L460
35,351
hail-framework/framework
src/Debugger/ChromeLogger.php
ChromeLogger.writeToResponse
public function writeToResponse(ResponseInterface $response): ResponseInterface { if ($this->entries !== []) { $value = $this->getHeaderValue(); $this->entries = []; return $response->withHeader(self::HEADER_NAME, $value); } return $response; }
php
public function writeToResponse(ResponseInterface $response): ResponseInterface { if ($this->entries !== []) { $value = $this->getHeaderValue(); $this->entries = []; return $response->withHeader(self::HEADER_NAME, $value); } return $response; }
[ "public", "function", "writeToResponse", "(", "ResponseInterface", "$", "response", ")", ":", "ResponseInterface", "{", "if", "(", "$", "this", "->", "entries", "!==", "[", "]", ")", "{", "$", "value", "=", "$", "this", "->", "getHeaderValue", "(", ")", ";", "$", "this", "->", "entries", "=", "[", "]", ";", "return", "$", "response", "->", "withHeader", "(", "self", "::", "HEADER_NAME", ",", "$", "value", ")", ";", "}", "return", "$", "response", ";", "}" ]
Adds headers for recorded log-entries in the ChromeLogger format, and clear the internal log-buffer. (You should call this at the end of the request/response cycle in your PSR-7 project, e.g. immediately before emitting the Response.) @param ResponseInterface $response @return ResponseInterface
[ "Adds", "headers", "for", "recorded", "log", "-", "entries", "in", "the", "ChromeLogger", "format", "and", "clear", "the", "internal", "log", "-", "buffer", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/ChromeLogger.php#L97-L108
35,352
hail-framework/framework
src/Debugger/ChromeLogger.php
ChromeLogger.createData
protected function createData(array $entries): array { $rows = []; foreach ($entries as $entry) { $rows[] = $this->createEntryData($entry); } return [ 'version' => self::VERSION, 'columns' => [self::COLUMN_LOG, self::COLUMN_TYPE, self::COLUMN_BACKTRACE], 'rows' => $rows, ]; }
php
protected function createData(array $entries): array { $rows = []; foreach ($entries as $entry) { $rows[] = $this->createEntryData($entry); } return [ 'version' => self::VERSION, 'columns' => [self::COLUMN_LOG, self::COLUMN_TYPE, self::COLUMN_BACKTRACE], 'rows' => $rows, ]; }
[ "protected", "function", "createData", "(", "array", "$", "entries", ")", ":", "array", "{", "$", "rows", "=", "[", "]", ";", "foreach", "(", "$", "entries", "as", "$", "entry", ")", "{", "$", "rows", "[", "]", "=", "$", "this", "->", "createEntryData", "(", "$", "entry", ")", ";", "}", "return", "[", "'version'", "=>", "self", "::", "VERSION", ",", "'columns'", "=>", "[", "self", "::", "COLUMN_LOG", ",", "self", "::", "COLUMN_TYPE", ",", "self", "::", "COLUMN_BACKTRACE", "]", ",", "'rows'", "=>", "$", "rows", ",", "]", ";", "}" ]
Internally builds the ChromeLogger-compatible data-structure from internal log-entries. @param array[][] $entries @return array
[ "Internally", "builds", "the", "ChromeLogger", "-", "compatible", "data", "-", "structure", "from", "internal", "log", "-", "entries", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/ChromeLogger.php#L186-L199
35,353
hail-framework/framework
src/Debugger/ChromeLogger.php
ChromeLogger.createEntryData
protected function createEntryData(array $entry): array { // NOTE: "log" level type is deliberately omitted from the following map, since // it's the default entry-type in ChromeLogger, and can be omitted. static $LEVELS = [ LogLevel::DEBUG => self::LOG, LogLevel::INFO => self::INFO, LogLevel::NOTICE => self::INFO, LogLevel::WARNING => self::WARN, LogLevel::ERROR => self::ERROR, LogLevel::CRITICAL => self::ERROR, LogLevel::ALERT => self::ERROR, LogLevel::EMERGENCY => self::ERROR, ]; $row = []; [$level, $message, $context] = $entry; $data = [ \str_replace('%', '%%', Dumper::interpolate($message, $context)), ]; if (\count($context)) { $context = $this->sanitize($context); $data = \array_merge($data, $context); } $row[] = $data; $row[] = $LEVELS[$level] ?? self::LOG; if (isset($context['exception'])) { // NOTE: per PSR-3, this reserved key could be anything, but if it is an Exception, we // can use that Exception to obtain a stack-trace for output in ChromeLogger. $exception = $context['exception']; if ($exception instanceof \Throwable) { $row[] = $exception->__toString(); } } // Optimization: ChromeLogger defaults to "log" if no entry-type is specified. if ($row[1] === self::LOG) { if (\count($row) === 2) { unset($row[1]); } else { $row[1] = ''; } } return $row; }
php
protected function createEntryData(array $entry): array { // NOTE: "log" level type is deliberately omitted from the following map, since // it's the default entry-type in ChromeLogger, and can be omitted. static $LEVELS = [ LogLevel::DEBUG => self::LOG, LogLevel::INFO => self::INFO, LogLevel::NOTICE => self::INFO, LogLevel::WARNING => self::WARN, LogLevel::ERROR => self::ERROR, LogLevel::CRITICAL => self::ERROR, LogLevel::ALERT => self::ERROR, LogLevel::EMERGENCY => self::ERROR, ]; $row = []; [$level, $message, $context] = $entry; $data = [ \str_replace('%', '%%', Dumper::interpolate($message, $context)), ]; if (\count($context)) { $context = $this->sanitize($context); $data = \array_merge($data, $context); } $row[] = $data; $row[] = $LEVELS[$level] ?? self::LOG; if (isset($context['exception'])) { // NOTE: per PSR-3, this reserved key could be anything, but if it is an Exception, we // can use that Exception to obtain a stack-trace for output in ChromeLogger. $exception = $context['exception']; if ($exception instanceof \Throwable) { $row[] = $exception->__toString(); } } // Optimization: ChromeLogger defaults to "log" if no entry-type is specified. if ($row[1] === self::LOG) { if (\count($row) === 2) { unset($row[1]); } else { $row[1] = ''; } } return $row; }
[ "protected", "function", "createEntryData", "(", "array", "$", "entry", ")", ":", "array", "{", "// NOTE: \"log\" level type is deliberately omitted from the following map, since", "// it's the default entry-type in ChromeLogger, and can be omitted.", "static", "$", "LEVELS", "=", "[", "LogLevel", "::", "DEBUG", "=>", "self", "::", "LOG", ",", "LogLevel", "::", "INFO", "=>", "self", "::", "INFO", ",", "LogLevel", "::", "NOTICE", "=>", "self", "::", "INFO", ",", "LogLevel", "::", "WARNING", "=>", "self", "::", "WARN", ",", "LogLevel", "::", "ERROR", "=>", "self", "::", "ERROR", ",", "LogLevel", "::", "CRITICAL", "=>", "self", "::", "ERROR", ",", "LogLevel", "::", "ALERT", "=>", "self", "::", "ERROR", ",", "LogLevel", "::", "EMERGENCY", "=>", "self", "::", "ERROR", ",", "]", ";", "$", "row", "=", "[", "]", ";", "[", "$", "level", ",", "$", "message", ",", "$", "context", "]", "=", "$", "entry", ";", "$", "data", "=", "[", "\\", "str_replace", "(", "'%'", ",", "'%%'", ",", "Dumper", "::", "interpolate", "(", "$", "message", ",", "$", "context", ")", ")", ",", "]", ";", "if", "(", "\\", "count", "(", "$", "context", ")", ")", "{", "$", "context", "=", "$", "this", "->", "sanitize", "(", "$", "context", ")", ";", "$", "data", "=", "\\", "array_merge", "(", "$", "data", ",", "$", "context", ")", ";", "}", "$", "row", "[", "]", "=", "$", "data", ";", "$", "row", "[", "]", "=", "$", "LEVELS", "[", "$", "level", "]", "??", "self", "::", "LOG", ";", "if", "(", "isset", "(", "$", "context", "[", "'exception'", "]", ")", ")", "{", "// NOTE: per PSR-3, this reserved key could be anything, but if it is an Exception, we", "// can use that Exception to obtain a stack-trace for output in ChromeLogger.", "$", "exception", "=", "$", "context", "[", "'exception'", "]", ";", "if", "(", "$", "exception", "instanceof", "\\", "Throwable", ")", "{", "$", "row", "[", "]", "=", "$", "exception", "->", "__toString", "(", ")", ";", "}", "}", "// Optimization: ChromeLogger defaults to \"log\" if no entry-type is specified.", "if", "(", "$", "row", "[", "1", "]", "===", "self", "::", "LOG", ")", "{", "if", "(", "\\", "count", "(", "$", "row", ")", "===", "2", ")", "{", "unset", "(", "$", "row", "[", "1", "]", ")", ";", "}", "else", "{", "$", "row", "[", "1", "]", "=", "''", ";", "}", "}", "return", "$", "row", ";", "}" ]
Encode an individual LogEntry in ChromeLogger-compatible format @param array $entry @return array log entry in ChromeLogger row-format
[ "Encode", "an", "individual", "LogEntry", "in", "ChromeLogger", "-", "compatible", "format" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/ChromeLogger.php#L208-L262
35,354
hail-framework/framework
src/Debugger/ChromeLogger.php
ChromeLogger.sanitize
protected function sanitize($data, array &$processed = []) { if (\is_array($data)) { /** * @var array $data */ foreach ($data as $name => $value) { $data[$name] = $this->sanitize($value, $processed); } return $data; } if (\is_object($data)) { /** * @var object $data */ $class_name = \get_class($data); $hash = \spl_object_hash($data); if (isset($processed[$hash])) { // NOTE: duplicate objects (circular references) are omitted to prevent recursion. return [self::CLASS_NAME => $class_name]; } $processed[$hash] = true; if ($data instanceof \JsonSerializable) { // NOTE: this doesn't serialize to JSON, it only marshalls to a JSON-compatible data-structure $data = $this->sanitize($data->jsonSerialize(), $processed); } elseif ($data instanceof \DateTimeInterface) { $data = $this->extractDateTimeProperties($data); } elseif ($data instanceof \Throwable) { $data = $this->extractExceptionProperties($data); } else { $data = $this->sanitize($this->extractObjectProperties($data), $processed); } return \array_merge([self::CLASS_NAME => $class_name], $data); } if (\is_scalar($data)) { return $data; // bool, int, float } if (\is_resource($data)) { $resource = \explode('#', (string) $data); return [ self::CLASS_NAME => 'resource<' . \get_resource_type($data) . '>', 'id' => \array_pop($resource), ]; } return null; // omit any other unsupported types (e.g. resource handles) }
php
protected function sanitize($data, array &$processed = []) { if (\is_array($data)) { /** * @var array $data */ foreach ($data as $name => $value) { $data[$name] = $this->sanitize($value, $processed); } return $data; } if (\is_object($data)) { /** * @var object $data */ $class_name = \get_class($data); $hash = \spl_object_hash($data); if (isset($processed[$hash])) { // NOTE: duplicate objects (circular references) are omitted to prevent recursion. return [self::CLASS_NAME => $class_name]; } $processed[$hash] = true; if ($data instanceof \JsonSerializable) { // NOTE: this doesn't serialize to JSON, it only marshalls to a JSON-compatible data-structure $data = $this->sanitize($data->jsonSerialize(), $processed); } elseif ($data instanceof \DateTimeInterface) { $data = $this->extractDateTimeProperties($data); } elseif ($data instanceof \Throwable) { $data = $this->extractExceptionProperties($data); } else { $data = $this->sanitize($this->extractObjectProperties($data), $processed); } return \array_merge([self::CLASS_NAME => $class_name], $data); } if (\is_scalar($data)) { return $data; // bool, int, float } if (\is_resource($data)) { $resource = \explode('#', (string) $data); return [ self::CLASS_NAME => 'resource<' . \get_resource_type($data) . '>', 'id' => \array_pop($resource), ]; } return null; // omit any other unsupported types (e.g. resource handles) }
[ "protected", "function", "sanitize", "(", "$", "data", ",", "array", "&", "$", "processed", "=", "[", "]", ")", "{", "if", "(", "\\", "is_array", "(", "$", "data", ")", ")", "{", "/**\n * @var array $data\n */", "foreach", "(", "$", "data", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "data", "[", "$", "name", "]", "=", "$", "this", "->", "sanitize", "(", "$", "value", ",", "$", "processed", ")", ";", "}", "return", "$", "data", ";", "}", "if", "(", "\\", "is_object", "(", "$", "data", ")", ")", "{", "/**\n * @var object $data\n */", "$", "class_name", "=", "\\", "get_class", "(", "$", "data", ")", ";", "$", "hash", "=", "\\", "spl_object_hash", "(", "$", "data", ")", ";", "if", "(", "isset", "(", "$", "processed", "[", "$", "hash", "]", ")", ")", "{", "// NOTE: duplicate objects (circular references) are omitted to prevent recursion.", "return", "[", "self", "::", "CLASS_NAME", "=>", "$", "class_name", "]", ";", "}", "$", "processed", "[", "$", "hash", "]", "=", "true", ";", "if", "(", "$", "data", "instanceof", "\\", "JsonSerializable", ")", "{", "// NOTE: this doesn't serialize to JSON, it only marshalls to a JSON-compatible data-structure", "$", "data", "=", "$", "this", "->", "sanitize", "(", "$", "data", "->", "jsonSerialize", "(", ")", ",", "$", "processed", ")", ";", "}", "elseif", "(", "$", "data", "instanceof", "\\", "DateTimeInterface", ")", "{", "$", "data", "=", "$", "this", "->", "extractDateTimeProperties", "(", "$", "data", ")", ";", "}", "elseif", "(", "$", "data", "instanceof", "\\", "Throwable", ")", "{", "$", "data", "=", "$", "this", "->", "extractExceptionProperties", "(", "$", "data", ")", ";", "}", "else", "{", "$", "data", "=", "$", "this", "->", "sanitize", "(", "$", "this", "->", "extractObjectProperties", "(", "$", "data", ")", ",", "$", "processed", ")", ";", "}", "return", "\\", "array_merge", "(", "[", "self", "::", "CLASS_NAME", "=>", "$", "class_name", "]", ",", "$", "data", ")", ";", "}", "if", "(", "\\", "is_scalar", "(", "$", "data", ")", ")", "{", "return", "$", "data", ";", "// bool, int, float", "}", "if", "(", "\\", "is_resource", "(", "$", "data", ")", ")", "{", "$", "resource", "=", "\\", "explode", "(", "'#'", ",", "(", "string", ")", "$", "data", ")", ";", "return", "[", "self", "::", "CLASS_NAME", "=>", "'resource<'", ".", "\\", "get_resource_type", "(", "$", "data", ")", ".", "'>'", ",", "'id'", "=>", "\\", "array_pop", "(", "$", "resource", ")", ",", "]", ";", "}", "return", "null", ";", "// omit any other unsupported types (e.g. resource handles)", "}" ]
Internally marshall and sanitize context values, producing a JSON-compatible data-structure. @param mixed $data any PHP object, array or value @param true[] $processed map where SPL object-hash => TRUE (eliminates duplicate objects from data-structures) @return mixed marshalled and sanitized context
[ "Internally", "marshall", "and", "sanitize", "context", "values", "producing", "a", "JSON", "-", "compatible", "data", "-", "structure", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/ChromeLogger.php#L272-L328
35,355
hail-framework/framework
src/Image/Commands/TextCommand.php
TextCommand.execute
public function execute($image) { $text = $this->argument(0)->required()->value(); $x = $this->argument(1)->type('numeric')->value(0); $y = $this->argument(2)->type('numeric')->value(0); $callback = $this->argument(3)->type('closure')->value(); $namespace = $image->getDriver()->getNamespace(); $fontclassname = "\{$namespace}\Font"; $font = new $fontclassname($text); if ($callback instanceof Closure) { $callback($font); } $font->applyToImage($image, $x, $y); return true; }
php
public function execute($image) { $text = $this->argument(0)->required()->value(); $x = $this->argument(1)->type('numeric')->value(0); $y = $this->argument(2)->type('numeric')->value(0); $callback = $this->argument(3)->type('closure')->value(); $namespace = $image->getDriver()->getNamespace(); $fontclassname = "\{$namespace}\Font"; $font = new $fontclassname($text); if ($callback instanceof Closure) { $callback($font); } $font->applyToImage($image, $x, $y); return true; }
[ "public", "function", "execute", "(", "$", "image", ")", "{", "$", "text", "=", "$", "this", "->", "argument", "(", "0", ")", "->", "required", "(", ")", "->", "value", "(", ")", ";", "$", "x", "=", "$", "this", "->", "argument", "(", "1", ")", "->", "type", "(", "'numeric'", ")", "->", "value", "(", "0", ")", ";", "$", "y", "=", "$", "this", "->", "argument", "(", "2", ")", "->", "type", "(", "'numeric'", ")", "->", "value", "(", "0", ")", ";", "$", "callback", "=", "$", "this", "->", "argument", "(", "3", ")", "->", "type", "(", "'closure'", ")", "->", "value", "(", ")", ";", "$", "namespace", "=", "$", "image", "->", "getDriver", "(", ")", "->", "getNamespace", "(", ")", ";", "$", "fontclassname", "=", "\"\\{$namespace}\\Font\"", ";", "$", "font", "=", "new", "$", "fontclassname", "(", "$", "text", ")", ";", "if", "(", "$", "callback", "instanceof", "Closure", ")", "{", "$", "callback", "(", "$", "font", ")", ";", "}", "$", "font", "->", "applyToImage", "(", "$", "image", ",", "$", "x", ",", "$", "y", ")", ";", "return", "true", ";", "}" ]
Write text on given image @param \Hail\Image\Image $image @return bool
[ "Write", "text", "on", "given", "image" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Commands/TextCommand.php#L16-L35
35,356
DoSomething/gateway
src/AuthorizesWithApiKey.php
AuthorizesWithApiKey.getAuthorizationHeader
protected function getAuthorizationHeader() { if (empty($this->apiKeyHeader) || empty($this->apiKey)) { throw new \Exception('API key is not set.'); } return [$this->apiKeyHeader => $this->apiKey]; }
php
protected function getAuthorizationHeader() { if (empty($this->apiKeyHeader) || empty($this->apiKey)) { throw new \Exception('API key is not set.'); } return [$this->apiKeyHeader => $this->apiKey]; }
[ "protected", "function", "getAuthorizationHeader", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "apiKeyHeader", ")", "||", "empty", "(", "$", "this", "->", "apiKey", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'API key is not set.'", ")", ";", "}", "return", "[", "$", "this", "->", "apiKeyHeader", "=>", "$", "this", "->", "apiKey", "]", ";", "}" ]
Get the authorization header for a request @return null|array @throws \Exception
[ "Get", "the", "authorization", "header", "for", "a", "request" ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/AuthorizesWithApiKey.php#L34-L41
35,357
htmlburger/wpemerge-cli
src/Presets/FrontEndPresetTrait.php
FrontEndPresetTrait.installNodePackage
protected function installNodePackage( $directory, OutputInterface $output, $package, $version = null, $dev = false ) { $package_manager = new Proxy(); if ( $package_manager->installed( $directory, $package ) ) { throw new RuntimeException( 'Package is already installed.' ); } $package_manager->install( $directory, $output, $package, $version, $dev ); }
php
protected function installNodePackage( $directory, OutputInterface $output, $package, $version = null, $dev = false ) { $package_manager = new Proxy(); if ( $package_manager->installed( $directory, $package ) ) { throw new RuntimeException( 'Package is already installed.' ); } $package_manager->install( $directory, $output, $package, $version, $dev ); }
[ "protected", "function", "installNodePackage", "(", "$", "directory", ",", "OutputInterface", "$", "output", ",", "$", "package", ",", "$", "version", "=", "null", ",", "$", "dev", "=", "false", ")", "{", "$", "package_manager", "=", "new", "Proxy", "(", ")", ";", "if", "(", "$", "package_manager", "->", "installed", "(", "$", "directory", ",", "$", "package", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'Package is already installed.'", ")", ";", "}", "$", "package_manager", "->", "install", "(", "$", "directory", ",", "$", "output", ",", "$", "package", ",", "$", "version", ",", "$", "dev", ")", ";", "}" ]
Install a node package. @param string $directory @param OutputInterface $output @param string $package @param string|null $version @param boolean $dev @return void
[ "Install", "a", "node", "package", "." ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/FrontEndPresetTrait.php#L22-L30
35,358
htmlburger/wpemerge-cli
src/Presets/FrontEndPresetTrait.php
FrontEndPresetTrait.addJsVendorImport
protected function addJsVendorImport( $directory, $import ) { $filepath = $this->path( $directory, 'resources', 'scripts', 'theme', 'vendor.js' ); $statement = "import '$import';"; $this->appendUniqueStatement( $filepath, $statement ); }
php
protected function addJsVendorImport( $directory, $import ) { $filepath = $this->path( $directory, 'resources', 'scripts', 'theme', 'vendor.js' ); $statement = "import '$import';"; $this->appendUniqueStatement( $filepath, $statement ); }
[ "protected", "function", "addJsVendorImport", "(", "$", "directory", ",", "$", "import", ")", "{", "$", "filepath", "=", "$", "this", "->", "path", "(", "$", "directory", ",", "'resources'", ",", "'scripts'", ",", "'theme'", ",", "'vendor.js'", ")", ";", "$", "statement", "=", "\"import '$import';\"", ";", "$", "this", "->", "appendUniqueStatement", "(", "$", "filepath", ",", "$", "statement", ")", ";", "}" ]
Add an import statement to the vendor.js file. @param string $directory @param string $import @return void
[ "Add", "an", "import", "statement", "to", "the", "vendor", ".", "js", "file", "." ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/FrontEndPresetTrait.php#L53-L58
35,359
Kajna/K-Core
Core/Util/Util.php
Util.base
public static function base($path = '') { // Check for cached version of base path if (null !== self::$base) { return self::$base . $path; } if (isset($_SERVER['HTTP_HOST'])) { $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http'; $base_url .= '://' . $_SERVER['HTTP_HOST']; $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); self::$base = $base_url; return $base_url . $path; } return ''; }
php
public static function base($path = '') { // Check for cached version of base path if (null !== self::$base) { return self::$base . $path; } if (isset($_SERVER['HTTP_HOST'])) { $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http'; $base_url .= '://' . $_SERVER['HTTP_HOST']; $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); self::$base = $base_url; return $base_url . $path; } return ''; }
[ "public", "static", "function", "base", "(", "$", "path", "=", "''", ")", "{", "// Check for cached version of base path", "if", "(", "null", "!==", "self", "::", "$", "base", ")", "{", "return", "self", "::", "$", "base", ".", "$", "path", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ")", ")", "{", "$", "base_url", "=", "isset", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "&&", "strtolower", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "!==", "'off'", "?", "'https'", ":", "'http'", ";", "$", "base_url", ".=", "'://'", ".", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ";", "$", "base_url", ".=", "str_replace", "(", "basename", "(", "$", "_SERVER", "[", "'SCRIPT_NAME'", "]", ")", ",", "''", ",", "$", "_SERVER", "[", "'SCRIPT_NAME'", "]", ")", ";", "self", "::", "$", "base", "=", "$", "base_url", ";", "return", "$", "base_url", ".", "$", "path", ";", "}", "return", "''", ";", "}" ]
Get site base url. @param string $path @return string
[ "Get", "site", "base", "url", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Util/Util.php#L29-L45
35,360
Kajna/K-Core
Core/Http/Response.php
Response.setStatusCode
public function setStatusCode($code, $reasonPhrase = null) { $this->statusCode = $code; $this->reasonPhrase = $reasonPhrase; return $this; }
php
public function setStatusCode($code, $reasonPhrase = null) { $this->statusCode = $code; $this->reasonPhrase = $reasonPhrase; return $this; }
[ "public", "function", "setStatusCode", "(", "$", "code", ",", "$", "reasonPhrase", "=", "null", ")", "{", "$", "this", "->", "statusCode", "=", "$", "code", ";", "$", "this", "->", "reasonPhrase", "=", "$", "reasonPhrase", ";", "return", "$", "this", ";", "}" ]
Set the response Status-Code @param integer $code The 3-digit integer result code to set. @param null|string $reasonPhrase The reason phrase to use with the provided status code; if none is provided default one associated with code will be used @return self
[ "Set", "the", "response", "Status", "-", "Code" ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Http/Response.php#L178-L183
35,361
Kajna/K-Core
Core/Http/Response.php
Response.send
public function send() { // Check if headers are sent already. if (headers_sent() === false) { // Determine reason phrase if ($this->reasonPhrase === null) { $this->reasonPhrase = self::$messages[$this->statusCode]; } // Send status code. header(sprintf('%s %s', $this->protocolVersion, $this->reasonPhrase), true, $this->statusCode); // Send headers. foreach ($this->headers as $header => $value) { header(sprintf('%s: %s', $header, $value), true, $this->statusCode); } // Send cookies. foreach ($this->cookies as $cookie) { setcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']); } // Send body. echo $this->body; } return $this; }
php
public function send() { // Check if headers are sent already. if (headers_sent() === false) { // Determine reason phrase if ($this->reasonPhrase === null) { $this->reasonPhrase = self::$messages[$this->statusCode]; } // Send status code. header(sprintf('%s %s', $this->protocolVersion, $this->reasonPhrase), true, $this->statusCode); // Send headers. foreach ($this->headers as $header => $value) { header(sprintf('%s: %s', $header, $value), true, $this->statusCode); } // Send cookies. foreach ($this->cookies as $cookie) { setcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']); } // Send body. echo $this->body; } return $this; }
[ "public", "function", "send", "(", ")", "{", "// Check if headers are sent already.", "if", "(", "headers_sent", "(", ")", "===", "false", ")", "{", "// Determine reason phrase", "if", "(", "$", "this", "->", "reasonPhrase", "===", "null", ")", "{", "$", "this", "->", "reasonPhrase", "=", "self", "::", "$", "messages", "[", "$", "this", "->", "statusCode", "]", ";", "}", "// Send status code.", "header", "(", "sprintf", "(", "'%s %s'", ",", "$", "this", "->", "protocolVersion", ",", "$", "this", "->", "reasonPhrase", ")", ",", "true", ",", "$", "this", "->", "statusCode", ")", ";", "// Send headers.", "foreach", "(", "$", "this", "->", "headers", "as", "$", "header", "=>", "$", "value", ")", "{", "header", "(", "sprintf", "(", "'%s: %s'", ",", "$", "header", ",", "$", "value", ")", ",", "true", ",", "$", "this", "->", "statusCode", ")", ";", "}", "// Send cookies.", "foreach", "(", "$", "this", "->", "cookies", "as", "$", "cookie", ")", "{", "setcookie", "(", "$", "cookie", "[", "'name'", "]", ",", "$", "cookie", "[", "'value'", "]", ",", "$", "cookie", "[", "'expire'", "]", ",", "$", "cookie", "[", "'path'", "]", ",", "$", "cookie", "[", "'domain'", "]", ",", "$", "cookie", "[", "'secure'", "]", ",", "$", "cookie", "[", "'httponly'", "]", ")", ";", "}", "// Send body.", "echo", "$", "this", "->", "body", ";", "}", "return", "$", "this", ";", "}" ]
Send final status, headers, cookies and body. @return self
[ "Send", "final", "status", "headers", "cookies", "and", "body", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Http/Response.php#L268-L297
35,362
hail-framework/framework
src/Database/Event/Event.php
Event.dump
public function dump($result = null) { static $keywords1 = 'SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE|START\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\s+TO\s+SAVEPOINT)?|(?:RELEASE\s+)?SAVEPOINT'; static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE'; // insert new lines $sql = " $result "; $sql = \preg_replace("#(?<=[\\s,(])($keywords1)(?=[\\s,)])#i", "\n\$1", $sql); // reduce spaces $sql = \preg_replace('#[ \t]{2,}#', ' ', $sql); $sql = \wordwrap($sql, 100); $sql = \preg_replace("#([ \t]*\r?\n){2,}#", "\n", $sql); // syntax highlight $highlighter = "#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])($keywords1)(?=[\\s,)])|(?<=[\\s,(=])($keywords2)(?=[\\s,)=])#is"; $sql = \htmlspecialchars($sql); $sql = \preg_replace_callback($highlighter, function ($m) { if (!empty($m[1])) { // comment return '<em style="color:gray">' . $m[1] . '</em>'; } if (!empty($m[2])) { // error return '<strong style="color:red">' . $m[2] . '</strong>'; } if (!empty($m[3])) { // most important keywords return '<strong style="color:blue">' . $m[3] . '</strong>'; } if (!empty($m[4])) { // other keywords return '<strong style="color:green">' . $m[4] . '</strong>'; } return ''; }, $sql); return '<pre class="dump">' . \trim($sql) . "</pre>\n\n"; }
php
public function dump($result = null) { static $keywords1 = 'SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE|START\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\s+TO\s+SAVEPOINT)?|(?:RELEASE\s+)?SAVEPOINT'; static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE'; // insert new lines $sql = " $result "; $sql = \preg_replace("#(?<=[\\s,(])($keywords1)(?=[\\s,)])#i", "\n\$1", $sql); // reduce spaces $sql = \preg_replace('#[ \t]{2,}#', ' ', $sql); $sql = \wordwrap($sql, 100); $sql = \preg_replace("#([ \t]*\r?\n){2,}#", "\n", $sql); // syntax highlight $highlighter = "#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])($keywords1)(?=[\\s,)])|(?<=[\\s,(=])($keywords2)(?=[\\s,)=])#is"; $sql = \htmlspecialchars($sql); $sql = \preg_replace_callback($highlighter, function ($m) { if (!empty($m[1])) { // comment return '<em style="color:gray">' . $m[1] . '</em>'; } if (!empty($m[2])) { // error return '<strong style="color:red">' . $m[2] . '</strong>'; } if (!empty($m[3])) { // most important keywords return '<strong style="color:blue">' . $m[3] . '</strong>'; } if (!empty($m[4])) { // other keywords return '<strong style="color:green">' . $m[4] . '</strong>'; } return ''; }, $sql); return '<pre class="dump">' . \trim($sql) . "</pre>\n\n"; }
[ "public", "function", "dump", "(", "$", "result", "=", "null", ")", "{", "static", "$", "keywords1", "=", "'SELECT|(?:ON\\s+DUPLICATE\\s+KEY)?UPDATE|INSERT(?:\\s+INTO)?|REPLACE(?:\\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\\s+BY|ORDER\\s+BY|LIMIT|OFFSET|FETCH\\s+NEXT|SET|VALUES|LEFT\\s+JOIN|INNER\\s+JOIN|TRUNCATE|START\\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\\s+TO\\s+SAVEPOINT)?|(?:RELEASE\\s+)?SAVEPOINT'", ";", "static", "$", "keywords2", "=", "'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE'", ";", "// insert new lines", "$", "sql", "=", "\" $result \"", ";", "$", "sql", "=", "\\", "preg_replace", "(", "\"#(?<=[\\\\s,(])($keywords1)(?=[\\\\s,)])#i\"", ",", "\"\\n\\$1\"", ",", "$", "sql", ")", ";", "// reduce spaces", "$", "sql", "=", "\\", "preg_replace", "(", "'#[ \\t]{2,}#'", ",", "' '", ",", "$", "sql", ")", ";", "$", "sql", "=", "\\", "wordwrap", "(", "$", "sql", ",", "100", ")", ";", "$", "sql", "=", "\\", "preg_replace", "(", "\"#([ \\t]*\\r?\\n){2,}#\"", ",", "\"\\n\"", ",", "$", "sql", ")", ";", "// syntax highlight", "$", "highlighter", "=", "\"#(/\\\\*.+?\\\\*/)|(\\\\*\\\\*.+?\\\\*\\\\*)|(?<=[\\\\s,(])($keywords1)(?=[\\\\s,)])|(?<=[\\\\s,(=])($keywords2)(?=[\\\\s,)=])#is\"", ";", "$", "sql", "=", "\\", "htmlspecialchars", "(", "$", "sql", ")", ";", "$", "sql", "=", "\\", "preg_replace_callback", "(", "$", "highlighter", ",", "function", "(", "$", "m", ")", "{", "if", "(", "!", "empty", "(", "$", "m", "[", "1", "]", ")", ")", "{", "// comment", "return", "'<em style=\"color:gray\">'", ".", "$", "m", "[", "1", "]", ".", "'</em>'", ";", "}", "if", "(", "!", "empty", "(", "$", "m", "[", "2", "]", ")", ")", "{", "// error", "return", "'<strong style=\"color:red\">'", ".", "$", "m", "[", "2", "]", ".", "'</strong>'", ";", "}", "if", "(", "!", "empty", "(", "$", "m", "[", "3", "]", ")", ")", "{", "// most important keywords", "return", "'<strong style=\"color:blue\">'", ".", "$", "m", "[", "3", "]", ".", "'</strong>'", ";", "}", "if", "(", "!", "empty", "(", "$", "m", "[", "4", "]", ")", ")", "{", "// other keywords", "return", "'<strong style=\"color:green\">'", ".", "$", "m", "[", "4", "]", ".", "'</strong>'", ";", "}", "return", "''", ";", "}", ",", "$", "sql", ")", ";", "return", "'<pre class=\"dump\">'", ".", "\\", "trim", "(", "$", "sql", ")", ".", "\"</pre>\\n\\n\"", ";", "}" ]
Prints out a syntax highlighted version of the SQL command or Result. @param string $result @return string
[ "Prints", "out", "a", "syntax", "highlighted", "version", "of", "the", "SQL", "command", "or", "Result", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Event/Event.php#L243-L280
35,363
hail-framework/framework
src/Console/Command.php
Command.getApplication
public function getApplication(): ?Application { if ($this->application) { return $this->application; } if ($p = $this->parent) { return $this->application = $p->getApplication(); } return null; }
php
public function getApplication(): ?Application { if ($this->application) { return $this->application; } if ($p = $this->parent) { return $this->application = $p->getApplication(); } return null; }
[ "public", "function", "getApplication", "(", ")", ":", "?", "Application", "{", "if", "(", "$", "this", "->", "application", ")", "{", "return", "$", "this", "->", "application", ";", "}", "if", "(", "$", "p", "=", "$", "this", "->", "parent", ")", "{", "return", "$", "this", "->", "application", "=", "$", "p", "->", "getApplication", "(", ")", ";", "}", "return", "null", ";", "}" ]
Get the main application object from parents @return Application|null
[ "Get", "the", "main", "application", "object", "from", "parents" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Command.php#L51-L62
35,364
hail-framework/framework
src/Console/Command.php
Command.addExtension
public function addExtension(AbstractExtension $extension) { if (!$extension->isAvailable()) { throw new ExtensionException('Extension ' . get_class($extension) . ' is not available', $extension); } $this->extensions[] = $extension->bind($this); }
php
public function addExtension(AbstractExtension $extension) { if (!$extension->isAvailable()) { throw new ExtensionException('Extension ' . get_class($extension) . ' is not available', $extension); } $this->extensions[] = $extension->bind($this); }
[ "public", "function", "addExtension", "(", "AbstractExtension", "$", "extension", ")", "{", "if", "(", "!", "$", "extension", "->", "isAvailable", "(", ")", ")", "{", "throw", "new", "ExtensionException", "(", "'Extension '", ".", "get_class", "(", "$", "extension", ")", ".", "' is not available'", ",", "$", "extension", ")", ";", "}", "$", "this", "->", "extensions", "[", "]", "=", "$", "extension", "->", "bind", "(", "$", "this", ")", ";", "}" ]
Register and bind the extension @param AbstractExtension $extension @throws ExtensionException
[ "Register", "and", "bind", "the", "extension" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Command.php#L76-L83
35,365
hail-framework/framework
src/Console/Command.php
Command.extension
public function extension($extension) { if (is_string($extension)) { $extension = new $extension; } elseif (!$extension instanceof AbstractExtension) { throw new \LogicException('Not an extension object or an extension class name.'); } $this->addExtension($extension); }
php
public function extension($extension) { if (is_string($extension)) { $extension = new $extension; } elseif (!$extension instanceof AbstractExtension) { throw new \LogicException('Not an extension object or an extension class name.'); } $this->addExtension($extension); }
[ "public", "function", "extension", "(", "$", "extension", ")", "{", "if", "(", "is_string", "(", "$", "extension", ")", ")", "{", "$", "extension", "=", "new", "$", "extension", ";", "}", "elseif", "(", "!", "$", "extension", "instanceof", "AbstractExtension", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Not an extension object or an extension class name.'", ")", ";", "}", "$", "this", "->", "addExtension", "(", "$", "extension", ")", ";", "}" ]
method `extension` is an alias of addExtension @param AbstractExtension|string $extension @throws ExtensionException
[ "method", "extension", "is", "an", "alias", "of", "addExtension" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Command.php#L92-L101
35,366
hail-framework/framework
src/Console/Component/Prompter.php
Prompter.ask
public function ask(string $prompt, array $validAnswers = [], string $default = null) { if ($validAnswers) { $answers = []; foreach ($validAnswers as $v) { if ($default && $default === $v) { $answers[] = '[' . $v . ']'; } else { $answers[] = $v; } } $prompt .= ' (' . implode('/', $answers) . ')'; } $prompt .= ' '; if ($this->style) { echo $this->formatter->getStartMark($this->style); } $answer = null; while (true) { $answer = trim($this->console->readLine($prompt)); if ($validAnswers) { if (in_array($answer, $validAnswers, true)) { break; } if (trim($answer) === '' && $default) { $answer = $default; break; } continue; } break; } if ($this->style) { echo $this->formatter->getClearMark(); } return $answer; }
php
public function ask(string $prompt, array $validAnswers = [], string $default = null) { if ($validAnswers) { $answers = []; foreach ($validAnswers as $v) { if ($default && $default === $v) { $answers[] = '[' . $v . ']'; } else { $answers[] = $v; } } $prompt .= ' (' . implode('/', $answers) . ')'; } $prompt .= ' '; if ($this->style) { echo $this->formatter->getStartMark($this->style); } $answer = null; while (true) { $answer = trim($this->console->readLine($prompt)); if ($validAnswers) { if (in_array($answer, $validAnswers, true)) { break; } if (trim($answer) === '' && $default) { $answer = $default; break; } continue; } break; } if ($this->style) { echo $this->formatter->getClearMark(); } return $answer; }
[ "public", "function", "ask", "(", "string", "$", "prompt", ",", "array", "$", "validAnswers", "=", "[", "]", ",", "string", "$", "default", "=", "null", ")", "{", "if", "(", "$", "validAnswers", ")", "{", "$", "answers", "=", "[", "]", ";", "foreach", "(", "$", "validAnswers", "as", "$", "v", ")", "{", "if", "(", "$", "default", "&&", "$", "default", "===", "$", "v", ")", "{", "$", "answers", "[", "]", "=", "'['", ".", "$", "v", ".", "']'", ";", "}", "else", "{", "$", "answers", "[", "]", "=", "$", "v", ";", "}", "}", "$", "prompt", ".=", "' ('", ".", "implode", "(", "'/'", ",", "$", "answers", ")", ".", "')'", ";", "}", "$", "prompt", ".=", "' '", ";", "if", "(", "$", "this", "->", "style", ")", "{", "echo", "$", "this", "->", "formatter", "->", "getStartMark", "(", "$", "this", "->", "style", ")", ";", "}", "$", "answer", "=", "null", ";", "while", "(", "true", ")", "{", "$", "answer", "=", "trim", "(", "$", "this", "->", "console", "->", "readLine", "(", "$", "prompt", ")", ")", ";", "if", "(", "$", "validAnswers", ")", "{", "if", "(", "in_array", "(", "$", "answer", ",", "$", "validAnswers", ",", "true", ")", ")", "{", "break", ";", "}", "if", "(", "trim", "(", "$", "answer", ")", "===", "''", "&&", "$", "default", ")", "{", "$", "answer", "=", "$", "default", ";", "break", ";", "}", "continue", ";", "}", "break", ";", "}", "if", "(", "$", "this", "->", "style", ")", "{", "echo", "$", "this", "->", "formatter", "->", "getClearMark", "(", ")", ";", "}", "return", "$", "answer", ";", "}" ]
Show prompt with message, you can provide valid options for the simple validation. @param string $prompt @param array $validAnswers an array of valid values (optional) @param string|null $default @return null|string
[ "Show", "prompt", "with", "message", "you", "can", "provide", "valid", "options", "for", "the", "simple", "validation", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Component/Prompter.php#L72-L114
35,367
hail-framework/framework
src/Console/Component/Prompter.php
Prompter.password
public function password(string $prompt) { if ($this->style) { echo $this->formatter->getStartMark($this->style); } $result = $this->console->readPassword($prompt); if ($this->style) { echo $this->formatter->getClearMark(); } return $result; }
php
public function password(string $prompt) { if ($this->style) { echo $this->formatter->getStartMark($this->style); } $result = $this->console->readPassword($prompt); if ($this->style) { echo $this->formatter->getClearMark(); } return $result; }
[ "public", "function", "password", "(", "string", "$", "prompt", ")", "{", "if", "(", "$", "this", "->", "style", ")", "{", "echo", "$", "this", "->", "formatter", "->", "getStartMark", "(", "$", "this", "->", "style", ")", ";", "}", "$", "result", "=", "$", "this", "->", "console", "->", "readPassword", "(", "$", "prompt", ")", ";", "if", "(", "$", "this", "->", "style", ")", "{", "echo", "$", "this", "->", "formatter", "->", "getClearMark", "(", ")", ";", "}", "return", "$", "result", ";", "}" ]
Show password prompt with a message. @param string $prompt @return mixed|string
[ "Show", "password", "prompt", "with", "a", "message", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Component/Prompter.php#L123-L136
35,368
hail-framework/framework
src/Console/Component/Prompter.php
Prompter.choose
public function choose(string $prompt, array $choices) { echo "$prompt: \n"; $choicesMap = []; $i = 0; if (Arrays::isAssoc($choices)) { foreach ($choices as $choice => $value) { $choicesMap[++$i] = $value; echo "\t$i: " . $choice . ' => ' . $value . "\n"; } } else { //is sequential foreach ($choices as $choice) { $choicesMap[++$i] = $choice; echo "\t$i: $choice\n"; } } if ($this->style) { echo $this->formatter->getStartMark($this->style); } $completionItems = array_keys($choicesMap); $choosePrompt = "Please Choose 1-$i > "; if (ReadlineConsole::isAvailable()) { readline_completion_function(function () use ($completionItems) { return $completionItems; }); } while (true) { $answer = (int) trim($this->console->readLine($choosePrompt)); if (isset($choicesMap[$answer])) { if ($this->style) { echo $this->formatter->getClearMark(); } return $choicesMap[$answer]; } } }
php
public function choose(string $prompt, array $choices) { echo "$prompt: \n"; $choicesMap = []; $i = 0; if (Arrays::isAssoc($choices)) { foreach ($choices as $choice => $value) { $choicesMap[++$i] = $value; echo "\t$i: " . $choice . ' => ' . $value . "\n"; } } else { //is sequential foreach ($choices as $choice) { $choicesMap[++$i] = $choice; echo "\t$i: $choice\n"; } } if ($this->style) { echo $this->formatter->getStartMark($this->style); } $completionItems = array_keys($choicesMap); $choosePrompt = "Please Choose 1-$i > "; if (ReadlineConsole::isAvailable()) { readline_completion_function(function () use ($completionItems) { return $completionItems; }); } while (true) { $answer = (int) trim($this->console->readLine($choosePrompt)); if (isset($choicesMap[$answer])) { if ($this->style) { echo $this->formatter->getClearMark(); } return $choicesMap[$answer]; } } }
[ "public", "function", "choose", "(", "string", "$", "prompt", ",", "array", "$", "choices", ")", "{", "echo", "\"$prompt: \\n\"", ";", "$", "choicesMap", "=", "[", "]", ";", "$", "i", "=", "0", ";", "if", "(", "Arrays", "::", "isAssoc", "(", "$", "choices", ")", ")", "{", "foreach", "(", "$", "choices", "as", "$", "choice", "=>", "$", "value", ")", "{", "$", "choicesMap", "[", "++", "$", "i", "]", "=", "$", "value", ";", "echo", "\"\\t$i: \"", ".", "$", "choice", ".", "' => '", ".", "$", "value", ".", "\"\\n\"", ";", "}", "}", "else", "{", "//is sequential", "foreach", "(", "$", "choices", "as", "$", "choice", ")", "{", "$", "choicesMap", "[", "++", "$", "i", "]", "=", "$", "choice", ";", "echo", "\"\\t$i: $choice\\n\"", ";", "}", "}", "if", "(", "$", "this", "->", "style", ")", "{", "echo", "$", "this", "->", "formatter", "->", "getStartMark", "(", "$", "this", "->", "style", ")", ";", "}", "$", "completionItems", "=", "array_keys", "(", "$", "choicesMap", ")", ";", "$", "choosePrompt", "=", "\"Please Choose 1-$i > \"", ";", "if", "(", "ReadlineConsole", "::", "isAvailable", "(", ")", ")", "{", "readline_completion_function", "(", "function", "(", ")", "use", "(", "$", "completionItems", ")", "{", "return", "$", "completionItems", ";", "}", ")", ";", "}", "while", "(", "true", ")", "{", "$", "answer", "=", "(", "int", ")", "trim", "(", "$", "this", "->", "console", "->", "readLine", "(", "$", "choosePrompt", ")", ")", ";", "if", "(", "isset", "(", "$", "choicesMap", "[", "$", "answer", "]", ")", ")", "{", "if", "(", "$", "this", "->", "style", ")", "{", "echo", "$", "this", "->", "formatter", "->", "getClearMark", "(", ")", ";", "}", "return", "$", "choicesMap", "[", "$", "answer", "]", ";", "}", "}", "}" ]
Provide a simple console menu for choices, which gives values an index number for user to choose items. @code $val = $app->choose('Your versions' , array( 'php-5.4.0' => '5.4.0', 'php-5.4.1' => '5.4.1', 'system' => '5.3.0', )); var_dump($val); @code @param string $prompt Prompt message @param array $choices @return mixed value
[ "Provide", "a", "simple", "console", "menu", "for", "choices", "which", "gives", "values", "an", "index", "number", "for", "user", "to", "choose", "items", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Component/Prompter.php#L158-L202
35,369
htmlburger/wpemerge-cli
src/Templates/Template.php
Template.storeOnDisc
public function storeOnDisc( $name, $namespace, $contents, $directory ) { $filepath = implode( DIRECTORY_SEPARATOR, [$directory, 'app', 'src', $namespace, $name . '.php'] ); if ( file_exists( $filepath ) ) { throw new InvalidArgumentException( 'Class file already exists (' . $filepath . ')' ); } file_put_contents( $filepath, $contents ); return $filepath; }
php
public function storeOnDisc( $name, $namespace, $contents, $directory ) { $filepath = implode( DIRECTORY_SEPARATOR, [$directory, 'app', 'src', $namespace, $name . '.php'] ); if ( file_exists( $filepath ) ) { throw new InvalidArgumentException( 'Class file already exists (' . $filepath . ')' ); } file_put_contents( $filepath, $contents ); return $filepath; }
[ "public", "function", "storeOnDisc", "(", "$", "name", ",", "$", "namespace", ",", "$", "contents", ",", "$", "directory", ")", "{", "$", "filepath", "=", "implode", "(", "DIRECTORY_SEPARATOR", ",", "[", "$", "directory", ",", "'app'", ",", "'src'", ",", "$", "namespace", ",", "$", "name", ".", "'.php'", "]", ")", ";", "if", "(", "file_exists", "(", "$", "filepath", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Class file already exists ('", ".", "$", "filepath", ".", "')'", ")", ";", "}", "file_put_contents", "(", "$", "filepath", ",", "$", "contents", ")", ";", "return", "$", "filepath", ";", "}" ]
Store file on disc returning the filepath @param string $name @param string $namespace @param string $contents @param string $directory @return string
[ "Store", "file", "on", "disc", "returning", "the", "filepath" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Templates/Template.php#L26-L36
35,370
hail-framework/framework
src/Filesystem/Adapter/Ftp.php
Ftp.disconnect
public function disconnect() { if (\is_resource($this->connection)) { \ftp_close($this->connection); } $this->connection = null; }
php
public function disconnect() { if (\is_resource($this->connection)) { \ftp_close($this->connection); } $this->connection = null; }
[ "public", "function", "disconnect", "(", ")", "{", "if", "(", "\\", "is_resource", "(", "$", "this", "->", "connection", ")", ")", "{", "\\", "ftp_close", "(", "$", "this", "->", "connection", ")", ";", "}", "$", "this", "->", "connection", "=", "null", ";", "}" ]
Disconnect from the FTP server.
[ "Disconnect", "from", "the", "FTP", "server", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Ftp.php#L221-L228
35,371
hail-framework/framework
src/Filesystem/Adapter/Ftp.php
Ftp.isConnected
public function isConnected() { try { return \is_resource($this->connection) && \ftp_rawlist($this->connection, $this->getRoot()) !== false; } catch (\ErrorException $e) { if (\strpos($e->getMessage(), 'ftp_rawlist') === false) { throw $e; } return false; } }
php
public function isConnected() { try { return \is_resource($this->connection) && \ftp_rawlist($this->connection, $this->getRoot()) !== false; } catch (\ErrorException $e) { if (\strpos($e->getMessage(), 'ftp_rawlist') === false) { throw $e; } return false; } }
[ "public", "function", "isConnected", "(", ")", "{", "try", "{", "return", "\\", "is_resource", "(", "$", "this", "->", "connection", ")", "&&", "\\", "ftp_rawlist", "(", "$", "this", "->", "connection", ",", "$", "this", "->", "getRoot", "(", ")", ")", "!==", "false", ";", "}", "catch", "(", "\\", "ErrorException", "$", "e", ")", "{", "if", "(", "\\", "strpos", "(", "$", "e", "->", "getMessage", "(", ")", ",", "'ftp_rawlist'", ")", "===", "false", ")", "{", "throw", "$", "e", ";", "}", "return", "false", ";", "}", "}" ]
Check if the connection is open. @return bool
[ "Check", "if", "the", "connection", "is", "open", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Ftp.php#L528-L539
35,372
cfxmarkets/php-public-models
src/Brokerage/AclEntriesCollection.php
AclEntriesCollection.actorHasPermissionsOnTarget
public function actorHasPermissionsOnTarget(string $actorType, string $actorId, string $targetType, string $targetId, int $permissions) { foreach($this->elements as $k => $v) { if ( $v->getActor()->getResourceType() === $actorType && $v->getActor()->getId() === $actorId && $v->getTarget()->getResourceType() === $targetType && $v->getTarget()->getId() === $targetId && $v->hasPermissions($permissions) ) { return true; } } return false; }
php
public function actorHasPermissionsOnTarget(string $actorType, string $actorId, string $targetType, string $targetId, int $permissions) { foreach($this->elements as $k => $v) { if ( $v->getActor()->getResourceType() === $actorType && $v->getActor()->getId() === $actorId && $v->getTarget()->getResourceType() === $targetType && $v->getTarget()->getId() === $targetId && $v->hasPermissions($permissions) ) { return true; } } return false; }
[ "public", "function", "actorHasPermissionsOnTarget", "(", "string", "$", "actorType", ",", "string", "$", "actorId", ",", "string", "$", "targetType", ",", "string", "$", "targetId", ",", "int", "$", "permissions", ")", "{", "foreach", "(", "$", "this", "->", "elements", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "v", "->", "getActor", "(", ")", "->", "getResourceType", "(", ")", "===", "$", "actorType", "&&", "$", "v", "->", "getActor", "(", ")", "->", "getId", "(", ")", "===", "$", "actorId", "&&", "$", "v", "->", "getTarget", "(", ")", "->", "getResourceType", "(", ")", "===", "$", "targetType", "&&", "$", "v", "->", "getTarget", "(", ")", "->", "getId", "(", ")", "===", "$", "targetId", "&&", "$", "v", "->", "hasPermissions", "(", "$", "permissions", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Searches all available AclEntries in collection for one that matches the given actor and target and then checks permissions @param string $actorType @param string $actorId @param string $targetType @param string $targetId @param int $permissions A bitmask defining the permissions to check
[ "Searches", "all", "available", "AclEntries", "in", "collection", "for", "one", "that", "matches", "the", "given", "actor", "and", "target", "and", "then", "checks", "permissions" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/Brokerage/AclEntriesCollection.php#L15-L30
35,373
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.validateType
protected function validateType($field, $val, $type, $required = true) { if ($val !== null) { if ($type === 'string') { $result = is_string($val); } elseif ($type === 'non-numeric string') { $result = is_string($val) && !is_numeric($val); } elseif ($type === 'int' || $type === 'integer') { $result = is_int($val); } elseif ($type === "numeric") { $result = is_numeric($val); } elseif ($type === 'non-string numeric') { $result = !is_string($val) && is_numeric($val); } elseif ($type === 'string or int') { $result = is_string($val) || is_int($val); } elseif ($type === 'boolean' || $type === 'bool') { $result = is_bool($val); } elseif ($type === 'datetime') { $result = ($val instanceof \DateTime); } elseif ($type === 'email') { $result = is_string($val) && preg_match($this->getKnownFormat("email"), $val); } elseif ($type === 'uri') { $result = is_string($val) && preg_match($this->getKnownFormat("uri"), $val); } elseif ($type === 'url') { $result = is_string($val) && preg_match($this->getKnownFormat("url"), $val) && $val !== ""; } else { throw new \RuntimeException("Programmer: Don't know how to validate for type `$type`!"); } } else { $result = !$required; } if ($result) { $this->clearError($field, 'validType'); return true; } else { $this->setError($field, 'validType', [ "title" => "Invalid Value for Field `$field`", "detail" => "Field `$field` must be a(n) $type value." ]); return false; } }
php
protected function validateType($field, $val, $type, $required = true) { if ($val !== null) { if ($type === 'string') { $result = is_string($val); } elseif ($type === 'non-numeric string') { $result = is_string($val) && !is_numeric($val); } elseif ($type === 'int' || $type === 'integer') { $result = is_int($val); } elseif ($type === "numeric") { $result = is_numeric($val); } elseif ($type === 'non-string numeric') { $result = !is_string($val) && is_numeric($val); } elseif ($type === 'string or int') { $result = is_string($val) || is_int($val); } elseif ($type === 'boolean' || $type === 'bool') { $result = is_bool($val); } elseif ($type === 'datetime') { $result = ($val instanceof \DateTime); } elseif ($type === 'email') { $result = is_string($val) && preg_match($this->getKnownFormat("email"), $val); } elseif ($type === 'uri') { $result = is_string($val) && preg_match($this->getKnownFormat("uri"), $val); } elseif ($type === 'url') { $result = is_string($val) && preg_match($this->getKnownFormat("url"), $val) && $val !== ""; } else { throw new \RuntimeException("Programmer: Don't know how to validate for type `$type`!"); } } else { $result = !$required; } if ($result) { $this->clearError($field, 'validType'); return true; } else { $this->setError($field, 'validType', [ "title" => "Invalid Value for Field `$field`", "detail" => "Field `$field` must be a(n) $type value." ]); return false; } }
[ "protected", "function", "validateType", "(", "$", "field", ",", "$", "val", ",", "$", "type", ",", "$", "required", "=", "true", ")", "{", "if", "(", "$", "val", "!==", "null", ")", "{", "if", "(", "$", "type", "===", "'string'", ")", "{", "$", "result", "=", "is_string", "(", "$", "val", ")", ";", "}", "elseif", "(", "$", "type", "===", "'non-numeric string'", ")", "{", "$", "result", "=", "is_string", "(", "$", "val", ")", "&&", "!", "is_numeric", "(", "$", "val", ")", ";", "}", "elseif", "(", "$", "type", "===", "'int'", "||", "$", "type", "===", "'integer'", ")", "{", "$", "result", "=", "is_int", "(", "$", "val", ")", ";", "}", "elseif", "(", "$", "type", "===", "\"numeric\"", ")", "{", "$", "result", "=", "is_numeric", "(", "$", "val", ")", ";", "}", "elseif", "(", "$", "type", "===", "'non-string numeric'", ")", "{", "$", "result", "=", "!", "is_string", "(", "$", "val", ")", "&&", "is_numeric", "(", "$", "val", ")", ";", "}", "elseif", "(", "$", "type", "===", "'string or int'", ")", "{", "$", "result", "=", "is_string", "(", "$", "val", ")", "||", "is_int", "(", "$", "val", ")", ";", "}", "elseif", "(", "$", "type", "===", "'boolean'", "||", "$", "type", "===", "'bool'", ")", "{", "$", "result", "=", "is_bool", "(", "$", "val", ")", ";", "}", "elseif", "(", "$", "type", "===", "'datetime'", ")", "{", "$", "result", "=", "(", "$", "val", "instanceof", "\\", "DateTime", ")", ";", "}", "elseif", "(", "$", "type", "===", "'email'", ")", "{", "$", "result", "=", "is_string", "(", "$", "val", ")", "&&", "preg_match", "(", "$", "this", "->", "getKnownFormat", "(", "\"email\"", ")", ",", "$", "val", ")", ";", "}", "elseif", "(", "$", "type", "===", "'uri'", ")", "{", "$", "result", "=", "is_string", "(", "$", "val", ")", "&&", "preg_match", "(", "$", "this", "->", "getKnownFormat", "(", "\"uri\"", ")", ",", "$", "val", ")", ";", "}", "elseif", "(", "$", "type", "===", "'url'", ")", "{", "$", "result", "=", "is_string", "(", "$", "val", ")", "&&", "preg_match", "(", "$", "this", "->", "getKnownFormat", "(", "\"url\"", ")", ",", "$", "val", ")", "&&", "$", "val", "!==", "\"\"", ";", "}", "else", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Programmer: Don't know how to validate for type `$type`!\"", ")", ";", "}", "}", "else", "{", "$", "result", "=", "!", "$", "required", ";", "}", "if", "(", "$", "result", ")", "{", "$", "this", "->", "clearError", "(", "$", "field", ",", "'validType'", ")", ";", "return", "true", ";", "}", "else", "{", "$", "this", "->", "setError", "(", "$", "field", ",", "'validType'", ",", "[", "\"title\"", "=>", "\"Invalid Value for Field `$field`\"", ",", "\"detail\"", "=>", "\"Field `$field` must be a(n) $type value.\"", "]", ")", ";", "return", "false", ";", "}", "}" ]
Validates that the value for a given field is of the specified type @param string $field The name of the field (attribute or relationship) being validated @param mixed $val The value to validate @param string $type The type that the value should be @param bool $required Whether or not the value is required (this affects how `null` is handled) @return bool Whether or not the validation has passed
[ "Validates", "that", "the", "value", "for", "a", "given", "field", "is", "of", "the", "specified", "type" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L18-L60
35,374
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.validateFormat
protected function validateFormat($field, ?string $val, $format, $required = true) { if ($val !== null) { $regexp = $this->getKnownFormat($format); if (!$regexp) { $regexp = $format; } $result = preg_match($regexp, $val); } else { $result = !$required; } if ($result) { $this->clearError($field, 'validFormat'); return true; } else { $error = [ "title" => "Invalid Format for Field `$field`", "detail" => "Value for field `$field` must be a(n) $format." ]; if ($format === $regexp) { $error["detail"] = "Value for field `$field` must match $format."; } $this->setError($field, 'validFormat', $error); return false; } }
php
protected function validateFormat($field, ?string $val, $format, $required = true) { if ($val !== null) { $regexp = $this->getKnownFormat($format); if (!$regexp) { $regexp = $format; } $result = preg_match($regexp, $val); } else { $result = !$required; } if ($result) { $this->clearError($field, 'validFormat'); return true; } else { $error = [ "title" => "Invalid Format for Field `$field`", "detail" => "Value for field `$field` must be a(n) $format." ]; if ($format === $regexp) { $error["detail"] = "Value for field `$field` must match $format."; } $this->setError($field, 'validFormat', $error); return false; } }
[ "protected", "function", "validateFormat", "(", "$", "field", ",", "?", "string", "$", "val", ",", "$", "format", ",", "$", "required", "=", "true", ")", "{", "if", "(", "$", "val", "!==", "null", ")", "{", "$", "regexp", "=", "$", "this", "->", "getKnownFormat", "(", "$", "format", ")", ";", "if", "(", "!", "$", "regexp", ")", "{", "$", "regexp", "=", "$", "format", ";", "}", "$", "result", "=", "preg_match", "(", "$", "regexp", ",", "$", "val", ")", ";", "}", "else", "{", "$", "result", "=", "!", "$", "required", ";", "}", "if", "(", "$", "result", ")", "{", "$", "this", "->", "clearError", "(", "$", "field", ",", "'validFormat'", ")", ";", "return", "true", ";", "}", "else", "{", "$", "error", "=", "[", "\"title\"", "=>", "\"Invalid Format for Field `$field`\"", ",", "\"detail\"", "=>", "\"Value for field `$field` must be a(n) $format.\"", "]", ";", "if", "(", "$", "format", "===", "$", "regexp", ")", "{", "$", "error", "[", "\"detail\"", "]", "=", "\"Value for field `$field` must match $format.\"", ";", "}", "$", "this", "->", "setError", "(", "$", "field", ",", "'validFormat'", ",", "$", "error", ")", ";", "return", "false", ";", "}", "}" ]
Validates that the value for a given field is of the specified format @param string $field The name of the field (attribute or relationship) being validated @param mixed $val The value to validate @param string $format Either a named format or regexp string @param bool $required Whether or not the value is required (this affects how `null` is handled) @return bool Whether or not the validation has passed
[ "Validates", "that", "the", "value", "for", "a", "given", "field", "is", "of", "the", "specified", "format" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L72-L98
35,375
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.validateAmong
protected function validateAmong($field, $val, array $validOptions, $required = true) { if ($val !== null) { $result = in_array($val, $validOptions, true); } else { $result = !$required; } if ($result) { $this->clearError($field, 'validAmongOptions'); return true; } else { $this->setError($field, 'validAmongOptions', [ "title" => "Invalid Value for Field `$field`", "detail" => "Field `$field` must be one of the accepted options: `".implode("`, `", $validOptions)."`" ]); return false; } }
php
protected function validateAmong($field, $val, array $validOptions, $required = true) { if ($val !== null) { $result = in_array($val, $validOptions, true); } else { $result = !$required; } if ($result) { $this->clearError($field, 'validAmongOptions'); return true; } else { $this->setError($field, 'validAmongOptions', [ "title" => "Invalid Value for Field `$field`", "detail" => "Field `$field` must be one of the accepted options: `".implode("`, `", $validOptions)."`" ]); return false; } }
[ "protected", "function", "validateAmong", "(", "$", "field", ",", "$", "val", ",", "array", "$", "validOptions", ",", "$", "required", "=", "true", ")", "{", "if", "(", "$", "val", "!==", "null", ")", "{", "$", "result", "=", "in_array", "(", "$", "val", ",", "$", "validOptions", ",", "true", ")", ";", "}", "else", "{", "$", "result", "=", "!", "$", "required", ";", "}", "if", "(", "$", "result", ")", "{", "$", "this", "->", "clearError", "(", "$", "field", ",", "'validAmongOptions'", ")", ";", "return", "true", ";", "}", "else", "{", "$", "this", "->", "setError", "(", "$", "field", ",", "'validAmongOptions'", ",", "[", "\"title\"", "=>", "\"Invalid Value for Field `$field`\"", ",", "\"detail\"", "=>", "\"Field `$field` must be one of the accepted options: `\"", ".", "implode", "(", "\"`, `\"", ",", "$", "validOptions", ")", ".", "\"`\"", "]", ")", ";", "return", "false", ";", "}", "}" ]
Validates that the value for a given field is in the given array of valid options @param string $field The name of the field (attribute or relationship) being validated @param mixed $val The value to validate @param array $validOptions The collection of valid options among which the value should be found @param bool $required Whether or not the value is required (this affects how `null` is handled) @return bool Whether or not the validation has passed
[ "Validates", "that", "the", "value", "for", "a", "given", "field", "is", "in", "the", "given", "array", "of", "valid", "options" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L111-L129
35,376
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.validateStrlen
protected function validateStrlen(string $field, ?string $val, int $min, int $max, bool $required = true) { if ($val !== null) { $strlen = strlen($val); $result = !($strlen < $min || $strlen > $max); } else { $result = !$required; } if ($result) { $this->clearError($field, "length"); } else { $this->setError($field, "length", [ "title" => "Length of `$field` Out of Bounds", "detail" => "Field `$field` must be between $min and $max characters long." ]); } return $result; }
php
protected function validateStrlen(string $field, ?string $val, int $min, int $max, bool $required = true) { if ($val !== null) { $strlen = strlen($val); $result = !($strlen < $min || $strlen > $max); } else { $result = !$required; } if ($result) { $this->clearError($field, "length"); } else { $this->setError($field, "length", [ "title" => "Length of `$field` Out of Bounds", "detail" => "Field `$field` must be between $min and $max characters long." ]); } return $result; }
[ "protected", "function", "validateStrlen", "(", "string", "$", "field", ",", "?", "string", "$", "val", ",", "int", "$", "min", ",", "int", "$", "max", ",", "bool", "$", "required", "=", "true", ")", "{", "if", "(", "$", "val", "!==", "null", ")", "{", "$", "strlen", "=", "strlen", "(", "$", "val", ")", ";", "$", "result", "=", "!", "(", "$", "strlen", "<", "$", "min", "||", "$", "strlen", ">", "$", "max", ")", ";", "}", "else", "{", "$", "result", "=", "!", "$", "required", ";", "}", "if", "(", "$", "result", ")", "{", "$", "this", "->", "clearError", "(", "$", "field", ",", "\"length\"", ")", ";", "}", "else", "{", "$", "this", "->", "setError", "(", "$", "field", ",", "\"length\"", ",", "[", "\"title\"", "=>", "\"Length of `$field` Out of Bounds\"", ",", "\"detail\"", "=>", "\"Field `$field` must be between $min and $max characters long.\"", "]", ")", ";", "}", "return", "$", "result", ";", "}" ]
Validates that the given value conforms to the given length specifications @param string $field The name of the field being validated @param string|null $val The value being evaluated @param int $min The minimum length of the string (defaults to 0) @param int $max The maximum length of the string @param bool $required Whether or not the value is required @return bool Whether or not the validation has passed
[ "Validates", "that", "the", "given", "value", "conforms", "to", "the", "given", "length", "specifications" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L169-L187
35,377
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.validateRelatedResourceExists
protected function validateRelatedResourceExists($field, \CFX\JsonApi\ResourceInterface $r, $required = true) { if ($r !== null) { try { $r->initialize(); $result = true; } catch (ResourceNotFoundException $e) { $result = false; } } else { $result = !$required; } if ($result) { $this->clearError($field, 'exists'); return true; } else { $this->setError($field, 'exists', [ "title" => "Invalid Relationship `$field`", "detail" => "The `$field` you've indicated for this order is not currently in our system." ]); return false; } }
php
protected function validateRelatedResourceExists($field, \CFX\JsonApi\ResourceInterface $r, $required = true) { if ($r !== null) { try { $r->initialize(); $result = true; } catch (ResourceNotFoundException $e) { $result = false; } } else { $result = !$required; } if ($result) { $this->clearError($field, 'exists'); return true; } else { $this->setError($field, 'exists', [ "title" => "Invalid Relationship `$field`", "detail" => "The `$field` you've indicated for this order is not currently in our system." ]); return false; } }
[ "protected", "function", "validateRelatedResourceExists", "(", "$", "field", ",", "\\", "CFX", "\\", "JsonApi", "\\", "ResourceInterface", "$", "r", ",", "$", "required", "=", "true", ")", "{", "if", "(", "$", "r", "!==", "null", ")", "{", "try", "{", "$", "r", "->", "initialize", "(", ")", ";", "$", "result", "=", "true", ";", "}", "catch", "(", "ResourceNotFoundException", "$", "e", ")", "{", "$", "result", "=", "false", ";", "}", "}", "else", "{", "$", "result", "=", "!", "$", "required", ";", "}", "if", "(", "$", "result", ")", "{", "$", "this", "->", "clearError", "(", "$", "field", ",", "'exists'", ")", ";", "return", "true", ";", "}", "else", "{", "$", "this", "->", "setError", "(", "$", "field", ",", "'exists'", ",", "[", "\"title\"", "=>", "\"Invalid Relationship `$field`\"", ",", "\"detail\"", "=>", "\"The `$field` you've indicated for this order is not currently in our system.\"", "]", ")", ";", "return", "false", ";", "}", "}" ]
Validates that the given resource actually exists in the database @param string $field The name of the field (attribute or relationship) being validated @param \CFX\JsonApi\ResourceInterface $r The resource to validate @param bool $required Whether or not the resource is required (this affects how `null` is handled) @return bool Whether or not the validation has passed
[ "Validates", "that", "the", "given", "resource", "actually", "exists", "in", "the", "database" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L197-L220
35,378
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.validateImmutable
protected function validateImmutable($field, $val, $required = true) { if ($this->getInitial($field) && $this->valueDiffersFromInitial($field, $val)) { $this->setError($field, 'immutable', [ "title" => "`$field` is Immutable", "detail" => "You can't change the `$field` field of this resource once it's been set.", ]); return false; } else { $this->clearError($field, 'immutable'); return true; } }
php
protected function validateImmutable($field, $val, $required = true) { if ($this->getInitial($field) && $this->valueDiffersFromInitial($field, $val)) { $this->setError($field, 'immutable', [ "title" => "`$field` is Immutable", "detail" => "You can't change the `$field` field of this resource once it's been set.", ]); return false; } else { $this->clearError($field, 'immutable'); return true; } }
[ "protected", "function", "validateImmutable", "(", "$", "field", ",", "$", "val", ",", "$", "required", "=", "true", ")", "{", "if", "(", "$", "this", "->", "getInitial", "(", "$", "field", ")", "&&", "$", "this", "->", "valueDiffersFromInitial", "(", "$", "field", ",", "$", "val", ")", ")", "{", "$", "this", "->", "setError", "(", "$", "field", ",", "'immutable'", ",", "[", "\"title\"", "=>", "\"`$field` is Immutable\"", ",", "\"detail\"", "=>", "\"You can't change the `$field` field of this resource once it's been set.\"", ",", "]", ")", ";", "return", "false", ";", "}", "else", "{", "$", "this", "->", "clearError", "(", "$", "field", ",", "'immutable'", ")", ";", "return", "true", ";", "}", "}" ]
Validates that the given value has not been changed since the first time it was set @param string $field The name of the field (attribute or relationship) being validated @param mixed $val The value to validate @param bool $required Whether or not the resource is required (this affects how `null` is handled) @return bool Whether or not the validation has passed
[ "Validates", "that", "the", "given", "value", "has", "not", "been", "changed", "since", "the", "first", "time", "it", "was", "set" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L230-L242
35,379
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.cleanStringValue
protected function cleanStringValue($val) { if ($val !== null) { if (is_string($val)) { $val = trim($val); if ($val === '') { $val = null; } } elseif (is_int($val)) { $val = (string)$val; } } return $val; }
php
protected function cleanStringValue($val) { if ($val !== null) { if (is_string($val)) { $val = trim($val); if ($val === '') { $val = null; } } elseif (is_int($val)) { $val = (string)$val; } } return $val; }
[ "protected", "function", "cleanStringValue", "(", "$", "val", ")", "{", "if", "(", "$", "val", "!==", "null", ")", "{", "if", "(", "is_string", "(", "$", "val", ")", ")", "{", "$", "val", "=", "trim", "(", "$", "val", ")", ";", "if", "(", "$", "val", "===", "''", ")", "{", "$", "val", "=", "null", ";", "}", "}", "elseif", "(", "is_int", "(", "$", "val", ")", ")", "{", "$", "val", "=", "(", "string", ")", "$", "val", ";", "}", "}", "return", "$", "val", ";", "}" ]
Cleans a value that is expected to be a string If the value _is_ a string, this trims it and sets it to null if it's an empty string. If the value is an integer, it coerces it into a string. Otherwise, it leaves the value alone. @param mixed $val The value to clean @return mixed The cleaned string or null or the original value, if not stringish
[ "Cleans", "a", "value", "that", "is", "expected", "to", "be", "a", "string" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L253-L266
35,380
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.cleanBooleanValue
protected function cleanBooleanValue($val) { if ($val !== null) { if ($val === 1 || $val === '1' || $val === 0 || $val === '0') { $val = (bool)$val; } elseif (is_string($val) && trim($val) === '') { $val = null; } } return $val; }
php
protected function cleanBooleanValue($val) { if ($val !== null) { if ($val === 1 || $val === '1' || $val === 0 || $val === '0') { $val = (bool)$val; } elseif (is_string($val) && trim($val) === '') { $val = null; } } return $val; }
[ "protected", "function", "cleanBooleanValue", "(", "$", "val", ")", "{", "if", "(", "$", "val", "!==", "null", ")", "{", "if", "(", "$", "val", "===", "1", "||", "$", "val", "===", "'1'", "||", "$", "val", "===", "0", "||", "$", "val", "===", "'0'", ")", "{", "$", "val", "=", "(", "bool", ")", "$", "val", ";", "}", "elseif", "(", "is_string", "(", "$", "val", ")", "&&", "trim", "(", "$", "val", ")", "===", "''", ")", "{", "$", "val", "=", "null", ";", "}", "}", "return", "$", "val", ";", "}" ]
Cleans a value that is expected to be a boolean If the value is a string or integer that can evaluate to a boolean, this coerces it into a boolean. Otherwise, it leaves the value alone. @param mixed $val The value to clean @return mixed A boolean value or the original value, if not boolish
[ "Cleans", "a", "value", "that", "is", "expected", "to", "be", "a", "boolean" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L277-L287
35,381
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.cleanNumberValue
protected function cleanNumberValue($val) { if ($val !== null) { if (is_string($val)) { if (trim($val) === '') { $val = null; } elseif (is_numeric($val)) { $val = $val*1; } } } return $val; }
php
protected function cleanNumberValue($val) { if ($val !== null) { if (is_string($val)) { if (trim($val) === '') { $val = null; } elseif (is_numeric($val)) { $val = $val*1; } } } return $val; }
[ "protected", "function", "cleanNumberValue", "(", "$", "val", ")", "{", "if", "(", "$", "val", "!==", "null", ")", "{", "if", "(", "is_string", "(", "$", "val", ")", ")", "{", "if", "(", "trim", "(", "$", "val", ")", "===", "''", ")", "{", "$", "val", "=", "null", ";", "}", "elseif", "(", "is_numeric", "(", "$", "val", ")", ")", "{", "$", "val", "=", "$", "val", "*", "1", ";", "}", "}", "}", "return", "$", "val", ";", "}" ]
Cleans a value that is expected to be a number If the value is a string, this coerces it into an int or float by multiplying by 1. Otherwise, it leaves the value alone. @param mixed $val The value to clean @return mixed An int or float value or the original value, if not numeric
[ "Cleans", "a", "value", "that", "is", "expected", "to", "be", "a", "number" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L298-L310
35,382
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.cleanDateTimeValue
protected function cleanDateTimeValue($val) { // Uninterpretable values get returned as is if ((is_string($val) && substr($val, 0, 4) === '0000') || $val === false) { return $val; } // null and null-equivalent get returned as null if ($val === '' || $val === null) { return null; } // For everything else, we try to make a date out of it try { if (is_numeric($val)) { $val = new \DateTime("@".$val); } else { $val = new \DateTime($val); } return $val; } catch (\Throwable $e) { return $val; } }
php
protected function cleanDateTimeValue($val) { // Uninterpretable values get returned as is if ((is_string($val) && substr($val, 0, 4) === '0000') || $val === false) { return $val; } // null and null-equivalent get returned as null if ($val === '' || $val === null) { return null; } // For everything else, we try to make a date out of it try { if (is_numeric($val)) { $val = new \DateTime("@".$val); } else { $val = new \DateTime($val); } return $val; } catch (\Throwable $e) { return $val; } }
[ "protected", "function", "cleanDateTimeValue", "(", "$", "val", ")", "{", "// Uninterpretable values get returned as is", "if", "(", "(", "is_string", "(", "$", "val", ")", "&&", "substr", "(", "$", "val", ",", "0", ",", "4", ")", "===", "'0000'", ")", "||", "$", "val", "===", "false", ")", "{", "return", "$", "val", ";", "}", "// null and null-equivalent get returned as null", "if", "(", "$", "val", "===", "''", "||", "$", "val", "===", "null", ")", "{", "return", "null", ";", "}", "// For everything else, we try to make a date out of it", "try", "{", "if", "(", "is_numeric", "(", "$", "val", ")", ")", "{", "$", "val", "=", "new", "\\", "DateTime", "(", "\"@\"", ".", "$", "val", ")", ";", "}", "else", "{", "$", "val", "=", "new", "\\", "DateTime", "(", "$", "val", ")", ";", "}", "return", "$", "val", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "return", "$", "val", ";", "}", "}" ]
Attempts to convert an integer or string into a DateTime object @param mixed $val The value to clean @return mixed A DateTime object or the original value, if not coercible
[ "Attempts", "to", "convert", "an", "integer", "or", "string", "into", "a", "DateTime", "object" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L318-L341
35,383
cfxmarkets/php-public-models
src/ResourceValidationsTrait.php
ResourceValidationsTrait.getKnownFormat
protected function getKnownFormat(string $formatName) { $knownFormats = [ "email" => "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,}$/ix", "swiftCode" => "/^[A-Za-z]{6}[A-Za-z0-9]{2}[0-9A-Za-z]{0,3}$/", "uri" => "/^\w+:(\/\/)?[^\s]+$/", "url" => "/^((\w+:)?\/\/[^\s\/]+)?(\/[^\s]+)*\/?$/", ]; if (array_key_exists($formatName, $knownFormats)) { return $knownFormats[$formatName]; } else { return null; } }
php
protected function getKnownFormat(string $formatName) { $knownFormats = [ "email" => "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,}$/ix", "swiftCode" => "/^[A-Za-z]{6}[A-Za-z0-9]{2}[0-9A-Za-z]{0,3}$/", "uri" => "/^\w+:(\/\/)?[^\s]+$/", "url" => "/^((\w+:)?\/\/[^\s\/]+)?(\/[^\s]+)*\/?$/", ]; if (array_key_exists($formatName, $knownFormats)) { return $knownFormats[$formatName]; } else { return null; } }
[ "protected", "function", "getKnownFormat", "(", "string", "$", "formatName", ")", "{", "$", "knownFormats", "=", "[", "\"email\"", "=>", "\"/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*@([a-z0-9\\-]+\\.)+[a-z]{2,}$/ix\"", ",", "\"swiftCode\"", "=>", "\"/^[A-Za-z]{6}[A-Za-z0-9]{2}[0-9A-Za-z]{0,3}$/\"", ",", "\"uri\"", "=>", "\"/^\\w+:(\\/\\/)?[^\\s]+$/\"", ",", "\"url\"", "=>", "\"/^((\\w+:)?\\/\\/[^\\s\\/]+)?(\\/[^\\s]+)*\\/?$/\"", ",", "]", ";", "if", "(", "array_key_exists", "(", "$", "formatName", ",", "$", "knownFormats", ")", ")", "{", "return", "$", "knownFormats", "[", "$", "formatName", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns a list of known formats for validation @param string $formatName The name of the format to get @return string|null The regexp string representing the requested format, or null if format is not known
[ "Returns", "a", "list", "of", "known", "formats", "for", "validation" ]
b91a58f7d9519b98b29c58f0911e976e361a5f65
https://github.com/cfxmarkets/php-public-models/blob/b91a58f7d9519b98b29c58f0911e976e361a5f65/src/ResourceValidationsTrait.php#L349-L363
35,384
htmlburger/wpemerge-cli
src/Presets/PresetEnablerTrait.php
PresetEnablerTrait.enablePreset
protected function enablePreset( $filepath, $preset ) { $begin = sprintf( '~^\s*/\* @preset-begin\(%1$s\).*?\r?\n~mi', preg_quote( $preset, '~' ) ); $end = sprintf( '~^\s*@preset-end\(%1$s\) \*/\s*?\r?\n~mi', preg_quote( $preset, '~' ) ); $contents = file_get_contents( $filepath ); if ( ! preg_match( $begin, $contents ) || ! preg_match( $end, $contents ) ) { return; } $contents = preg_replace( $begin, '', $contents ); $contents = preg_replace( $end, '', $contents ); file_put_contents( $filepath, $contents ); }
php
protected function enablePreset( $filepath, $preset ) { $begin = sprintf( '~^\s*/\* @preset-begin\(%1$s\).*?\r?\n~mi', preg_quote( $preset, '~' ) ); $end = sprintf( '~^\s*@preset-end\(%1$s\) \*/\s*?\r?\n~mi', preg_quote( $preset, '~' ) ); $contents = file_get_contents( $filepath ); if ( ! preg_match( $begin, $contents ) || ! preg_match( $end, $contents ) ) { return; } $contents = preg_replace( $begin, '', $contents ); $contents = preg_replace( $end, '', $contents ); file_put_contents( $filepath, $contents ); }
[ "protected", "function", "enablePreset", "(", "$", "filepath", ",", "$", "preset", ")", "{", "$", "begin", "=", "sprintf", "(", "'~^\\s*/\\* @preset-begin\\(%1$s\\).*?\\r?\\n~mi'", ",", "preg_quote", "(", "$", "preset", ",", "'~'", ")", ")", ";", "$", "end", "=", "sprintf", "(", "'~^\\s*@preset-end\\(%1$s\\) \\*/\\s*?\\r?\\n~mi'", ",", "preg_quote", "(", "$", "preset", ",", "'~'", ")", ")", ";", "$", "contents", "=", "file_get_contents", "(", "$", "filepath", ")", ";", "if", "(", "!", "preg_match", "(", "$", "begin", ",", "$", "contents", ")", "||", "!", "preg_match", "(", "$", "end", ",", "$", "contents", ")", ")", "{", "return", ";", "}", "$", "contents", "=", "preg_replace", "(", "$", "begin", ",", "''", ",", "$", "contents", ")", ";", "$", "contents", "=", "preg_replace", "(", "$", "end", ",", "''", ",", "$", "contents", ")", ";", "file_put_contents", "(", "$", "filepath", ",", "$", "contents", ")", ";", "}" ]
Uncomment preset statements in file. @param string $filepath @param string $preset @return void
[ "Uncomment", "preset", "statements", "in", "file", "." ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/PresetEnablerTrait.php#L13-L26
35,385
Kuestenschmiede/TrackingBundle
Resources/contao/dca/tl_page.php
tl_c4gtracking_page.getTrackingConfigurations
public function getTrackingConfigurations() { /*if (!$this->User->isAdmin && !is_array($this->User->forms)) { return array(); }*/ $arrTrackingConfigurations = array(); $objTrackingConfigurations = $this->Database->execute("SELECT id, name FROM tl_c4g_tracking ORDER BY name"); while ($objTrackingConfigurations->next()) { //if ($this->User->isAdmin || $this->User->hasAccess($objForms->id, 'forms')) //{ $arrTrackingConfigurations[$objTrackingConfigurations->id] = $objTrackingConfigurations->name . ' (ID ' . $objTrackingConfigurations->id . ')'; //} } return $arrTrackingConfigurations; }
php
public function getTrackingConfigurations() { /*if (!$this->User->isAdmin && !is_array($this->User->forms)) { return array(); }*/ $arrTrackingConfigurations = array(); $objTrackingConfigurations = $this->Database->execute("SELECT id, name FROM tl_c4g_tracking ORDER BY name"); while ($objTrackingConfigurations->next()) { //if ($this->User->isAdmin || $this->User->hasAccess($objForms->id, 'forms')) //{ $arrTrackingConfigurations[$objTrackingConfigurations->id] = $objTrackingConfigurations->name . ' (ID ' . $objTrackingConfigurations->id . ')'; //} } return $arrTrackingConfigurations; }
[ "public", "function", "getTrackingConfigurations", "(", ")", "{", "/*if (!$this->User->isAdmin && !is_array($this->User->forms))\n \t\t{\n \t\t\treturn array();\n \t\t}*/", "$", "arrTrackingConfigurations", "=", "array", "(", ")", ";", "$", "objTrackingConfigurations", "=", "$", "this", "->", "Database", "->", "execute", "(", "\"SELECT id, name FROM tl_c4g_tracking ORDER BY name\"", ")", ";", "while", "(", "$", "objTrackingConfigurations", "->", "next", "(", ")", ")", "{", "//if ($this->User->isAdmin || $this->User->hasAccess($objForms->id, 'forms'))", "//{", "$", "arrTrackingConfigurations", "[", "$", "objTrackingConfigurations", "->", "id", "]", "=", "$", "objTrackingConfigurations", "->", "name", ".", "' (ID '", ".", "$", "objTrackingConfigurations", "->", "id", ".", "')'", ";", "//}", "}", "return", "$", "arrTrackingConfigurations", ";", "}" ]
Get all trcking-configurations and return them as array @return array
[ "Get", "all", "trcking", "-", "configurations", "and", "return", "them", "as", "array" ]
7ad1b8ef3103854dfce8309d2eed7060febaa4ee
https://github.com/Kuestenschmiede/TrackingBundle/blob/7ad1b8ef3103854dfce8309d2eed7060febaa4ee/Resources/contao/dca/tl_page.php#L48-L67
35,386
hail-framework/framework
src/Template/Extension/URI.php
URI.runUri
public function runUri($var1 = null, $var2 = null, $var3 = null, $var4 = null) { if (null === $var1) { return $this->uri; } if (\is_numeric($var1) && null === $var2) { return $this->parts[$var1] ?? null; } if (\is_numeric($var1) && \is_string($var2)) { return $this->checkUriSegmentMatch($var1, $var2, $var3, $var4); } if (\is_string($var1)) { return $this->checkUriRegexMatch($var1, $var2, $var3); } throw new \LogicException('Invalid use of the uri function.'); }
php
public function runUri($var1 = null, $var2 = null, $var3 = null, $var4 = null) { if (null === $var1) { return $this->uri; } if (\is_numeric($var1) && null === $var2) { return $this->parts[$var1] ?? null; } if (\is_numeric($var1) && \is_string($var2)) { return $this->checkUriSegmentMatch($var1, $var2, $var3, $var4); } if (\is_string($var1)) { return $this->checkUriRegexMatch($var1, $var2, $var3); } throw new \LogicException('Invalid use of the uri function.'); }
[ "public", "function", "runUri", "(", "$", "var1", "=", "null", ",", "$", "var2", "=", "null", ",", "$", "var3", "=", "null", ",", "$", "var4", "=", "null", ")", "{", "if", "(", "null", "===", "$", "var1", ")", "{", "return", "$", "this", "->", "uri", ";", "}", "if", "(", "\\", "is_numeric", "(", "$", "var1", ")", "&&", "null", "===", "$", "var2", ")", "{", "return", "$", "this", "->", "parts", "[", "$", "var1", "]", "??", "null", ";", "}", "if", "(", "\\", "is_numeric", "(", "$", "var1", ")", "&&", "\\", "is_string", "(", "$", "var2", ")", ")", "{", "return", "$", "this", "->", "checkUriSegmentMatch", "(", "$", "var1", ",", "$", "var2", ",", "$", "var3", ",", "$", "var4", ")", ";", "}", "if", "(", "\\", "is_string", "(", "$", "var1", ")", ")", "{", "return", "$", "this", "->", "checkUriRegexMatch", "(", "$", "var1", ",", "$", "var2", ",", "$", "var3", ")", ";", "}", "throw", "new", "\\", "LogicException", "(", "'Invalid use of the uri function.'", ")", ";", "}" ]
Perform URI check. @param null|int|string $var1 @param mixed $var2 @param mixed $var3 @param mixed $var4 @return mixed
[ "Perform", "URI", "check", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Extension/URI.php#L60-L79
35,387
hail-framework/framework
src/Template/Extension/URI.php
URI.checkUriSegmentMatch
protected function checkUriSegmentMatch($key, $string, $returnOnTrue = null, $returnOnFalse = null) { if (\array_key_exists($key, $this->parts) && $this->parts[$key] === $string) { return $returnOnTrue ?? true; } return $returnOnFalse ?? false; }
php
protected function checkUriSegmentMatch($key, $string, $returnOnTrue = null, $returnOnFalse = null) { if (\array_key_exists($key, $this->parts) && $this->parts[$key] === $string) { return $returnOnTrue ?? true; } return $returnOnFalse ?? false; }
[ "protected", "function", "checkUriSegmentMatch", "(", "$", "key", ",", "$", "string", ",", "$", "returnOnTrue", "=", "null", ",", "$", "returnOnFalse", "=", "null", ")", "{", "if", "(", "\\", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "parts", ")", "&&", "$", "this", "->", "parts", "[", "$", "key", "]", "===", "$", "string", ")", "{", "return", "$", "returnOnTrue", "??", "true", ";", "}", "return", "$", "returnOnFalse", "??", "false", ";", "}" ]
Perform a URI segment match. @param integer $key @param string $string @param mixed $returnOnTrue @param mixed $returnOnFalse @return mixed
[ "Perform", "a", "URI", "segment", "match", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Extension/URI.php#L89-L96
35,388
hail-framework/framework
src/Template/Extension/URI.php
URI.checkUriRegexMatch
protected function checkUriRegexMatch($regex, $returnOnTrue = null, $returnOnFalse = null) { if (\preg_match('#^' . $regex . '$#', $this->uri) === 1) { return $returnOnTrue ?? true; } return $returnOnFalse ?? false; }
php
protected function checkUriRegexMatch($regex, $returnOnTrue = null, $returnOnFalse = null) { if (\preg_match('#^' . $regex . '$#', $this->uri) === 1) { return $returnOnTrue ?? true; } return $returnOnFalse ?? false; }
[ "protected", "function", "checkUriRegexMatch", "(", "$", "regex", ",", "$", "returnOnTrue", "=", "null", ",", "$", "returnOnFalse", "=", "null", ")", "{", "if", "(", "\\", "preg_match", "(", "'#^'", ".", "$", "regex", ".", "'$#'", ",", "$", "this", "->", "uri", ")", "===", "1", ")", "{", "return", "$", "returnOnTrue", "??", "true", ";", "}", "return", "$", "returnOnFalse", "??", "false", ";", "}" ]
Perform a regular express match. @param string $regex @param mixed $returnOnTrue @param mixed $returnOnFalse @return mixed
[ "Perform", "a", "regular", "express", "match", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Extension/URI.php#L105-L112
35,389
systemson/collection
src/Base/NoKeysTrait.php
NoKeysTrait.add
public function add($value): bool { if ($this->has($value)) { return false; } $this->set($value); return true; }
php
public function add($value): bool { if ($this->has($value)) { return false; } $this->set($value); return true; }
[ "public", "function", "add", "(", "$", "value", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "has", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "set", "(", "$", "value", ")", ";", "return", "true", ";", "}" ]
Adds a new item to the collection. @param mixed $value @return bool true on success, false if the item already exists.
[ "Adds", "a", "new", "item", "to", "the", "collection", "." ]
fb3ae1a78806aafabc0562db96822e8b99dc2a64
https://github.com/systemson/collection/blob/fb3ae1a78806aafabc0562db96822e8b99dc2a64/src/Base/NoKeysTrait.php#L38-L47
35,390
hail-framework/framework
src/Database/Migration/Adapter/SqlServerAdapter.php
SqlServerAdapter.migrated
public function migrated(MigrationInterface $migration, $direction, $startTime, $endTime) { $startTime = str_replace(' ', 'T', $startTime); $endTime = str_replace(' ', 'T', $endTime); return parent::migrated($migration, $direction, $startTime, $endTime); }
php
public function migrated(MigrationInterface $migration, $direction, $startTime, $endTime) { $startTime = str_replace(' ', 'T', $startTime); $endTime = str_replace(' ', 'T', $endTime); return parent::migrated($migration, $direction, $startTime, $endTime); }
[ "public", "function", "migrated", "(", "MigrationInterface", "$", "migration", ",", "$", "direction", ",", "$", "startTime", ",", "$", "endTime", ")", "{", "$", "startTime", "=", "str_replace", "(", "' '", ",", "'T'", ",", "$", "startTime", ")", ";", "$", "endTime", "=", "str_replace", "(", "' '", ",", "'T'", ",", "$", "endTime", ")", ";", "return", "parent", "::", "migrated", "(", "$", "migration", ",", "$", "direction", ",", "$", "startTime", ",", "$", "endTime", ")", ";", "}" ]
Records a migration being run. @param MigrationInterface $migration Migration @param string $direction Direction @param int $startTime Start Time @param int $endTime End Time @return AdapterInterface
[ "Records", "a", "migration", "being", "run", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Adapter/SqlServerAdapter.php#L1138-L1144
35,391
htmlburger/wpemerge-cli
src/Presets/CarbonFields.php
CarbonFields.getCopyList
protected function getCopyList( $directory ) { $copy_list = [ $this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'Carbon_Rich_Text_Widget.php' ) => $this->path( $directory, 'app', 'src', 'Widgets', 'Carbon_Rich_Text_Widget.php' ), $this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'carbon-fields.php' ) => $this->path( $directory, 'app', 'helpers', 'carbon-fields.php' ), ]; $source_dir = $this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'carbon-fields' ) . DIRECTORY_SEPARATOR; $destination_dir = $this->path( $directory, 'app', 'setup', 'carbon-fields' ) . DIRECTORY_SEPARATOR; $files = scandir( $source_dir ); $files = array_filter( $files, function( $file ) { return preg_match( '~\.php$~', $file ); } ); foreach ( $files as $file ) { $copy_list[ $source_dir . $file ] = $destination_dir . $file; } return $copy_list; }
php
protected function getCopyList( $directory ) { $copy_list = [ $this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'Carbon_Rich_Text_Widget.php' ) => $this->path( $directory, 'app', 'src', 'Widgets', 'Carbon_Rich_Text_Widget.php' ), $this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'carbon-fields.php' ) => $this->path( $directory, 'app', 'helpers', 'carbon-fields.php' ), ]; $source_dir = $this->path( WPEMERGE_CLI_DIR, 'src', 'CarbonFields', 'carbon-fields' ) . DIRECTORY_SEPARATOR; $destination_dir = $this->path( $directory, 'app', 'setup', 'carbon-fields' ) . DIRECTORY_SEPARATOR; $files = scandir( $source_dir ); $files = array_filter( $files, function( $file ) { return preg_match( '~\.php$~', $file ); } ); foreach ( $files as $file ) { $copy_list[ $source_dir . $file ] = $destination_dir . $file; } return $copy_list; }
[ "protected", "function", "getCopyList", "(", "$", "directory", ")", "{", "$", "copy_list", "=", "[", "$", "this", "->", "path", "(", "WPEMERGE_CLI_DIR", ",", "'src'", ",", "'CarbonFields'", ",", "'Carbon_Rich_Text_Widget.php'", ")", "=>", "$", "this", "->", "path", "(", "$", "directory", ",", "'app'", ",", "'src'", ",", "'Widgets'", ",", "'Carbon_Rich_Text_Widget.php'", ")", ",", "$", "this", "->", "path", "(", "WPEMERGE_CLI_DIR", ",", "'src'", ",", "'CarbonFields'", ",", "'carbon-fields.php'", ")", "=>", "$", "this", "->", "path", "(", "$", "directory", ",", "'app'", ",", "'helpers'", ",", "'carbon-fields.php'", ")", ",", "]", ";", "$", "source_dir", "=", "$", "this", "->", "path", "(", "WPEMERGE_CLI_DIR", ",", "'src'", ",", "'CarbonFields'", ",", "'carbon-fields'", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "destination_dir", "=", "$", "this", "->", "path", "(", "$", "directory", ",", "'app'", ",", "'setup'", ",", "'carbon-fields'", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "files", "=", "scandir", "(", "$", "source_dir", ")", ";", "$", "files", "=", "array_filter", "(", "$", "files", ",", "function", "(", "$", "file", ")", "{", "return", "preg_match", "(", "'~\\.php$~'", ",", "$", "file", ")", ";", "}", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "copy_list", "[", "$", "source_dir", ".", "$", "file", "]", "=", "$", "destination_dir", ".", "$", "file", ";", "}", "return", "$", "copy_list", ";", "}" ]
Get array of files to copy @param string $directory @return array
[ "Get", "array", "of", "files", "to", "copy" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/CarbonFields.php#L69-L91
35,392
htmlburger/wpemerge-cli
src/Presets/CarbonFields.php
CarbonFields.addHooks
protected function addHooks( $directory ) { $hooks_filepath = $this->path( $directory, 'app', 'hooks.php' ); $this->appendUniqueStatement( $hooks_filepath, <<<'EOT' /** * Carbon Fields */ EOT ); $this->appendUniqueStatement( $hooks_filepath, <<<'EOT' add_action( 'after_setup_theme', 'app_bootstrap_carbon_fields', 100 ); EOT ); $this->appendUniqueStatement( $hooks_filepath, <<<'EOT' add_action( 'carbon_fields_register_fields', 'app_bootstrap_carbon_fields_register_fields' ); EOT ); $this->appendUniqueStatement( $hooks_filepath, <<<'EOT' add_filter( 'carbon_fields_map_field_api_key', 'app_filter_carbon_fields_google_maps_api_key' ); EOT ); }
php
protected function addHooks( $directory ) { $hooks_filepath = $this->path( $directory, 'app', 'hooks.php' ); $this->appendUniqueStatement( $hooks_filepath, <<<'EOT' /** * Carbon Fields */ EOT ); $this->appendUniqueStatement( $hooks_filepath, <<<'EOT' add_action( 'after_setup_theme', 'app_bootstrap_carbon_fields', 100 ); EOT ); $this->appendUniqueStatement( $hooks_filepath, <<<'EOT' add_action( 'carbon_fields_register_fields', 'app_bootstrap_carbon_fields_register_fields' ); EOT ); $this->appendUniqueStatement( $hooks_filepath, <<<'EOT' add_filter( 'carbon_fields_map_field_api_key', 'app_filter_carbon_fields_google_maps_api_key' ); EOT ); }
[ "protected", "function", "addHooks", "(", "$", "directory", ")", "{", "$", "hooks_filepath", "=", "$", "this", "->", "path", "(", "$", "directory", ",", "'app'", ",", "'hooks.php'", ")", ";", "$", "this", "->", "appendUniqueStatement", "(", "$", "hooks_filepath", ",", "\n\t\t\t<<<'EOT'\n\n/**\n * Carbon Fields\n */\nEOT", ")", ";", "$", "this", "->", "appendUniqueStatement", "(", "$", "hooks_filepath", ",", "\n\t\t\t<<<'EOT'\nadd_action( 'after_setup_theme', 'app_bootstrap_carbon_fields', 100 );\nEOT", ")", ";", "$", "this", "->", "appendUniqueStatement", "(", "$", "hooks_filepath", ",", "\n\t\t\t<<<'EOT'\nadd_action( 'carbon_fields_register_fields', 'app_bootstrap_carbon_fields_register_fields' );\nEOT", ")", ";", "$", "this", "->", "appendUniqueStatement", "(", "$", "hooks_filepath", ",", "\n\t\t\t<<<'EOT'\nadd_filter( 'carbon_fields_map_field_api_key', 'app_filter_carbon_fields_google_maps_api_key' );\nEOT", ")", ";", "}" ]
Add hook statements @param string $directory @return void
[ "Add", "hook", "statements" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/Presets/CarbonFields.php#L114-L147
35,393
hail-framework/framework
src/Filesystem/MountManager.php
MountManager.forceRename
public function forceRename(string $path, string $newpath) { $deleted = true; if ($this->has($newpath)) { try { $deleted = $this->delete($newpath); } catch (FileNotFoundException $e) { // The destination path does not exist. That's ok. $deleted = true; } } if ($deleted) { return $this->move($path, $newpath); } return false; }
php
public function forceRename(string $path, string $newpath) { $deleted = true; if ($this->has($newpath)) { try { $deleted = $this->delete($newpath); } catch (FileNotFoundException $e) { // The destination path does not exist. That's ok. $deleted = true; } } if ($deleted) { return $this->move($path, $newpath); } return false; }
[ "public", "function", "forceRename", "(", "string", "$", "path", ",", "string", "$", "newpath", ")", "{", "$", "deleted", "=", "true", ";", "if", "(", "$", "this", "->", "has", "(", "$", "newpath", ")", ")", "{", "try", "{", "$", "deleted", "=", "$", "this", "->", "delete", "(", "$", "newpath", ")", ";", "}", "catch", "(", "FileNotFoundException", "$", "e", ")", "{", "// The destination path does not exist. That's ok.", "$", "deleted", "=", "true", ";", "}", "}", "if", "(", "$", "deleted", ")", "{", "return", "$", "this", "->", "move", "(", "$", "path", ",", "$", "newpath", ")", ";", "}", "return", "false", ";", "}" ]
Renames a file, overwriting the destination if it exists. @param string $path Path to the existing file. @param string $newpath The new path of the file. @return bool True on success, false on failure. @throws FileNotFoundException Thrown if $path does not exist. @throws FilesystemNotFoundException @throws FileExistsException
[ "Renames", "a", "file", "overwriting", "the", "destination", "if", "it", "exists", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/MountManager.php#L267-L284
35,394
hail-framework/framework
src/Filesystem/MountManager.php
MountManager.readStream
public function readStream($path) { [$prefix, $path] = $this->getPrefixAndPath($path); return $this->getFilesystem($prefix)->readStream($path); }
php
public function readStream($path) { [$prefix, $path] = $this->getPrefixAndPath($path); return $this->getFilesystem($prefix)->readStream($path); }
[ "public", "function", "readStream", "(", "$", "path", ")", "{", "[", "$", "prefix", ",", "$", "path", "]", "=", "$", "this", "->", "getPrefixAndPath", "(", "$", "path", ")", ";", "return", "$", "this", "->", "getFilesystem", "(", "$", "prefix", ")", "->", "readStream", "(", "$", "path", ")", ";", "}" ]
Retrieves a read-stream for a path. @param string $path The path to the file. @throws FileNotFoundException @return resource|false The path resource or false on failure.
[ "Retrieves", "a", "read", "-", "stream", "for", "a", "path", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/MountManager.php#L347-L352
35,395
hail-framework/framework
src/Filesystem/MountManager.php
MountManager.getTimestamp
public function getTimestamp($path) { [$prefix, $path] = $this->getPrefixAndPath($path); return $this->getFilesystem($prefix)->getTimestamp($path); }
php
public function getTimestamp($path) { [$prefix, $path] = $this->getPrefixAndPath($path); return $this->getFilesystem($prefix)->getTimestamp($path); }
[ "public", "function", "getTimestamp", "(", "$", "path", ")", "{", "[", "$", "prefix", ",", "$", "path", "]", "=", "$", "this", "->", "getPrefixAndPath", "(", "$", "path", ")", ";", "return", "$", "this", "->", "getFilesystem", "(", "$", "prefix", ")", "->", "getTimestamp", "(", "$", "path", ")", ";", "}" ]
Get a file's timestamp. @param string $path The path to the file. @throws FileNotFoundException @return string|false The timestamp or false on failure.
[ "Get", "a", "file", "s", "timestamp", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/MountManager.php#L411-L416
35,396
hail-framework/framework
src/Filesystem/MountManager.php
MountManager.readAndDelete
public function readAndDelete($path) { [$prefix, $path] = $this->getPrefixAndPath($path); return $this->getFilesystem($prefix)->readAndDelete($path); }
php
public function readAndDelete($path) { [$prefix, $path] = $this->getPrefixAndPath($path); return $this->getFilesystem($prefix)->readAndDelete($path); }
[ "public", "function", "readAndDelete", "(", "$", "path", ")", "{", "[", "$", "prefix", ",", "$", "path", "]", "=", "$", "this", "->", "getPrefixAndPath", "(", "$", "path", ")", ";", "return", "$", "this", "->", "getFilesystem", "(", "$", "prefix", ")", "->", "readAndDelete", "(", "$", "path", ")", ";", "}" ]
Read and delete a file. @param string $path The path to the file. @throws FileNotFoundException @return string|false The file contents, or false on failure.
[ "Read", "and", "delete", "a", "file", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/MountManager.php#L633-L638
35,397
Becklyn/RadBundle
src/Form/FormErrorMapper.php
FormErrorMapper.addChildErrors
private function addChildErrors (FormInterface $form, string $fieldPrefix, string $translationDomain, array &$allErrors) : void { foreach ($form->all() as $children) { $childErrors = $children->getErrors(); $fieldName = \ltrim("{$fieldPrefix}{$children->getName()}"); if (0 < \count($childErrors)) { $allErrors[$fieldName] = \array_map( function (FormError $error) use ($translationDomain) { return $this->translator->trans($error->getMessage(), [], $translationDomain); }, \iterator_to_array($childErrors) ); } $this->addChildErrors($children, "{$fieldName}_", $translationDomain, $allErrors); } }
php
private function addChildErrors (FormInterface $form, string $fieldPrefix, string $translationDomain, array &$allErrors) : void { foreach ($form->all() as $children) { $childErrors = $children->getErrors(); $fieldName = \ltrim("{$fieldPrefix}{$children->getName()}"); if (0 < \count($childErrors)) { $allErrors[$fieldName] = \array_map( function (FormError $error) use ($translationDomain) { return $this->translator->trans($error->getMessage(), [], $translationDomain); }, \iterator_to_array($childErrors) ); } $this->addChildErrors($children, "{$fieldName}_", $translationDomain, $allErrors); } }
[ "private", "function", "addChildErrors", "(", "FormInterface", "$", "form", ",", "string", "$", "fieldPrefix", ",", "string", "$", "translationDomain", ",", "array", "&", "$", "allErrors", ")", ":", "void", "{", "foreach", "(", "$", "form", "->", "all", "(", ")", "as", "$", "children", ")", "{", "$", "childErrors", "=", "$", "children", "->", "getErrors", "(", ")", ";", "$", "fieldName", "=", "\\", "ltrim", "(", "\"{$fieldPrefix}{$children->getName()}\"", ")", ";", "if", "(", "0", "<", "\\", "count", "(", "$", "childErrors", ")", ")", "{", "$", "allErrors", "[", "$", "fieldName", "]", "=", "\\", "array_map", "(", "function", "(", "FormError", "$", "error", ")", "use", "(", "$", "translationDomain", ")", "{", "return", "$", "this", "->", "translator", "->", "trans", "(", "$", "error", "->", "getMessage", "(", ")", ",", "[", "]", ",", "$", "translationDomain", ")", ";", "}", ",", "\\", "iterator_to_array", "(", "$", "childErrors", ")", ")", ";", "}", "$", "this", "->", "addChildErrors", "(", "$", "children", ",", "\"{$fieldName}_\"", ",", "$", "translationDomain", ",", "$", "allErrors", ")", ";", "}", "}" ]
Adds all child errors to the mapping of errors. @param FormInterface $form @param string $fieldPrefix @param array $allErrors
[ "Adds", "all", "child", "errors", "to", "the", "mapping", "of", "errors", "." ]
34d5887e13f5a4018843b77dcbefc2eb2f3169f4
https://github.com/Becklyn/RadBundle/blob/34d5887e13f5a4018843b77dcbefc2eb2f3169f4/src/Form/FormErrorMapper.php#L61-L81
35,398
hail-framework/framework
src/Filesystem/Filesystem.php
Filesystem.getMetadataByName
protected function getMetadataByName(array $object, $key) { $method = 'get' . \ucfirst($key); if (!\method_exists($this, $method)) { throw new \InvalidArgumentException('Could not get meta-data for key: ' . $key); } $object[$key] = $this->{$method}($object['path']); return $object; }
php
protected function getMetadataByName(array $object, $key) { $method = 'get' . \ucfirst($key); if (!\method_exists($this, $method)) { throw new \InvalidArgumentException('Could not get meta-data for key: ' . $key); } $object[$key] = $this->{$method}($object['path']); return $object; }
[ "protected", "function", "getMetadataByName", "(", "array", "$", "object", ",", "$", "key", ")", "{", "$", "method", "=", "'get'", ".", "\\", "ucfirst", "(", "$", "key", ")", ";", "if", "(", "!", "\\", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Could not get meta-data for key: '", ".", "$", "key", ")", ";", "}", "$", "object", "[", "$", "key", "]", "=", "$", "this", "->", "{", "$", "method", "}", "(", "$", "object", "[", "'path'", "]", ")", ";", "return", "$", "object", ";", "}" ]
Get a meta-data value by key name. @param array $object @param string $key @return array
[ "Get", "a", "meta", "-", "data", "value", "by", "key", "name", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Filesystem.php#L632-L643
35,399
Kajna/K-Core
Core/Http/Request.php
Request.getUriSegment
public function getUriSegment($index) { $segments = explode('/', $this->server->get('REQUEST_URI')); if (isset($segments[$index])) { return $segments[$index]; } return false; }
php
public function getUriSegment($index) { $segments = explode('/', $this->server->get('REQUEST_URI')); if (isset($segments[$index])) { return $segments[$index]; } return false; }
[ "public", "function", "getUriSegment", "(", "$", "index", ")", "{", "$", "segments", "=", "explode", "(", "'/'", ",", "$", "this", "->", "server", "->", "get", "(", "'REQUEST_URI'", ")", ")", ";", "if", "(", "isset", "(", "$", "segments", "[", "$", "index", "]", ")", ")", "{", "return", "$", "segments", "[", "$", "index", "]", ";", "}", "return", "false", ";", "}" ]
Get request URI segment. @param int $index @return string|bool
[ "Get", "request", "URI", "segment", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Http/Request.php#L190-L197