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
partition
stringclasses
1 value
brightnucleus/view
src/View/Support/AbstractFinder.php
AbstractFinder.initializeNullObject
protected function initializeNullObject($arguments = null) { $this->nullObject = $this->maybeInstantiateFindable($this->nullObject, $arguments); }
php
protected function initializeNullObject($arguments = null) { $this->nullObject = $this->maybeInstantiateFindable($this->nullObject, $arguments); }
[ "protected", "function", "initializeNullObject", "(", "$", "arguments", "=", "null", ")", "{", "$", "this", "->", "nullObject", "=", "$", "this", "->", "maybeInstantiateFindable", "(", "$", "this", "->", "nullObject", ",", "$", "arguments", ")", ";", "}" ]
Initialize the NullObject. @since 0.1.1 @param mixed $arguments Optional. Arguments to use. @throws FailedToInstantiateFindable If the Findable could not be instantiated.
[ "Initialize", "the", "NullObject", "." ]
f26703b78bf452403fda112563825f172dc9e8ce
https://github.com/brightnucleus/view/blob/f26703b78bf452403fda112563825f172dc9e8ce/src/View/Support/AbstractFinder.php#L142-L145
train
brightnucleus/view
src/View/Support/AbstractFinder.php
AbstractFinder.initializeFindables
protected function initializeFindables($arguments = null): Findables { return $this->findables->map(function ($findable) use ($arguments) { return $this->initializeFindable($findable, $arguments); }); }
php
protected function initializeFindables($arguments = null): Findables { return $this->findables->map(function ($findable) use ($arguments) { return $this->initializeFindable($findable, $arguments); }); }
[ "protected", "function", "initializeFindables", "(", "$", "arguments", "=", "null", ")", ":", "Findables", "{", "return", "$", "this", "->", "findables", "->", "map", "(", "function", "(", "$", "findable", ")", "use", "(", "$", "arguments", ")", "{", "re...
Initialize the Findables that can be iterated. @param mixed $arguments Optional. Arguments to use. @since 0.1.0 @return Findables Collection of Findables. @throws FailedToInstantiateFindable If the Findable could not be instantiated.
[ "Initialize", "the", "Findables", "that", "can", "be", "iterated", "." ]
f26703b78bf452403fda112563825f172dc9e8ce
https://github.com/brightnucleus/view/blob/f26703b78bf452403fda112563825f172dc9e8ce/src/View/Support/AbstractFinder.php#L157-L162
train
brightnucleus/view
src/View/Support/AbstractFinder.php
AbstractFinder.maybeInstantiateFindable
protected function maybeInstantiateFindable($findable, $arguments = null): Findable { if (is_string($findable)) { $findable = $this->instantiateFindableFromString($findable, $arguments); } if (is_callable($findable)) { $findable = $this->instantiateFindableFromCallable($findable, $arguments); } if (! $findable instanceof Findable) { throw new FailedToInstantiateFindable( sprintf( _('Could not instantiate Findable "%s".'), serialize($findable) ) ); } return $findable; }
php
protected function maybeInstantiateFindable($findable, $arguments = null): Findable { if (is_string($findable)) { $findable = $this->instantiateFindableFromString($findable, $arguments); } if (is_callable($findable)) { $findable = $this->instantiateFindableFromCallable($findable, $arguments); } if (! $findable instanceof Findable) { throw new FailedToInstantiateFindable( sprintf( _('Could not instantiate Findable "%s".'), serialize($findable) ) ); } return $findable; }
[ "protected", "function", "maybeInstantiateFindable", "(", "$", "findable", ",", "$", "arguments", "=", "null", ")", ":", "Findable", "{", "if", "(", "is_string", "(", "$", "findable", ")", ")", "{", "$", "findable", "=", "$", "this", "->", "instantiateFind...
Maybe instantiate a Findable if it is not yet an object. @since 0.1.1 @param mixed $findable Findable to instantiate. @param mixed $arguments Optional. Arguments to use. @return Findable Instantiated findable. @throws FailedToInstantiateFindable If the findable could not be instantiated.
[ "Maybe", "instantiate", "a", "Findable", "if", "it", "is", "not", "yet", "an", "object", "." ]
f26703b78bf452403fda112563825f172dc9e8ce
https://github.com/brightnucleus/view/blob/f26703b78bf452403fda112563825f172dc9e8ce/src/View/Support/AbstractFinder.php#L191-L211
train
shardimage/shardimage-php
src/services/SystemService.php
SystemService.ping
public function ping($params = [], $optParams = []) { return $this->sendRequest([], [ 'restAction' => 'view', 'restId' => 'ping', 'getParams' => $optParams, ], function ($response) { return isset($response->data) ? new Ping($response->data) : $response; }); }
php
public function ping($params = [], $optParams = []) { return $this->sendRequest([], [ 'restAction' => 'view', 'restId' => 'ping', 'getParams' => $optParams, ], function ($response) { return isset($response->data) ? new Ping($response->data) : $response; }); }
[ "public", "function", "ping", "(", "$", "params", "=", "[", "]", ",", "$", "optParams", "=", "[", "]", ")", "{", "return", "$", "this", "->", "sendRequest", "(", "[", "]", ",", "[", "'restAction'", "=>", "'view'", ",", "'restId'", "=>", "'ping'", "...
Pings a Shardimage server and fetches statistical data about the request. @param array $params Required API parameters @param array $optParams Optional API parameters @return Ping|Response
[ "Pings", "a", "Shardimage", "server", "and", "fetches", "statistical", "data", "about", "the", "request", "." ]
1988e3996dfdf7e17d1bd44d5d807f9884ac64bd
https://github.com/shardimage/shardimage-php/blob/1988e3996dfdf7e17d1bd44d5d807f9884ac64bd/src/services/SystemService.php#L28-L37
train
selective-php/encoding
src/Utf8Encoding.php
Utf8Encoding.encodeUtf8
public function encodeUtf8($data) { if ($data === null || $data === '') { return $data; } if (is_array($data)) { foreach ($data as $key => $value) { $data[$key] = $this->encodeUtf8($value); } return $data; } else { if (!mb_check_encoding($data, 'UTF-8')) { return mb_convert_encoding($data, 'UTF-8'); } return $data; } }
php
public function encodeUtf8($data) { if ($data === null || $data === '') { return $data; } if (is_array($data)) { foreach ($data as $key => $value) { $data[$key] = $this->encodeUtf8($value); } return $data; } else { if (!mb_check_encoding($data, 'UTF-8')) { return mb_convert_encoding($data, 'UTF-8'); } return $data; } }
[ "public", "function", "encodeUtf8", "(", "$", "data", ")", "{", "if", "(", "$", "data", "===", "null", "||", "$", "data", "===", "''", ")", "{", "return", "$", "data", ";", "}", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "foreach", ...
Encodes an ISO-8859-1 string or array to UTF-8. @param mixed $data string or array to convert @return mixed encoded data
[ "Encodes", "an", "ISO", "-", "8859", "-", "1", "string", "or", "array", "to", "UTF", "-", "8", "." ]
e984a2a8a514c60d2e5948564a681eaf47e06b74
https://github.com/selective-php/encoding/blob/e984a2a8a514c60d2e5948564a681eaf47e06b74/src/Utf8Encoding.php#L17-L35
train
MetaModels/attribute_timestamp
src/Attribute/Timestamp.php
Timestamp.getDateTimeFormatString
public function getDateTimeFormatString() { $format = $this->getDateTimeType() . 'Format'; $page = $this->getObjPage(); if ($page && $page->$format) { return $page->$format; } return Config::get($format); }
php
public function getDateTimeFormatString() { $format = $this->getDateTimeType() . 'Format'; $page = $this->getObjPage(); if ($page && $page->$format) { return $page->$format; } return Config::get($format); }
[ "public", "function", "getDateTimeFormatString", "(", ")", "{", "$", "format", "=", "$", "this", "->", "getDateTimeType", "(", ")", ".", "'Format'", ";", "$", "page", "=", "$", "this", "->", "getObjPage", "(", ")", ";", "if", "(", "$", "page", "&&", ...
Retrieve the selected type or fallback to 'date' if none selected. @return string
[ "Retrieve", "the", "selected", "type", "or", "fallback", "to", "date", "if", "none", "selected", "." ]
ba2e5e946e752fc269cc59b62a9a3c8fbf8768c3
https://github.com/MetaModels/attribute_timestamp/blob/ba2e5e946e752fc269cc59b62a9a3c8fbf8768c3/src/Attribute/Timestamp.php#L163-L172
train
teepluss/laravel4-categorize
src/Teepluss/Categorize/Categories/Category.php
Category.boot
public static function boot() { parent::boot(); // Delete hierarchies first. static::deleting(function($model) { $model->children()->detach(); $model->parents()->detach(); }); }
php
public static function boot() { parent::boot(); // Delete hierarchies first. static::deleting(function($model) { $model->children()->detach(); $model->parents()->detach(); }); }
[ "public", "static", "function", "boot", "(", ")", "{", "parent", "::", "boot", "(", ")", ";", "// Delete hierarchies first.", "static", "::", "deleting", "(", "function", "(", "$", "model", ")", "{", "$", "model", "->", "children", "(", ")", "->", "detac...
Model event. @return void
[ "Model", "event", "." ]
bd183d7965cfcc709fef443e704e688faf2db715
https://github.com/teepluss/laravel4-categorize/blob/bd183d7965cfcc709fef443e704e688faf2db715/src/Teepluss/Categorize/Categories/Category.php#L27-L38
train
teepluss/laravel4-categorize
src/Teepluss/Categorize/Categories/Category.php
Category.makeChildOf
public function makeChildOf(CategoryInterface $category) { $this->save(); $this->parents()->sync(array($category->getKey())); return $this; }
php
public function makeChildOf(CategoryInterface $category) { $this->save(); $this->parents()->sync(array($category->getKey())); return $this; }
[ "public", "function", "makeChildOf", "(", "CategoryInterface", "$", "category", ")", "{", "$", "this", "->", "save", "(", ")", ";", "$", "this", "->", "parents", "(", ")", "->", "sync", "(", "array", "(", "$", "category", "->", "getKey", "(", ")", ")...
Make new category into some parent. @param CategoryInterface $category @return object
[ "Make", "new", "category", "into", "some", "parent", "." ]
bd183d7965cfcc709fef443e704e688faf2db715
https://github.com/teepluss/laravel4-categorize/blob/bd183d7965cfcc709fef443e704e688faf2db715/src/Teepluss/Categorize/Categories/Category.php#L89-L95
train
teepluss/laravel4-categorize
src/Teepluss/Categorize/Categories/Category.php
Category.deleteWithChildren
public function deleteWithChildren() { $ids = array(); $children = $this->getChildren()->toArray(); array_walk_recursive($children, function($i, $k) use (&$ids) { if ($k == 'id') $ids[] = $i; }); foreach ($ids as $id) { $this->destroy($id); } }
php
public function deleteWithChildren() { $ids = array(); $children = $this->getChildren()->toArray(); array_walk_recursive($children, function($i, $k) use (&$ids) { if ($k == 'id') $ids[] = $i; }); foreach ($ids as $id) { $this->destroy($id); } }
[ "public", "function", "deleteWithChildren", "(", ")", "{", "$", "ids", "=", "array", "(", ")", ";", "$", "children", "=", "$", "this", "->", "getChildren", "(", ")", "->", "toArray", "(", ")", ";", "array_walk_recursive", "(", "$", "children", ",", "fu...
Delete category with all children. @return object
[ "Delete", "category", "with", "all", "children", "." ]
bd183d7965cfcc709fef443e704e688faf2db715
https://github.com/teepluss/laravel4-categorize/blob/bd183d7965cfcc709fef443e704e688faf2db715/src/Teepluss/Categorize/Categories/Category.php#L135-L147
train
Roave/RoaveDeveloperTools
src/Roave/DeveloperTools/Mvc/Listener/ApplicationInspectorListener.php
ApplicationInspectorListener.collectInspectionsOnApplicationFinish
public function collectInspectionsOnApplicationFinish(EventInterface $event) { $inspection = $this->inspector->inspect($event); $uuid = $this->uuidGenerator->generateUUID(); $this->inspectionRepository->add($uuid, $inspection); $event->setParam(self::PARAM_INSPECTION, $inspection); $event->setParam(self::PARAM_INSPECTION_ID, $uuid); return $uuid; }
php
public function collectInspectionsOnApplicationFinish(EventInterface $event) { $inspection = $this->inspector->inspect($event); $uuid = $this->uuidGenerator->generateUUID(); $this->inspectionRepository->add($uuid, $inspection); $event->setParam(self::PARAM_INSPECTION, $inspection); $event->setParam(self::PARAM_INSPECTION_ID, $uuid); return $uuid; }
[ "public", "function", "collectInspectionsOnApplicationFinish", "(", "EventInterface", "$", "event", ")", "{", "$", "inspection", "=", "$", "this", "->", "inspector", "->", "inspect", "(", "$", "event", ")", ";", "$", "uuid", "=", "$", "this", "->", "uuidGene...
Collects and persists the current inspection results @param EventInterface $event @return string
[ "Collects", "and", "persists", "the", "current", "inspection", "results" ]
424285eb861c9df7891ce7c6e66a21756eecd81c
https://github.com/Roave/RoaveDeveloperTools/blob/424285eb861c9df7891ce7c6e66a21756eecd81c/src/Roave/DeveloperTools/Mvc/Listener/ApplicationInspectorListener.php#L95-L106
train
ARCANEDEV/LaravelActive
src/Active.php
Active.route
public function route($routes, $class = null, $fallback = null) { return $this->getCssClass( $this->isRoute($routes), $class, $fallback ); }
php
public function route($routes, $class = null, $fallback = null) { return $this->getCssClass( $this->isRoute($routes), $class, $fallback ); }
[ "public", "function", "route", "(", "$", "routes", ",", "$", "class", "=", "null", ",", "$", "fallback", "=", "null", ")", "{", "return", "$", "this", "->", "getCssClass", "(", "$", "this", "->", "isRoute", "(", "$", "routes", ")", ",", "$", "class...
Get the active class if the current route is in haystack routes. @param string|array $routes @param string|null $class @param string|null $fallback @return string|null
[ "Get", "the", "active", "class", "if", "the", "current", "route", "is", "in", "haystack", "routes", "." ]
993d76ad4bcdc6e293cacb719048e40e2f0a2255
https://github.com/ARCANEDEV/LaravelActive/blob/993d76ad4bcdc6e293cacb719048e40e2f0a2255/src/Active.php#L116-L121
train
ARCANEDEV/LaravelActive
src/Active.php
Active.path
public function path($routes, $class = null, $fallback = null) { return $this->getCssClass( $this->isPath($routes), $class, $fallback ); }
php
public function path($routes, $class = null, $fallback = null) { return $this->getCssClass( $this->isPath($routes), $class, $fallback ); }
[ "public", "function", "path", "(", "$", "routes", ",", "$", "class", "=", "null", ",", "$", "fallback", "=", "null", ")", "{", "return", "$", "this", "->", "getCssClass", "(", "$", "this", "->", "isPath", "(", "$", "routes", ")", ",", "$", "class",...
Get the active class if the current path is in haystack paths. @param string|array $routes @param string|null $class @param string|null $fallback @return string|null
[ "Get", "the", "active", "class", "if", "the", "current", "path", "is", "in", "haystack", "paths", "." ]
993d76ad4bcdc6e293cacb719048e40e2f0a2255
https://github.com/ARCANEDEV/LaravelActive/blob/993d76ad4bcdc6e293cacb719048e40e2f0a2255/src/Active.php#L132-L137
train
ARCANEDEV/LaravelActive
src/Active.php
Active.is
protected function is($object, $routes) { list($routes, $ignored) = $this->parseRoutes(Arr::wrap($routes)); return $this->isIgnored($ignored) ? false : call_user_func_array([$object, 'is'], $routes); }
php
protected function is($object, $routes) { list($routes, $ignored) = $this->parseRoutes(Arr::wrap($routes)); return $this->isIgnored($ignored) ? false : call_user_func_array([$object, 'is'], $routes); }
[ "protected", "function", "is", "(", "$", "object", ",", "$", "routes", ")", "{", "list", "(", "$", "routes", ",", "$", "ignored", ")", "=", "$", "this", "->", "parseRoutes", "(", "Arr", "::", "wrap", "(", "$", "routes", ")", ")", ";", "return", "...
Check if one the given routes is active. @param mixed $object @param string|array $routes @return bool
[ "Check", "if", "one", "the", "given", "routes", "is", "active", "." ]
993d76ad4bcdc6e293cacb719048e40e2f0a2255
https://github.com/ARCANEDEV/LaravelActive/blob/993d76ad4bcdc6e293cacb719048e40e2f0a2255/src/Active.php#L192-L199
train
ARCANEDEV/LaravelActive
src/Active.php
Active.parseRoutes
protected function parseRoutes(array $allRoutes) { return Collection::make($allRoutes) ->partition(function ($route) { return ! Str::startsWith($route, ['not:']); }) ->transform(function (Collection $routes, $index) { return $index === 0 ? $routes : $routes->transform(function ($route) { return substr($route, 4); }); }) ->toArray(); }
php
protected function parseRoutes(array $allRoutes) { return Collection::make($allRoutes) ->partition(function ($route) { return ! Str::startsWith($route, ['not:']); }) ->transform(function (Collection $routes, $index) { return $index === 0 ? $routes : $routes->transform(function ($route) { return substr($route, 4); }); }) ->toArray(); }
[ "protected", "function", "parseRoutes", "(", "array", "$", "allRoutes", ")", "{", "return", "Collection", "::", "make", "(", "$", "allRoutes", ")", "->", "partition", "(", "function", "(", "$", "route", ")", "{", "return", "!", "Str", "::", "startsWith", ...
Separate ignored routes from the whitelist routes. @param array $allRoutes @return array
[ "Separate", "ignored", "routes", "from", "the", "whitelist", "routes", "." ]
993d76ad4bcdc6e293cacb719048e40e2f0a2255
https://github.com/ARCANEDEV/LaravelActive/blob/993d76ad4bcdc6e293cacb719048e40e2f0a2255/src/Active.php#L221-L233
train
meritoo/common-bundle
src/Controller/Base/BaseController.php
BaseController.redirectToReferer
protected function redirectToReferer(): RedirectResponse { $url = $this->requestService->fetchRefererUrl(); // Oops, url of referer is unknown if ('' === $url) { throw CannotRedirectToEmptyRefererUrlException::create(); } return $this->redirect($url); }
php
protected function redirectToReferer(): RedirectResponse { $url = $this->requestService->fetchRefererUrl(); // Oops, url of referer is unknown if ('' === $url) { throw CannotRedirectToEmptyRefererUrlException::create(); } return $this->redirect($url); }
[ "protected", "function", "redirectToReferer", "(", ")", ":", "RedirectResponse", "{", "$", "url", "=", "$", "this", "->", "requestService", "->", "fetchRefererUrl", "(", ")", ";", "// Oops, url of referer is unknown", "if", "(", "''", "===", "$", "url", ")", "...
Redirects to url of referer @throws CannotRedirectToEmptyRefererUrlException @return RedirectResponse
[ "Redirects", "to", "url", "of", "referer" ]
560c3a6c14fce2e17208261b8c606f6208f44e23
https://github.com/meritoo/common-bundle/blob/560c3a6c14fce2e17208261b8c606f6208f44e23/src/Controller/Base/BaseController.php#L49-L59
train
klermonte/zerg
src/Zerg/Field/Int.php
Int.read
public function read(AbstractStream $stream) { return $stream->getBuffer()->readInt($this->getSize(), $this->getSigned(), $this->getEndian()); }
php
public function read(AbstractStream $stream) { return $stream->getBuffer()->readInt($this->getSize(), $this->getSigned(), $this->getEndian()); }
[ "public", "function", "read", "(", "AbstractStream", "$", "stream", ")", "{", "return", "$", "stream", "->", "getBuffer", "(", ")", "->", "readInt", "(", "$", "this", "->", "getSize", "(", ")", ",", "$", "this", "->", "getSigned", "(", ")", ",", "$",...
Read data from Stream and cast it to integer. @param AbstractStream $stream Stream from which read. @return int Result value.
[ "Read", "data", "from", "Stream", "and", "cast", "it", "to", "integer", "." ]
c5d9c52cfade1fe9169e3cbae855b49a054f04ff
https://github.com/klermonte/zerg/blob/c5d9c52cfade1fe9169e3cbae855b49a054f04ff/src/Zerg/Field/Int.php#L46-L49
train
okapon/DoctrineSetTypeBundle
Validator/Constraints/SetTypeValidator.php
SetTypeValidator.validate
public function validate($value, Constraint $constraint) { /** @var SetType $constraint */ if (!$constraint->class) { throw new ConstraintDefinitionException('Target is not specified'); } /** @var string $class class name of inheriting \Okapon\DoctrineSetTypeBundle\DBAL\Types\AbstractSetType */ $class = $constraint->class; if (!class_exists($class)) { throw new TargetClassNotExistException('Target class not exist.'); } $constraint->choices = $class::getValues(); $constraint->multiple =true; parent::validate($value, $constraint); }
php
public function validate($value, Constraint $constraint) { /** @var SetType $constraint */ if (!$constraint->class) { throw new ConstraintDefinitionException('Target is not specified'); } /** @var string $class class name of inheriting \Okapon\DoctrineSetTypeBundle\DBAL\Types\AbstractSetType */ $class = $constraint->class; if (!class_exists($class)) { throw new TargetClassNotExistException('Target class not exist.'); } $constraint->choices = $class::getValues(); $constraint->multiple =true; parent::validate($value, $constraint); }
[ "public", "function", "validate", "(", "$", "value", ",", "Constraint", "$", "constraint", ")", "{", "/** @var SetType $constraint */", "if", "(", "!", "$", "constraint", "->", "class", ")", "{", "throw", "new", "ConstraintDefinitionException", "(", "'Target is no...
Checks if the passed value is valid @param mixed $value The value that should be validated @param Constraint $constraint The constraint for the validation @throws ConstraintDefinitionException @return void
[ "Checks", "if", "the", "passed", "value", "is", "valid" ]
a619b487b555696a3df55f38b57ff8a0175f4dbc
https://github.com/okapon/DoctrineSetTypeBundle/blob/a619b487b555696a3df55f38b57ff8a0175f4dbc/Validator/Constraints/SetTypeValidator.php#L28-L45
train
meritoo/common-bundle
src/Type/DependencyInjection/ConfigurationFileType.php
ConfigurationFileType.getTypeFromFileName
public static function getTypeFromFileName(string $fileName): string { $fileExtension = strtolower(Miscellaneous::getFileExtension($fileName)); // Oops, incorrect type/extension of configuration file if (false === (new static())->isCorrectType($fileExtension)) { throw UnknownConfigurationFileTypeException::createException($fileExtension); } return $fileExtension; }
php
public static function getTypeFromFileName(string $fileName): string { $fileExtension = strtolower(Miscellaneous::getFileExtension($fileName)); // Oops, incorrect type/extension of configuration file if (false === (new static())->isCorrectType($fileExtension)) { throw UnknownConfigurationFileTypeException::createException($fileExtension); } return $fileExtension; }
[ "public", "static", "function", "getTypeFromFileName", "(", "string", "$", "fileName", ")", ":", "string", "{", "$", "fileExtension", "=", "strtolower", "(", "Miscellaneous", "::", "getFileExtension", "(", "$", "fileName", ")", ")", ";", "// Oops, incorrect type/e...
Returns type of configuration file based on name of the file @param string $fileName Name of configuration file @throws UnknownConfigurationFileTypeException @return string
[ "Returns", "type", "of", "configuration", "file", "based", "on", "name", "of", "the", "file" ]
560c3a6c14fce2e17208261b8c606f6208f44e23
https://github.com/meritoo/common-bundle/blob/560c3a6c14fce2e17208261b8c606f6208f44e23/src/Type/DependencyInjection/ConfigurationFileType.php#L53-L63
train
webwarejp/OpenppWebPushAdapter
src/Encryptor/MessageEncryptor.php
MessageEncryptor.encrypt
public function encrypt($message, $userPublicKey, $userAuthToken, $regenerateKeys = false) { if (self::MAX_MESSAGE_LENGTH < strlen($message)) { throw new \RuntimeException(sprintf( 'Length of message must not be greater than %d octets.', self::MAX_MESSAGE_LENGTH )); } // pad the message $message = self::padMessage($message); if ($regenerateKeys) { $this->initialize(); } $userPublicKey = Base64Url::decode($userPublicKey); $userAuthToken = Base64Url::decode($userAuthToken); // get the shared secret $sharedSecret = $this->getSharedSecret($userPublicKey); $ikm = !empty($userAuthToken) ? self::hkdf($userAuthToken, $sharedSecret, 'Content-Encoding: auth'.chr(0), 32) : $sharedSecret; $context = $this->createContext($userPublicKey); // derive the Content Encryption Key $contentEncryptionKey = self::hkdf($this->salt, $ikm, self::createInfo('aesgcm', $context), 16); // derive the nonce $nonce = self::hkdf($this->salt, $ikm, self::createInfo('nonce', $context), 12); if (version_compare(PHP_VERSION, '7.1') >= 0) { $encryptedText = openssl_encrypt($message, 'aes-128-gcm', $contentEncryptionKey, OPENSSL_RAW_DATA, $nonce, $tag); } else { list($encryptedText, $tag) = \AESGCM\AESGCM::encrypt($contentEncryptionKey, $nonce, $message, ''); } return $encryptedText.$tag; }
php
public function encrypt($message, $userPublicKey, $userAuthToken, $regenerateKeys = false) { if (self::MAX_MESSAGE_LENGTH < strlen($message)) { throw new \RuntimeException(sprintf( 'Length of message must not be greater than %d octets.', self::MAX_MESSAGE_LENGTH )); } // pad the message $message = self::padMessage($message); if ($regenerateKeys) { $this->initialize(); } $userPublicKey = Base64Url::decode($userPublicKey); $userAuthToken = Base64Url::decode($userAuthToken); // get the shared secret $sharedSecret = $this->getSharedSecret($userPublicKey); $ikm = !empty($userAuthToken) ? self::hkdf($userAuthToken, $sharedSecret, 'Content-Encoding: auth'.chr(0), 32) : $sharedSecret; $context = $this->createContext($userPublicKey); // derive the Content Encryption Key $contentEncryptionKey = self::hkdf($this->salt, $ikm, self::createInfo('aesgcm', $context), 16); // derive the nonce $nonce = self::hkdf($this->salt, $ikm, self::createInfo('nonce', $context), 12); if (version_compare(PHP_VERSION, '7.1') >= 0) { $encryptedText = openssl_encrypt($message, 'aes-128-gcm', $contentEncryptionKey, OPENSSL_RAW_DATA, $nonce, $tag); } else { list($encryptedText, $tag) = \AESGCM\AESGCM::encrypt($contentEncryptionKey, $nonce, $message, ''); } return $encryptedText.$tag; }
[ "public", "function", "encrypt", "(", "$", "message", ",", "$", "userPublicKey", ",", "$", "userAuthToken", ",", "$", "regenerateKeys", "=", "false", ")", "{", "if", "(", "self", "::", "MAX_MESSAGE_LENGTH", "<", "strlen", "(", "$", "message", ")", ")", "...
Encrypt the message for Web Push. @param string $message @param string $userPublicKey @param string $userAuthToken @param bool $regenerateKeys @return string
[ "Encrypt", "the", "message", "for", "Web", "Push", "." ]
3592fe8e2078371b347fb8c1fe446f20b536992e
https://github.com/webwarejp/OpenppWebPushAdapter/blob/3592fe8e2078371b347fb8c1fe446f20b536992e/src/Encryptor/MessageEncryptor.php#L125-L165
train
webwarejp/OpenppWebPushAdapter
src/Encryptor/MessageEncryptor.php
MessageEncryptor.initialize
private function initialize() { // generate key pair. $this->privateKey = $this->generator->createPrivateKey(); $this->publicKey = $this->privateKey->getPublicKey(); // generate salt $this->salt = openssl_random_pseudo_bytes(16); $this->publicKeyContent = hex2bin($this->serializer->serialize($this->publicKey->getPoint())); }
php
private function initialize() { // generate key pair. $this->privateKey = $this->generator->createPrivateKey(); $this->publicKey = $this->privateKey->getPublicKey(); // generate salt $this->salt = openssl_random_pseudo_bytes(16); $this->publicKeyContent = hex2bin($this->serializer->serialize($this->publicKey->getPoint())); }
[ "private", "function", "initialize", "(", ")", "{", "// generate key pair.", "$", "this", "->", "privateKey", "=", "$", "this", "->", "generator", "->", "createPrivateKey", "(", ")", ";", "$", "this", "->", "publicKey", "=", "$", "this", "->", "privateKey", ...
Generate key pare and salt.
[ "Generate", "key", "pare", "and", "salt", "." ]
3592fe8e2078371b347fb8c1fe446f20b536992e
https://github.com/webwarejp/OpenppWebPushAdapter/blob/3592fe8e2078371b347fb8c1fe446f20b536992e/src/Encryptor/MessageEncryptor.php#L170-L180
train
webwarejp/OpenppWebPushAdapter
src/Encryptor/MessageEncryptor.php
MessageEncryptor.getSharedSecret
private function getSharedSecret($userPublicKey) { $userPublicKeyPoint = $this->serializer->unserialize($this->curve, bin2hex($userPublicKey)); $userPublicKeyObject = $this->generator->getPublicKeyFrom( $userPublicKeyPoint->getX(), $userPublicKeyPoint->getY(), $this->generator->getOrder() ); $point = $userPublicKeyObject->getPoint()->mul($this->privateKey->getSecret())->getX(); return hex2bin($this->adapter->decHex((string) $point)); }
php
private function getSharedSecret($userPublicKey) { $userPublicKeyPoint = $this->serializer->unserialize($this->curve, bin2hex($userPublicKey)); $userPublicKeyObject = $this->generator->getPublicKeyFrom( $userPublicKeyPoint->getX(), $userPublicKeyPoint->getY(), $this->generator->getOrder() ); $point = $userPublicKeyObject->getPoint()->mul($this->privateKey->getSecret())->getX(); return hex2bin($this->adapter->decHex((string) $point)); }
[ "private", "function", "getSharedSecret", "(", "$", "userPublicKey", ")", "{", "$", "userPublicKeyPoint", "=", "$", "this", "->", "serializer", "->", "unserialize", "(", "$", "this", "->", "curve", ",", "bin2hex", "(", "$", "userPublicKey", ")", ")", ";", ...
Get shared secret from user public key and server private key. @param string $userPublicKey @return string
[ "Get", "shared", "secret", "from", "user", "public", "key", "and", "server", "private", "key", "." ]
3592fe8e2078371b347fb8c1fe446f20b536992e
https://github.com/webwarejp/OpenppWebPushAdapter/blob/3592fe8e2078371b347fb8c1fe446f20b536992e/src/Encryptor/MessageEncryptor.php#L189-L201
train
koolkode/async
src/Concurrent/Pool/ErrorDeserializer.php
ErrorDeserializer.populateErrorData
protected function populateErrorData(\Throwable $e, array $data): \Throwable { static $cache = []; static $props = [ 'code', 'message', 'file', 'line' ]; $type = ($e instanceof \Error) ? \Error::class : \Exception::class; if (!isset($cache[$type])) { $cache[$type] = []; foreach ($props as $k) { $ref = new \ReflectionProperty($type, $k); $ref->setAccessible(true); $cache[$type][$k] = $ref; } } foreach ($props as $k) { if (isset($data[$k])) { $cache[$type][$k]->setValue($e, $data[$k]); } } return $e; }
php
protected function populateErrorData(\Throwable $e, array $data): \Throwable { static $cache = []; static $props = [ 'code', 'message', 'file', 'line' ]; $type = ($e instanceof \Error) ? \Error::class : \Exception::class; if (!isset($cache[$type])) { $cache[$type] = []; foreach ($props as $k) { $ref = new \ReflectionProperty($type, $k); $ref->setAccessible(true); $cache[$type][$k] = $ref; } } foreach ($props as $k) { if (isset($data[$k])) { $cache[$type][$k]->setValue($e, $data[$k]); } } return $e; }
[ "protected", "function", "populateErrorData", "(", "\\", "Throwable", "$", "e", ",", "array", "$", "data", ")", ":", "\\", "Throwable", "{", "static", "$", "cache", "=", "[", "]", ";", "static", "$", "props", "=", "[", "'code'", ",", "'message'", ",", ...
Populate properties of the given error from unserialized data. @param \Throwable $e The error to be enriched with transferred data. @param array $data Received error data.
[ "Populate", "properties", "of", "the", "given", "error", "from", "unserialized", "data", "." ]
9c985dcdd3b328323826dd4254d9f2e5aea0b75b
https://github.com/koolkode/async/blob/9c985dcdd3b328323826dd4254d9f2e5aea0b75b/src/Concurrent/Pool/ErrorDeserializer.php#L24-L54
train
larryli/ipv4-yii2
actions/InitAction.php
InitAction.run
public function run() { $force = $this->controller->force; $this->stdout("initialize ip database:\n", Console::FG_GREEN); foreach ($this->ipv4->getQueries() as $name => $query) { $providers = $query->getProviders(); if (empty($providers)) { $this->download($query, $name, $force); } else { $this->division(); $this->generate($query, $name, $force); } } }
php
public function run() { $force = $this->controller->force; $this->stdout("initialize ip database:\n", Console::FG_GREEN); foreach ($this->ipv4->getQueries() as $name => $query) { $providers = $query->getProviders(); if (empty($providers)) { $this->download($query, $name, $force); } else { $this->division(); $this->generate($query, $name, $force); } } }
[ "public", "function", "run", "(", ")", "{", "$", "force", "=", "$", "this", "->", "controller", "->", "force", ";", "$", "this", "->", "stdout", "(", "\"initialize ip database:\\n\"", ",", "Console", "::", "FG_GREEN", ")", ";", "foreach", "(", "$", "this...
initialize ip database
[ "initialize", "ip", "database" ]
6215f67db4b620b15e5f763407c034dc1badc4b8
https://github.com/larryli/ipv4-yii2/blob/6215f67db4b620b15e5f763407c034dc1badc4b8/actions/InitAction.php#L29-L42
train
Roave/RoaveDeveloperTools
src/Roave/DeveloperTools/Mvc/Listener/ToolbarInjectorListener.php
ToolbarInjectorListener.injectToolbarHtml
public function injectToolbarHtml(MvcEvent $event) { if (! $inspection = $event->getParam(ApplicationInspectorListener::PARAM_INSPECTION)) { return; } $response = $event->getResponse(); if (! $response instanceof Response) { return; } $headers = $response->getHeaders(); $contentType = $headers->get('Content-Type'); if ($contentType) { if (!$contentType instanceof ContentType) { return; } if (false === strpos(strtolower($contentType->getFieldValue()), 'html')) { return; } } $response->setContent(preg_replace( '/<\/body>/i', $this->renderer->render($this->inspectionRenderer->render($inspection)) . '</body>', $response->getContent(), 1 )); }
php
public function injectToolbarHtml(MvcEvent $event) { if (! $inspection = $event->getParam(ApplicationInspectorListener::PARAM_INSPECTION)) { return; } $response = $event->getResponse(); if (! $response instanceof Response) { return; } $headers = $response->getHeaders(); $contentType = $headers->get('Content-Type'); if ($contentType) { if (!$contentType instanceof ContentType) { return; } if (false === strpos(strtolower($contentType->getFieldValue()), 'html')) { return; } } $response->setContent(preg_replace( '/<\/body>/i', $this->renderer->render($this->inspectionRenderer->render($inspection)) . '</body>', $response->getContent(), 1 )); }
[ "public", "function", "injectToolbarHtml", "(", "MvcEvent", "$", "event", ")", "{", "if", "(", "!", "$", "inspection", "=", "$", "event", "->", "getParam", "(", "ApplicationInspectorListener", "::", "PARAM_INSPECTION", ")", ")", "{", "return", ";", "}", "$",...
Attaches the HTML rendered for the toolbar to the output if the output is recognized as an HTML HTTP response @param MvcEvent $event @return void
[ "Attaches", "the", "HTML", "rendered", "for", "the", "toolbar", "to", "the", "output", "if", "the", "output", "is", "recognized", "as", "an", "HTML", "HTTP", "response" ]
424285eb861c9df7891ce7c6e66a21756eecd81c
https://github.com/Roave/RoaveDeveloperTools/blob/424285eb861c9df7891ce7c6e66a21756eecd81c/src/Roave/DeveloperTools/Mvc/Listener/ToolbarInjectorListener.php#L82-L113
train
widoz/wordpress-model
src/DateTime.php
DateTime.modifiedDate
public function modifiedDate(WP_Post $post, string $format): string { Assert::stringNotEmpty($format); $postDate = get_the_modified_date($format, $post); $this->bailIfInvalidValue($postDate, $post); return $postDate; }
php
public function modifiedDate(WP_Post $post, string $format): string { Assert::stringNotEmpty($format); $postDate = get_the_modified_date($format, $post); $this->bailIfInvalidValue($postDate, $post); return $postDate; }
[ "public", "function", "modifiedDate", "(", "WP_Post", "$", "post", ",", "string", "$", "format", ")", ":", "string", "{", "Assert", "::", "stringNotEmpty", "(", "$", "format", ")", ";", "$", "postDate", "=", "get_the_modified_date", "(", "$", "format", ","...
Retrieve the Modified Date for a Post @param WP_Post $post @param string $format @return string @throws InvalidArgumentException @throws InvalidPostDateException
[ "Retrieve", "the", "Modified", "Date", "for", "a", "Post" ]
273301de4b6946144b285c235aea0d79b867244c
https://github.com/widoz/wordpress-model/blob/273301de4b6946144b285c235aea0d79b867244c/src/DateTime.php#L41-L50
train
widoz/wordpress-model
src/DateTime.php
DateTime.modifiedTime
public function modifiedTime(WP_Post $post, string $format): string { Assert::stringNotEmpty($format); $postDate = get_the_modified_time($format, $post); $this->bailIfInvalidValue($postDate, $post); return $postDate; }
php
public function modifiedTime(WP_Post $post, string $format): string { Assert::stringNotEmpty($format); $postDate = get_the_modified_time($format, $post); $this->bailIfInvalidValue($postDate, $post); return $postDate; }
[ "public", "function", "modifiedTime", "(", "WP_Post", "$", "post", ",", "string", "$", "format", ")", ":", "string", "{", "Assert", "::", "stringNotEmpty", "(", "$", "format", ")", ";", "$", "postDate", "=", "get_the_modified_time", "(", "$", "format", ","...
Retrieve the Modified Time for a Post @param WP_Post $post @param string $format @return string @throws InvalidArgumentException @throws InvalidPostDateException
[ "Retrieve", "the", "Modified", "Time", "for", "a", "Post" ]
273301de4b6946144b285c235aea0d79b867244c
https://github.com/widoz/wordpress-model/blob/273301de4b6946144b285c235aea0d79b867244c/src/DateTime.php#L61-L70
train
widoz/wordpress-model
src/DateTime.php
DateTime.date
public function date(WP_Post $post, string $format): string { Assert::stringNotEmpty($format); $postDate = get_the_date($format, $post); $this->bailIfInvalidValue($postDate, $post); return $postDate; }
php
public function date(WP_Post $post, string $format): string { Assert::stringNotEmpty($format); $postDate = get_the_date($format, $post); $this->bailIfInvalidValue($postDate, $post); return $postDate; }
[ "public", "function", "date", "(", "WP_Post", "$", "post", ",", "string", "$", "format", ")", ":", "string", "{", "Assert", "::", "stringNotEmpty", "(", "$", "format", ")", ";", "$", "postDate", "=", "get_the_date", "(", "$", "format", ",", "$", "post"...
Retrieve the Written Date for a Post @param WP_Post $post @param string $format @return string @throws InvalidArgumentException @throws InvalidPostDateException
[ "Retrieve", "the", "Written", "Date", "for", "a", "Post" ]
273301de4b6946144b285c235aea0d79b867244c
https://github.com/widoz/wordpress-model/blob/273301de4b6946144b285c235aea0d79b867244c/src/DateTime.php#L81-L90
train
widoz/wordpress-model
src/DateTime.php
DateTime.time
public function time(WP_Post $post, string $format): string { Assert::stringNotEmpty($format); $postTime = get_the_time($format, $post); $this->bailIfInvalidValue($postTime, $post); return $postTime; }
php
public function time(WP_Post $post, string $format): string { Assert::stringNotEmpty($format); $postTime = get_the_time($format, $post); $this->bailIfInvalidValue($postTime, $post); return $postTime; }
[ "public", "function", "time", "(", "WP_Post", "$", "post", ",", "string", "$", "format", ")", ":", "string", "{", "Assert", "::", "stringNotEmpty", "(", "$", "format", ")", ";", "$", "postTime", "=", "get_the_time", "(", "$", "format", ",", "$", "post"...
Retrieve the Written Time for a Post @param WP_Post $post @param string $format @return string @throws InvalidArgumentException @throws InvalidPostDateException
[ "Retrieve", "the", "Written", "Time", "for", "a", "Post" ]
273301de4b6946144b285c235aea0d79b867244c
https://github.com/widoz/wordpress-model/blob/273301de4b6946144b285c235aea0d79b867244c/src/DateTime.php#L101-L110
train
widoz/wordpress-model
src/DateTime.php
DateTime.dateTime
public function dateTime(WP_Post $post, string $format, string $separator): string { // phpcs:enable Assert::stringNotEmpty($format); Assert::stringNotEmpty($separator); $postDate = $this->date($post, $format); $postTime = $this->time($post, $format); return implode([$postDate, $postTime], $separator); }
php
public function dateTime(WP_Post $post, string $format, string $separator): string { // phpcs:enable Assert::stringNotEmpty($format); Assert::stringNotEmpty($separator); $postDate = $this->date($post, $format); $postTime = $this->time($post, $format); return implode([$postDate, $postTime], $separator); }
[ "public", "function", "dateTime", "(", "WP_Post", "$", "post", ",", "string", "$", "format", ",", "string", "$", "separator", ")", ":", "string", "{", "// phpcs:enable", "Assert", "::", "stringNotEmpty", "(", "$", "format", ")", ";", "Assert", "::", "strin...
Retrieve the Written Date Time for a Post @param WP_Post $post @param string $format @param string $separator @return string @throws InvalidArgumentException @throws InvalidPostDateException phpcs:disable Generic.NamingConventions.ConstructorName.OldStyle
[ "Retrieve", "the", "Written", "Date", "Time", "for", "a", "Post" ]
273301de4b6946144b285c235aea0d79b867244c
https://github.com/widoz/wordpress-model/blob/273301de4b6946144b285c235aea0d79b867244c/src/DateTime.php#L124-L135
train
koolkode/async
src/Concurrent/Pool/MethodCall.php
MethodCall.createCallback
protected function createCallback(string $method): \Closure { return \Closure::bind(static function (...$args) use ($method) { return self::$method(...$args); }, null, $this->type); }
php
protected function createCallback(string $method): \Closure { return \Closure::bind(static function (...$args) use ($method) { return self::$method(...$args); }, null, $this->type); }
[ "protected", "function", "createCallback", "(", "string", "$", "method", ")", ":", "\\", "Closure", "{", "return", "\\", "Closure", "::", "bind", "(", "static", "function", "(", "...", "$", "args", ")", "use", "(", "$", "method", ")", "{", "return", "s...
Create a closure that can execute a protected or private static method. @param string $method Name of the method to be called. @return \Closure
[ "Create", "a", "closure", "that", "can", "execute", "a", "protected", "or", "private", "static", "method", "." ]
9c985dcdd3b328323826dd4254d9f2e5aea0b75b
https://github.com/koolkode/async/blob/9c985dcdd3b328323826dd4254d9f2e5aea0b75b/src/Concurrent/Pool/MethodCall.php#L129-L134
train
Speelpenning-nl/laravel-authentication
src/Repositories/PasswordResetRepository.php
PasswordResetRepository.exists
public function exists($token) { $reset = PasswordReset::where('token', $token)->first(); return $reset and ! $reset->isExpired(); }
php
public function exists($token) { $reset = PasswordReset::where('token', $token)->first(); return $reset and ! $reset->isExpired(); }
[ "public", "function", "exists", "(", "$", "token", ")", "{", "$", "reset", "=", "PasswordReset", "::", "where", "(", "'token'", ",", "$", "token", ")", "->", "first", "(", ")", ";", "return", "$", "reset", "and", "!", "$", "reset", "->", "isExpired",...
Checks if a certain password reset exists. @param string $token @return bool
[ "Checks", "if", "a", "certain", "password", "reset", "exists", "." ]
44671afa8d654a9c6281cce13353d95126478d8b
https://github.com/Speelpenning-nl/laravel-authentication/blob/44671afa8d654a9c6281cce13353d95126478d8b/src/Repositories/PasswordResetRepository.php#L18-L22
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.countries
public function countries(array $countryCodes = null): array { if (!Configure::read('countries')) { Configure::load('CkTools.countries'); } if ($countryCodes) { $countries = Configure::read('countries'); $subset = []; foreach ($countryCodes as $countryCode) { $subset[$countryCode] = $countries[$countryCode] ?? $countryCode; } return $subset; } return Configure::read('countries'); }
php
public function countries(array $countryCodes = null): array { if (!Configure::read('countries')) { Configure::load('CkTools.countries'); } if ($countryCodes) { $countries = Configure::read('countries'); $subset = []; foreach ($countryCodes as $countryCode) { $subset[$countryCode] = $countries[$countryCode] ?? $countryCode; } return $subset; } return Configure::read('countries'); }
[ "public", "function", "countries", "(", "array", "$", "countryCodes", "=", "null", ")", ":", "array", "{", "if", "(", "!", "Configure", "::", "read", "(", "'countries'", ")", ")", "{", "Configure", "::", "load", "(", "'CkTools.countries'", ")", ";", "}",...
Returns a map of countries with their translations @param array $countryCodes If an array of country codes is given, a map of just these will be returned @return array
[ "Returns", "a", "map", "of", "countries", "with", "their", "translations" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L34-L50
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.country
public function country(string $country): string { if (!Configure::read('countries')) { Configure::load('CkTools.countries'); } $countries = Configure::read('countries'); return $countries[$country] ?? $country; }
php
public function country(string $country): string { if (!Configure::read('countries')) { Configure::load('CkTools.countries'); } $countries = Configure::read('countries'); return $countries[$country] ?? $country; }
[ "public", "function", "country", "(", "string", "$", "country", ")", ":", "string", "{", "if", "(", "!", "Configure", "::", "read", "(", "'countries'", ")", ")", "{", "Configure", "::", "load", "(", "'CkTools.countries'", ")", ";", "}", "$", "countries",...
Returns the translated version of the given country @param string $country E.g. "de", "en" @return string
[ "Returns", "the", "translated", "version", "of", "the", "given", "country" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L58-L66
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.datepickerInput
public function datepickerInput(string $field, array $options = []): string { $options = Hash::merge([ 'type' => 'date', ], $options); return $this->Form->input($field, $options); }
php
public function datepickerInput(string $field, array $options = []): string { $options = Hash::merge([ 'type' => 'date', ], $options); return $this->Form->input($field, $options); }
[ "public", "function", "datepickerInput", "(", "string", "$", "field", ",", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "$", "options", "=", "Hash", "::", "merge", "(", "[", "'type'", "=>", "'date'", ",", "]", ",", "$", "options",...
Render a datepicker input to be processed by DatePicker.js @param string $field Field Name @param array $options Options @return string
[ "Render", "a", "datepicker", "input", "to", "be", "processed", "by", "DatePicker", ".", "js" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L75-L82
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.editButton
public function editButton(EntityInterface $entity, array $options = []): string { $options = Hash::merge([ 'url' => null, 'title' => __d('ck_tools', 'edit'), 'icon' => 'fa fa-pencil', 'escape' => false, 'class' => 'btn btn-default btn-xs btn-edit', ], $options); $url = $options['url']; $title = $options['title']; $icon = $options['icon']; unset($options['url'], $options['title'], $options['icon']); if (!$url) { // phpcs:ignore list($plugin, $controller) = pluginSplit($entity->source()); $url = [ 'plugin' => $this->_View->request->plugin, 'controller' => $controller, 'action' => 'edit', $entity->id, ]; $url = $this->augmentUrlByBackParam($url); } if ($icon) { $title = '<i class="' . $icon . '"></i> ' . '<span class="button-text">' . $title . '</span>'; $options['escape'] = false; } return $this->Html->link($title, $url, $options); }
php
public function editButton(EntityInterface $entity, array $options = []): string { $options = Hash::merge([ 'url' => null, 'title' => __d('ck_tools', 'edit'), 'icon' => 'fa fa-pencil', 'escape' => false, 'class' => 'btn btn-default btn-xs btn-edit', ], $options); $url = $options['url']; $title = $options['title']; $icon = $options['icon']; unset($options['url'], $options['title'], $options['icon']); if (!$url) { // phpcs:ignore list($plugin, $controller) = pluginSplit($entity->source()); $url = [ 'plugin' => $this->_View->request->plugin, 'controller' => $controller, 'action' => 'edit', $entity->id, ]; $url = $this->augmentUrlByBackParam($url); } if ($icon) { $title = '<i class="' . $icon . '"></i> ' . '<span class="button-text">' . $title . '</span>'; $options['escape'] = false; } return $this->Html->link($title, $url, $options); }
[ "public", "function", "editButton", "(", "EntityInterface", "$", "entity", ",", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "$", "options", "=", "Hash", "::", "merge", "(", "[", "'url'", "=>", "null", ",", "'title'", "=>", "__d", ...
Renders an edit button @param \Cake\Datasource\EntityInterface $entity Entity to take the ID from @param array $options Config options @return string
[ "Renders", "an", "edit", "button" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L136-L167
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.addButton
public function addButton(string $title = null, array $options = []): string { if (!$title) { $title = __d('ck_tools', 'add'); } $options = Hash::merge([ 'url' => null, 'icon' => 'fa fa-plus', 'class' => 'btn btn-default btn-xs btn-add', ], $options); $url = $options['url']; if (!$url) { $url = ['action' => 'add']; $url = $this->augmentUrlByBackParam($url); } $icon = $options['icon']; unset($options['url'], $options['icon']); if ($icon) { $title = '<i class="' . $icon . '"></i> ' . '<span class="button-text">' . $title . '</span>'; $options['escape'] = false; } return $this->Html->link($title, $url, $options); }
php
public function addButton(string $title = null, array $options = []): string { if (!$title) { $title = __d('ck_tools', 'add'); } $options = Hash::merge([ 'url' => null, 'icon' => 'fa fa-plus', 'class' => 'btn btn-default btn-xs btn-add', ], $options); $url = $options['url']; if (!$url) { $url = ['action' => 'add']; $url = $this->augmentUrlByBackParam($url); } $icon = $options['icon']; unset($options['url'], $options['icon']); if ($icon) { $title = '<i class="' . $icon . '"></i> ' . '<span class="button-text">' . $title . '</span>'; $options['escape'] = false; } return $this->Html->link($title, $url, $options); }
[ "public", "function", "addButton", "(", "string", "$", "title", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "if", "(", "!", "$", "title", ")", "{", "$", "title", "=", "__d", "(", "'ck_tools'", ",", "'add'", ...
Renders an add button @param string $title Link Caption @param array $options Additional Options @return string
[ "Renders", "an", "add", "button" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L215-L238
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.formButtons
public function formButtons(array $options = []): string { $url = ['action' => 'index']; $options = Hash::merge([ 'useReferer' => false, 'horizontalLine' => true, 'cancelButton' => true, 'saveButtonTitle' => __d('ck_tools', 'save'), 'cancelButtonTitle' => __d('ck_tools', 'cancel'), ], $options); if (!empty($options['useReferer']) && $this->request->referer() !== '/') { $url = $this->request->referer(); } $formButtons = '<div class="submit-group">'; if ($options['horizontalLine']) { $formButtons .= '<hr>'; } $formButtons .= $this->Form->button($options['saveButtonTitle'], ['class' => 'btn-success']); if ($options['cancelButton']) { $formButtons .= $this->backButton($options['cancelButtonTitle'], $url, ['class' => 'btn btn-default cancel-button', 'icon' => null]); } $formButtons .= '</div>'; return $formButtons; }
php
public function formButtons(array $options = []): string { $url = ['action' => 'index']; $options = Hash::merge([ 'useReferer' => false, 'horizontalLine' => true, 'cancelButton' => true, 'saveButtonTitle' => __d('ck_tools', 'save'), 'cancelButtonTitle' => __d('ck_tools', 'cancel'), ], $options); if (!empty($options['useReferer']) && $this->request->referer() !== '/') { $url = $this->request->referer(); } $formButtons = '<div class="submit-group">'; if ($options['horizontalLine']) { $formButtons .= '<hr>'; } $formButtons .= $this->Form->button($options['saveButtonTitle'], ['class' => 'btn-success']); if ($options['cancelButton']) { $formButtons .= $this->backButton($options['cancelButtonTitle'], $url, ['class' => 'btn btn-default cancel-button', 'icon' => null]); } $formButtons .= '</div>'; return $formButtons; }
[ "public", "function", "formButtons", "(", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "$", "url", "=", "[", "'action'", "=>", "'index'", "]", ";", "$", "options", "=", "Hash", "::", "merge", "(", "[", "'useReferer'", "=>", "false...
Renders form buttons @return string
[ "Renders", "form", "buttons" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L288-L314
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.backButton
public function backButton(string $title = null, $url = null, array $options = []): string { $options = Hash::merge([ 'icon' => 'arrow-left', 'escape' => false, ], $options); if (!$title) { $title = '<span class="button-text">' . __d('ck_tools', 'Back') . '</span>'; } $here = $this->getRequestedAction(); if ($this->request->getSession()->check('back_action.' . $here)) { $url = $this->request->getSession()->read('back_action.' . $here); } if (empty($url)) { $url = [ 'action' => 'index', ]; } return $this->button($title, $url, $options); }
php
public function backButton(string $title = null, $url = null, array $options = []): string { $options = Hash::merge([ 'icon' => 'arrow-left', 'escape' => false, ], $options); if (!$title) { $title = '<span class="button-text">' . __d('ck_tools', 'Back') . '</span>'; } $here = $this->getRequestedAction(); if ($this->request->getSession()->check('back_action.' . $here)) { $url = $this->request->getSession()->read('back_action.' . $here); } if (empty($url)) { $url = [ 'action' => 'index', ]; } return $this->button($title, $url, $options); }
[ "public", "function", "backButton", "(", "string", "$", "title", "=", "null", ",", "$", "url", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "$", "options", "=", "Hash", "::", "merge", "(", "[", "'icon'", "=>", ...
Renders a back button using the back actions within the session @param string $title button caption @param string|array $url url to link to @param array $options link() config @return string
[ "Renders", "a", "back", "button", "using", "the", "back", "actions", "within", "the", "session" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L350-L372
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.nestedList
public function nestedList(array $data, string $content, int $level = 0, array $isActiveCallback = null): string { $tabs = "\n" . str_repeat(' ', $level * 2); $liTabs = $tabs . ' '; $output = $tabs . '<ul>'; foreach ($data as $record) { $liClasses = []; $liContent = $content; if ($isActiveCallback !== null) { $additionalArguments = !empty($isActiveCallback['arguments']) ? $isActiveCallback['arguments'] : []; $isActive = call_user_func_array($isActiveCallback['callback'], [&$record, $additionalArguments]); if ($isActive) { $liClasses[] = 'active'; } } // find the model variables preg_match_all("/\{\{([a-z0-9\._]+)\}\}/i", $liContent, $matches); if (!empty($matches)) { $variables = array_unique($matches[1]); foreach ($variables as $modelField) { $liContent = str_replace('{{' . $modelField . '}}', $record[$modelField], $liContent); } } if (!empty($record['children'])) { $liClasses[] = 'has-children'; } $output .= $liTabs . '<li class="' . implode(' ', $liClasses) . '">' . $liContent; if (isset($record['children'][0])) { $output .= $this->nestedList($record['children'], $content, $level + 1, $isActiveCallback); $output .= $liTabs . '</li>'; } else { $output .= '</li>'; } } $output .= $tabs . '</ul>'; return $output; }
php
public function nestedList(array $data, string $content, int $level = 0, array $isActiveCallback = null): string { $tabs = "\n" . str_repeat(' ', $level * 2); $liTabs = $tabs . ' '; $output = $tabs . '<ul>'; foreach ($data as $record) { $liClasses = []; $liContent = $content; if ($isActiveCallback !== null) { $additionalArguments = !empty($isActiveCallback['arguments']) ? $isActiveCallback['arguments'] : []; $isActive = call_user_func_array($isActiveCallback['callback'], [&$record, $additionalArguments]); if ($isActive) { $liClasses[] = 'active'; } } // find the model variables preg_match_all("/\{\{([a-z0-9\._]+)\}\}/i", $liContent, $matches); if (!empty($matches)) { $variables = array_unique($matches[1]); foreach ($variables as $modelField) { $liContent = str_replace('{{' . $modelField . '}}', $record[$modelField], $liContent); } } if (!empty($record['children'])) { $liClasses[] = 'has-children'; } $output .= $liTabs . '<li class="' . implode(' ', $liClasses) . '">' . $liContent; if (isset($record['children'][0])) { $output .= $this->nestedList($record['children'], $content, $level + 1, $isActiveCallback); $output .= $liTabs . '</li>'; } else { $output .= '</li>'; } } $output .= $tabs . '</ul>'; return $output; }
[ "public", "function", "nestedList", "(", "array", "$", "data", ",", "string", "$", "content", ",", "int", "$", "level", "=", "0", ",", "array", "$", "isActiveCallback", "=", "null", ")", ":", "string", "{", "$", "tabs", "=", "\"\\n\"", ".", "str_repeat...
Renders a nested list Usage: $tree = $this->Posts->find('threaded'); echo $this->CkTools->nestedList($tree, '<a href="{{url}}">{{title}}</a>'); @param array $data Nested array @param string $content String template for each node @param int $level Depth @param array $isActiveCallback Will be passed the record @return string
[ "Renders", "a", "nested", "list" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L410-L450
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.historyBackButton
public function historyBackButton(array $options = []): string { //FIXME: Add detection for IE8 & IE9 and create fallback $options = Hash::merge([ 'icon' => 'fa fa-arrow-left', 'class' => 'btn btn-default btn-xs', ], $options); $div = '<div class="' . $options['class'] . '" onclick="history.back()">'; $i = '<i class="' . $options['icon'] . '"></i>'; return $div . $i . ' ' . __d('ck_tools', 'history_back_button') . '</div>'; }
php
public function historyBackButton(array $options = []): string { //FIXME: Add detection for IE8 & IE9 and create fallback $options = Hash::merge([ 'icon' => 'fa fa-arrow-left', 'class' => 'btn btn-default btn-xs', ], $options); $div = '<div class="' . $options['class'] . '" onclick="history.back()">'; $i = '<i class="' . $options['icon'] . '"></i>'; return $div . $i . ' ' . __d('ck_tools', 'history_back_button') . '</div>'; }
[ "public", "function", "historyBackButton", "(", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "//FIXME: Add detection for IE8 & IE9 and create fallback", "$", "options", "=", "Hash", "::", "merge", "(", "[", "'icon'", "=>", "'fa fa-arrow-left'", ...
Renders a div with an onclick-hanlder, which uses the history API of the Browser @return string
[ "Renders", "a", "div", "with", "an", "onclick", "-", "hanlder", "which", "uses", "the", "history", "API", "of", "the", "Browser" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L457-L469
train
scherersoftware/cake-cktools
src/View/Helper/CkToolsHelper.php
CkToolsHelper.displayStructuredData
public function displayStructuredData(array $data, array $options = []): string { $options = Hash::merge([ 'expanded' => true, 'expandLinkText' => __d('ck_tools', 'utility.toggle_content'), 'type' => 'array', ], $options); switch ($options['type']) { case 'table': $list = $this->arrayToTable($data, $options); break; case 'array': default: $list = $this->arrayToUnorderedList($data); break; } if (!$options['expanded']) { $id = 'dsd-' . uniqid(); $out = $this->Html->link($options['expandLinkText'], 'javascript:', [ 'type' => 'button', 'data-toggle' => 'collapse', 'aria-expanded' => 'false', 'aria-controls' => $id, 'data-target' => '#' . $id, ]); $out .= '<div class="collapse" id="' . $id . '">' . $list . '</div>'; } else { $out = $list; } return $out; }
php
public function displayStructuredData(array $data, array $options = []): string { $options = Hash::merge([ 'expanded' => true, 'expandLinkText' => __d('ck_tools', 'utility.toggle_content'), 'type' => 'array', ], $options); switch ($options['type']) { case 'table': $list = $this->arrayToTable($data, $options); break; case 'array': default: $list = $this->arrayToUnorderedList($data); break; } if (!$options['expanded']) { $id = 'dsd-' . uniqid(); $out = $this->Html->link($options['expandLinkText'], 'javascript:', [ 'type' => 'button', 'data-toggle' => 'collapse', 'aria-expanded' => 'false', 'aria-controls' => $id, 'data-target' => '#' . $id, ]); $out .= '<div class="collapse" id="' . $id . '">' . $list . '</div>'; } else { $out = $list; } return $out; }
[ "public", "function", "displayStructuredData", "(", "array", "$", "data", ",", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "$", "options", "=", "Hash", "::", "merge", "(", "[", "'expanded'", "=>", "true", ",", "'expandLinkText'", "=>...
Display an array in human-readable format and provide options to toggle its display @param array $data Data to display @param array $options Options: - expanded: Whether the data should be shown by default - expandLinkText: Link text for toggling the content - callback: A callback used on every entry @return string
[ "Display", "an", "array", "in", "human", "-", "readable", "format", "and", "provide", "options", "to", "toggle", "its", "display" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/CkToolsHelper.php#L482-L515
train
webwarejp/OpenppWebPushAdapter
src/Adapter/Web.php
Web.createMessageBody
protected function createMessageBody(MessageInterface $message) { $body = []; if ($message instanceof BaseOptionedModel) { $body = $message->getOptions(); } $body['message'] = $message->getText(); return json_encode($body); }
php
protected function createMessageBody(MessageInterface $message) { $body = []; if ($message instanceof BaseOptionedModel) { $body = $message->getOptions(); } $body['message'] = $message->getText(); return json_encode($body); }
[ "protected", "function", "createMessageBody", "(", "MessageInterface", "$", "message", ")", "{", "$", "body", "=", "[", "]", ";", "if", "(", "$", "message", "instanceof", "BaseOptionedModel", ")", "{", "$", "body", "=", "$", "message", "->", "getOptions", ...
Create message body. @param MessageInterface $message @return string
[ "Create", "message", "body", "." ]
3592fe8e2078371b347fb8c1fe446f20b536992e
https://github.com/webwarejp/OpenppWebPushAdapter/blob/3592fe8e2078371b347fb8c1fe446f20b536992e/src/Adapter/Web.php#L245-L254
train
webwarejp/OpenppWebPushAdapter
src/Adapter/Web.php
Web.createSignatureToken
protected function createSignatureToken($origin, \DateTime $expiration = null) { if (is_null($expiration)) { $expiration = new \DateTime('+ 1 hours'); } $signer = new ES256(); $privateKey = new Key('file://'.$this->getParameter('privateKey')); $builder = new Builder(); $token = $builder ->setAudience($origin) ->setExpiration($expiration->getTimestamp()) ->sign($signer, $privateKey) ->getToken(); return $token; }
php
protected function createSignatureToken($origin, \DateTime $expiration = null) { if (is_null($expiration)) { $expiration = new \DateTime('+ 1 hours'); } $signer = new ES256(); $privateKey = new Key('file://'.$this->getParameter('privateKey')); $builder = new Builder(); $token = $builder ->setAudience($origin) ->setExpiration($expiration->getTimestamp()) ->sign($signer, $privateKey) ->getToken(); return $token; }
[ "protected", "function", "createSignatureToken", "(", "$", "origin", ",", "\\", "DateTime", "$", "expiration", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "expiration", ")", ")", "{", "$", "expiration", "=", "new", "\\", "DateTime", "(", "'+ 1...
Create the JWT signed by using ES256. @param string $origin @param \DateTime $expiration @return \Lcobucci\JWT\Token
[ "Create", "the", "JWT", "signed", "by", "using", "ES256", "." ]
3592fe8e2078371b347fb8c1fe446f20b536992e
https://github.com/webwarejp/OpenppWebPushAdapter/blob/3592fe8e2078371b347fb8c1fe446f20b536992e/src/Adapter/Web.php#L305-L322
train
selective-php/encoding
src/JsonEncoding.php
JsonEncoding.encodeJson
public function encodeJson($data): string { if ($data instanceof JsonSerializable) { $data = $data->jsonSerialize(); } $result = json_encode($this->utf8Encoding->encodeUtf8($data), 512, JSON_THROW_ON_ERROR); if ($result === false) { throw new JsonException('Json encoding failed'); } return $result; }
php
public function encodeJson($data): string { if ($data instanceof JsonSerializable) { $data = $data->jsonSerialize(); } $result = json_encode($this->utf8Encoding->encodeUtf8($data), 512, JSON_THROW_ON_ERROR); if ($result === false) { throw new JsonException('Json encoding failed'); } return $result; }
[ "public", "function", "encodeJson", "(", "$", "data", ")", ":", "string", "{", "if", "(", "$", "data", "instanceof", "JsonSerializable", ")", "{", "$", "data", "=", "$", "data", "->", "jsonSerialize", "(", ")", ";", "}", "$", "result", "=", "json_encod...
Encode an array to JSON. Also makes sure the data is encoded in UTF-8. @param mixed $data the array to encode in JSON @throws JsonException @return string the JSON encoded string
[ "Encode", "an", "array", "to", "JSON", "." ]
e984a2a8a514c60d2e5948564a681eaf47e06b74
https://github.com/selective-php/encoding/blob/e984a2a8a514c60d2e5948564a681eaf47e06b74/src/JsonEncoding.php#L38-L51
train
scherersoftware/cake-cktools
src/Shell/InternationalizationShell.php
InternationalizationShell.getOptionParser
public function getOptionParser(): ConsoleOptionParser { $parser = parent::getOptionParser(); $updateFromCatalogParser = parent::getOptionParser(); $updateFromCatalogParser->addOption('domain', [ 'default' => 'default', 'help' => 'The domain to use', ]); $updateFromCatalogParser->addOption('overwrite', [ 'default' => false, 'help' => 'If set, there will be no interactive question whether to continue.', 'boolean' => true, ]); $updateFromCatalogParser->addOption('strip-references', [ 'boolean' => true, 'help' => 'Whether to remove file usage references from resulting po and mo files.', ]); return $parser ->setDescription([ 'CkTools Shell', '', 'Utilities', ]) ->addSubcommand('updateFromCatalog', [ 'help' => 'Updates the PO file from the given catalog', 'parser' => $updateFromCatalogParser, ]); }
php
public function getOptionParser(): ConsoleOptionParser { $parser = parent::getOptionParser(); $updateFromCatalogParser = parent::getOptionParser(); $updateFromCatalogParser->addOption('domain', [ 'default' => 'default', 'help' => 'The domain to use', ]); $updateFromCatalogParser->addOption('overwrite', [ 'default' => false, 'help' => 'If set, there will be no interactive question whether to continue.', 'boolean' => true, ]); $updateFromCatalogParser->addOption('strip-references', [ 'boolean' => true, 'help' => 'Whether to remove file usage references from resulting po and mo files.', ]); return $parser ->setDescription([ 'CkTools Shell', '', 'Utilities', ]) ->addSubcommand('updateFromCatalog', [ 'help' => 'Updates the PO file from the given catalog', 'parser' => $updateFromCatalogParser, ]); }
[ "public", "function", "getOptionParser", "(", ")", ":", "ConsoleOptionParser", "{", "$", "parser", "=", "parent", "::", "getOptionParser", "(", ")", ";", "$", "updateFromCatalogParser", "=", "parent", "::", "getOptionParser", "(", ")", ";", "$", "updateFromCatal...
Manage the available sub-commands along with their arguments and help @see http://book.cakephp.org/3.0/en/console-and-shells.html#configuring-options-and-generating-help @return \Cake\Console\ConsoleOptionParser
[ "Manage", "the", "available", "sub", "-", "commands", "along", "with", "their", "arguments", "and", "help" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/Shell/InternationalizationShell.php#L23-L52
train
scherersoftware/cake-cktools
src/Shell/InternationalizationShell.php
InternationalizationShell.updateFromCatalog
public function updateFromCatalog(): void { $domain = $this->params['domain']; $localePath = ROOT . '/src/Locale/'; $catalogFile = $localePath . $domain . '.pot'; if (!file_exists($catalogFile)) { $this->abort(sprintf('Catalog File %s not found.', $catalogFile)); } $poFiles = []; $folder = new Folder($localePath); $tree = $folder->tree(); foreach ($tree[1] as $file) { $basename = basename($file); if ($domain . '.po' === $basename) { $poFiles[] = $file; } } if (empty($poFiles)) { $this->abort(sprintf('I could not find any matching po files in the given locale path (%s) for the domain (%s)', $localePath, $domain)); } if (!$this->params['overwrite']) { $this->out('I will update the following .po files and their corresponding .mo file with the keys from catalog: ' . $catalogFile); foreach ($poFiles as $poFile) { $this->out(' - ' . $poFile); } $response = $this->in('Would you like to continue?', ['y', 'n'], 'n'); if ($response !== 'y') { $this->abort('Aborted'); } } foreach ($poFiles as $poFile) { $catalogEntries = Translations::fromPoFile($catalogFile); $moFile = str_replace('.po', '.mo', $poFile); $translationEntries = Translations::fromPoFile($poFile); $newTranslationEntries = $catalogEntries->mergeWith($translationEntries, Merge::REFERENCES_THEIRS); $newTranslationEntries->deleteHeaders(); foreach ($translationEntries->getHeaders() as $key => $value) { $newTranslationEntries->setHeader($key, $value); } if ($this->params['strip-references']) { foreach ($newTranslationEntries as $translation) { $translation->deleteReferences(); } } $newTranslationEntries->toPoFile($poFile); $newTranslationEntries->toMoFile($moFile); $this->out('Updated ' . $poFile); $this->out('Updated ' . $moFile); } }
php
public function updateFromCatalog(): void { $domain = $this->params['domain']; $localePath = ROOT . '/src/Locale/'; $catalogFile = $localePath . $domain . '.pot'; if (!file_exists($catalogFile)) { $this->abort(sprintf('Catalog File %s not found.', $catalogFile)); } $poFiles = []; $folder = new Folder($localePath); $tree = $folder->tree(); foreach ($tree[1] as $file) { $basename = basename($file); if ($domain . '.po' === $basename) { $poFiles[] = $file; } } if (empty($poFiles)) { $this->abort(sprintf('I could not find any matching po files in the given locale path (%s) for the domain (%s)', $localePath, $domain)); } if (!$this->params['overwrite']) { $this->out('I will update the following .po files and their corresponding .mo file with the keys from catalog: ' . $catalogFile); foreach ($poFiles as $poFile) { $this->out(' - ' . $poFile); } $response = $this->in('Would you like to continue?', ['y', 'n'], 'n'); if ($response !== 'y') { $this->abort('Aborted'); } } foreach ($poFiles as $poFile) { $catalogEntries = Translations::fromPoFile($catalogFile); $moFile = str_replace('.po', '.mo', $poFile); $translationEntries = Translations::fromPoFile($poFile); $newTranslationEntries = $catalogEntries->mergeWith($translationEntries, Merge::REFERENCES_THEIRS); $newTranslationEntries->deleteHeaders(); foreach ($translationEntries->getHeaders() as $key => $value) { $newTranslationEntries->setHeader($key, $value); } if ($this->params['strip-references']) { foreach ($newTranslationEntries as $translation) { $translation->deleteReferences(); } } $newTranslationEntries->toPoFile($poFile); $newTranslationEntries->toMoFile($moFile); $this->out('Updated ' . $poFile); $this->out('Updated ' . $moFile); } }
[ "public", "function", "updateFromCatalog", "(", ")", ":", "void", "{", "$", "domain", "=", "$", "this", "->", "params", "[", "'domain'", "]", ";", "$", "localePath", "=", "ROOT", ".", "'/src/Locale/'", ";", "$", "catalogFile", "=", "$", "localePath", "."...
Updates the catalog file from the given po file @return void
[ "Updates", "the", "catalog", "file", "from", "the", "given", "po", "file" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/Shell/InternationalizationShell.php#L69-L128
train
songshenzong/api
src/Exception/Handler.php
Handler.register
public function register(callable $callback): void { $hint = $this->handlerHint($callback); $this->handlers[$hint] = $callback; }
php
public function register(callable $callback): void { $hint = $this->handlerHint($callback); $this->handlers[$hint] = $callback; }
[ "public", "function", "register", "(", "callable", "$", "callback", ")", ":", "void", "{", "$", "hint", "=", "$", "this", "->", "handlerHint", "(", "$", "callback", ")", ";", "$", "this", "->", "handlers", "[", "$", "hint", "]", "=", "$", "callback",...
Register a new exception handler. @param callable $callback @return void @throws \ReflectionException
[ "Register", "a", "new", "exception", "handler", "." ]
b81751be0fe64eb9e6c775957aa2e8f8c6c2444e
https://github.com/songshenzong/api/blob/b81751be0fe64eb9e6c775957aa2e8f8c6c2444e/src/Exception/Handler.php#L108-L113
train
songshenzong/api
src/Exception/Handler.php
Handler.getHttpStatusCode
protected function getHttpStatusCode(Exception $exception): int { if ($exception instanceof ApiException) { return $exception->apiMessage->getHttpStatusCode(); } if ($exception instanceof HttpExceptionInterface && method_exists($exception, 'getStatusCode')) { return $exception->getStatusCode(); } return 500; }
php
protected function getHttpStatusCode(Exception $exception): int { if ($exception instanceof ApiException) { return $exception->apiMessage->getHttpStatusCode(); } if ($exception instanceof HttpExceptionInterface && method_exists($exception, 'getStatusCode')) { return $exception->getStatusCode(); } return 500; }
[ "protected", "function", "getHttpStatusCode", "(", "Exception", "$", "exception", ")", ":", "int", "{", "if", "(", "$", "exception", "instanceof", "ApiException", ")", "{", "return", "$", "exception", "->", "apiMessage", "->", "getHttpStatusCode", "(", ")", ";...
Get the Http status code from the exception. @param \Exception $exception @return int
[ "Get", "the", "Http", "status", "code", "from", "the", "exception", "." ]
b81751be0fe64eb9e6c775957aa2e8f8c6c2444e
https://github.com/songshenzong/api/blob/b81751be0fe64eb9e6c775957aa2e8f8c6c2444e/src/Exception/Handler.php#L185-L196
train
songshenzong/api
src/Exception/Handler.php
Handler.handlerHint
protected function handlerHint(callable $callback): string { $reflection = new ReflectionFunction($callback); $exception = $reflection->getParameters()[0]; return $exception->getClass()->getName(); }
php
protected function handlerHint(callable $callback): string { $reflection = new ReflectionFunction($callback); $exception = $reflection->getParameters()[0]; return $exception->getClass()->getName(); }
[ "protected", "function", "handlerHint", "(", "callable", "$", "callback", ")", ":", "string", "{", "$", "reflection", "=", "new", "ReflectionFunction", "(", "$", "callback", ")", ";", "$", "exception", "=", "$", "reflection", "->", "getParameters", "(", ")",...
Get the hint for an exception handler. @param callable $callback @return string @throws \ReflectionException
[ "Get", "the", "hint", "for", "an", "exception", "handler", "." ]
b81751be0fe64eb9e6c775957aa2e8f8c6c2444e
https://github.com/songshenzong/api/blob/b81751be0fe64eb9e6c775957aa2e8f8c6c2444e/src/Exception/Handler.php#L307-L314
train
MovingImage24/VMProApiClient
lib/Manager/TokenManager.php
TokenManager.createNewTokens
protected function createNewTokens() { $logger = $this->getLogger(); $logger->debug('Starting request to create fresh access & refresh tokens'); $body = [ 'client_id' => 'anonymous', 'grant_type' => 'password', 'response_type' => 'token', 'scope' => 'openid', 'username' => $this->credentials->getUsername(), 'password' => $this->credentials->getPassword(), ]; $response = $this->sendPostRequest($body); $logger->debug('Successfully retrieved new access & refresh tokens', $response); return [ 'accessToken' => new Token( $response['access_token'], $this->tokenExtractor->extract($response['access_token']) ), 'refreshToken' => new Token( $response['refresh_token'], $this->tokenExtractor->extract($response['refresh_token']) ), ]; }
php
protected function createNewTokens() { $logger = $this->getLogger(); $logger->debug('Starting request to create fresh access & refresh tokens'); $body = [ 'client_id' => 'anonymous', 'grant_type' => 'password', 'response_type' => 'token', 'scope' => 'openid', 'username' => $this->credentials->getUsername(), 'password' => $this->credentials->getPassword(), ]; $response = $this->sendPostRequest($body); $logger->debug('Successfully retrieved new access & refresh tokens', $response); return [ 'accessToken' => new Token( $response['access_token'], $this->tokenExtractor->extract($response['access_token']) ), 'refreshToken' => new Token( $response['refresh_token'], $this->tokenExtractor->extract($response['refresh_token']) ), ]; }
[ "protected", "function", "createNewTokens", "(", ")", "{", "$", "logger", "=", "$", "this", "->", "getLogger", "(", ")", ";", "$", "logger", "->", "debug", "(", "'Starting request to create fresh access & refresh tokens'", ")", ";", "$", "body", "=", "[", "'cl...
Create completely fresh Access + Refresh tokens. @TODO Implement proper error handling @return array
[ "Create", "completely", "fresh", "Access", "+", "Refresh", "tokens", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Manager/TokenManager.php#L82-L110
train
MovingImage24/VMProApiClient
lib/Manager/TokenManager.php
TokenManager.createAccessTokenFromRefreshToken
protected function createAccessTokenFromRefreshToken(Token $refreshToken) { $logger = $this->getLogger(); $logger->debug('Starting request to create fresh access token from refresh token'); $body = [ 'client_id' => 'anonymous', 'grant_type' => 'refresh_token', 'refresh_token' => $refreshToken->getTokenString(), ]; $response = $this->sendPostRequest($body); $logger->debug('Successfully retrieved new access token', $response); return new Token( $response['access_token'], $this->tokenExtractor->extract($response['access_token']) ); }
php
protected function createAccessTokenFromRefreshToken(Token $refreshToken) { $logger = $this->getLogger(); $logger->debug('Starting request to create fresh access token from refresh token'); $body = [ 'client_id' => 'anonymous', 'grant_type' => 'refresh_token', 'refresh_token' => $refreshToken->getTokenString(), ]; $response = $this->sendPostRequest($body); $logger->debug('Successfully retrieved new access token', $response); return new Token( $response['access_token'], $this->tokenExtractor->extract($response['access_token']) ); }
[ "protected", "function", "createAccessTokenFromRefreshToken", "(", "Token", "$", "refreshToken", ")", "{", "$", "logger", "=", "$", "this", "->", "getLogger", "(", ")", ";", "$", "logger", "->", "debug", "(", "'Starting request to create fresh access token from refres...
Create a new access token for a video manager using a refresh token. @param Token $refreshToken @return Token
[ "Create", "a", "new", "access", "token", "for", "a", "video", "manager", "using", "a", "refresh", "token", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Manager/TokenManager.php#L119-L138
train
MovingImage24/VMProApiClient
lib/Manager/TokenManager.php
TokenManager.logTokenData
protected function logTokenData() { $this->getLogger()->debug('Token information', [ 'accessTokenExists' => isset($this->accessToken), 'accessTokenExpiration' => isset($this->accessToken) ? $this->accessToken->getTokenData()['exp'] : null, 'accessTokenHasExpired' => isset($this->accessToken) ? $this->accessToken->expired() : null, 'refreshTokenExists' => isset($this->refreshToken), 'refreshTokenExpiration' => isset($this->refreshToken) ? $this->refreshToken->getTokenData()['exp'] : null, 'refreshTokenHasExpired' => isset($this->refreshToken) ? $this->refreshToken->expired() : null, 'localTime' => time(), ]); }
php
protected function logTokenData() { $this->getLogger()->debug('Token information', [ 'accessTokenExists' => isset($this->accessToken), 'accessTokenExpiration' => isset($this->accessToken) ? $this->accessToken->getTokenData()['exp'] : null, 'accessTokenHasExpired' => isset($this->accessToken) ? $this->accessToken->expired() : null, 'refreshTokenExists' => isset($this->refreshToken), 'refreshTokenExpiration' => isset($this->refreshToken) ? $this->refreshToken->getTokenData()['exp'] : null, 'refreshTokenHasExpired' => isset($this->refreshToken) ? $this->refreshToken->expired() : null, 'localTime' => time(), ]); }
[ "protected", "function", "logTokenData", "(", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "debug", "(", "'Token information'", ",", "[", "'accessTokenExists'", "=>", "isset", "(", "$", "this", "->", "accessToken", ")", ",", "'accessTokenExpiratio...
Log information about which tokens we have.
[ "Log", "information", "about", "which", "tokens", "we", "have", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Manager/TokenManager.php#L143-L154
train
MovingImage24/VMProApiClient
lib/Manager/TokenManager.php
TokenManager.getToken
public function getToken() { $logger = $this->getLogger(); $this->logTokenData(); $cacheKey = sha1(sprintf('%s.%s', __METHOD__, json_encode(func_get_args()))); $cacheItem = $this->cacheItemPool->getItem($cacheKey); if (!$this->accessToken && $cacheItem->isHit()) { $this->accessToken = $cacheItem->get(); } // Access token has expired, but expiration token has not expired. // Issue ourselves a new access token for the same video manager. if (!is_null($this->accessToken) && $this->accessToken->expired() && !is_null($this->refreshToken) && !$this->refreshToken->expired()) { $logger->info('Access token has expired - getting new one for same video manager with refresh token'); $this->accessToken = $this->createAccessTokenFromRefreshToken($this->refreshToken); } elseif (is_null($this->accessToken) || (!is_null($this->refreshToken) && $this->refreshToken->expired())) { // Either we have no token, or the refresh token has expired // so we will need to generate completely new tokens $logger->info('No access token, or refresh token has expired - generate completely new ones'); $tokenData = $this->createNewTokens(); $this->accessToken = $tokenData['accessToken']; $this->refreshToken = $tokenData['refreshToken']; } $cacheItem->set($this->accessToken); $cacheItem->expiresAt((new \DateTime()) ->setTimestamp($this->accessToken->getTokenData()['exp']) ->sub(new \DateInterval('PT30S')) ); $this->cacheItemPool->save($cacheItem); return $this->accessToken->getTokenString(); }
php
public function getToken() { $logger = $this->getLogger(); $this->logTokenData(); $cacheKey = sha1(sprintf('%s.%s', __METHOD__, json_encode(func_get_args()))); $cacheItem = $this->cacheItemPool->getItem($cacheKey); if (!$this->accessToken && $cacheItem->isHit()) { $this->accessToken = $cacheItem->get(); } // Access token has expired, but expiration token has not expired. // Issue ourselves a new access token for the same video manager. if (!is_null($this->accessToken) && $this->accessToken->expired() && !is_null($this->refreshToken) && !$this->refreshToken->expired()) { $logger->info('Access token has expired - getting new one for same video manager with refresh token'); $this->accessToken = $this->createAccessTokenFromRefreshToken($this->refreshToken); } elseif (is_null($this->accessToken) || (!is_null($this->refreshToken) && $this->refreshToken->expired())) { // Either we have no token, or the refresh token has expired // so we will need to generate completely new tokens $logger->info('No access token, or refresh token has expired - generate completely new ones'); $tokenData = $this->createNewTokens(); $this->accessToken = $tokenData['accessToken']; $this->refreshToken = $tokenData['refreshToken']; } $cacheItem->set($this->accessToken); $cacheItem->expiresAt((new \DateTime()) ->setTimestamp($this->accessToken->getTokenData()['exp']) ->sub(new \DateInterval('PT30S')) ); $this->cacheItemPool->save($cacheItem); return $this->accessToken->getTokenString(); }
[ "public", "function", "getToken", "(", ")", "{", "$", "logger", "=", "$", "this", "->", "getLogger", "(", ")", ";", "$", "this", "->", "logTokenData", "(", ")", ";", "$", "cacheKey", "=", "sha1", "(", "sprintf", "(", "'%s.%s'", ",", "__METHOD__", ","...
Retrieve a valid token. @return string
[ "Retrieve", "a", "valid", "token", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Manager/TokenManager.php#L161-L199
train
MovingImage24/VMProApiClient
lib/Manager/TokenManager.php
TokenManager.sendPostRequest
private function sendPostRequest(array $body) { $requestBodyKey = version_compare(ClientInterface::VERSION, '6.0', '>=') ? 'form_params' : 'body'; $response = $this->httpClient->post('', [ $requestBodyKey => $body, ]); return \json_decode($response->getBody(), true); }
php
private function sendPostRequest(array $body) { $requestBodyKey = version_compare(ClientInterface::VERSION, '6.0', '>=') ? 'form_params' : 'body'; $response = $this->httpClient->post('', [ $requestBodyKey => $body, ]); return \json_decode($response->getBody(), true); }
[ "private", "function", "sendPostRequest", "(", "array", "$", "body", ")", "{", "$", "requestBodyKey", "=", "version_compare", "(", "ClientInterface", "::", "VERSION", ",", "'6.0'", ",", "'>='", ")", "?", "'form_params'", ":", "'body'", ";", "$", "response", ...
Sends a post request to the OAuth endpoint Supports both guzzle 5 and 6 versions. @param array $body @return mixed
[ "Sends", "a", "post", "request", "to", "the", "OAuth", "endpoint", "Supports", "both", "guzzle", "5", "and", "6", "versions", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Manager/TokenManager.php#L209-L217
train
koolkode/async
src/DNS/Resolver.php
Resolver.awaitFirstResult
protected function awaitFirstResult(Context $context, array $tasks, CancellationHandler $cancel, array & $errors): \Generator { if (empty($tasks)) { return; } try { $result = yield $context->first($tasks, $cancel, $errors); } catch (MultiReasonException $e) { $result = null; } return $result; }
php
protected function awaitFirstResult(Context $context, array $tasks, CancellationHandler $cancel, array & $errors): \Generator { if (empty($tasks)) { return; } try { $result = yield $context->first($tasks, $cancel, $errors); } catch (MultiReasonException $e) { $result = null; } return $result; }
[ "protected", "function", "awaitFirstResult", "(", "Context", "$", "context", ",", "array", "$", "tasks", ",", "CancellationHandler", "$", "cancel", ",", "array", "&", "$", "errors", ")", ":", "\\", "Generator", "{", "if", "(", "empty", "(", "$", "tasks", ...
Helper method that collects errors thrown by promises into an array and allways resolves. @param Context $context Async execution context. @param array $tasks @param CancellationHandler $cancel @param array $errors
[ "Helper", "method", "that", "collects", "errors", "thrown", "by", "promises", "into", "an", "array", "and", "allways", "resolves", "." ]
9c985dcdd3b328323826dd4254d9f2e5aea0b75b
https://github.com/koolkode/async/blob/9c985dcdd3b328323826dd4254d9f2e5aea0b75b/src/DNS/Resolver.php#L250-L263
train
koolkode/async
src/DNS/Resolver.php
Resolver.query
protected function query(Context $context, string $server, string $host, int $type): \Generator { $response = yield $this->getUdpConnector($server)->send($context, $this->createRequest($host, $type)); if ($response->isTruncated()) { $response = yield $this->getTcpConnector($server)->send($context, $this->createRequest($host, $type)); } $resolved = []; $ttl = \PHP_INT_MAX; foreach ($response->getAnswers() as $record) { if ($record['type'] === $type) { $resolved[] = new Address($record['data']); $ttl = \min($ttl, $record['ttl']); } } if (empty($resolved)) { throw new \RuntimeException(\sprintf('Unable to resolve host "%s" into an IP using DNS server %s', $host, $server)); } return [ 'ttl' => \max(1, \min(300, $ttl)), 'ips' => $resolved ]; }
php
protected function query(Context $context, string $server, string $host, int $type): \Generator { $response = yield $this->getUdpConnector($server)->send($context, $this->createRequest($host, $type)); if ($response->isTruncated()) { $response = yield $this->getTcpConnector($server)->send($context, $this->createRequest($host, $type)); } $resolved = []; $ttl = \PHP_INT_MAX; foreach ($response->getAnswers() as $record) { if ($record['type'] === $type) { $resolved[] = new Address($record['data']); $ttl = \min($ttl, $record['ttl']); } } if (empty($resolved)) { throw new \RuntimeException(\sprintf('Unable to resolve host "%s" into an IP using DNS server %s', $host, $server)); } return [ 'ttl' => \max(1, \min(300, $ttl)), 'ips' => $resolved ]; }
[ "protected", "function", "query", "(", "Context", "$", "context", ",", "string", "$", "server", ",", "string", "$", "host", ",", "int", "$", "type", ")", ":", "\\", "Generator", "{", "$", "response", "=", "yield", "$", "this", "->", "getUdpConnector", ...
Lookup IP addresses using DNS server. @param Context $context Async execution context. @param string $server DNS server adress. @param string $host Host name to be resolved. @param int $type Question type (A or AAAA). @return array Resolved IP addresses. @throws \RuntimeException When no IP address could be resolved.
[ "Lookup", "IP", "addresses", "using", "DNS", "server", "." ]
9c985dcdd3b328323826dd4254d9f2e5aea0b75b
https://github.com/koolkode/async/blob/9c985dcdd3b328323826dd4254d9f2e5aea0b75b/src/DNS/Resolver.php#L276-L302
train
koolkode/async
src/DNS/Resolver.php
Resolver.getUdpConnector
protected function getUdpConnector(string $server): UdpConnector { if (empty($this->udp[$server])) { $this->udp[$server] = new UdpConnector($server, $this->timeout); } return $this->udp[$server]; }
php
protected function getUdpConnector(string $server): UdpConnector { if (empty($this->udp[$server])) { $this->udp[$server] = new UdpConnector($server, $this->timeout); } return $this->udp[$server]; }
[ "protected", "function", "getUdpConnector", "(", "string", "$", "server", ")", ":", "UdpConnector", "{", "if", "(", "empty", "(", "$", "this", "->", "udp", "[", "$", "server", "]", ")", ")", "{", "$", "this", "->", "udp", "[", "$", "server", "]", "...
Get a UDP connector for the given server.
[ "Get", "a", "UDP", "connector", "for", "the", "given", "server", "." ]
9c985dcdd3b328323826dd4254d9f2e5aea0b75b
https://github.com/koolkode/async/blob/9c985dcdd3b328323826dd4254d9f2e5aea0b75b/src/DNS/Resolver.php#L307-L314
train
koolkode/async
src/DNS/Resolver.php
Resolver.getTcpConnector
protected function getTcpConnector(string $server): TcpConnector { if (empty($this->tcp[$server])) { $this->tcp[$server] = new TcpConnector($server, $this->timeout); } return $this->tcp[$server]; }
php
protected function getTcpConnector(string $server): TcpConnector { if (empty($this->tcp[$server])) { $this->tcp[$server] = new TcpConnector($server, $this->timeout); } return $this->tcp[$server]; }
[ "protected", "function", "getTcpConnector", "(", "string", "$", "server", ")", ":", "TcpConnector", "{", "if", "(", "empty", "(", "$", "this", "->", "tcp", "[", "$", "server", "]", ")", ")", "{", "$", "this", "->", "tcp", "[", "$", "server", "]", "...
Get a TCP connector for the given server.
[ "Get", "a", "TCP", "connector", "for", "the", "given", "server", "." ]
9c985dcdd3b328323826dd4254d9f2e5aea0b75b
https://github.com/koolkode/async/blob/9c985dcdd3b328323826dd4254d9f2e5aea0b75b/src/DNS/Resolver.php#L319-L326
train
koolkode/async
src/DNS/Resolver.php
Resolver.createRequest
protected function createRequest(string $host, int $type): Request { $request = new Request(); $request->addQuestion($host, $type); $request->setRecursionDesired(true); return $request; }
php
protected function createRequest(string $host, int $type): Request { $request = new Request(); $request->addQuestion($host, $type); $request->setRecursionDesired(true); return $request; }
[ "protected", "function", "createRequest", "(", "string", "$", "host", ",", "int", "$", "type", ")", ":", "Request", "{", "$", "request", "=", "new", "Request", "(", ")", ";", "$", "request", "->", "addQuestion", "(", "$", "host", ",", "$", "type", ")...
Create a request for the given host and record type.
[ "Create", "a", "request", "for", "the", "given", "host", "and", "record", "type", "." ]
9c985dcdd3b328323826dd4254d9f2e5aea0b75b
https://github.com/koolkode/async/blob/9c985dcdd3b328323826dd4254d9f2e5aea0b75b/src/DNS/Resolver.php#L331-L338
train
kevintweber/HtmlTokenizer
src/Tokens/Element.php
Element.parseAttribute
private function parseAttribute(string $html) : string { $remainingHtml = ltrim($html); try { // Will match the first entire name/value attribute pair. preg_match( "/((([a-z0-9\-_]+:)?[a-z0-9\-_]+)(\s*=\s*)?)/i", $remainingHtml, $attributeMatches ); $attributeName = $attributeMatches[2]; $remainingHtml = mb_substr(mb_strstr($remainingHtml, $attributeName), mb_strlen($attributeName)); if ($this->isAttributeValueless($remainingHtml)) { $this->attributes[trim($attributeName)] = true; return $remainingHtml; } return $this->parseAttributeValue($html, $remainingHtml, $attributeName); } catch (ParseException $e) { if ($this->getThrowOnError()) { throw $e; } } return ''; }
php
private function parseAttribute(string $html) : string { $remainingHtml = ltrim($html); try { // Will match the first entire name/value attribute pair. preg_match( "/((([a-z0-9\-_]+:)?[a-z0-9\-_]+)(\s*=\s*)?)/i", $remainingHtml, $attributeMatches ); $attributeName = $attributeMatches[2]; $remainingHtml = mb_substr(mb_strstr($remainingHtml, $attributeName), mb_strlen($attributeName)); if ($this->isAttributeValueless($remainingHtml)) { $this->attributes[trim($attributeName)] = true; return $remainingHtml; } return $this->parseAttributeValue($html, $remainingHtml, $attributeName); } catch (ParseException $e) { if ($this->getThrowOnError()) { throw $e; } } return ''; }
[ "private", "function", "parseAttribute", "(", "string", "$", "html", ")", ":", "string", "{", "$", "remainingHtml", "=", "ltrim", "(", "$", "html", ")", ";", "try", "{", "// Will match the first entire name/value attribute pair.", "preg_match", "(", "\"/((([a-z0-9\\...
Will parse attributes. @param string $html @return string Remaining HTML.
[ "Will", "parse", "attributes", "." ]
45b861d29f8c303ebf97533b883e2584811a89fc
https://github.com/kevintweber/HtmlTokenizer/blob/45b861d29f8c303ebf97533b883e2584811a89fc/src/Tokens/Element.php#L183-L211
train
acelot/helpers
src/Retry.php
Retry.run
public function run() { $count = 0; $start = microtime(true); while (true) { try { return call_user_func($this->callable); } catch (\Throwable $e) { // Check exception if (!$e instanceof $this->exceptionType) { throw $e; } // Check timeout if ($this->timeout > -1 && microtime(true) - $start > ($this->timeout / self::SECONDS)) { throw $e; } // Check count if ($this->count > -1 && ++$count >= $this->count) { throw $e; } // Before pause hook if (array_key_exists(self::BEFORE_PAUSE_HOOK, $this->hooks)) { call_user_func($this->hooks[self::BEFORE_PAUSE_HOOK], $e); } usleep($this->pause); // After pause hook if (array_key_exists(self::AFTER_PAUSE_HOOK, $this->hooks)) { call_user_func($this->hooks[self::AFTER_PAUSE_HOOK], $e); } } } }
php
public function run() { $count = 0; $start = microtime(true); while (true) { try { return call_user_func($this->callable); } catch (\Throwable $e) { // Check exception if (!$e instanceof $this->exceptionType) { throw $e; } // Check timeout if ($this->timeout > -1 && microtime(true) - $start > ($this->timeout / self::SECONDS)) { throw $e; } // Check count if ($this->count > -1 && ++$count >= $this->count) { throw $e; } // Before pause hook if (array_key_exists(self::BEFORE_PAUSE_HOOK, $this->hooks)) { call_user_func($this->hooks[self::BEFORE_PAUSE_HOOK], $e); } usleep($this->pause); // After pause hook if (array_key_exists(self::AFTER_PAUSE_HOOK, $this->hooks)) { call_user_func($this->hooks[self::AFTER_PAUSE_HOOK], $e); } } } }
[ "public", "function", "run", "(", ")", "{", "$", "count", "=", "0", ";", "$", "start", "=", "microtime", "(", "true", ")", ";", "while", "(", "true", ")", "{", "try", "{", "return", "call_user_func", "(", "$", "this", "->", "callable", ")", ";", ...
Runs the retry loop. @return mixed @throws \Throwable
[ "Runs", "the", "retry", "loop", "." ]
574d1c940b2dc24343edcd08dd3d746c45c26316
https://github.com/acelot/helpers/blob/574d1c940b2dc24343edcd08dd3d746c45c26316/src/Retry.php#L75-L112
train
acelot/helpers
src/Retry.php
Retry.setHook
public function setHook(string $hook, callable $callable): self { $availableHooks = [self::BEFORE_PAUSE_HOOK, self::AFTER_PAUSE_HOOK]; if (!in_array($hook, $availableHooks)) { throw new \InvalidArgumentException('Invalid hook. Available hooks: ' . join(', ', $availableHooks)); } $this->hooks[$hook] = $callable; return $this; }
php
public function setHook(string $hook, callable $callable): self { $availableHooks = [self::BEFORE_PAUSE_HOOK, self::AFTER_PAUSE_HOOK]; if (!in_array($hook, $availableHooks)) { throw new \InvalidArgumentException('Invalid hook. Available hooks: ' . join(', ', $availableHooks)); } $this->hooks[$hook] = $callable; return $this; }
[ "public", "function", "setHook", "(", "string", "$", "hook", ",", "callable", "$", "callable", ")", ":", "self", "{", "$", "availableHooks", "=", "[", "self", "::", "BEFORE_PAUSE_HOOK", ",", "self", "::", "AFTER_PAUSE_HOOK", "]", ";", "if", "(", "!", "in...
Sets the hook callback function which will be called if exceptions will raise. @param string $hook @param callable $callable @return Retry
[ "Sets", "the", "hook", "callback", "function", "which", "will", "be", "called", "if", "exceptions", "will", "raise", "." ]
574d1c940b2dc24343edcd08dd3d746c45c26316
https://github.com/acelot/helpers/blob/574d1c940b2dc24343edcd08dd3d746c45c26316/src/Retry.php#L127-L137
train
acelot/helpers
src/Retry.php
Retry.setExceptionType
public function setExceptionType(string $exceptionType): self { try { $ref = new \ReflectionClass($exceptionType); if (!$ref->implementsInterface(\Throwable::class)) { throw new \InvalidArgumentException('Exception class must implement Throwable interface'); } } catch (\ReflectionException $e) { throw new \InvalidArgumentException('Exception class not found'); } $this->exceptionType = $exceptionType; return $this; }
php
public function setExceptionType(string $exceptionType): self { try { $ref = new \ReflectionClass($exceptionType); if (!$ref->implementsInterface(\Throwable::class)) { throw new \InvalidArgumentException('Exception class must implement Throwable interface'); } } catch (\ReflectionException $e) { throw new \InvalidArgumentException('Exception class not found'); } $this->exceptionType = $exceptionType; return $this; }
[ "public", "function", "setExceptionType", "(", "string", "$", "exceptionType", ")", ":", "self", "{", "try", "{", "$", "ref", "=", "new", "\\", "ReflectionClass", "(", "$", "exceptionType", ")", ";", "if", "(", "!", "$", "ref", "->", "implementsInterface",...
Sets the exception class name which should be catched during tries. @param string $exceptionType @return self
[ "Sets", "the", "exception", "class", "name", "which", "should", "be", "catched", "during", "tries", "." ]
574d1c940b2dc24343edcd08dd3d746c45c26316
https://github.com/acelot/helpers/blob/574d1c940b2dc24343edcd08dd3d746c45c26316/src/Retry.php#L229-L242
train
shardimage/shardimage-php
src/services/CloudService.php
CloudService.update
public function update($params, $optParams = []) { if (!$params instanceof Cloud) { throw new InvalidParamException(Cloud::class . ' is required!'); } return $this->sendRequest([], [ 'restAction' => 'update', 'restId' => $params->id, 'postParams' => $params->toArray(), 'getParams' => $optParams, ], function ($response) { return isset($response->data) ? new Cloud($response->data) : $response; }); }
php
public function update($params, $optParams = []) { if (!$params instanceof Cloud) { throw new InvalidParamException(Cloud::class . ' is required!'); } return $this->sendRequest([], [ 'restAction' => 'update', 'restId' => $params->id, 'postParams' => $params->toArray(), 'getParams' => $optParams, ], function ($response) { return isset($response->data) ? new Cloud($response->data) : $response; }); }
[ "public", "function", "update", "(", "$", "params", ",", "$", "optParams", "=", "[", "]", ")", "{", "if", "(", "!", "$", "params", "instanceof", "Cloud", ")", "{", "throw", "new", "InvalidParamException", "(", "Cloud", "::", "class", ".", "' is required!...
Updates a cloud. @param Cloud $params Cloud object @param array|Cloud $optParams Optional API parameters @return Cloud|Response @throws InvalidParamException
[ "Updates", "a", "cloud", "." ]
1988e3996dfdf7e17d1bd44d5d807f9884ac64bd
https://github.com/shardimage/shardimage-php/blob/1988e3996dfdf7e17d1bd44d5d807f9884ac64bd/src/services/CloudService.php#L97-L111
train
shardimage/shardimage-php
src/services/CloudService.php
CloudService.delete
public function delete($params, $optParams = []) { if ($params instanceof Cloud) { $params = $params->id; } return $this->sendRequest([], [ 'restAction' => 'delete', 'restId' => $params, 'getParams' => $optParams, ], function ($response) { return $response->success; }); }
php
public function delete($params, $optParams = []) { if ($params instanceof Cloud) { $params = $params->id; } return $this->sendRequest([], [ 'restAction' => 'delete', 'restId' => $params, 'getParams' => $optParams, ], function ($response) { return $response->success; }); }
[ "public", "function", "delete", "(", "$", "params", ",", "$", "optParams", "=", "[", "]", ")", "{", "if", "(", "$", "params", "instanceof", "Cloud", ")", "{", "$", "params", "=", "$", "params", "->", "id", ";", "}", "return", "$", "this", "->", "...
Deletes a cloud. @param Cloud|string $params Cloud object or Cloud ID @param array $optParams Optional API parameters @return bool
[ "Deletes", "a", "cloud", "." ]
1988e3996dfdf7e17d1bd44d5d807f9884ac64bd
https://github.com/shardimage/shardimage-php/blob/1988e3996dfdf7e17d1bd44d5d807f9884ac64bd/src/services/CloudService.php#L121-L134
train
kevintweber/HtmlTokenizer
src/HtmlTokenizer.php
HtmlTokenizer.parse
public function parse(string $html) : TokenCollection { self::$allHtml = $html; $tokens = new TokenCollection(); $remainingHtml = trim($html); while (mb_strlen($remainingHtml) > 0) { $token = TokenFactory::buildFromHtml( $remainingHtml, null, $this->throwOnError ); if (!$token instanceof Token) { // Error has occurred, so we stop. break; } $remainingHtml = $token->parse($remainingHtml); $tokens[] = $token; } return $tokens; }
php
public function parse(string $html) : TokenCollection { self::$allHtml = $html; $tokens = new TokenCollection(); $remainingHtml = trim($html); while (mb_strlen($remainingHtml) > 0) { $token = TokenFactory::buildFromHtml( $remainingHtml, null, $this->throwOnError ); if (!$token instanceof Token) { // Error has occurred, so we stop. break; } $remainingHtml = $token->parse($remainingHtml); $tokens[] = $token; } return $tokens; }
[ "public", "function", "parse", "(", "string", "$", "html", ")", ":", "TokenCollection", "{", "self", "::", "$", "allHtml", "=", "$", "html", ";", "$", "tokens", "=", "new", "TokenCollection", "(", ")", ";", "$", "remainingHtml", "=", "trim", "(", "$", ...
Will parse html into tokens. @param $html string The HTML to tokenize. @return TokenCollection @throws \Kevintweber\HtmlTokenizer\Exceptions\TokenMatchingException
[ "Will", "parse", "html", "into", "tokens", "." ]
45b861d29f8c303ebf97533b883e2584811a89fc
https://github.com/kevintweber/HtmlTokenizer/blob/45b861d29f8c303ebf97533b883e2584811a89fc/src/HtmlTokenizer.php#L35-L56
train
klermonte/zerg
src/Zerg/Field/Arr.php
Arr.parse
public function parse(AbstractStream $stream) { try { return parent::parse($stream); } catch (\OutOfBoundsException $e) { if ($this->isUntilEof()) { return $this->dataSet->getData(); } throw $e; } }
php
public function parse(AbstractStream $stream) { try { return parent::parse($stream); } catch (\OutOfBoundsException $e) { if ($this->isUntilEof()) { return $this->dataSet->getData(); } throw $e; } }
[ "public", "function", "parse", "(", "AbstractStream", "$", "stream", ")", "{", "try", "{", "return", "parent", "::", "parse", "(", "$", "stream", ")", ";", "}", "catch", "(", "\\", "OutOfBoundsException", "$", "e", ")", "{", "if", "(", "$", "this", "...
Call parse method on arrayed field needed times. @api @param AbstractStream $stream Stream from which children read. @return array Array of parsed values. @since 1.0
[ "Call", "parse", "method", "on", "arrayed", "field", "needed", "times", "." ]
c5d9c52cfade1fe9169e3cbae855b49a054f04ff
https://github.com/klermonte/zerg/blob/c5d9c52cfade1fe9169e3cbae855b49a054f04ff/src/Zerg/Field/Arr.php#L58-L69
train
Eden-PHP/Handlebars
src/Compiler.php
Compiler.generateText
protected function generateText($node) { $buffer = ''; $value = explode("\n", $node['value']); $last = count($value) - 1; foreach ($value as $i => $line) { $line = str_replace("'", '\\\'', $line); if ($i === $last) { $buffer .= $this->prettyPrint(sprintf(self::BLOCK_TEXT_LAST, $line)); continue; } $buffer .= $this->prettyPrint(sprintf(self::BLOCK_TEXT_LINE, $line)); } return $buffer; }
php
protected function generateText($node) { $buffer = ''; $value = explode("\n", $node['value']); $last = count($value) - 1; foreach ($value as $i => $line) { $line = str_replace("'", '\\\'', $line); if ($i === $last) { $buffer .= $this->prettyPrint(sprintf(self::BLOCK_TEXT_LAST, $line)); continue; } $buffer .= $this->prettyPrint(sprintf(self::BLOCK_TEXT_LINE, $line)); } return $buffer; }
[ "protected", "function", "generateText", "(", "$", "node", ")", "{", "$", "buffer", "=", "''", ";", "$", "value", "=", "explode", "(", "\"\\n\"", ",", "$", "node", "[", "'value'", "]", ")", ";", "$", "last", "=", "count", "(", "$", "value", ")", ...
Partially renders the text tokens @param *array $node @param *array $open @return string
[ "Partially", "renders", "the", "text", "tokens" ]
ad961e4a6d8505212c3e90edca66e408784c38bd
https://github.com/Eden-PHP/Handlebars/blob/ad961e4a6d8505212c3e90edca66e408784c38bd/src/Compiler.php#L343-L362
train
Eden-PHP/Handlebars
src/Compiler.php
Compiler.generatePartials
protected function generatePartials() { $partials = $this->handlebars->getPartials(); foreach ($partials as $name => $partial) { $partials[$name] = sprintf( self::BLOCK_OPTIONS_HASH_KEY_VALUE, $name, "'" . str_replace("'", '\\\'', $partial) . "'" ); } return $this->prettyPrint(self::BLOCK_OPTIONS_OPEN) . $this->prettyPrint('\r\t') . implode($this->prettyPrint(',\r\t'), $partials) . $this->prettyPrint(self::BLOCK_OPTIONS_CLOSE); }
php
protected function generatePartials() { $partials = $this->handlebars->getPartials(); foreach ($partials as $name => $partial) { $partials[$name] = sprintf( self::BLOCK_OPTIONS_HASH_KEY_VALUE, $name, "'" . str_replace("'", '\\\'', $partial) . "'" ); } return $this->prettyPrint(self::BLOCK_OPTIONS_OPEN) . $this->prettyPrint('\r\t') . implode($this->prettyPrint(',\r\t'), $partials) . $this->prettyPrint(self::BLOCK_OPTIONS_CLOSE); }
[ "protected", "function", "generatePartials", "(", ")", "{", "$", "partials", "=", "$", "this", "->", "handlebars", "->", "getPartials", "(", ")", ";", "foreach", "(", "$", "partials", "as", "$", "name", "=>", "$", "partial", ")", "{", "$", "partials", ...
Generates partials to add to the layout This is a placeholder incase we want to add in the future @return string
[ "Generates", "partials", "to", "add", "to", "the", "layout", "This", "is", "a", "placeholder", "incase", "we", "want", "to", "add", "in", "the", "future" ]
ad961e4a6d8505212c3e90edca66e408784c38bd
https://github.com/Eden-PHP/Handlebars/blob/ad961e4a6d8505212c3e90edca66e408784c38bd/src/Compiler.php#L600-L616
train
Eden-PHP/Handlebars
src/Compiler.php
Compiler.parseArguments
protected function parseArguments($string) { //Argument 1 must be a string Argument::i()->test(1, 'string'); $args = array(); $hash = array(); $regex = array( '([a-zA-Z0-9]+\="[^"]*")', // cat="meow" '([a-zA-Z0-9]+\=\'[^\']*\')', // mouse='squeak squeak' '([a-zA-Z0-9]+\=[a-zA-Z0-9]+)', // dog=false '("[^"]*")', // "some\'thi ' ng" '(\'[^\']*\')', // 'some"thi " ng' '([^\s]+)' // <any group with no spaces> ); preg_match_all('#'.implode('|', $regex).'#is', $string, $matches); $stringArgs = $matches[0]; $name = array_shift($stringArgs); $hashRegex = array( '([a-zA-Z0-9]+\="[^"]*")', // cat="meow" '([a-zA-Z0-9]+\=\'[^\']*\')', // mouse='squeak squeak' '([a-zA-Z0-9]+\=[a-zA-Z0-9]+)', // dog=false ); foreach ($stringArgs as $arg) { //if it's an attribute if (!(substr($arg, 0, 1) === "'" && substr($arg, -1) === "'") && !(substr($arg, 0, 1) === '"' && substr($arg, -1) === '"') && preg_match('#'.implode('|', $hashRegex).'#is', $arg) ) { list($hashKey, $hashValue) = explode('=', $arg, 2); $hash[$hashKey] = $this->parseArgument($hashValue); continue; } $args[] = $this->parseArgument($arg); } return array($name, $args, $hash); }
php
protected function parseArguments($string) { //Argument 1 must be a string Argument::i()->test(1, 'string'); $args = array(); $hash = array(); $regex = array( '([a-zA-Z0-9]+\="[^"]*")', // cat="meow" '([a-zA-Z0-9]+\=\'[^\']*\')', // mouse='squeak squeak' '([a-zA-Z0-9]+\=[a-zA-Z0-9]+)', // dog=false '("[^"]*")', // "some\'thi ' ng" '(\'[^\']*\')', // 'some"thi " ng' '([^\s]+)' // <any group with no spaces> ); preg_match_all('#'.implode('|', $regex).'#is', $string, $matches); $stringArgs = $matches[0]; $name = array_shift($stringArgs); $hashRegex = array( '([a-zA-Z0-9]+\="[^"]*")', // cat="meow" '([a-zA-Z0-9]+\=\'[^\']*\')', // mouse='squeak squeak' '([a-zA-Z0-9]+\=[a-zA-Z0-9]+)', // dog=false ); foreach ($stringArgs as $arg) { //if it's an attribute if (!(substr($arg, 0, 1) === "'" && substr($arg, -1) === "'") && !(substr($arg, 0, 1) === '"' && substr($arg, -1) === '"') && preg_match('#'.implode('|', $hashRegex).'#is', $arg) ) { list($hashKey, $hashValue) = explode('=', $arg, 2); $hash[$hashKey] = $this->parseArgument($hashValue); continue; } $args[] = $this->parseArgument($arg); } return array($name, $args, $hash); }
[ "protected", "function", "parseArguments", "(", "$", "string", ")", "{", "//Argument 1 must be a string", "Argument", "::", "i", "(", ")", "->", "test", "(", "1", ",", "'string'", ")", ";", "$", "args", "=", "array", "(", ")", ";", "$", "hash", "=", "a...
Handlebars will give arguments in a string This will transform them into a legit argument array @param *string $string The argument string @return array
[ "Handlebars", "will", "give", "arguments", "in", "a", "string", "This", "will", "transform", "them", "into", "a", "legit", "argument", "array" ]
ad961e4a6d8505212c3e90edca66e408784c38bd
https://github.com/Eden-PHP/Handlebars/blob/ad961e4a6d8505212c3e90edca66e408784c38bd/src/Compiler.php#L627-L670
train
Eden-PHP/Handlebars
src/Compiler.php
Compiler.parseArgument
protected function parseArgument($arg) { //if it's a literal string value if (strpos($arg, '"') === 0 || strpos($arg, "'") === 0 ) { return "'" . str_replace("'", '\\\'', substr($arg, 1, -1)) . "'"; } //if it's null if (strtolower($arg) === 'null' || strtolower($arg) === 'true' || strtolower($arg) === 'false' || is_numeric($arg) ) { return $arg; } $arg = str_replace(array('[', ']', '(', ')'), '', $arg); $arg = str_replace("'", '\\\'', $arg); return sprintf(self::BLOCK_ARGUMENT_VALUE, $arg); }
php
protected function parseArgument($arg) { //if it's a literal string value if (strpos($arg, '"') === 0 || strpos($arg, "'") === 0 ) { return "'" . str_replace("'", '\\\'', substr($arg, 1, -1)) . "'"; } //if it's null if (strtolower($arg) === 'null' || strtolower($arg) === 'true' || strtolower($arg) === 'false' || is_numeric($arg) ) { return $arg; } $arg = str_replace(array('[', ']', '(', ')'), '', $arg); $arg = str_replace("'", '\\\'', $arg); return sprintf(self::BLOCK_ARGUMENT_VALUE, $arg); }
[ "protected", "function", "parseArgument", "(", "$", "arg", ")", "{", "//if it's a literal string value", "if", "(", "strpos", "(", "$", "arg", ",", "'\"'", ")", "===", "0", "||", "strpos", "(", "$", "arg", ",", "\"'\"", ")", "===", "0", ")", "{", "retu...
If there's a quote, null, bool, int, float... it's the literal value @param *string $value One string argument value @return mixed
[ "If", "there", "s", "a", "quote", "null", "bool", "int", "float", "...", "it", "s", "the", "literal", "value" ]
ad961e4a6d8505212c3e90edca66e408784c38bd
https://github.com/Eden-PHP/Handlebars/blob/ad961e4a6d8505212c3e90edca66e408784c38bd/src/Compiler.php#L680-L701
train
MovingImage24/VMProApiClient
lib/Util/Logging/Traits/LoggerAwareTrait.php
LoggerAwareTrait.getLogger
protected function getLogger() { if (!isset($this->logger)) { // When no logger is injected, create a new one // that doesn't do anything $this->logger = new Logger('api-client'); $this->logger->setHandlers([ new NullHandler(), ]); } return $this->logger; }
php
protected function getLogger() { if (!isset($this->logger)) { // When no logger is injected, create a new one // that doesn't do anything $this->logger = new Logger('api-client'); $this->logger->setHandlers([ new NullHandler(), ]); } return $this->logger; }
[ "protected", "function", "getLogger", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "logger", ")", ")", "{", "// When no logger is injected, create a new one", "// that doesn't do anything", "$", "this", "->", "logger", "=", "new", "Logger", "(...
Get the logger instance associated with this instance. @return LoggerInterface
[ "Get", "the", "logger", "instance", "associated", "with", "this", "instance", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Util/Logging/Traits/LoggerAwareTrait.php#L37-L49
train
MovingImage24/VMProApiClient
lib/Services/Ratings.php
Ratings.addRating
public function addRating($videoId, $rating) { $this->validateRating($rating); $customMetaData = $this->getVideo($videoId)->getCustomMetadata(); $average = $this->getRatingAverage($videoId); $count = $this->getRatingCount($videoId); $newCount = $count + 1; $customMetaData[$this->metadataFieldCount] = $newCount; $customMetaData[$this->metadataFieldAverage] = (($average * $count) + $rating) / $newCount; $this->storeCustomMetaData($customMetaData, $videoId); }
php
public function addRating($videoId, $rating) { $this->validateRating($rating); $customMetaData = $this->getVideo($videoId)->getCustomMetadata(); $average = $this->getRatingAverage($videoId); $count = $this->getRatingCount($videoId); $newCount = $count + 1; $customMetaData[$this->metadataFieldCount] = $newCount; $customMetaData[$this->metadataFieldAverage] = (($average * $count) + $rating) / $newCount; $this->storeCustomMetaData($customMetaData, $videoId); }
[ "public", "function", "addRating", "(", "$", "videoId", ",", "$", "rating", ")", "{", "$", "this", "->", "validateRating", "(", "$", "rating", ")", ";", "$", "customMetaData", "=", "$", "this", "->", "getVideo", "(", "$", "videoId", ")", "->", "getCust...
Increases the count of all ratings by one and calculates a new average rating value. @param string $videoId @param int $rating @throws \InvalidArgumentException
[ "Increases", "the", "count", "of", "all", "ratings", "by", "one", "and", "calculates", "a", "new", "average", "rating", "value", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Services/Ratings.php#L54-L67
train
MovingImage24/VMProApiClient
lib/Services/Ratings.php
Ratings.getCustomMetaDataField
private function getCustomMetaDataField($videoId, $customMetaDataField) { $customMetaData = $this->getVideo($videoId)->getCustomMetadata(); return array_key_exists($customMetaDataField, $customMetaData) ? (float) $customMetaData[$customMetaDataField] : 0; }
php
private function getCustomMetaDataField($videoId, $customMetaDataField) { $customMetaData = $this->getVideo($videoId)->getCustomMetadata(); return array_key_exists($customMetaDataField, $customMetaData) ? (float) $customMetaData[$customMetaDataField] : 0; }
[ "private", "function", "getCustomMetaDataField", "(", "$", "videoId", ",", "$", "customMetaDataField", ")", "{", "$", "customMetaData", "=", "$", "this", "->", "getVideo", "(", "$", "videoId", ")", "->", "getCustomMetadata", "(", ")", ";", "return", "array_key...
Returns a meta data field of a video always as a number. @param $videoId @param $customMetaDataField @return float|int
[ "Returns", "a", "meta", "data", "field", "of", "a", "video", "always", "as", "a", "number", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Services/Ratings.php#L124-L131
train
MovingImage24/VMProApiClient
lib/Services/Ratings.php
Ratings.storeCustomMetaData
private function storeCustomMetaData($customMetaData, $videoId) { // only update custom meta data fields related to rating $this->client->setCustomMetaData( $this->vmId, $videoId, $this->filterCustomMetaData($customMetaData) ); // also store custom meta data fields locally, if video is fetched again by function $this->getVideo($videoId) $this->getVideo($videoId)->setCustomMetadata($customMetaData); }
php
private function storeCustomMetaData($customMetaData, $videoId) { // only update custom meta data fields related to rating $this->client->setCustomMetaData( $this->vmId, $videoId, $this->filterCustomMetaData($customMetaData) ); // also store custom meta data fields locally, if video is fetched again by function $this->getVideo($videoId) $this->getVideo($videoId)->setCustomMetadata($customMetaData); }
[ "private", "function", "storeCustomMetaData", "(", "$", "customMetaData", ",", "$", "videoId", ")", "{", "// only update custom meta data fields related to rating", "$", "this", "->", "client", "->", "setCustomMetaData", "(", "$", "this", "->", "vmId", ",", "$", "vi...
Stores the custom meta data fields with the api client. @param array $customMetaData @param string $videoId
[ "Stores", "the", "custom", "meta", "data", "fields", "with", "the", "api", "client", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Services/Ratings.php#L139-L150
train
MovingImage24/VMProApiClient
lib/Services/Ratings.php
Ratings.getVideo
private function getVideo($videoId) { if (!array_key_exists($videoId, $this->videos)) { $options = new VideoRequestParameters(); $options->setIncludeCustomMetadata(true); $this->videos[$videoId] = $this->client->getVideo($this->vmId, $videoId, $options); } return $this->videos[$videoId]; }
php
private function getVideo($videoId) { if (!array_key_exists($videoId, $this->videos)) { $options = new VideoRequestParameters(); $options->setIncludeCustomMetadata(true); $this->videos[$videoId] = $this->client->getVideo($this->vmId, $videoId, $options); } return $this->videos[$videoId]; }
[ "private", "function", "getVideo", "(", "$", "videoId", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "videoId", ",", "$", "this", "->", "videos", ")", ")", "{", "$", "options", "=", "new", "VideoRequestParameters", "(", ")", ";", "$", "optio...
Fetches and returns video from api client and stores it locally. This way api client will be requested only once for every video. @param string $videoId @return Video
[ "Fetches", "and", "returns", "video", "from", "api", "client", "and", "stores", "it", "locally", ".", "This", "way", "api", "client", "will", "be", "requested", "only", "once", "for", "every", "video", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Services/Ratings.php#L160-L169
train
MovingImage24/VMProApiClient
lib/Services/Ratings.php
Ratings.filterCustomMetaData
private function filterCustomMetaData($customMetaData) { foreach ($customMetaData as $key => $data) { if (!in_array($key, [$this->metadataFieldCount, $this->metadataFieldAverage])) { unset($customMetaData[$key]); } } return $customMetaData; }
php
private function filterCustomMetaData($customMetaData) { foreach ($customMetaData as $key => $data) { if (!in_array($key, [$this->metadataFieldCount, $this->metadataFieldAverage])) { unset($customMetaData[$key]); } } return $customMetaData; }
[ "private", "function", "filterCustomMetaData", "(", "$", "customMetaData", ")", "{", "foreach", "(", "$", "customMetaData", "as", "$", "key", "=>", "$", "data", ")", "{", "if", "(", "!", "in_array", "(", "$", "key", ",", "[", "$", "this", "->", "metada...
Returns custom meta data fields which are related to rating. @param array $customMetaData @return array
[ "Returns", "custom", "meta", "data", "fields", "which", "are", "related", "to", "rating", "." ]
e242a88a93a7a915898c888a575502c21434e35b
https://github.com/MovingImage24/VMProApiClient/blob/e242a88a93a7a915898c888a575502c21434e35b/lib/Services/Ratings.php#L178-L187
train
BlackBonjour/stdlib
src/Util/Sequence.php
Sequence.push
public function push($value, int $repeat = null): self { if ($repeat !== null && $repeat <= 0) { throw new InvalidArgumentException(sprintf(static::MSG_NEGATIVE_ARGUMENT_NOT_ALLOWED, 2, 1)); } for ($i = 0; $i < ($repeat ?? 1); $i++) { $this->values[] = $value; } return $this; }
php
public function push($value, int $repeat = null): self { if ($repeat !== null && $repeat <= 0) { throw new InvalidArgumentException(sprintf(static::MSG_NEGATIVE_ARGUMENT_NOT_ALLOWED, 2, 1)); } for ($i = 0; $i < ($repeat ?? 1); $i++) { $this->values[] = $value; } return $this; }
[ "public", "function", "push", "(", "$", "value", ",", "int", "$", "repeat", "=", "null", ")", ":", "self", "{", "if", "(", "$", "repeat", "!==", "null", "&&", "$", "repeat", "<=", "0", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprin...
Pushes specified value into array @param mixed $value @param int|null $repeat @return static @throws InvalidArgumentException
[ "Pushes", "specified", "value", "into", "array" ]
0ec59db9d8b77c2b3877c8d8a3d6ecbdcf75f814
https://github.com/BlackBonjour/stdlib/blob/0ec59db9d8b77c2b3877c8d8a3d6ecbdcf75f814/src/Util/Sequence.php#L193-L204
train
BlackBonjour/stdlib
src/Util/Sequence.php
Sequence.pushAll
public function pushAll(array $values): self { foreach ($values as $value) { $this->push($value); } return $this; }
php
public function pushAll(array $values): self { foreach ($values as $value) { $this->push($value); } return $this; }
[ "public", "function", "pushAll", "(", "array", "$", "values", ")", ":", "self", "{", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "$", "this", "->", "push", "(", "$", "value", ")", ";", "}", "return", "$", "this", ";", "}" ]
Pushes multiple values to array @param array $values @return static @throws InvalidArgumentException
[ "Pushes", "multiple", "values", "to", "array" ]
0ec59db9d8b77c2b3877c8d8a3d6ecbdcf75f814
https://github.com/BlackBonjour/stdlib/blob/0ec59db9d8b77c2b3877c8d8a3d6ecbdcf75f814/src/Util/Sequence.php#L213-L220
train
shardimage/shardimage-php
src/services/AccessTokenService.php
AccessTokenService.update
public function update($params, $optParams = []) { if (!$params instanceof AccessToken) { throw new InvalidParamException(AccessToken::class . ' is required!'); } $class = get_class($params); return $this->sendRequest([], [ 'restAction' => 'update', 'restId' => $params->id, 'postParams' => $params->toArray(), 'getParams' => $optParams, ], function ($response) use ($class) { return isset($response->data) ? new $class($response->data) : $response; }); }
php
public function update($params, $optParams = []) { if (!$params instanceof AccessToken) { throw new InvalidParamException(AccessToken::class . ' is required!'); } $class = get_class($params); return $this->sendRequest([], [ 'restAction' => 'update', 'restId' => $params->id, 'postParams' => $params->toArray(), 'getParams' => $optParams, ], function ($response) use ($class) { return isset($response->data) ? new $class($response->data) : $response; }); }
[ "public", "function", "update", "(", "$", "params", ",", "$", "optParams", "=", "[", "]", ")", "{", "if", "(", "!", "$", "params", "instanceof", "AccessToken", ")", "{", "throw", "new", "InvalidParamException", "(", "AccessToken", "::", "class", ".", "' ...
Updates an access token. @param AccessToken $params Access Token object @param array $optParams Optional API parameters @return AccessToken|Response @throws InvalidParamException
[ "Updates", "an", "access", "token", "." ]
1988e3996dfdf7e17d1bd44d5d807f9884ac64bd
https://github.com/shardimage/shardimage-php/blob/1988e3996dfdf7e17d1bd44d5d807f9884ac64bd/src/services/AccessTokenService.php#L57-L72
train
shardimage/shardimage-php
src/services/AccessTokenService.php
AccessTokenService.view
public function view($params, $optParams = []) { if (!$params instanceof AccessToken) { throw new InvalidParamException(AccessToken::class . ' is required!'); } $class = get_class($params); return $this->sendRequest([], [ 'restAction' => 'view', 'restId' => $params->id, 'getParams' => $optParams, ], function ($response) use ($class) { return isset($response->data) ? new $class($response->data) : $response; }); }
php
public function view($params, $optParams = []) { if (!$params instanceof AccessToken) { throw new InvalidParamException(AccessToken::class . ' is required!'); } $class = get_class($params); return $this->sendRequest([], [ 'restAction' => 'view', 'restId' => $params->id, 'getParams' => $optParams, ], function ($response) use ($class) { return isset($response->data) ? new $class($response->data) : $response; }); }
[ "public", "function", "view", "(", "$", "params", ",", "$", "optParams", "=", "[", "]", ")", "{", "if", "(", "!", "$", "params", "instanceof", "AccessToken", ")", "{", "throw", "new", "InvalidParamException", "(", "AccessToken", "::", "class", ".", "' is...
Fetches an access token. @param AccessToken|string $params Access Token object or Access Token ID @param array $optParams Optional API parameters @return AccessToken|Response
[ "Fetches", "an", "access", "token", "." ]
1988e3996dfdf7e17d1bd44d5d807f9884ac64bd
https://github.com/shardimage/shardimage-php/blob/1988e3996dfdf7e17d1bd44d5d807f9884ac64bd/src/services/AccessTokenService.php#L105-L119
train
christianblos/codedocs
src/SourceCode/AnnotationParser.php
AnnotationParser.extractContent
private function extractContent($docComment, $annotationClass) { $isRecording = false; $content = ''; // remove doc comment stars at line start $docComment = preg_replace('/^[ \t]*(\*\/? ?|\/\*\*)/m', '', $docComment); $search = '(' . preg_quote($annotationClass, '/') . '|' . substr($annotationClass, strrpos($annotationClass, '\\') + 1) . ')'; $lines = preg_split('/\n|\r\n/', $docComment); foreach ($lines as $line) { if ($isRecording === false && preg_match('/^@' . $search . '(\s|\(|$)/', $line)) { $isRecording = true; } elseif ($isRecording) { if (preg_match('/^@/', $line)) { break; } $content .= $line . PHP_EOL; } } return trim($content); }
php
private function extractContent($docComment, $annotationClass) { $isRecording = false; $content = ''; // remove doc comment stars at line start $docComment = preg_replace('/^[ \t]*(\*\/? ?|\/\*\*)/m', '', $docComment); $search = '(' . preg_quote($annotationClass, '/') . '|' . substr($annotationClass, strrpos($annotationClass, '\\') + 1) . ')'; $lines = preg_split('/\n|\r\n/', $docComment); foreach ($lines as $line) { if ($isRecording === false && preg_match('/^@' . $search . '(\s|\(|$)/', $line)) { $isRecording = true; } elseif ($isRecording) { if (preg_match('/^@/', $line)) { break; } $content .= $line . PHP_EOL; } } return trim($content); }
[ "private", "function", "extractContent", "(", "$", "docComment", ",", "$", "annotationClass", ")", "{", "$", "isRecording", "=", "false", ";", "$", "content", "=", "''", ";", "// remove doc comment stars at line start", "$", "docComment", "=", "preg_replace", "(",...
Extract content below doc comment annotation @param string $docComment @param string $annotationClass @return string
[ "Extract", "content", "below", "doc", "comment", "annotation" ]
f78e0803ad96605b463f2e40b8e9bfe06c5a3aab
https://github.com/christianblos/codedocs/blob/f78e0803ad96605b463f2e40b8e9bfe06c5a3aab/src/SourceCode/AnnotationParser.php#L123-L150
train
dazzle-php/util
src/Util/Support/StringSupport.php
StringSupport.parametrize
public static function parametrize($str, $params) { $keys = array_keys($params); $vals = array_values($params); array_walk($keys, function(&$key) { $key = '%' . $key . '%'; }); return str_replace($keys, $vals, $str); }
php
public static function parametrize($str, $params) { $keys = array_keys($params); $vals = array_values($params); array_walk($keys, function(&$key) { $key = '%' . $key . '%'; }); return str_replace($keys, $vals, $str); }
[ "public", "static", "function", "parametrize", "(", "$", "str", ",", "$", "params", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "params", ")", ";", "$", "vals", "=", "array_values", "(", "$", "params", ")", ";", "array_walk", "(", "$", "keys"...
Parametrize string using array of params. @param string $str @param string[] $params @return string
[ "Parametrize", "string", "using", "array", "of", "params", "." ]
eb78617678964579b40104ad55780d4465817314
https://github.com/dazzle-php/util/blob/eb78617678964579b40104ad55780d4465817314/src/Util/Support/StringSupport.php#L14-L24
train
dazzle-php/util
src/Util/Support/StringSupport.php
StringSupport.findOne
public static function findOne($pattern, $entries) { $found = []; foreach ($entries as $entry) { if (static::match($pattern, $entry)) { $found[] = $entry; } } return $found; }
php
public static function findOne($pattern, $entries) { $found = []; foreach ($entries as $entry) { if (static::match($pattern, $entry)) { $found[] = $entry; } } return $found; }
[ "public", "static", "function", "findOne", "(", "$", "pattern", ",", "$", "entries", ")", "{", "$", "found", "=", "[", "]", ";", "foreach", "(", "$", "entries", "as", "$", "entry", ")", "{", "if", "(", "static", "::", "match", "(", "$", "pattern", ...
Filter and return entries that match specified pattern. @param string $pattern @param string[] $entries @return string[]
[ "Filter", "and", "return", "entries", "that", "match", "specified", "pattern", "." ]
eb78617678964579b40104ad55780d4465817314
https://github.com/dazzle-php/util/blob/eb78617678964579b40104ad55780d4465817314/src/Util/Support/StringSupport.php#L62-L75
train
larryli/ipv4-yii2
actions/DumpAction.php
DumpAction.run
public function run($type = 'default') { $this->stdout("dump {$type}:\n", Console::FG_GREEN); switch ($type) { case 'default': foreach ($this->ipv4->getQueries() as $name => $query) { $this->dumpDefault($query, $name); } break; case 'division': foreach ($this->ipv4->getQueries() as $name => $query) { $this->dumpDivision($query, $name); } break; case 'division_id': foreach ($this->ipv4->getQueries() as $name => $query) { if (FileQuery::is_a($query)) { $this->dumpDivisionWithId($query, $name); } } break; default: $this->stderr("Unknown type \"{$type}\".\n", Console::FG_GREY, Console::BG_RED); break; } }
php
public function run($type = 'default') { $this->stdout("dump {$type}:\n", Console::FG_GREEN); switch ($type) { case 'default': foreach ($this->ipv4->getQueries() as $name => $query) { $this->dumpDefault($query, $name); } break; case 'division': foreach ($this->ipv4->getQueries() as $name => $query) { $this->dumpDivision($query, $name); } break; case 'division_id': foreach ($this->ipv4->getQueries() as $name => $query) { if (FileQuery::is_a($query)) { $this->dumpDivisionWithId($query, $name); } } break; default: $this->stderr("Unknown type \"{$type}\".\n", Console::FG_GREY, Console::BG_RED); break; } }
[ "public", "function", "run", "(", "$", "type", "=", "'default'", ")", "{", "$", "this", "->", "stdout", "(", "\"dump {$type}:\\n\"", ",", "Console", "::", "FG_GREEN", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "'default'", ":", "foreach", ...
dump ip database @param string $type division or division_id @throws \Exception
[ "dump", "ip", "database" ]
6215f67db4b620b15e5f763407c034dc1badc4b8
https://github.com/larryli/ipv4-yii2/blob/6215f67db4b620b15e5f763407c034dc1badc4b8/actions/DumpAction.php#L28-L53
train
thinktomorrow/assetlibrary
src/Utilities/AssetFormHelper.php
AssetFormHelper.typeField
public static function typeField($type = '', $locale = null, $name = 'type'): string { $result = '<input type="hidden" value="'.$type.'" name="'; if (! $locale) { return $result.$name.'">'; } return $result.'trans['.$locale.'][files][]">'; }
php
public static function typeField($type = '', $locale = null, $name = 'type'): string { $result = '<input type="hidden" value="'.$type.'" name="'; if (! $locale) { return $result.$name.'">'; } return $result.'trans['.$locale.'][files][]">'; }
[ "public", "static", "function", "typeField", "(", "$", "type", "=", "''", ",", "$", "locale", "=", "null", ",", "$", "name", "=", "'type'", ")", ":", "string", "{", "$", "result", "=", "'<input type=\"hidden\" value=\"'", ".", "$", "type", ".", "'\" name...
Generates the hidden field that links the file to a specific type. @param string $type @param null $locale @param string $name @return string
[ "Generates", "the", "hidden", "field", "that", "links", "the", "file", "to", "a", "specific", "type", "." ]
606c14924dc03b858d88bcc47668038365f717cf
https://github.com/thinktomorrow/assetlibrary/blob/606c14924dc03b858d88bcc47668038365f717cf/src/Utilities/AssetFormHelper.php#L16-L25
train
scherersoftware/cake-cktools
src/View/Helper/MenuHelper.php
MenuHelper.setPageTitle
public function setPageTitle(array $config): void { foreach ($config as $item) { if (isset($item['active']) && $item['active']) { $this->_View->assign('title', $item['title']); break; } } }
php
public function setPageTitle(array $config): void { foreach ($config as $item) { if (isset($item['active']) && $item['active']) { $this->_View->assign('title', $item['title']); break; } } }
[ "public", "function", "setPageTitle", "(", "array", "$", "config", ")", ":", "void", "{", "foreach", "(", "$", "config", "as", "$", "item", ")", "{", "if", "(", "isset", "(", "$", "item", "[", "'active'", "]", ")", "&&", "$", "item", "[", "'active'...
Set page title automatically based on the current menu item @param array $config Menu Config @return void
[ "Set", "page", "title", "automatically", "based", "on", "the", "current", "menu", "item" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/MenuHelper.php#L125-L133
train
scherersoftware/cake-cktools
src/View/Helper/MenuHelper.php
MenuHelper._hasAllowedChildren
protected function _hasAllowedChildren(array $children): bool { foreach ($children as $child) { if ($this->Auth->urlAllowed($child['url'])) { return true; } } return false; }
php
protected function _hasAllowedChildren(array $children): bool { foreach ($children as $child) { if ($this->Auth->urlAllowed($child['url'])) { return true; } } return false; }
[ "protected", "function", "_hasAllowedChildren", "(", "array", "$", "children", ")", ":", "bool", "{", "foreach", "(", "$", "children", "as", "$", "child", ")", "{", "if", "(", "$", "this", "->", "Auth", "->", "urlAllowed", "(", "$", "child", "[", "'url...
Checks if the given array of item children contains at least one URL that is allowed to the current user. @param array $children item children @return bool
[ "Checks", "if", "the", "given", "array", "of", "item", "children", "contains", "at", "least", "one", "URL", "that", "is", "allowed", "to", "the", "current", "user", "." ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/MenuHelper.php#L242-L251
train
scherersoftware/cake-cktools
src/View/Helper/MenuHelper.php
MenuHelper._isItemActive
protected function _isItemActive(array $item): bool { if (empty($item['url'])) { return false; } $current = $this->_currentUrl; if (!empty($item['url']['plugin']) && $item['url']['plugin'] != $current['plugin']) { return false; } if ($item['url']['controller'] == $current['controller'] && $item['url']['action'] == $current['action']) { $this->_controllerActive = $current['controller']; $this->_actionActive = $item['url']['action']; return true; } if (!empty($this->_actionActive) && $item['url']['controller'] == $current['controller']) { $this->_controllerActive = $current['controller']; return true; } return false; }
php
protected function _isItemActive(array $item): bool { if (empty($item['url'])) { return false; } $current = $this->_currentUrl; if (!empty($item['url']['plugin']) && $item['url']['plugin'] != $current['plugin']) { return false; } if ($item['url']['controller'] == $current['controller'] && $item['url']['action'] == $current['action']) { $this->_controllerActive = $current['controller']; $this->_actionActive = $item['url']['action']; return true; } if (!empty($this->_actionActive) && $item['url']['controller'] == $current['controller']) { $this->_controllerActive = $current['controller']; return true; } return false; }
[ "protected", "function", "_isItemActive", "(", "array", "$", "item", ")", ":", "bool", "{", "if", "(", "empty", "(", "$", "item", "[", "'url'", "]", ")", ")", "{", "return", "false", ";", "}", "$", "current", "=", "$", "this", "->", "_currentUrl", ...
Checks if the given item URL should be marked active in the menu @param array $item Item to check @return bool
[ "Checks", "if", "the", "given", "item", "URL", "should", "be", "marked", "active", "in", "the", "menu" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/View/Helper/MenuHelper.php#L259-L281
train
thelia-modules/FeatureType
Model/Base/FeatureTypeAvMeta.php
FeatureTypeAvMeta.setFeatureAv
public function setFeatureAv(ChildFeatureAv $v = null) { if ($v === null) { $this->setFeatureAvId(NULL); } else { $this->setFeatureAvId($v->getId()); } $this->aFeatureAv = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the ChildFeatureAv object, it will not be re-added. if ($v !== null) { $v->addFeatureTypeAvMeta($this); } return $this; }
php
public function setFeatureAv(ChildFeatureAv $v = null) { if ($v === null) { $this->setFeatureAvId(NULL); } else { $this->setFeatureAvId($v->getId()); } $this->aFeatureAv = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the ChildFeatureAv object, it will not be re-added. if ($v !== null) { $v->addFeatureTypeAvMeta($this); } return $this; }
[ "public", "function", "setFeatureAv", "(", "ChildFeatureAv", "$", "v", "=", "null", ")", "{", "if", "(", "$", "v", "===", "null", ")", "{", "$", "this", "->", "setFeatureAvId", "(", "NULL", ")", ";", "}", "else", "{", "$", "this", "->", "setFeatureAv...
Declares an association between this object and a ChildFeatureAv object. @param ChildFeatureAv $v @return \FeatureType\Model\FeatureTypeAvMeta The current object (for fluent API support) @throws PropelException
[ "Declares", "an", "association", "between", "this", "object", "and", "a", "ChildFeatureAv", "object", "." ]
fc73eaaf53583758a316bb7e4af69ea50ec89997
https://github.com/thelia-modules/FeatureType/blob/fc73eaaf53583758a316bb7e4af69ea50ec89997/Model/Base/FeatureTypeAvMeta.php#L1358-L1376
train
thelia-modules/FeatureType
Model/Base/FeatureTypeAvMeta.php
FeatureTypeAvMeta.getFeatureAv
public function getFeatureAv(ConnectionInterface $con = null) { if ($this->aFeatureAv === null && ($this->feature_av_id !== null)) { $this->aFeatureAv = FeatureAvQuery::create()->findPk($this->feature_av_id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aFeatureAv->addFeatureTypeAvMetas($this); */ } return $this->aFeatureAv; }
php
public function getFeatureAv(ConnectionInterface $con = null) { if ($this->aFeatureAv === null && ($this->feature_av_id !== null)) { $this->aFeatureAv = FeatureAvQuery::create()->findPk($this->feature_av_id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aFeatureAv->addFeatureTypeAvMetas($this); */ } return $this->aFeatureAv; }
[ "public", "function", "getFeatureAv", "(", "ConnectionInterface", "$", "con", "=", "null", ")", "{", "if", "(", "$", "this", "->", "aFeatureAv", "===", "null", "&&", "(", "$", "this", "->", "feature_av_id", "!==", "null", ")", ")", "{", "$", "this", "-...
Get the associated ChildFeatureAv object @param ConnectionInterface $con Optional Connection object. @return ChildFeatureAv The associated ChildFeatureAv object. @throws PropelException
[ "Get", "the", "associated", "ChildFeatureAv", "object" ]
fc73eaaf53583758a316bb7e4af69ea50ec89997
https://github.com/thelia-modules/FeatureType/blob/fc73eaaf53583758a316bb7e4af69ea50ec89997/Model/Base/FeatureTypeAvMeta.php#L1386-L1400
train
thelia-modules/FeatureType
Model/Base/FeatureTypeAvMeta.php
FeatureTypeAvMeta.setFeatureFeatureType
public function setFeatureFeatureType(ChildFeatureFeatureType $v = null) { if ($v === null) { $this->setFeatureFeatureTypeId(NULL); } else { $this->setFeatureFeatureTypeId($v->getId()); } $this->aFeatureFeatureType = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the ChildFeatureFeatureType object, it will not be re-added. if ($v !== null) { $v->addFeatureTypeAvMeta($this); } return $this; }
php
public function setFeatureFeatureType(ChildFeatureFeatureType $v = null) { if ($v === null) { $this->setFeatureFeatureTypeId(NULL); } else { $this->setFeatureFeatureTypeId($v->getId()); } $this->aFeatureFeatureType = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the ChildFeatureFeatureType object, it will not be re-added. if ($v !== null) { $v->addFeatureTypeAvMeta($this); } return $this; }
[ "public", "function", "setFeatureFeatureType", "(", "ChildFeatureFeatureType", "$", "v", "=", "null", ")", "{", "if", "(", "$", "v", "===", "null", ")", "{", "$", "this", "->", "setFeatureFeatureTypeId", "(", "NULL", ")", ";", "}", "else", "{", "$", "thi...
Declares an association between this object and a ChildFeatureFeatureType object. @param ChildFeatureFeatureType $v @return \FeatureType\Model\FeatureTypeAvMeta The current object (for fluent API support) @throws PropelException
[ "Declares", "an", "association", "between", "this", "object", "and", "a", "ChildFeatureFeatureType", "object", "." ]
fc73eaaf53583758a316bb7e4af69ea50ec89997
https://github.com/thelia-modules/FeatureType/blob/fc73eaaf53583758a316bb7e4af69ea50ec89997/Model/Base/FeatureTypeAvMeta.php#L1409-L1427
train
thelia-modules/FeatureType
Model/Base/FeatureTypeAvMeta.php
FeatureTypeAvMeta.getFeatureFeatureType
public function getFeatureFeatureType(ConnectionInterface $con = null) { if ($this->aFeatureFeatureType === null && ($this->feature_feature_type_id !== null)) { $this->aFeatureFeatureType = ChildFeatureFeatureTypeQuery::create()->findPk($this->feature_feature_type_id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aFeatureFeatureType->addFeatureTypeAvMetas($this); */ } return $this->aFeatureFeatureType; }
php
public function getFeatureFeatureType(ConnectionInterface $con = null) { if ($this->aFeatureFeatureType === null && ($this->feature_feature_type_id !== null)) { $this->aFeatureFeatureType = ChildFeatureFeatureTypeQuery::create()->findPk($this->feature_feature_type_id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aFeatureFeatureType->addFeatureTypeAvMetas($this); */ } return $this->aFeatureFeatureType; }
[ "public", "function", "getFeatureFeatureType", "(", "ConnectionInterface", "$", "con", "=", "null", ")", "{", "if", "(", "$", "this", "->", "aFeatureFeatureType", "===", "null", "&&", "(", "$", "this", "->", "feature_feature_type_id", "!==", "null", ")", ")", ...
Get the associated ChildFeatureFeatureType object @param ConnectionInterface $con Optional Connection object. @return ChildFeatureFeatureType The associated ChildFeatureFeatureType object. @throws PropelException
[ "Get", "the", "associated", "ChildFeatureFeatureType", "object" ]
fc73eaaf53583758a316bb7e4af69ea50ec89997
https://github.com/thelia-modules/FeatureType/blob/fc73eaaf53583758a316bb7e4af69ea50ec89997/Model/Base/FeatureTypeAvMeta.php#L1437-L1451
train
postalservice14/php-actuator
src/Health/HealthBuilder.php
HealthBuilder.status
public function status($status) { if (!($status instanceof Status)) { $status = new Status($status); } $this->status = $status; return $this; }
php
public function status($status) { if (!($status instanceof Status)) { $status = new Status($status); } $this->status = $status; return $this; }
[ "public", "function", "status", "(", "$", "status", ")", "{", "if", "(", "!", "(", "$", "status", "instanceof", "Status", ")", ")", "{", "$", "status", "=", "new", "Status", "(", "$", "status", ")", ";", "}", "$", "this", "->", "status", "=", "$"...
Set status to given Status instance or status code. @param Status|string $status @return $this
[ "Set", "status", "to", "given", "Status", "instance", "or", "status", "code", "." ]
08e0ab32fb0cdc24356aa8cc86245fab294ec841
https://github.com/postalservice14/php-actuator/blob/08e0ab32fb0cdc24356aa8cc86245fab294ec841/src/Health/HealthBuilder.php#L91-L100
train
postalservice14/php-actuator
src/Health/HealthBuilder.php
HealthBuilder.withDetail
public function withDetail($key, $message) { assert(!is_null($key), 'Key must not be null'); assert(!is_null($message), 'Message must not be null'); $this->details[strval($key)] = $message; return $this; }
php
public function withDetail($key, $message) { assert(!is_null($key), 'Key must not be null'); assert(!is_null($message), 'Message must not be null'); $this->details[strval($key)] = $message; return $this; }
[ "public", "function", "withDetail", "(", "$", "key", ",", "$", "message", ")", "{", "assert", "(", "!", "is_null", "(", "$", "key", ")", ",", "'Key must not be null'", ")", ";", "assert", "(", "!", "is_null", "(", "$", "message", ")", ",", "'Message mu...
Record detail using key and message. @param string $key the detail key @param mixed $message the detail message @return $this
[ "Record", "detail", "using", "key", "and", "message", "." ]
08e0ab32fb0cdc24356aa8cc86245fab294ec841
https://github.com/postalservice14/php-actuator/blob/08e0ab32fb0cdc24356aa8cc86245fab294ec841/src/Health/HealthBuilder.php#L124-L131
train
digbang/security
src/Users/DefaultDoctrineUserRepository.php
DefaultDoctrineUserRepository.createUser
protected function createUser(array $credentials) { $entity = static::ENTITY_CLASSNAME; if (count(array_only($credentials, ['email', 'password', 'username'])) < 3) { throw new \InvalidArgumentException("Missing arguments."); } /** @var User $user */ $user = new $entity( $credentials['email'], $credentials['password'], $credentials['username'] ); $rest = array_except($credentials, ['email', 'username', 'password']); if (! empty($rest)) { $user->update($rest); } return $user; }
php
protected function createUser(array $credentials) { $entity = static::ENTITY_CLASSNAME; if (count(array_only($credentials, ['email', 'password', 'username'])) < 3) { throw new \InvalidArgumentException("Missing arguments."); } /** @var User $user */ $user = new $entity( $credentials['email'], $credentials['password'], $credentials['username'] ); $rest = array_except($credentials, ['email', 'username', 'password']); if (! empty($rest)) { $user->update($rest); } return $user; }
[ "protected", "function", "createUser", "(", "array", "$", "credentials", ")", "{", "$", "entity", "=", "static", "::", "ENTITY_CLASSNAME", ";", "if", "(", "count", "(", "array_only", "(", "$", "credentials", ",", "[", "'email'", ",", "'password'", ",", "'u...
Create a new user based on the given credentials. @param array $credentials @return User
[ "Create", "a", "new", "user", "based", "on", "the", "given", "credentials", "." ]
ee925c5a144a1553f5a72ded6f5a66c01a86ab21
https://github.com/digbang/security/blob/ee925c5a144a1553f5a72ded6f5a66c01a86ab21/src/Users/DefaultDoctrineUserRepository.php#L26-L49
train
scherersoftware/cake-cktools
src/Utility/SortableControllerTrait.php
SortableControllerTrait.sort
public function sort(): ServiceResponse { $this->request->allowMethod('post'); if (!empty($this->sortModelName) && !empty($this->request->getData('foreignKey'))) { $table = TableRegistry::getTableLocator()->get($this->sortModelName); $entity = $table->get($this->request->getData('foreignKey')); $entity->sort = $this->request->getData('sort'); if ($table->save($entity)) { return new ServiceResponse(ApiReturnCode::SUCCESS, [ $entity->id, $this->request->getData('sort'), ]); } return new ServiceResponse(ApiReturnCode::INTERNAL_ERROR, []); } throw new NotFoundException(); }
php
public function sort(): ServiceResponse { $this->request->allowMethod('post'); if (!empty($this->sortModelName) && !empty($this->request->getData('foreignKey'))) { $table = TableRegistry::getTableLocator()->get($this->sortModelName); $entity = $table->get($this->request->getData('foreignKey')); $entity->sort = $this->request->getData('sort'); if ($table->save($entity)) { return new ServiceResponse(ApiReturnCode::SUCCESS, [ $entity->id, $this->request->getData('sort'), ]); } return new ServiceResponse(ApiReturnCode::INTERNAL_ERROR, []); } throw new NotFoundException(); }
[ "public", "function", "sort", "(", ")", ":", "ServiceResponse", "{", "$", "this", "->", "request", "->", "allowMethod", "(", "'post'", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "sortModelName", ")", "&&", "!", "empty", "(", "$", "thi...
endpoint for sorting ajax calls @return \FrontendBridge\Lib\ServiceResponse @throws \Cake\Network\Exception\NotFoundException if either not a post request or missing/wrong params
[ "endpoint", "for", "sorting", "ajax", "calls" ]
efba42cf4e1804df8f1faa83ef75927bee6c206b
https://github.com/scherersoftware/cake-cktools/blob/efba42cf4e1804df8f1faa83ef75927bee6c206b/src/Utility/SortableControllerTrait.php#L27-L44
train
phug-php/lexer
src/Phug/Lexer/Partial/IndentStyleTrait.php
IndentStyleTrait.setIndentStyle
public function setIndentStyle($indentStyle) { if (!in_array($indentStyle, [null, Lexer::INDENT_TAB, Lexer::INDENT_SPACE])) { throw new \InvalidArgumentException( 'indentStyle needs to be null or one of the INDENT_* constants of the lexer' ); } $this->indentStyle = $indentStyle; return $this; }
php
public function setIndentStyle($indentStyle) { if (!in_array($indentStyle, [null, Lexer::INDENT_TAB, Lexer::INDENT_SPACE])) { throw new \InvalidArgumentException( 'indentStyle needs to be null or one of the INDENT_* constants of the lexer' ); } $this->indentStyle = $indentStyle; return $this; }
[ "public", "function", "setIndentStyle", "(", "$", "indentStyle", ")", "{", "if", "(", "!", "in_array", "(", "$", "indentStyle", ",", "[", "null", ",", "Lexer", "::", "INDENT_TAB", ",", "Lexer", "::", "INDENT_SPACE", "]", ")", ")", "{", "throw", "new", ...
Sets the current indentation style to a new one. The value needs to be one of the `Lexer::INDENT_*` constants, but you can also just pass either a single space or a single tab for the respective style. @param $indentStyle @return $this
[ "Sets", "the", "current", "indentation", "style", "to", "a", "new", "one", "." ]
63d8876899168b136cf27304c2d888f0f7fe3414
https://github.com/phug-php/lexer/blob/63d8876899168b136cf27304c2d888f0f7fe3414/src/Phug/Lexer/Partial/IndentStyleTrait.php#L43-L54
train
phug-php/lexer
src/Phug/Lexer/Partial/IndentStyleTrait.php
IndentStyleTrait.setIndentWidth
public function setIndentWidth($indentWidth) { if (!is_null($indentWidth) && (!is_int($indentWidth) || $indentWidth < 1) ) { throw new \InvalidArgumentException( 'indentWidth needs to be null or an integer above 0' ); } $this->indentWidth = $indentWidth; return $this; }
php
public function setIndentWidth($indentWidth) { if (!is_null($indentWidth) && (!is_int($indentWidth) || $indentWidth < 1) ) { throw new \InvalidArgumentException( 'indentWidth needs to be null or an integer above 0' ); } $this->indentWidth = $indentWidth; return $this; }
[ "public", "function", "setIndentWidth", "(", "$", "indentWidth", ")", "{", "if", "(", "!", "is_null", "(", "$", "indentWidth", ")", "&&", "(", "!", "is_int", "(", "$", "indentWidth", ")", "||", "$", "indentWidth", "<", "1", ")", ")", "{", "throw", "n...
Sets the currently used indentation width. The value of this specifies if e.g. 2 spaces make up one indentation level or 4. @param $indentWidth @return $this
[ "Sets", "the", "currently", "used", "indentation", "width", "." ]
63d8876899168b136cf27304c2d888f0f7fe3414
https://github.com/phug-php/lexer/blob/63d8876899168b136cf27304c2d888f0f7fe3414/src/Phug/Lexer/Partial/IndentStyleTrait.php#L75-L88
train
kassko/data-mapper
src/ObjectManager.php
ObjectManager.getHydratorFor
public function getHydratorFor($objectClass) { if (! isset($this->hydratorInstances[$objectClass])) { $this->hydratorInstances[$objectClass] = $this->createHydratorFor($objectClass); } return $this->hydratorInstances[$objectClass]; }
php
public function getHydratorFor($objectClass) { if (! isset($this->hydratorInstances[$objectClass])) { $this->hydratorInstances[$objectClass] = $this->createHydratorFor($objectClass); } return $this->hydratorInstances[$objectClass]; }
[ "public", "function", "getHydratorFor", "(", "$", "objectClass", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "hydratorInstances", "[", "$", "objectClass", "]", ")", ")", "{", "$", "this", "->", "hydratorInstances", "[", "$", "objectClass", ...
Factory method to get an hydrator instance or create an hydrator if no instance available. @param $objectClass Object class to hydrate @return AbstractHydrator
[ "Factory", "method", "to", "get", "an", "hydrator", "instance", "or", "create", "an", "hydrator", "if", "no", "instance", "available", "." ]
653b3d735977d95f6eadb3334ab8787db1dca275
https://github.com/kassko/data-mapper/blob/653b3d735977d95f6eadb3334ab8787db1dca275/src/ObjectManager.php#L227-L235
train