id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
35,600
hail-framework/framework
src/Util/Yaml/Parser.php
Parser.trimTag
private function trimTag(string $value): string { if ('!' === $value[0]) { return \ltrim(\substr($value, 1, \strcspn($value, " \r\n", 1)), ' '); } return $value; }
php
private function trimTag(string $value): string { if ('!' === $value[0]) { return \ltrim(\substr($value, 1, \strcspn($value, " \r\n", 1)), ' '); } return $value; }
[ "private", "function", "trimTag", "(", "string", "$", "value", ")", ":", "string", "{", "if", "(", "'!'", "===", "$", "value", "[", "0", "]", ")", "{", "return", "\\", "ltrim", "(", "\\", "substr", "(", "$", "value", ",", "1", ",", "\\", "strcspn", "(", "$", "value", ",", "\" \\r\\n\"", ",", "1", ")", ")", ",", "' '", ")", ";", "}", "return", "$", "value", ";", "}" ]
Trim the tag on top of the value. Prevent values such as `!foo {quz: bar}` to be considered as a mapping block.
[ "Trim", "the", "tag", "on", "top", "of", "the", "value", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Yaml/Parser.php#L1073-L1080
35,601
hail-framework/framework
src/Filesystem/Util.php
Util.emulateDirectories
public static function emulateDirectories(array $listing) { $directories = []; $listedDirectories = []; foreach ($listing as $object) { [$directories, $listedDirectories] = static::emulateObjectDirectories($object, $directories, $listedDirectories); } $directories = \array_diff( \array_unique($directories), \array_unique($listedDirectories) ); foreach ($directories as $directory) { $listing[] = static::pathinfo($directory) + ['type' => 'dir']; } return $listing; }
php
public static function emulateDirectories(array $listing) { $directories = []; $listedDirectories = []; foreach ($listing as $object) { [$directories, $listedDirectories] = static::emulateObjectDirectories($object, $directories, $listedDirectories); } $directories = \array_diff( \array_unique($directories), \array_unique($listedDirectories) ); foreach ($directories as $directory) { $listing[] = static::pathinfo($directory) + ['type' => 'dir']; } return $listing; }
[ "public", "static", "function", "emulateDirectories", "(", "array", "$", "listing", ")", "{", "$", "directories", "=", "[", "]", ";", "$", "listedDirectories", "=", "[", "]", ";", "foreach", "(", "$", "listing", "as", "$", "object", ")", "{", "[", "$", "directories", ",", "$", "listedDirectories", "]", "=", "static", "::", "emulateObjectDirectories", "(", "$", "object", ",", "$", "directories", ",", "$", "listedDirectories", ")", ";", "}", "$", "directories", "=", "\\", "array_diff", "(", "\\", "array_unique", "(", "$", "directories", ")", ",", "\\", "array_unique", "(", "$", "listedDirectories", ")", ")", ";", "foreach", "(", "$", "directories", "as", "$", "directory", ")", "{", "$", "listing", "[", "]", "=", "static", "::", "pathinfo", "(", "$", "directory", ")", "+", "[", "'type'", "=>", "'dir'", "]", ";", "}", "return", "$", "listing", ";", "}" ]
Emulate directories. @param array $listing @return array listing with emulated directories
[ "Emulate", "directories", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Util.php#L190-L209
35,602
hail-framework/framework
src/Filesystem/Util.php
Util.emulateObjectDirectories
protected static function emulateObjectDirectories(array $object, array $directories, array $listedDirectories) { if ($object['type'] === 'dir') { $listedDirectories[] = $object['path']; } if (empty($object['dirname'])) { return [$directories, $listedDirectories]; } $parent = $object['dirname']; while (!empty($parent) && !\in_array($parent, $directories, true)) { $directories[] = $parent; $parent = static::dirname($parent); } if (isset($object['type']) && $object['type'] === 'dir') { $listedDirectories[] = $object['path']; return [$directories, $listedDirectories]; } return [$directories, $listedDirectories]; }
php
protected static function emulateObjectDirectories(array $object, array $directories, array $listedDirectories) { if ($object['type'] === 'dir') { $listedDirectories[] = $object['path']; } if (empty($object['dirname'])) { return [$directories, $listedDirectories]; } $parent = $object['dirname']; while (!empty($parent) && !\in_array($parent, $directories, true)) { $directories[] = $parent; $parent = static::dirname($parent); } if (isset($object['type']) && $object['type'] === 'dir') { $listedDirectories[] = $object['path']; return [$directories, $listedDirectories]; } return [$directories, $listedDirectories]; }
[ "protected", "static", "function", "emulateObjectDirectories", "(", "array", "$", "object", ",", "array", "$", "directories", ",", "array", "$", "listedDirectories", ")", "{", "if", "(", "$", "object", "[", "'type'", "]", "===", "'dir'", ")", "{", "$", "listedDirectories", "[", "]", "=", "$", "object", "[", "'path'", "]", ";", "}", "if", "(", "empty", "(", "$", "object", "[", "'dirname'", "]", ")", ")", "{", "return", "[", "$", "directories", ",", "$", "listedDirectories", "]", ";", "}", "$", "parent", "=", "$", "object", "[", "'dirname'", "]", ";", "while", "(", "!", "empty", "(", "$", "parent", ")", "&&", "!", "\\", "in_array", "(", "$", "parent", ",", "$", "directories", ",", "true", ")", ")", "{", "$", "directories", "[", "]", "=", "$", "parent", ";", "$", "parent", "=", "static", "::", "dirname", "(", "$", "parent", ")", ";", "}", "if", "(", "isset", "(", "$", "object", "[", "'type'", "]", ")", "&&", "$", "object", "[", "'type'", "]", "===", "'dir'", ")", "{", "$", "listedDirectories", "[", "]", "=", "$", "object", "[", "'path'", "]", ";", "return", "[", "$", "directories", ",", "$", "listedDirectories", "]", ";", "}", "return", "[", "$", "directories", ",", "$", "listedDirectories", "]", ";", "}" ]
Emulate the directories of a single object. @param array $object @param array $directories @param array $listedDirectories @return array
[ "Emulate", "the", "directories", "of", "a", "single", "object", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Util.php#L289-L313
35,603
netgen-layouts/content-browser-sylius
lib/Repository/ProductRepository.php
ProductRepository.createQueryBuilderWithLocaleCode
private function createQueryBuilderWithLocaleCode(string $localeCode): QueryBuilder { $queryBuilder = $this->createQueryBuilder('o'); $queryBuilder ->addSelect('translation') ->leftJoin('o.translations', 'translation') ->andWhere('translation.locale = :localeCode') ->setParameter('localeCode', $localeCode) ; return $queryBuilder; }
php
private function createQueryBuilderWithLocaleCode(string $localeCode): QueryBuilder { $queryBuilder = $this->createQueryBuilder('o'); $queryBuilder ->addSelect('translation') ->leftJoin('o.translations', 'translation') ->andWhere('translation.locale = :localeCode') ->setParameter('localeCode', $localeCode) ; return $queryBuilder; }
[ "private", "function", "createQueryBuilderWithLocaleCode", "(", "string", "$", "localeCode", ")", ":", "QueryBuilder", "{", "$", "queryBuilder", "=", "$", "this", "->", "createQueryBuilder", "(", "'o'", ")", ";", "$", "queryBuilder", "->", "addSelect", "(", "'translation'", ")", "->", "leftJoin", "(", "'o.translations'", ",", "'translation'", ")", "->", "andWhere", "(", "'translation.locale = :localeCode'", ")", "->", "setParameter", "(", "'localeCode'", ",", "$", "localeCode", ")", ";", "return", "$", "queryBuilder", ";", "}" ]
Creates a query builder to filter products by locale.
[ "Creates", "a", "query", "builder", "to", "filter", "products", "by", "locale", "." ]
feb3ab56b584f6fbf4b8b6557ba6398513b116e5
https://github.com/netgen-layouts/content-browser-sylius/blob/feb3ab56b584f6fbf4b8b6557ba6398513b116e5/lib/Repository/ProductRepository.php#L57-L68
35,604
2amigos/yii2-translateable-behavior
TranslateableBehavior.php
TranslateableBehavior.getAttributeTranslation
private function getAttributeTranslation($attribute, $language) { $seen = []; do { $model = $this->getTranslation($language); $modelLanguage = $language; $fallbackLanguage = $this->getFallbackLanguage($language); $seen[$language] = true; if (isset($seen[$fallbackLanguage])) { // break infinite loop in fallback path return [$model->$attribute, $modelLanguage]; } $language = $fallbackLanguage; } while($model->$attribute === null); return [$model->$attribute, $modelLanguage]; }
php
private function getAttributeTranslation($attribute, $language) { $seen = []; do { $model = $this->getTranslation($language); $modelLanguage = $language; $fallbackLanguage = $this->getFallbackLanguage($language); $seen[$language] = true; if (isset($seen[$fallbackLanguage])) { // break infinite loop in fallback path return [$model->$attribute, $modelLanguage]; } $language = $fallbackLanguage; } while($model->$attribute === null); return [$model->$attribute, $modelLanguage]; }
[ "private", "function", "getAttributeTranslation", "(", "$", "attribute", ",", "$", "language", ")", "{", "$", "seen", "=", "[", "]", ";", "do", "{", "$", "model", "=", "$", "this", "->", "getTranslation", "(", "$", "language", ")", ";", "$", "modelLanguage", "=", "$", "language", ";", "$", "fallbackLanguage", "=", "$", "this", "->", "getFallbackLanguage", "(", "$", "language", ")", ";", "$", "seen", "[", "$", "language", "]", "=", "true", ";", "if", "(", "isset", "(", "$", "seen", "[", "$", "fallbackLanguage", "]", ")", ")", "{", "// break infinite loop in fallback path", "return", "[", "$", "model", "->", "$", "attribute", ",", "$", "modelLanguage", "]", ";", "}", "$", "language", "=", "$", "fallbackLanguage", ";", "}", "while", "(", "$", "model", "->", "$", "attribute", "===", "null", ")", ";", "return", "[", "$", "model", "->", "$", "attribute", ",", "$", "modelLanguage", "]", ";", "}" ]
Retrieve translation for an attribute. @param string $attribute the attribute name. @param string $language the desired translation language. @return array first element is the translation, second element is the language. Language may differ from `$language` when a fallback translation has been used.
[ "Retrieve", "translation", "for", "an", "attribute", "." ]
d50c714d0d63c085a926991ed36c50ed460b8184
https://github.com/2amigos/yii2-translateable-behavior/blob/d50c714d0d63c085a926991ed36c50ed460b8184/TranslateableBehavior.php#L157-L172
35,605
2amigos/yii2-translateable-behavior
TranslateableBehavior.php
TranslateableBehavior.getFallbackLanguage
public function getFallbackLanguage($forLanguage = null) { if ($this->_fallbackLanguage === null) { $this->_fallbackLanguage = Yii::$app->sourceLanguage; } if ($forLanguage === null) { return $this->_fallbackLanguage; } if ($this->_fallbackLanguage === false) { return $forLanguage; } if (is_array($this->_fallbackLanguage)) { if (isset($this->_fallbackLanguage[$forLanguage])) { return $this->_fallbackLanguage[$forLanguage]; } // check fallback de-DE -> de $fallbackLanguage = substr($forLanguage, 0, 2); if ($forLanguage !== $fallbackLanguage) { return $fallbackLanguage; } // when no fallback is available, use the first defined fallback return reset($this->_fallbackLanguage); } // check fallback de-DE -> de $fallbackLanguage = substr($forLanguage, 0, 2); if ($forLanguage !== $fallbackLanguage) { return $fallbackLanguage; } return $this->_fallbackLanguage; }
php
public function getFallbackLanguage($forLanguage = null) { if ($this->_fallbackLanguage === null) { $this->_fallbackLanguage = Yii::$app->sourceLanguage; } if ($forLanguage === null) { return $this->_fallbackLanguage; } if ($this->_fallbackLanguage === false) { return $forLanguage; } if (is_array($this->_fallbackLanguage)) { if (isset($this->_fallbackLanguage[$forLanguage])) { return $this->_fallbackLanguage[$forLanguage]; } // check fallback de-DE -> de $fallbackLanguage = substr($forLanguage, 0, 2); if ($forLanguage !== $fallbackLanguage) { return $fallbackLanguage; } // when no fallback is available, use the first defined fallback return reset($this->_fallbackLanguage); } // check fallback de-DE -> de $fallbackLanguage = substr($forLanguage, 0, 2); if ($forLanguage !== $fallbackLanguage) { return $fallbackLanguage; } return $this->_fallbackLanguage; }
[ "public", "function", "getFallbackLanguage", "(", "$", "forLanguage", "=", "null", ")", "{", "if", "(", "$", "this", "->", "_fallbackLanguage", "===", "null", ")", "{", "$", "this", "->", "_fallbackLanguage", "=", "Yii", "::", "$", "app", "->", "sourceLanguage", ";", "}", "if", "(", "$", "forLanguage", "===", "null", ")", "{", "return", "$", "this", "->", "_fallbackLanguage", ";", "}", "if", "(", "$", "this", "->", "_fallbackLanguage", "===", "false", ")", "{", "return", "$", "forLanguage", ";", "}", "if", "(", "is_array", "(", "$", "this", "->", "_fallbackLanguage", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_fallbackLanguage", "[", "$", "forLanguage", "]", ")", ")", "{", "return", "$", "this", "->", "_fallbackLanguage", "[", "$", "forLanguage", "]", ";", "}", "// check fallback de-DE -> de", "$", "fallbackLanguage", "=", "substr", "(", "$", "forLanguage", ",", "0", ",", "2", ")", ";", "if", "(", "$", "forLanguage", "!==", "$", "fallbackLanguage", ")", "{", "return", "$", "fallbackLanguage", ";", "}", "// when no fallback is available, use the first defined fallback", "return", "reset", "(", "$", "this", "->", "_fallbackLanguage", ")", ";", "}", "// check fallback de-DE -> de", "$", "fallbackLanguage", "=", "substr", "(", "$", "forLanguage", ",", "0", ",", "2", ")", ";", "if", "(", "$", "forLanguage", "!==", "$", "fallbackLanguage", ")", "{", "return", "$", "fallbackLanguage", ";", "}", "return", "$", "this", "->", "_fallbackLanguage", ";", "}" ]
Returns current models' fallback language. If null, will return app's configured source language. @return string
[ "Returns", "current", "models", "fallback", "language", ".", "If", "null", "will", "return", "app", "s", "configured", "source", "language", "." ]
d50c714d0d63c085a926991ed36c50ed460b8184
https://github.com/2amigos/yii2-translateable-behavior/blob/d50c714d0d63c085a926991ed36c50ed460b8184/TranslateableBehavior.php#L282-L313
35,606
2amigos/yii2-translateable-behavior
TranslateableBehavior.php
TranslateableBehavior.modelEqualsFallbackTranslation
private function modelEqualsFallbackTranslation($model, $language) { $fallbackLanguage = $this->getFallbackLanguage($language); foreach($this->translationAttributes as $translationAttribute) { if (isset($model->$translationAttribute)) { list($translation, $transLanguage) = $this->getAttributeTranslation($translationAttribute, $fallbackLanguage); if ($transLanguage === $language || $model->$translationAttribute !== $translation) { return false; } } } return true; }
php
private function modelEqualsFallbackTranslation($model, $language) { $fallbackLanguage = $this->getFallbackLanguage($language); foreach($this->translationAttributes as $translationAttribute) { if (isset($model->$translationAttribute)) { list($translation, $transLanguage) = $this->getAttributeTranslation($translationAttribute, $fallbackLanguage); if ($transLanguage === $language || $model->$translationAttribute !== $translation) { return false; } } } return true; }
[ "private", "function", "modelEqualsFallbackTranslation", "(", "$", "model", ",", "$", "language", ")", "{", "$", "fallbackLanguage", "=", "$", "this", "->", "getFallbackLanguage", "(", "$", "language", ")", ";", "foreach", "(", "$", "this", "->", "translationAttributes", "as", "$", "translationAttribute", ")", "{", "if", "(", "isset", "(", "$", "model", "->", "$", "translationAttribute", ")", ")", "{", "list", "(", "$", "translation", ",", "$", "transLanguage", ")", "=", "$", "this", "->", "getAttributeTranslation", "(", "$", "translationAttribute", ",", "$", "fallbackLanguage", ")", ";", "if", "(", "$", "transLanguage", "===", "$", "language", "||", "$", "model", "->", "$", "translationAttribute", "!==", "$", "translation", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Check whether translation model has relevant translation data. This will return false if any translation is set and different from the fallback. This method is used to only store translations if they differ from the fallback. @param ActiveRecord $model @param string $language @return bool whether a translation model contains relevant translation data.
[ "Check", "whether", "translation", "model", "has", "relevant", "translation", "data", "." ]
d50c714d0d63c085a926991ed36c50ed460b8184
https://github.com/2amigos/yii2-translateable-behavior/blob/d50c714d0d63c085a926991ed36c50ed460b8184/TranslateableBehavior.php#L375-L387
35,607
2amigos/yii2-translateable-behavior
TranslateableBehavior.php
TranslateableBehavior.populateTranslations
private function populateTranslations() { //translations $aRelated = $this->owner->getRelatedRecords(); if (isset($aRelated[$this->relation]) && $aRelated[$this->relation] != null) { if (is_array($aRelated[$this->relation])) { foreach ($aRelated[$this->relation] as $model) { $this->_models[$model->getAttribute($this->languageField)] = $model; } } else { $model = $aRelated[$this->relation]; $this->_models[$model->getAttribute($this->languageField)] = $model; } } }
php
private function populateTranslations() { //translations $aRelated = $this->owner->getRelatedRecords(); if (isset($aRelated[$this->relation]) && $aRelated[$this->relation] != null) { if (is_array($aRelated[$this->relation])) { foreach ($aRelated[$this->relation] as $model) { $this->_models[$model->getAttribute($this->languageField)] = $model; } } else { $model = $aRelated[$this->relation]; $this->_models[$model->getAttribute($this->languageField)] = $model; } } }
[ "private", "function", "populateTranslations", "(", ")", "{", "//translations", "$", "aRelated", "=", "$", "this", "->", "owner", "->", "getRelatedRecords", "(", ")", ";", "if", "(", "isset", "(", "$", "aRelated", "[", "$", "this", "->", "relation", "]", ")", "&&", "$", "aRelated", "[", "$", "this", "->", "relation", "]", "!=", "null", ")", "{", "if", "(", "is_array", "(", "$", "aRelated", "[", "$", "this", "->", "relation", "]", ")", ")", "{", "foreach", "(", "$", "aRelated", "[", "$", "this", "->", "relation", "]", "as", "$", "model", ")", "{", "$", "this", "->", "_models", "[", "$", "model", "->", "getAttribute", "(", "$", "this", "->", "languageField", ")", "]", "=", "$", "model", ";", "}", "}", "else", "{", "$", "model", "=", "$", "aRelated", "[", "$", "this", "->", "relation", "]", ";", "$", "this", "->", "_models", "[", "$", "model", "->", "getAttribute", "(", "$", "this", "->", "languageField", ")", "]", "=", "$", "model", ";", "}", "}", "}" ]
Populates already loaded translations
[ "Populates", "already", "loaded", "translations" ]
d50c714d0d63c085a926991ed36c50ed460b8184
https://github.com/2amigos/yii2-translateable-behavior/blob/d50c714d0d63c085a926991ed36c50ed460b8184/TranslateableBehavior.php#L469-L483
35,608
matthiasmullie/scrapbook
src/Adapters/SQL.php
SQL.unserialize
protected function unserialize($value) { if (is_numeric($value)) { $int = (int) $value; if ((string) $int === $value) { return $int; } $float = (float) $value; if ((string) $float === $value) { return $float; } return $value; } return unserialize($value); }
php
protected function unserialize($value) { if (is_numeric($value)) { $int = (int) $value; if ((string) $int === $value) { return $int; } $float = (float) $value; if ((string) $float === $value) { return $float; } return $value; } return unserialize($value); }
[ "protected", "function", "unserialize", "(", "$", "value", ")", "{", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "{", "$", "int", "=", "(", "int", ")", "$", "value", ";", "if", "(", "(", "string", ")", "$", "int", "===", "$", "value", ")", "{", "return", "$", "int", ";", "}", "$", "float", "=", "(", "float", ")", "$", "value", ";", "if", "(", "(", "string", ")", "$", "float", "===", "$", "value", ")", "{", "return", "$", "float", ";", "}", "return", "$", "value", ";", "}", "return", "unserialize", "(", "$", "value", ")", ";", "}" ]
Numbers aren't serialized for storage size purposes. @param mixed $value @return mixed|int|float
[ "Numbers", "aren", "t", "serialized", "for", "storage", "size", "purposes", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/SQL.php#L496-L513
35,609
matthiasmullie/scrapbook
src/Adapters/Couchbase.php
Couchbase.assertServerHealhy
protected function assertServerHealhy() { $info = $this->client->manager()->info(); foreach ($info['nodes'] as $node) { if ($node['status'] !== 'healthy') { throw new ServerUnhealthy('Server isn\'t ready yet'); } } }
php
protected function assertServerHealhy() { $info = $this->client->manager()->info(); foreach ($info['nodes'] as $node) { if ($node['status'] !== 'healthy') { throw new ServerUnhealthy('Server isn\'t ready yet'); } } }
[ "protected", "function", "assertServerHealhy", "(", ")", "{", "$", "info", "=", "$", "this", "->", "client", "->", "manager", "(", ")", "->", "info", "(", ")", ";", "foreach", "(", "$", "info", "[", "'nodes'", "]", "as", "$", "node", ")", "{", "if", "(", "$", "node", "[", "'status'", "]", "!==", "'healthy'", ")", "{", "throw", "new", "ServerUnhealthy", "(", "'Server isn\\'t ready yet'", ")", ";", "}", "}", "}" ]
Verify that the server is healthy. @throws ServerUnhealthy
[ "Verify", "that", "the", "server", "is", "healthy", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Couchbase.php#L453-L461
35,610
matthiasmullie/scrapbook
src/Adapters/Apc.php
Apc.lock
protected function lock($keys) { // both string (single key) and array (multiple) are accepted $keys = (array) $keys; $locked = array(); for ($i = 0; $i < 10; ++$i) { $locked += $this->acquire($keys); $keys = array_diff($keys, $locked); if (empty($keys)) { break; } usleep(1); } return $locked; }
php
protected function lock($keys) { // both string (single key) and array (multiple) are accepted $keys = (array) $keys; $locked = array(); for ($i = 0; $i < 10; ++$i) { $locked += $this->acquire($keys); $keys = array_diff($keys, $locked); if (empty($keys)) { break; } usleep(1); } return $locked; }
[ "protected", "function", "lock", "(", "$", "keys", ")", "{", "// both string (single key) and array (multiple) are accepted", "$", "keys", "=", "(", "array", ")", "$", "keys", ";", "$", "locked", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "10", ";", "++", "$", "i", ")", "{", "$", "locked", "+=", "$", "this", "->", "acquire", "(", "$", "keys", ")", ";", "$", "keys", "=", "array_diff", "(", "$", "keys", ",", "$", "locked", ")", ";", "if", "(", "empty", "(", "$", "keys", ")", ")", "{", "break", ";", "}", "usleep", "(", "1", ")", ";", "}", "return", "$", "locked", ";", "}" ]
Acquire a lock. If we failed to acquire a lock, it'll automatically try again in 1ms, for a maximum of 10 times. APC provides nothing that would allow us to do CAS. To "emulate" CAS, we'll work with locks: all cache writes also briefly create a lock cache entry (yup: #writes * 3, for lock & unlock - luckily, they're not over the network) Writes are disallows when a lock can't be obtained (= locked by another write), which makes it possible for us to first retrieve, compare & then set in a nob-atomic way. However, there's a possibility for interference with direct APC access touching the same keys - e.g. other scripts, not using this class. If CAS is of importance, make sure the only things touching APC on your server is using these classes! @param string|string[] $keys @return array Array of successfully locked keys
[ "Acquire", "a", "lock", ".", "If", "we", "failed", "to", "acquire", "a", "lock", "it", "ll", "automatically", "try", "again", "in", "1ms", "for", "a", "maximum", "of", "10", "times", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Apc.php#L493-L511
35,611
matthiasmullie/scrapbook
src/Adapters/Apc.php
Apc.acquire
protected function acquire($keys) { $keys = (array) $keys; $values = array(); foreach ($keys as $key) { $values["scrapbook.lock.$key"] = null; } // there's no point in locking longer than max allowed execution time // for this script $ttl = ini_get('max_execution_time'); // lock these keys, then compile a list of successfully locked keys // (using the returned failure array) $result = (array) $this->apcu_add($values, null, $ttl); $failed = array(); foreach ($result as $key => $err) { $failed[] = substr($key, strlen('scrapbook.lock.')); } return array_diff($keys, $failed); }
php
protected function acquire($keys) { $keys = (array) $keys; $values = array(); foreach ($keys as $key) { $values["scrapbook.lock.$key"] = null; } // there's no point in locking longer than max allowed execution time // for this script $ttl = ini_get('max_execution_time'); // lock these keys, then compile a list of successfully locked keys // (using the returned failure array) $result = (array) $this->apcu_add($values, null, $ttl); $failed = array(); foreach ($result as $key => $err) { $failed[] = substr($key, strlen('scrapbook.lock.')); } return array_diff($keys, $failed); }
[ "protected", "function", "acquire", "(", "$", "keys", ")", "{", "$", "keys", "=", "(", "array", ")", "$", "keys", ";", "$", "values", "=", "array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "values", "[", "\"scrapbook.lock.$key\"", "]", "=", "null", ";", "}", "// there's no point in locking longer than max allowed execution time", "// for this script", "$", "ttl", "=", "ini_get", "(", "'max_execution_time'", ")", ";", "// lock these keys, then compile a list of successfully locked keys", "// (using the returned failure array)", "$", "result", "=", "(", "array", ")", "$", "this", "->", "apcu_add", "(", "$", "values", ",", "null", ",", "$", "ttl", ")", ";", "$", "failed", "=", "array", "(", ")", ";", "foreach", "(", "$", "result", "as", "$", "key", "=>", "$", "err", ")", "{", "$", "failed", "[", "]", "=", "substr", "(", "$", "key", ",", "strlen", "(", "'scrapbook.lock.'", ")", ")", ";", "}", "return", "array_diff", "(", "$", "keys", ",", "$", "failed", ")", ";", "}" ]
Acquire a lock - required to provide CAS functionality. @param string|string[] $keys @return string[] Array of successfully locked keys
[ "Acquire", "a", "lock", "-", "required", "to", "provide", "CAS", "functionality", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Apc.php#L520-L542
35,612
matthiasmullie/scrapbook
src/Adapters/Apc.php
Apc.unlock
protected function unlock($keys) { $keys = (array) $keys; foreach ($keys as $i => $key) { $keys[$i] = "scrapbook.lock.$key"; } $this->apcu_delete($keys); return true; }
php
protected function unlock($keys) { $keys = (array) $keys; foreach ($keys as $i => $key) { $keys[$i] = "scrapbook.lock.$key"; } $this->apcu_delete($keys); return true; }
[ "protected", "function", "unlock", "(", "$", "keys", ")", "{", "$", "keys", "=", "(", "array", ")", "$", "keys", ";", "foreach", "(", "$", "keys", "as", "$", "i", "=>", "$", "key", ")", "{", "$", "keys", "[", "$", "i", "]", "=", "\"scrapbook.lock.$key\"", ";", "}", "$", "this", "->", "apcu_delete", "(", "$", "keys", ")", ";", "return", "true", ";", "}" ]
Release a lock. @param string|string[] $keys @return bool
[ "Release", "a", "lock", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Apc.php#L551-L561
35,613
matthiasmullie/scrapbook
src/Adapters/Apc.php
Apc.expire
protected function expire($key = array(), $ttl = 0) { if ($ttl === 0) { // when storing indefinitely, there's no point in keeping it around, // it won't just expire return; } // $key can be both string (1 key) or array (multiple) $keys = (array) $key; $time = time() + $ttl; foreach ($keys as $key) { $this->expires[$key] = $time; } }
php
protected function expire($key = array(), $ttl = 0) { if ($ttl === 0) { // when storing indefinitely, there's no point in keeping it around, // it won't just expire return; } // $key can be both string (1 key) or array (multiple) $keys = (array) $key; $time = time() + $ttl; foreach ($keys as $key) { $this->expires[$key] = $time; } }
[ "protected", "function", "expire", "(", "$", "key", "=", "array", "(", ")", ",", "$", "ttl", "=", "0", ")", "{", "if", "(", "$", "ttl", "===", "0", ")", "{", "// when storing indefinitely, there's no point in keeping it around,", "// it won't just expire", "return", ";", "}", "// $key can be both string (1 key) or array (multiple)", "$", "keys", "=", "(", "array", ")", "$", "key", ";", "$", "time", "=", "time", "(", ")", "+", "$", "ttl", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "this", "->", "expires", "[", "$", "key", "]", "=", "$", "time", ";", "}", "}" ]
Store the expiration time for items we're setting in this request, to work around APC's behavior of only clearing expires per page request. @see static::$expires @param array|string $key @param int $ttl
[ "Store", "the", "expiration", "time", "for", "items", "we", "re", "setting", "in", "this", "request", "to", "work", "around", "APC", "s", "behavior", "of", "only", "clearing", "expires", "per", "page", "request", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Apc.php#L572-L587
35,614
matthiasmullie/scrapbook
src/Buffered/TransactionalStore.php
TransactionalStore.commit
public function commit() { if (count($this->transactions) <= 1) { throw new UnbegunTransaction('Attempted to commit without having begun a transaction.'); } /** @var Transaction $transaction */ $transaction = array_pop($this->transactions); return $transaction->commit(); }
php
public function commit() { if (count($this->transactions) <= 1) { throw new UnbegunTransaction('Attempted to commit without having begun a transaction.'); } /** @var Transaction $transaction */ $transaction = array_pop($this->transactions); return $transaction->commit(); }
[ "public", "function", "commit", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "transactions", ")", "<=", "1", ")", "{", "throw", "new", "UnbegunTransaction", "(", "'Attempted to commit without having begun a transaction.'", ")", ";", "}", "/** @var Transaction $transaction */", "$", "transaction", "=", "array_pop", "(", "$", "this", "->", "transactions", ")", ";", "return", "$", "transaction", "->", "commit", "(", ")", ";", "}" ]
Commits all deferred updates to real cache. If the any write fails, all subsequent writes will be aborted & all keys that had already been written to will be deleted. @return bool @throws UnbegunTransaction
[ "Commits", "all", "deferred", "updates", "to", "real", "cache", ".", "If", "the", "any", "write", "fails", "all", "subsequent", "writes", "will", "be", "aborted", "&", "all", "keys", "that", "had", "already", "been", "written", "to", "will", "be", "deleted", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/TransactionalStore.php#L85-L95
35,615
matthiasmullie/scrapbook
src/Buffered/TransactionalStore.php
TransactionalStore.rollback
public function rollback() { if (count($this->transactions) <= 1) { throw new UnbegunTransaction('Attempted to rollback without having begun a transaction.'); } /** @var Transaction $transaction */ $transaction = array_pop($this->transactions); return $transaction->rollback(); }
php
public function rollback() { if (count($this->transactions) <= 1) { throw new UnbegunTransaction('Attempted to rollback without having begun a transaction.'); } /** @var Transaction $transaction */ $transaction = array_pop($this->transactions); return $transaction->rollback(); }
[ "public", "function", "rollback", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "transactions", ")", "<=", "1", ")", "{", "throw", "new", "UnbegunTransaction", "(", "'Attempted to rollback without having begun a transaction.'", ")", ";", "}", "/** @var Transaction $transaction */", "$", "transaction", "=", "array_pop", "(", "$", "this", "->", "transactions", ")", ";", "return", "$", "transaction", "->", "rollback", "(", ")", ";", "}" ]
Roll back all scheduled changes. @return bool @throws UnbegunTransaction
[ "Roll", "back", "all", "scheduled", "changes", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/TransactionalStore.php#L104-L114
35,616
matthiasmullie/scrapbook
src/Psr6/Repository.php
Repository.resolve
protected function resolve() { $keys = array_unique(array_values($this->unresolved)); $values = $this->store->getMulti($keys); foreach ($this->unresolved as $unique => $key) { if (!array_key_exists($key, $values)) { // key doesn't exist in cache continue; } /* * In theory, there could've been multiple unresolved requests for * the same cache key. In the case of objects, we'll clone them * to make sure that when the value for 1 item is manipulated, it * doesn't affect the value of the other item (because those objects * would be passed by-ref without the cloning) */ $value = $values[$key]; $value = is_object($value) ? clone $value : $value; $this->resolved[$unique] = $value; } $this->unresolved = array(); }
php
protected function resolve() { $keys = array_unique(array_values($this->unresolved)); $values = $this->store->getMulti($keys); foreach ($this->unresolved as $unique => $key) { if (!array_key_exists($key, $values)) { // key doesn't exist in cache continue; } /* * In theory, there could've been multiple unresolved requests for * the same cache key. In the case of objects, we'll clone them * to make sure that when the value for 1 item is manipulated, it * doesn't affect the value of the other item (because those objects * would be passed by-ref without the cloning) */ $value = $values[$key]; $value = is_object($value) ? clone $value : $value; $this->resolved[$unique] = $value; } $this->unresolved = array(); }
[ "protected", "function", "resolve", "(", ")", "{", "$", "keys", "=", "array_unique", "(", "array_values", "(", "$", "this", "->", "unresolved", ")", ")", ";", "$", "values", "=", "$", "this", "->", "store", "->", "getMulti", "(", "$", "keys", ")", ";", "foreach", "(", "$", "this", "->", "unresolved", "as", "$", "unique", "=>", "$", "key", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "values", ")", ")", "{", "// key doesn't exist in cache", "continue", ";", "}", "/*\n * In theory, there could've been multiple unresolved requests for\n * the same cache key. In the case of objects, we'll clone them\n * to make sure that when the value for 1 item is manipulated, it\n * doesn't affect the value of the other item (because those objects\n * would be passed by-ref without the cloning)\n */", "$", "value", "=", "$", "values", "[", "$", "key", "]", ";", "$", "value", "=", "is_object", "(", "$", "value", ")", "?", "clone", "$", "value", ":", "$", "value", ";", "$", "this", "->", "resolved", "[", "$", "unique", "]", "=", "$", "value", ";", "}", "$", "this", "->", "unresolved", "=", "array", "(", ")", ";", "}" ]
Resolve all unresolved keys at once.
[ "Resolve", "all", "unresolved", "keys", "at", "once", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Psr6/Repository.php#L102-L127
35,617
matthiasmullie/scrapbook
src/Adapters/Flysystem.php
Flysystem.lock
protected function lock($key) { $path = $key.'.lock'; for ($i = 0; $i < 25; ++$i) { try { $this->filesystem->write($path, ''); return true; } catch (FileExistsException $e) { usleep(200); } } return false; }
php
protected function lock($key) { $path = $key.'.lock'; for ($i = 0; $i < 25; ++$i) { try { $this->filesystem->write($path, ''); return true; } catch (FileExistsException $e) { usleep(200); } } return false; }
[ "protected", "function", "lock", "(", "$", "key", ")", "{", "$", "path", "=", "$", "key", ".", "'.lock'", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "25", ";", "++", "$", "i", ")", "{", "try", "{", "$", "this", "->", "filesystem", "->", "write", "(", "$", "path", ",", "''", ")", ";", "return", "true", ";", "}", "catch", "(", "FileExistsException", "$", "e", ")", "{", "usleep", "(", "200", ")", ";", "}", "}", "return", "false", ";", "}" ]
Obtain a lock for a given key. It'll try to get a lock for a couple of times, but ultimately give up if no lock can be obtained in a reasonable time. @param string $key @return bool
[ "Obtain", "a", "lock", "for", "a", "given", "key", ".", "It", "ll", "try", "to", "get", "a", "lock", "for", "a", "couple", "of", "times", "but", "ultimately", "give", "up", "if", "no", "lock", "can", "be", "obtained", "in", "a", "reasonable", "time", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Flysystem.php#L406-L421
35,618
matthiasmullie/scrapbook
src/Adapters/Flysystem.php
Flysystem.unlock
protected function unlock($key) { $path = $key.'.lock'; try { $this->filesystem->delete($path); } catch (FileNotFoundException $e) { return false; } return true; }
php
protected function unlock($key) { $path = $key.'.lock'; try { $this->filesystem->delete($path); } catch (FileNotFoundException $e) { return false; } return true; }
[ "protected", "function", "unlock", "(", "$", "key", ")", "{", "$", "path", "=", "$", "key", ".", "'.lock'", ";", "try", "{", "$", "this", "->", "filesystem", "->", "delete", "(", "$", "path", ")", ";", "}", "catch", "(", "FileNotFoundException", "$", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Release the lock for a given key. @param string $key @return bool
[ "Release", "the", "lock", "for", "a", "given", "key", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Flysystem.php#L430-L440
35,619
matthiasmullie/scrapbook
src/Adapters/Flysystem.php
Flysystem.wrap
protected function wrap($value, $expire) { $expire = $this->normalizeTime($expire); return $expire."\n".serialize($value); }
php
protected function wrap($value, $expire) { $expire = $this->normalizeTime($expire); return $expire."\n".serialize($value); }
[ "protected", "function", "wrap", "(", "$", "value", ",", "$", "expire", ")", "{", "$", "expire", "=", "$", "this", "->", "normalizeTime", "(", "$", "expire", ")", ";", "return", "$", "expire", ".", "\"\\n\"", ".", "serialize", "(", "$", "value", ")", ";", "}" ]
Build value, token & expiration time to be stored in cache file. @param string $value @param int $expire @return string
[ "Build", "value", "token", "&", "expiration", "time", "to", "be", "stored", "in", "cache", "file", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Flysystem.php#L478-L483
35,620
matthiasmullie/scrapbook
src/Adapters/Flysystem.php
Flysystem.read
protected function read($key) { $path = $this->path($key); try { $data = $this->filesystem->read($path); } catch (FileNotFoundException $e) { // unlikely given previous 'exists' check, but let's play safe... // (outside process may have removed it since) return false; } if ($data === false) { // in theory, a file could still be deleted between Flysystem's // assertPresent & the time it actually fetched the content // extremely unlikely though return false; } $data = explode("\n", $data, 2); $data[0] = (int) $data[0]; return $data; }
php
protected function read($key) { $path = $this->path($key); try { $data = $this->filesystem->read($path); } catch (FileNotFoundException $e) { // unlikely given previous 'exists' check, but let's play safe... // (outside process may have removed it since) return false; } if ($data === false) { // in theory, a file could still be deleted between Flysystem's // assertPresent & the time it actually fetched the content // extremely unlikely though return false; } $data = explode("\n", $data, 2); $data[0] = (int) $data[0]; return $data; }
[ "protected", "function", "read", "(", "$", "key", ")", "{", "$", "path", "=", "$", "this", "->", "path", "(", "$", "key", ")", ";", "try", "{", "$", "data", "=", "$", "this", "->", "filesystem", "->", "read", "(", "$", "path", ")", ";", "}", "catch", "(", "FileNotFoundException", "$", "e", ")", "{", "// unlikely given previous 'exists' check, but let's play safe...", "// (outside process may have removed it since)", "return", "false", ";", "}", "if", "(", "$", "data", "===", "false", ")", "{", "// in theory, a file could still be deleted between Flysystem's", "// assertPresent & the time it actually fetched the content", "// extremely unlikely though", "return", "false", ";", "}", "$", "data", "=", "explode", "(", "\"\\n\"", ",", "$", "data", ",", "2", ")", ";", "$", "data", "[", "0", "]", "=", "(", "int", ")", "$", "data", "[", "0", "]", ";", "return", "$", "data", ";", "}" ]
Fetch stored data from cache file. @param string $key @return bool|array
[ "Fetch", "stored", "data", "from", "cache", "file", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Flysystem.php#L492-L514
35,621
matthiasmullie/scrapbook
src/Adapters/MemoryStore.php
MemoryStore.exists
protected function exists($key) { if (!array_key_exists($key, $this->items)) { // key not in cache return false; } $expire = $this->items[$key][1]; if ($expire !== 0 && $expire < time()) { // not permanent & already expired $this->size -= strlen($this->items[$key][0]); unset($this->items[$key]); return false; } $this->lru($key); return true; }
php
protected function exists($key) { if (!array_key_exists($key, $this->items)) { // key not in cache return false; } $expire = $this->items[$key][1]; if ($expire !== 0 && $expire < time()) { // not permanent & already expired $this->size -= strlen($this->items[$key][0]); unset($this->items[$key]); return false; } $this->lru($key); return true; }
[ "protected", "function", "exists", "(", "$", "key", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "items", ")", ")", "{", "// key not in cache", "return", "false", ";", "}", "$", "expire", "=", "$", "this", "->", "items", "[", "$", "key", "]", "[", "1", "]", ";", "if", "(", "$", "expire", "!==", "0", "&&", "$", "expire", "<", "time", "(", ")", ")", "{", "// not permanent & already expired", "$", "this", "->", "size", "-=", "strlen", "(", "$", "this", "->", "items", "[", "$", "key", "]", "[", "0", "]", ")", ";", "unset", "(", "$", "this", "->", "items", "[", "$", "key", "]", ")", ";", "return", "false", ";", "}", "$", "this", "->", "lru", "(", "$", "key", ")", ";", "return", "true", ";", "}" ]
Checks if a value exists in cache and is not yet expired. @param string $key @return bool
[ "Checks", "if", "a", "value", "exists", "in", "cache", "and", "is", "not", "yet", "expired", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/MemoryStore.php#L258-L277
35,622
matthiasmullie/scrapbook
src/Adapters/MemoryStore.php
MemoryStore.lru
protected function lru($key) { // move key that has just been used to last position in the array $value = $this->items[$key]; unset($this->items[$key]); $this->items[$key] = $value; }
php
protected function lru($key) { // move key that has just been used to last position in the array $value = $this->items[$key]; unset($this->items[$key]); $this->items[$key] = $value; }
[ "protected", "function", "lru", "(", "$", "key", ")", "{", "// move key that has just been used to last position in the array", "$", "value", "=", "$", "this", "->", "items", "[", "$", "key", "]", ";", "unset", "(", "$", "this", "->", "items", "[", "$", "key", "]", ")", ";", "$", "this", "->", "items", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
This cache uses least recently used algorithm. This is to be called with the key to be marked as just used.
[ "This", "cache", "uses", "least", "recently", "used", "algorithm", ".", "This", "is", "to", "be", "called", "with", "the", "key", "to", "be", "marked", "as", "just", "used", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/MemoryStore.php#L344-L350
35,623
matthiasmullie/scrapbook
src/Adapters/MemoryStore.php
MemoryStore.evict
protected function evict() { while ($this->size > $this->limit && !empty($this->items)) { $item = array_shift($this->items); $this->size -= strlen($item[0]); } }
php
protected function evict() { while ($this->size > $this->limit && !empty($this->items)) { $item = array_shift($this->items); $this->size -= strlen($item[0]); } }
[ "protected", "function", "evict", "(", ")", "{", "while", "(", "$", "this", "->", "size", ">", "$", "this", "->", "limit", "&&", "!", "empty", "(", "$", "this", "->", "items", ")", ")", "{", "$", "item", "=", "array_shift", "(", "$", "this", "->", "items", ")", ";", "$", "this", "->", "size", "-=", "strlen", "(", "$", "item", "[", "0", "]", ")", ";", "}", "}" ]
Least recently used cache values will be evicted from cache should it fill up too much.
[ "Least", "recently", "used", "cache", "values", "will", "be", "evicted", "from", "cache", "should", "it", "fill", "up", "too", "much", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/MemoryStore.php#L356-L362
35,624
matthiasmullie/scrapbook
src/Buffered/Utils/BufferCollection.php
BufferCollection.expired
public function expired($key) { if ($this->get($key) !== false) { // returned a value, clearly not yet expired return false; } // a known item, not returned by get, is expired return array_key_exists($key, $this->cache->items); }
php
public function expired($key) { if ($this->get($key) !== false) { // returned a value, clearly not yet expired return false; } // a known item, not returned by get, is expired return array_key_exists($key, $this->cache->items); }
[ "public", "function", "expired", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "get", "(", "$", "key", ")", "!==", "false", ")", "{", "// returned a value, clearly not yet expired", "return", "false", ";", "}", "// a known item, not returned by get, is expired", "return", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "cache", "->", "items", ")", ";", "}" ]
Check if a key existed in local storage, but is now expired. Because our local buffer is also just a real cache, expired items will just return nothing, which will lead us to believe no such item exists in that local cache, and we'll reach out to the real cache (where the value may not yet have been expired because that may have been part of an uncommitted write) So we'll want to know when a value is in local cache, but expired! @param string $key @return bool
[ "Check", "if", "a", "key", "existed", "in", "local", "storage", "but", "is", "now", "expired", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/BufferCollection.php#L44-L53
35,625
matthiasmullie/scrapbook
src/Adapters/Memcached.php
Memcached.encode
protected function encode($key) { $regex = '/[^\x21\x22\x24\x26-\x39\x3b-\x7e]+/'; $key = preg_replace_callback($regex, function ($match) { return rawurlencode($match[0]); }, $key); if (strlen($key) > 255) { throw new InvalidKey( "Invalid key: $key. Encoded Memcached keys can not exceed 255 chars." ); } return $key; }
php
protected function encode($key) { $regex = '/[^\x21\x22\x24\x26-\x39\x3b-\x7e]+/'; $key = preg_replace_callback($regex, function ($match) { return rawurlencode($match[0]); }, $key); if (strlen($key) > 255) { throw new InvalidKey( "Invalid key: $key. Encoded Memcached keys can not exceed 255 chars." ); } return $key; }
[ "protected", "function", "encode", "(", "$", "key", ")", "{", "$", "regex", "=", "'/[^\\x21\\x22\\x24\\x26-\\x39\\x3b-\\x7e]+/'", ";", "$", "key", "=", "preg_replace_callback", "(", "$", "regex", ",", "function", "(", "$", "match", ")", "{", "return", "rawurlencode", "(", "$", "match", "[", "0", "]", ")", ";", "}", ",", "$", "key", ")", ";", "if", "(", "strlen", "(", "$", "key", ")", ">", "255", ")", "{", "throw", "new", "InvalidKey", "(", "\"Invalid key: $key. Encoded Memcached keys can not exceed 255 chars.\"", ")", ";", "}", "return", "$", "key", ";", "}" ]
Encode a key for use on the wire inside the memcached protocol. We encode spaces and line breaks to avoid protocol errors. We encode the other control characters for compatibility with libmemcached verify_key. We leave other punctuation alone, to maximise backwards compatibility. @see https://github.com/wikimedia/mediawiki/commit/be76d869#diff-75b7c03970b5e43de95ff95f5faa6ef1R100 @see https://github.com/wikimedia/mediawiki/blob/master/includes/libs/objectcache/MemcachedBagOStuff.php#L116 @param string $key @return string @throws InvalidKey
[ "Encode", "a", "key", "for", "use", "on", "the", "wire", "inside", "the", "memcached", "protocol", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Memcached.php#L374-L388
35,626
matthiasmullie/scrapbook
src/Adapters/Memcached.php
Memcached.throwExceptionOnClientCallFailure
protected function throwExceptionOnClientCallFailure($result) { if ($result !== false) { return; } throw new OperationFailed( $this->client->getResultMessage(), $this->client->getResultCode() ); }
php
protected function throwExceptionOnClientCallFailure($result) { if ($result !== false) { return; } throw new OperationFailed( $this->client->getResultMessage(), $this->client->getResultCode() ); }
[ "protected", "function", "throwExceptionOnClientCallFailure", "(", "$", "result", ")", "{", "if", "(", "$", "result", "!==", "false", ")", "{", "return", ";", "}", "throw", "new", "OperationFailed", "(", "$", "this", "->", "client", "->", "getResultMessage", "(", ")", ",", "$", "this", "->", "client", "->", "getResultCode", "(", ")", ")", ";", "}" ]
Will throw an exception if the returned result from a Memcached call indicates a failure in the operation. The exception will contain debug information about the failure. @param mixed $result @throws OperationFailed
[ "Will", "throw", "an", "exception", "if", "the", "returned", "result", "from", "a", "Memcached", "call", "indicates", "a", "failure", "in", "the", "operation", ".", "The", "exception", "will", "contain", "debug", "information", "about", "the", "failure", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Memcached.php#L445-L455
35,627
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.commit
public function commit() { list($old, $new) = $this->generateRollback(); $updates = $this->generateUpdates(); $updates = $this->combineUpdates($updates); usort($updates, array($this, 'sortUpdates')); foreach ($updates as $update) { // apply update to cache & receive a simple bool to indicate // success (true) or failure (false) $success = call_user_func_array($update[1], $update[2]); if ($success === false) { $this->rollback($old, $new); return false; } } $this->clear(); return true; }
php
public function commit() { list($old, $new) = $this->generateRollback(); $updates = $this->generateUpdates(); $updates = $this->combineUpdates($updates); usort($updates, array($this, 'sortUpdates')); foreach ($updates as $update) { // apply update to cache & receive a simple bool to indicate // success (true) or failure (false) $success = call_user_func_array($update[1], $update[2]); if ($success === false) { $this->rollback($old, $new); return false; } } $this->clear(); return true; }
[ "public", "function", "commit", "(", ")", "{", "list", "(", "$", "old", ",", "$", "new", ")", "=", "$", "this", "->", "generateRollback", "(", ")", ";", "$", "updates", "=", "$", "this", "->", "generateUpdates", "(", ")", ";", "$", "updates", "=", "$", "this", "->", "combineUpdates", "(", "$", "updates", ")", ";", "usort", "(", "$", "updates", ",", "array", "(", "$", "this", ",", "'sortUpdates'", ")", ")", ";", "foreach", "(", "$", "updates", "as", "$", "update", ")", "{", "// apply update to cache & receive a simple bool to indicate", "// success (true) or failure (false)", "$", "success", "=", "call_user_func_array", "(", "$", "update", "[", "1", "]", ",", "$", "update", "[", "2", "]", ")", ";", "if", "(", "$", "success", "===", "false", ")", "{", "$", "this", "->", "rollback", "(", "$", "old", ",", "$", "new", ")", ";", "return", "false", ";", "}", "}", "$", "this", "->", "clear", "(", ")", ";", "return", "true", ";", "}" ]
Commit all deferred writes to cache. When the commit fails, no changes in this transaction will be applied (and those that had already been applied will be undone). False will be returned in that case. @return bool
[ "Commit", "all", "deferred", "writes", "to", "cache", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L352-L373
35,628
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.rollback
protected function rollback(array $old, array $new) { foreach ($old as $key => $value) { $current = $this->cache->get($key, $token); /* * If the value right now equals the one we planned to write, it * should be restored to what it was before. If it's yet something * else, another process must've stored it and we should leave it * alone. */ if ($current === $new) { /* * CAS the rollback. If it fails, that means another process * has stored in the meantime and we can just leave it alone. * Note that we can't know the original expiration time! */ $this->cas($token, $key, $value, 0); } } $this->clear(); }
php
protected function rollback(array $old, array $new) { foreach ($old as $key => $value) { $current = $this->cache->get($key, $token); /* * If the value right now equals the one we planned to write, it * should be restored to what it was before. If it's yet something * else, another process must've stored it and we should leave it * alone. */ if ($current === $new) { /* * CAS the rollback. If it fails, that means another process * has stored in the meantime and we can just leave it alone. * Note that we can't know the original expiration time! */ $this->cas($token, $key, $value, 0); } } $this->clear(); }
[ "protected", "function", "rollback", "(", "array", "$", "old", ",", "array", "$", "new", ")", "{", "foreach", "(", "$", "old", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "current", "=", "$", "this", "->", "cache", "->", "get", "(", "$", "key", ",", "$", "token", ")", ";", "/*\n * If the value right now equals the one we planned to write, it\n * should be restored to what it was before. If it's yet something\n * else, another process must've stored it and we should leave it\n * alone.\n */", "if", "(", "$", "current", "===", "$", "new", ")", "{", "/*\n * CAS the rollback. If it fails, that means another process\n * has stored in the meantime and we can just leave it alone.\n * Note that we can't know the original expiration time!\n */", "$", "this", "->", "cas", "(", "$", "token", ",", "$", "key", ",", "$", "value", ",", "0", ")", ";", "}", "}", "$", "this", "->", "clear", "(", ")", ";", "}" ]
Roll the cache back to pre-transaction state by comparing the current cache values with what we planned to set them to. @param array $old @param array $new
[ "Roll", "the", "cache", "back", "to", "pre", "-", "transaction", "state", "by", "comparing", "the", "current", "cache", "values", "with", "what", "we", "planned", "to", "set", "them", "to", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L382-L404
35,629
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.generateUpdates
protected function generateUpdates() { $updates = array(); if ($this->flush) { $updates[] = array('flush', array($this->cache, 'flush'), array()); } foreach ($this->keys as $key => $data) { $updates[] = $data; } return $updates; }
php
protected function generateUpdates() { $updates = array(); if ($this->flush) { $updates[] = array('flush', array($this->cache, 'flush'), array()); } foreach ($this->keys as $key => $data) { $updates[] = $data; } return $updates; }
[ "protected", "function", "generateUpdates", "(", ")", "{", "$", "updates", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "flush", ")", "{", "$", "updates", "[", "]", "=", "array", "(", "'flush'", ",", "array", "(", "$", "this", "->", "cache", ",", "'flush'", ")", ",", "array", "(", ")", ")", ";", "}", "foreach", "(", "$", "this", "->", "keys", "as", "$", "key", "=>", "$", "data", ")", "{", "$", "updates", "[", "]", "=", "$", "data", ";", "}", "return", "$", "updates", ";", "}" ]
By storing all updates by key, we've already made sure we don't perform redundant operations on a per-key basis. Now we'll turn those into actual updates. @return array
[ "By", "storing", "all", "updates", "by", "key", "we", "ve", "already", "made", "sure", "we", "don", "t", "perform", "redundant", "operations", "on", "a", "per", "-", "key", "basis", ".", "Now", "we", "ll", "turn", "those", "into", "actual", "updates", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L450-L463
35,630
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.combineUpdates
protected function combineUpdates($updates) { $setMulti = array(); $deleteMulti = array(); foreach ($updates as $i => $update) { $operation = $update[0]; $args = $update[2]; switch ($operation) { // all set & delete operations can be grouped into setMulti & deleteMulti case 'set': unset($updates[$i]); // only group sets with same expiration $setMulti[$args['expire']][$args['key']] = $args['value']; break; case 'delete': unset($updates[$i]); $deleteMulti[] = $args['key']; break; default: break; } } if (!empty($setMulti)) { $cache = $this->cache; /* * We'll use the return value of all deferred writes to check if they * should be rolled back. * commit() expects a single bool, not a per-key array of success bools. * * @param mixed[] $items * @param int $expire * @return bool */ $callback = function ($items, $expire) use ($cache) { $success = $cache->setMulti($items, $expire); return !in_array(false, $success); }; foreach ($setMulti as $expire => $items) { $updates[] = array('setMulti', $callback, array($items, $expire)); } } if (!empty($deleteMulti)) { $cache = $this->cache; /* * commit() expected a single bool, not an array of success bools. * Besides, deleteMulti() is never cause for failure here: if the * key didn't exist because it has been deleted elsewhere already, * the data isn't corrupt, it's still as we'd expect it. * * @param string[] $keys * @return bool */ $callback = function ($keys) use ($cache) { $cache->deleteMulti($keys); return true; }; $updates[] = array('deleteMulti', $callback, array($deleteMulti)); } return $updates; }
php
protected function combineUpdates($updates) { $setMulti = array(); $deleteMulti = array(); foreach ($updates as $i => $update) { $operation = $update[0]; $args = $update[2]; switch ($operation) { // all set & delete operations can be grouped into setMulti & deleteMulti case 'set': unset($updates[$i]); // only group sets with same expiration $setMulti[$args['expire']][$args['key']] = $args['value']; break; case 'delete': unset($updates[$i]); $deleteMulti[] = $args['key']; break; default: break; } } if (!empty($setMulti)) { $cache = $this->cache; /* * We'll use the return value of all deferred writes to check if they * should be rolled back. * commit() expects a single bool, not a per-key array of success bools. * * @param mixed[] $items * @param int $expire * @return bool */ $callback = function ($items, $expire) use ($cache) { $success = $cache->setMulti($items, $expire); return !in_array(false, $success); }; foreach ($setMulti as $expire => $items) { $updates[] = array('setMulti', $callback, array($items, $expire)); } } if (!empty($deleteMulti)) { $cache = $this->cache; /* * commit() expected a single bool, not an array of success bools. * Besides, deleteMulti() is never cause for failure here: if the * key didn't exist because it has been deleted elsewhere already, * the data isn't corrupt, it's still as we'd expect it. * * @param string[] $keys * @return bool */ $callback = function ($keys) use ($cache) { $cache->deleteMulti($keys); return true; }; $updates[] = array('deleteMulti', $callback, array($deleteMulti)); } return $updates; }
[ "protected", "function", "combineUpdates", "(", "$", "updates", ")", "{", "$", "setMulti", "=", "array", "(", ")", ";", "$", "deleteMulti", "=", "array", "(", ")", ";", "foreach", "(", "$", "updates", "as", "$", "i", "=>", "$", "update", ")", "{", "$", "operation", "=", "$", "update", "[", "0", "]", ";", "$", "args", "=", "$", "update", "[", "2", "]", ";", "switch", "(", "$", "operation", ")", "{", "// all set & delete operations can be grouped into setMulti & deleteMulti", "case", "'set'", ":", "unset", "(", "$", "updates", "[", "$", "i", "]", ")", ";", "// only group sets with same expiration", "$", "setMulti", "[", "$", "args", "[", "'expire'", "]", "]", "[", "$", "args", "[", "'key'", "]", "]", "=", "$", "args", "[", "'value'", "]", ";", "break", ";", "case", "'delete'", ":", "unset", "(", "$", "updates", "[", "$", "i", "]", ")", ";", "$", "deleteMulti", "[", "]", "=", "$", "args", "[", "'key'", "]", ";", "break", ";", "default", ":", "break", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "setMulti", ")", ")", "{", "$", "cache", "=", "$", "this", "->", "cache", ";", "/*\n * We'll use the return value of all deferred writes to check if they\n * should be rolled back.\n * commit() expects a single bool, not a per-key array of success bools.\n *\n * @param mixed[] $items\n * @param int $expire\n * @return bool\n */", "$", "callback", "=", "function", "(", "$", "items", ",", "$", "expire", ")", "use", "(", "$", "cache", ")", "{", "$", "success", "=", "$", "cache", "->", "setMulti", "(", "$", "items", ",", "$", "expire", ")", ";", "return", "!", "in_array", "(", "false", ",", "$", "success", ")", ";", "}", ";", "foreach", "(", "$", "setMulti", "as", "$", "expire", "=>", "$", "items", ")", "{", "$", "updates", "[", "]", "=", "array", "(", "'setMulti'", ",", "$", "callback", ",", "array", "(", "$", "items", ",", "$", "expire", ")", ")", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "deleteMulti", ")", ")", "{", "$", "cache", "=", "$", "this", "->", "cache", ";", "/*\n * commit() expected a single bool, not an array of success bools.\n * Besides, deleteMulti() is never cause for failure here: if the\n * key didn't exist because it has been deleted elsewhere already,\n * the data isn't corrupt, it's still as we'd expect it.\n *\n * @param string[] $keys\n * @return bool\n */", "$", "callback", "=", "function", "(", "$", "keys", ")", "use", "(", "$", "cache", ")", "{", "$", "cache", "->", "deleteMulti", "(", "$", "keys", ")", ";", "return", "true", ";", "}", ";", "$", "updates", "[", "]", "=", "array", "(", "'deleteMulti'", ",", "$", "callback", ",", "array", "(", "$", "deleteMulti", ")", ")", ";", "}", "return", "$", "updates", ";", "}" ]
We may have multiple sets & deletes, which can be combined into a single setMulti or deleteMulti operation. @param array $updates @return array
[ "We", "may", "have", "multiple", "sets", "&", "deletes", "which", "can", "be", "combined", "into", "a", "single", "setMulti", "or", "deleteMulti", "operation", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L473-L545
35,631
matthiasmullie/scrapbook
src/Buffered/Utils/Defer.php
Defer.sortUpdates
protected function sortUpdates(array $a, array $b) { $updateOrder = array( // there's no point in applying this after doing the below updates // we also shouldn't really worry about cas/replace failing after this, // there won't be any after cache having been flushed 'flush', // prone to fail: they depend on certain conditions (token must match // or value must (not) exist) 'cas', 'replace', 'add', // unlikely/impossible to fail, assuming the input is valid 'touch', 'increment', 'decrement', 'set', 'setMulti', 'delete', 'deleteMulti', ); if ($a[0] === $b[0]) { return 0; } return array_search($a[0], $updateOrder) < array_search($b[0], $updateOrder) ? -1 : 1; }
php
protected function sortUpdates(array $a, array $b) { $updateOrder = array( // there's no point in applying this after doing the below updates // we also shouldn't really worry about cas/replace failing after this, // there won't be any after cache having been flushed 'flush', // prone to fail: they depend on certain conditions (token must match // or value must (not) exist) 'cas', 'replace', 'add', // unlikely/impossible to fail, assuming the input is valid 'touch', 'increment', 'decrement', 'set', 'setMulti', 'delete', 'deleteMulti', ); if ($a[0] === $b[0]) { return 0; } return array_search($a[0], $updateOrder) < array_search($b[0], $updateOrder) ? -1 : 1; }
[ "protected", "function", "sortUpdates", "(", "array", "$", "a", ",", "array", "$", "b", ")", "{", "$", "updateOrder", "=", "array", "(", "// there's no point in applying this after doing the below updates", "// we also shouldn't really worry about cas/replace failing after this,", "// there won't be any after cache having been flushed", "'flush'", ",", "// prone to fail: they depend on certain conditions (token must match", "// or value must (not) exist)", "'cas'", ",", "'replace'", ",", "'add'", ",", "// unlikely/impossible to fail, assuming the input is valid", "'touch'", ",", "'increment'", ",", "'decrement'", ",", "'set'", ",", "'setMulti'", ",", "'delete'", ",", "'deleteMulti'", ",", ")", ";", "if", "(", "$", "a", "[", "0", "]", "===", "$", "b", "[", "0", "]", ")", "{", "return", "0", ";", "}", "return", "array_search", "(", "$", "a", "[", "0", "]", ",", "$", "updateOrder", ")", "<", "array_search", "(", "$", "b", "[", "0", "]", ",", "$", "updateOrder", ")", "?", "-", "1", ":", "1", ";", "}" ]
Change the order of the updates in this transaction to ensure we have those most likely to fail first. That'll decrease odds of having to roll back, and make rolling back easier. @param array $a Update, where index 0 is the operation name @param array $b Update, where index 0 is the operation name @return int
[ "Change", "the", "order", "of", "the", "updates", "in", "this", "transaction", "to", "ensure", "we", "have", "those", "most", "likely", "to", "fail", "first", ".", "That", "ll", "decrease", "odds", "of", "having", "to", "roll", "back", "and", "make", "rolling", "back", "easier", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Buffered/Utils/Defer.php#L557-L584
35,632
matthiasmullie/scrapbook
src/Adapters/Redis.php
Redis.getVersion
protected function getVersion() { if ($this->version === null) { $info = $this->client->info(); $this->version = $info['redis_version']; } return $this->version; }
php
protected function getVersion() { if ($this->version === null) { $info = $this->client->info(); $this->version = $info['redis_version']; } return $this->version; }
[ "protected", "function", "getVersion", "(", ")", "{", "if", "(", "$", "this", "->", "version", "===", "null", ")", "{", "$", "info", "=", "$", "this", "->", "client", "->", "info", "(", ")", ";", "$", "this", "->", "version", "=", "$", "info", "[", "'redis_version'", "]", ";", "}", "return", "$", "this", "->", "version", ";", "}" ]
Returns the version of the Redis server we're connecting to. @return string
[ "Returns", "the", "version", "of", "the", "Redis", "server", "we", "re", "connecting", "to", "." ]
87ff6c5a6273eb45452d38d2f01378af8b812a8b
https://github.com/matthiasmullie/scrapbook/blob/87ff6c5a6273eb45452d38d2f01378af8b812a8b/src/Adapters/Redis.php#L611-L619
35,633
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.generate
public function generate(array $definitionFileDirectories): string { $authEnabled = config('lighthouse-utils.authorization'); if ($authEnabled) { GraphQLSchema::truncate(); } $this->validateFilesPaths($definitionFileDirectories); $schema = $this->getSchemaForFiles($definitionFileDirectories); $definedTypes = $this->getDefinedTypesFromSchema($schema, $definitionFileDirectories); $queries = $this->generateQueriesForDefinedTypes($definedTypes, $definitionFileDirectories); $typesImports = $this->concatSchemaDefinitionFilesFromPath( $this->definitionsParser->getGraphqlDefinitionFilePaths($definitionFileDirectories['types']) ); if ($authEnabled) { event(new GraphQLSchemaGenerated(GraphQLSchema::all())); } //Merge queries and types into one file with required newlines return sprintf("%s\r\n\r\n%s\r\n", $typesImports, $queries); }
php
public function generate(array $definitionFileDirectories): string { $authEnabled = config('lighthouse-utils.authorization'); if ($authEnabled) { GraphQLSchema::truncate(); } $this->validateFilesPaths($definitionFileDirectories); $schema = $this->getSchemaForFiles($definitionFileDirectories); $definedTypes = $this->getDefinedTypesFromSchema($schema, $definitionFileDirectories); $queries = $this->generateQueriesForDefinedTypes($definedTypes, $definitionFileDirectories); $typesImports = $this->concatSchemaDefinitionFilesFromPath( $this->definitionsParser->getGraphqlDefinitionFilePaths($definitionFileDirectories['types']) ); if ($authEnabled) { event(new GraphQLSchemaGenerated(GraphQLSchema::all())); } //Merge queries and types into one file with required newlines return sprintf("%s\r\n\r\n%s\r\n", $typesImports, $queries); }
[ "public", "function", "generate", "(", "array", "$", "definitionFileDirectories", ")", ":", "string", "{", "$", "authEnabled", "=", "config", "(", "'lighthouse-utils.authorization'", ")", ";", "if", "(", "$", "authEnabled", ")", "{", "GraphQLSchema", "::", "truncate", "(", ")", ";", "}", "$", "this", "->", "validateFilesPaths", "(", "$", "definitionFileDirectories", ")", ";", "$", "schema", "=", "$", "this", "->", "getSchemaForFiles", "(", "$", "definitionFileDirectories", ")", ";", "$", "definedTypes", "=", "$", "this", "->", "getDefinedTypesFromSchema", "(", "$", "schema", ",", "$", "definitionFileDirectories", ")", ";", "$", "queries", "=", "$", "this", "->", "generateQueriesForDefinedTypes", "(", "$", "definedTypes", ",", "$", "definitionFileDirectories", ")", ";", "$", "typesImports", "=", "$", "this", "->", "concatSchemaDefinitionFilesFromPath", "(", "$", "this", "->", "definitionsParser", "->", "getGraphqlDefinitionFilePaths", "(", "$", "definitionFileDirectories", "[", "'types'", "]", ")", ")", ";", "if", "(", "$", "authEnabled", ")", "{", "event", "(", "new", "GraphQLSchemaGenerated", "(", "GraphQLSchema", "::", "all", "(", ")", ")", ")", ";", "}", "//Merge queries and types into one file with required newlines", "return", "sprintf", "(", "\"%s\\r\\n\\r\\n%s\\r\\n\"", ",", "$", "typesImports", ",", "$", "queries", ")", ";", "}" ]
Generates a schema from an array of definition file directories For now, this only supports Types. In the future it should also support Mutations and Queries. @param array $definitionFileDirectories @return string Generated Schema with Types and Queries @throws InvalidConfigurationException @throws \Nuwave\Lighthouse\Exceptions\DirectiveException @throws \Nuwave\Lighthouse\Exceptions\ParseException
[ "Generates", "a", "schema", "from", "an", "array", "of", "definition", "file", "directories", "For", "now", "this", "only", "supports", "Types", ".", "In", "the", "future", "it", "should", "also", "support", "Mutations", "and", "Queries", "." ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L86-L110
35,634
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.validateFilesPaths
private function validateFilesPaths(array $definitionFileDirectories): bool { if (count($definitionFileDirectories) < 1) { throw new InvalidConfigurationException( 'The "schema_paths" config value is empty, it should contain a value with a valid path for the following keys: mutations, queries, types' ); } if (array_diff(array_keys($definitionFileDirectories), $this->requiredSchemaFileKeys)) { throw new InvalidConfigurationException( 'The "schema_paths" config value is incomplete, it should contain a value with a valid path for the following keys: mutations, queries, types' ); } foreach ($definitionFileDirectories as $key => $path) { if (empty($path)) { throw new InvalidConfigurationException( sprintf( 'The "schema_paths" config value for key "%s" is empty, it should contain a value with a valid path', $key ) ); } if (! file_exists($path)) { throw new InvalidConfigurationException( sprintf('The "schema_paths" config value for key "%s" contains a path that does not exist', $key) ); } } return true; }
php
private function validateFilesPaths(array $definitionFileDirectories): bool { if (count($definitionFileDirectories) < 1) { throw new InvalidConfigurationException( 'The "schema_paths" config value is empty, it should contain a value with a valid path for the following keys: mutations, queries, types' ); } if (array_diff(array_keys($definitionFileDirectories), $this->requiredSchemaFileKeys)) { throw new InvalidConfigurationException( 'The "schema_paths" config value is incomplete, it should contain a value with a valid path for the following keys: mutations, queries, types' ); } foreach ($definitionFileDirectories as $key => $path) { if (empty($path)) { throw new InvalidConfigurationException( sprintf( 'The "schema_paths" config value for key "%s" is empty, it should contain a value with a valid path', $key ) ); } if (! file_exists($path)) { throw new InvalidConfigurationException( sprintf('The "schema_paths" config value for key "%s" contains a path that does not exist', $key) ); } } return true; }
[ "private", "function", "validateFilesPaths", "(", "array", "$", "definitionFileDirectories", ")", ":", "bool", "{", "if", "(", "count", "(", "$", "definitionFileDirectories", ")", "<", "1", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "'The \"schema_paths\" config value is empty, it should contain a value with a valid path for the following keys: mutations, queries, types'", ")", ";", "}", "if", "(", "array_diff", "(", "array_keys", "(", "$", "definitionFileDirectories", ")", ",", "$", "this", "->", "requiredSchemaFileKeys", ")", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "'The \"schema_paths\" config value is incomplete, it should contain a value with a valid path for the following keys: mutations, queries, types'", ")", ";", "}", "foreach", "(", "$", "definitionFileDirectories", "as", "$", "key", "=>", "$", "path", ")", "{", "if", "(", "empty", "(", "$", "path", ")", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "sprintf", "(", "'The \"schema_paths\" config value for key \"%s\" is empty, it should contain a value with a valid path'", ",", "$", "key", ")", ")", ";", "}", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "sprintf", "(", "'The \"schema_paths\" config value for key \"%s\" contains a path that does not exist'", ",", "$", "key", ")", ")", ";", "}", "}", "return", "true", ";", "}" ]
Validates if the given defintionFileDirectories contains; - All required keys - Filled values for each key - Existing paths for each key @param array $definitionFileDirectories @return bool @throws InvalidConfigurationException
[ "Validates", "if", "the", "given", "defintionFileDirectories", "contains", ";", "-", "All", "required", "keys", "-", "Filled", "values", "for", "each", "key", "-", "Existing", "paths", "for", "each", "key" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L122-L153
35,635
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.getSchemaForFiles
private function getSchemaForFiles(array $definitionFileDirectories): Schema { resolve('events')->listen( BuildingAST::class, function () use ($definitionFileDirectories) { $typeDefinitionPaths = $this->definitionsParser->getGraphqlDefinitionFilePaths( $definitionFileDirectories['types'] ); $relativeTypeImports = $this->concatSchemaDefinitionFilesFromPath($typeDefinitionPaths); // Webonyx GraphQL will not generate a schema if there is not at least one query // So just pretend we have one $placeholderQuery = 'type Query{placeholder:String}'; return "$relativeTypeImports\r\n$placeholderQuery"; } ); $schema = graphql()->prepSchema(); return $schema; }
php
private function getSchemaForFiles(array $definitionFileDirectories): Schema { resolve('events')->listen( BuildingAST::class, function () use ($definitionFileDirectories) { $typeDefinitionPaths = $this->definitionsParser->getGraphqlDefinitionFilePaths( $definitionFileDirectories['types'] ); $relativeTypeImports = $this->concatSchemaDefinitionFilesFromPath($typeDefinitionPaths); // Webonyx GraphQL will not generate a schema if there is not at least one query // So just pretend we have one $placeholderQuery = 'type Query{placeholder:String}'; return "$relativeTypeImports\r\n$placeholderQuery"; } ); $schema = graphql()->prepSchema(); return $schema; }
[ "private", "function", "getSchemaForFiles", "(", "array", "$", "definitionFileDirectories", ")", ":", "Schema", "{", "resolve", "(", "'events'", ")", "->", "listen", "(", "BuildingAST", "::", "class", ",", "function", "(", ")", "use", "(", "$", "definitionFileDirectories", ")", "{", "$", "typeDefinitionPaths", "=", "$", "this", "->", "definitionsParser", "->", "getGraphqlDefinitionFilePaths", "(", "$", "definitionFileDirectories", "[", "'types'", "]", ")", ";", "$", "relativeTypeImports", "=", "$", "this", "->", "concatSchemaDefinitionFilesFromPath", "(", "$", "typeDefinitionPaths", ")", ";", "// Webonyx GraphQL will not generate a schema if there is not at least one query", "// So just pretend we have one", "$", "placeholderQuery", "=", "'type Query{placeholder:String}'", ";", "return", "\"$relativeTypeImports\\r\\n$placeholderQuery\"", ";", "}", ")", ";", "$", "schema", "=", "graphql", "(", ")", "->", "prepSchema", "(", ")", ";", "return", "$", "schema", ";", "}" ]
Generates a GraphQL schema for a set of definition files Definition files can only be Types at this time In the future this should also support Mutations and Queries @param array $definitionFileDirectories @return Schema @throws \Nuwave\Lighthouse\Exceptions\DirectiveException @throws \Nuwave\Lighthouse\Exceptions\ParseException
[ "Generates", "a", "GraphQL", "schema", "for", "a", "set", "of", "definition", "files", "Definition", "files", "can", "only", "be", "Types", "at", "this", "time", "In", "the", "future", "this", "should", "also", "support", "Mutations", "and", "Queries" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L165-L185
35,636
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.getDefinedTypesFromSchema
private function getDefinedTypesFromSchema(Schema $schema, array $definitionFileDirectories): array { $definedTypes = $this->definitionsParser->getGraphqlDefinitionFilePaths( $definitionFileDirectories['types'] ); foreach ($definedTypes as $key => $type) { $definedTypes[$key] = str_replace('.graphql', '', basename($type)); } $internalTypes = []; /** * @var string $typeName * @var ObjectType $type */ foreach ($schema->getTypeMap() as $typeName => $type) { if (! in_array($typeName, $definedTypes) || ! method_exists($type, 'getFields')) { continue; } /** * @var string $fieldName * @var FieldDefinition $fieldType */ foreach ($type->getFields() as $fieldName => $fieldType) { $graphQLType = $fieldType->getType(); //Every required field is defined by a parent 'NonNullType' if (method_exists($graphQLType, 'getWrappedType')) { // Clone the field to prevent pass by reference, // because we want to add a config value unique to this field. $graphQLType = clone $graphQLType->getWrappedType(); //We want to know later on wether or not a field is required $graphQLType->config['generator-required'] = true; } if (! in_array(get_class($graphQLType), $this->supportedGraphQLTypes)) { continue; }; // This retrieves the GraphQL type for this field from the webonyx/graphql-php package $internalTypes[$typeName][$fieldName] = $graphQLType; } } return $internalTypes; }
php
private function getDefinedTypesFromSchema(Schema $schema, array $definitionFileDirectories): array { $definedTypes = $this->definitionsParser->getGraphqlDefinitionFilePaths( $definitionFileDirectories['types'] ); foreach ($definedTypes as $key => $type) { $definedTypes[$key] = str_replace('.graphql', '', basename($type)); } $internalTypes = []; /** * @var string $typeName * @var ObjectType $type */ foreach ($schema->getTypeMap() as $typeName => $type) { if (! in_array($typeName, $definedTypes) || ! method_exists($type, 'getFields')) { continue; } /** * @var string $fieldName * @var FieldDefinition $fieldType */ foreach ($type->getFields() as $fieldName => $fieldType) { $graphQLType = $fieldType->getType(); //Every required field is defined by a parent 'NonNullType' if (method_exists($graphQLType, 'getWrappedType')) { // Clone the field to prevent pass by reference, // because we want to add a config value unique to this field. $graphQLType = clone $graphQLType->getWrappedType(); //We want to know later on wether or not a field is required $graphQLType->config['generator-required'] = true; } if (! in_array(get_class($graphQLType), $this->supportedGraphQLTypes)) { continue; }; // This retrieves the GraphQL type for this field from the webonyx/graphql-php package $internalTypes[$typeName][$fieldName] = $graphQLType; } } return $internalTypes; }
[ "private", "function", "getDefinedTypesFromSchema", "(", "Schema", "$", "schema", ",", "array", "$", "definitionFileDirectories", ")", ":", "array", "{", "$", "definedTypes", "=", "$", "this", "->", "definitionsParser", "->", "getGraphqlDefinitionFilePaths", "(", "$", "definitionFileDirectories", "[", "'types'", "]", ")", ";", "foreach", "(", "$", "definedTypes", "as", "$", "key", "=>", "$", "type", ")", "{", "$", "definedTypes", "[", "$", "key", "]", "=", "str_replace", "(", "'.graphql'", ",", "''", ",", "basename", "(", "$", "type", ")", ")", ";", "}", "$", "internalTypes", "=", "[", "]", ";", "/**\n * @var string $typeName\n * @var ObjectType $type\n */", "foreach", "(", "$", "schema", "->", "getTypeMap", "(", ")", "as", "$", "typeName", "=>", "$", "type", ")", "{", "if", "(", "!", "in_array", "(", "$", "typeName", ",", "$", "definedTypes", ")", "||", "!", "method_exists", "(", "$", "type", ",", "'getFields'", ")", ")", "{", "continue", ";", "}", "/**\n * @var string $fieldName\n * @var FieldDefinition $fieldType\n */", "foreach", "(", "$", "type", "->", "getFields", "(", ")", "as", "$", "fieldName", "=>", "$", "fieldType", ")", "{", "$", "graphQLType", "=", "$", "fieldType", "->", "getType", "(", ")", ";", "//Every required field is defined by a parent 'NonNullType'", "if", "(", "method_exists", "(", "$", "graphQLType", ",", "'getWrappedType'", ")", ")", "{", "// Clone the field to prevent pass by reference,", "// because we want to add a config value unique to this field.", "$", "graphQLType", "=", "clone", "$", "graphQLType", "->", "getWrappedType", "(", ")", ";", "//We want to know later on wether or not a field is required", "$", "graphQLType", "->", "config", "[", "'generator-required'", "]", "=", "true", ";", "}", "if", "(", "!", "in_array", "(", "get_class", "(", "$", "graphQLType", ")", ",", "$", "this", "->", "supportedGraphQLTypes", ")", ")", "{", "continue", ";", "}", ";", "// This retrieves the GraphQL type for this field from the webonyx/graphql-php package", "$", "internalTypes", "[", "$", "typeName", "]", "[", "$", "fieldName", "]", "=", "$", "graphQLType", ";", "}", "}", "return", "$", "internalTypes", ";", "}" ]
Parse defined types from a schema into an array with the native GraphQL Scalar types for each field @param Schema $schema @param array $definitionFileDirectories @return Type[]
[ "Parse", "defined", "types", "from", "a", "schema", "into", "an", "array", "with", "the", "native", "GraphQL", "Scalar", "types", "for", "each", "field" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L209-L256
35,637
deInternetJongens/Lighthouse-Utils
src/Generators/SchemaGenerator.php
SchemaGenerator.generateQueriesForDefinedTypes
private function generateQueriesForDefinedTypes(array $definedTypes, array $definitionFileDirectories): string { $queries = []; $mutations = []; $inputTypes = []; /** * @var string $typeName * @var Type $type */ foreach ($definedTypes as $typeName => $type) { $paginateAndAllQuery = PaginateAllQueryGenerator::generate($typeName, $type); if (! empty($paginateAndAllQuery)) { $queries[] = $paginateAndAllQuery; } $findQuery = FindQueryGenerator::generate($typeName, $type); if (! empty($findQuery)) { $queries[] = $findQuery; } $createMutation = createMutationWithInputTypeGenerator::generate($typeName, $type); if ($createMutation->isNotEmpty()) { $mutations[] = $createMutation->getMutation(); $inputTypes[] = $createMutation->getInputType(); } $updateMutation = updateMutationWithInputTypeGenerator::generate($typeName, $type); if ($updateMutation->isNotEmpty()) { $mutations[] = $updateMutation->getMutation(); $inputTypes[] = $updateMutation->getInputType(); } $deleteMutation = DeleteMutationGenerator::generate($typeName, $type); if (! empty($deleteMutation)) { $mutations[] = $deleteMutation; } } $queries = array_merge( $queries, $this->definitionsParser->parseCustomQueriesFrom($definitionFileDirectories['queries']) ); $mutations = array_merge( $mutations, $this->definitionsParser->parseCustomMutationsFrom($definitionFileDirectories['mutations']) ); $return = sprintf("type Query{\r\n%s\r\n}", implode("\r\n", $queries)); $return .= "\r\n\r\n"; $return .= sprintf("type Mutation{\r\n%s\r\n}", implode("\r\n", $mutations)); $return .= "\r\n\r\n"; $return .= implode("\r\n", $inputTypes); return $return; }
php
private function generateQueriesForDefinedTypes(array $definedTypes, array $definitionFileDirectories): string { $queries = []; $mutations = []; $inputTypes = []; /** * @var string $typeName * @var Type $type */ foreach ($definedTypes as $typeName => $type) { $paginateAndAllQuery = PaginateAllQueryGenerator::generate($typeName, $type); if (! empty($paginateAndAllQuery)) { $queries[] = $paginateAndAllQuery; } $findQuery = FindQueryGenerator::generate($typeName, $type); if (! empty($findQuery)) { $queries[] = $findQuery; } $createMutation = createMutationWithInputTypeGenerator::generate($typeName, $type); if ($createMutation->isNotEmpty()) { $mutations[] = $createMutation->getMutation(); $inputTypes[] = $createMutation->getInputType(); } $updateMutation = updateMutationWithInputTypeGenerator::generate($typeName, $type); if ($updateMutation->isNotEmpty()) { $mutations[] = $updateMutation->getMutation(); $inputTypes[] = $updateMutation->getInputType(); } $deleteMutation = DeleteMutationGenerator::generate($typeName, $type); if (! empty($deleteMutation)) { $mutations[] = $deleteMutation; } } $queries = array_merge( $queries, $this->definitionsParser->parseCustomQueriesFrom($definitionFileDirectories['queries']) ); $mutations = array_merge( $mutations, $this->definitionsParser->parseCustomMutationsFrom($definitionFileDirectories['mutations']) ); $return = sprintf("type Query{\r\n%s\r\n}", implode("\r\n", $queries)); $return .= "\r\n\r\n"; $return .= sprintf("type Mutation{\r\n%s\r\n}", implode("\r\n", $mutations)); $return .= "\r\n\r\n"; $return .= implode("\r\n", $inputTypes); return $return; }
[ "private", "function", "generateQueriesForDefinedTypes", "(", "array", "$", "definedTypes", ",", "array", "$", "definitionFileDirectories", ")", ":", "string", "{", "$", "queries", "=", "[", "]", ";", "$", "mutations", "=", "[", "]", ";", "$", "inputTypes", "=", "[", "]", ";", "/**\n * @var string $typeName\n * @var Type $type\n */", "foreach", "(", "$", "definedTypes", "as", "$", "typeName", "=>", "$", "type", ")", "{", "$", "paginateAndAllQuery", "=", "PaginateAllQueryGenerator", "::", "generate", "(", "$", "typeName", ",", "$", "type", ")", ";", "if", "(", "!", "empty", "(", "$", "paginateAndAllQuery", ")", ")", "{", "$", "queries", "[", "]", "=", "$", "paginateAndAllQuery", ";", "}", "$", "findQuery", "=", "FindQueryGenerator", "::", "generate", "(", "$", "typeName", ",", "$", "type", ")", ";", "if", "(", "!", "empty", "(", "$", "findQuery", ")", ")", "{", "$", "queries", "[", "]", "=", "$", "findQuery", ";", "}", "$", "createMutation", "=", "createMutationWithInputTypeGenerator", "::", "generate", "(", "$", "typeName", ",", "$", "type", ")", ";", "if", "(", "$", "createMutation", "->", "isNotEmpty", "(", ")", ")", "{", "$", "mutations", "[", "]", "=", "$", "createMutation", "->", "getMutation", "(", ")", ";", "$", "inputTypes", "[", "]", "=", "$", "createMutation", "->", "getInputType", "(", ")", ";", "}", "$", "updateMutation", "=", "updateMutationWithInputTypeGenerator", "::", "generate", "(", "$", "typeName", ",", "$", "type", ")", ";", "if", "(", "$", "updateMutation", "->", "isNotEmpty", "(", ")", ")", "{", "$", "mutations", "[", "]", "=", "$", "updateMutation", "->", "getMutation", "(", ")", ";", "$", "inputTypes", "[", "]", "=", "$", "updateMutation", "->", "getInputType", "(", ")", ";", "}", "$", "deleteMutation", "=", "DeleteMutationGenerator", "::", "generate", "(", "$", "typeName", ",", "$", "type", ")", ";", "if", "(", "!", "empty", "(", "$", "deleteMutation", ")", ")", "{", "$", "mutations", "[", "]", "=", "$", "deleteMutation", ";", "}", "}", "$", "queries", "=", "array_merge", "(", "$", "queries", ",", "$", "this", "->", "definitionsParser", "->", "parseCustomQueriesFrom", "(", "$", "definitionFileDirectories", "[", "'queries'", "]", ")", ")", ";", "$", "mutations", "=", "array_merge", "(", "$", "mutations", ",", "$", "this", "->", "definitionsParser", "->", "parseCustomMutationsFrom", "(", "$", "definitionFileDirectories", "[", "'mutations'", "]", ")", ")", ";", "$", "return", "=", "sprintf", "(", "\"type Query{\\r\\n%s\\r\\n}\"", ",", "implode", "(", "\"\\r\\n\"", ",", "$", "queries", ")", ")", ";", "$", "return", ".=", "\"\\r\\n\\r\\n\"", ";", "$", "return", ".=", "sprintf", "(", "\"type Mutation{\\r\\n%s\\r\\n}\"", ",", "implode", "(", "\"\\r\\n\"", ",", "$", "mutations", ")", ")", ";", "$", "return", ".=", "\"\\r\\n\\r\\n\"", ";", "$", "return", ".=", "implode", "(", "\"\\r\\n\"", ",", "$", "inputTypes", ")", ";", "return", "$", "return", ";", "}" ]
Auto-generates a query for each definedType These queries contain arguments for each field defined in the Type @param array $definedTypes @param array $definitionFileDirectories @return string
[ "Auto", "-", "generates", "a", "query", "for", "each", "definedType", "These", "queries", "contain", "arguments", "for", "each", "field", "defined", "in", "the", "Type" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/SchemaGenerator.php#L266-L323
35,638
deInternetJongens/Lighthouse-Utils
src/Generators/Arguments/RelationArgumentGenerator.php
RelationArgumentGenerator.generate
public static function generate(array $typeFields): array { $arguments = []; foreach ($typeFields as $fieldName => $field) { $config = $field->config; $required = isset($config['generator-required']) ? ($config['generator-required'] ? '!' : '') : ''; $className = get_class($field); if ($className !== ObjectType::class) { continue; } $arguments[] = sprintf('%s_id: ID%s', $fieldName, $required); } return $arguments; }
php
public static function generate(array $typeFields): array { $arguments = []; foreach ($typeFields as $fieldName => $field) { $config = $field->config; $required = isset($config['generator-required']) ? ($config['generator-required'] ? '!' : '') : ''; $className = get_class($field); if ($className !== ObjectType::class) { continue; } $arguments[] = sprintf('%s_id: ID%s', $fieldName, $required); } return $arguments; }
[ "public", "static", "function", "generate", "(", "array", "$", "typeFields", ")", ":", "array", "{", "$", "arguments", "=", "[", "]", ";", "foreach", "(", "$", "typeFields", "as", "$", "fieldName", "=>", "$", "field", ")", "{", "$", "config", "=", "$", "field", "->", "config", ";", "$", "required", "=", "isset", "(", "$", "config", "[", "'generator-required'", "]", ")", "?", "(", "$", "config", "[", "'generator-required'", "]", "?", "'!'", ":", "''", ")", ":", "''", ";", "$", "className", "=", "get_class", "(", "$", "field", ")", ";", "if", "(", "$", "className", "!==", "ObjectType", "::", "class", ")", "{", "continue", ";", "}", "$", "arguments", "[", "]", "=", "sprintf", "(", "'%s_id: ID%s'", ",", "$", "fieldName", ",", "$", "required", ")", ";", "}", "return", "$", "arguments", ";", "}" ]
Generates a GraphQL mutation argument for a relation field @param Type[] $typeFields @param bool $required Should the relationship fields be required? @return array
[ "Generates", "a", "GraphQL", "mutation", "argument", "for", "a", "relation", "field" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/Arguments/RelationArgumentGenerator.php#L17-L34
35,639
deInternetJongens/Lighthouse-Utils
src/Generators/Queries/FindQueryGenerator.php
FindQueryGenerator.generate
public static function generate(string $typeName, array $typeFields): string { $arguments = []; //Loop through fields to find the 'ID' field. foreach ($typeFields as $fieldName => $field) { if (false === ($field instanceof IDType)) { continue; } $arguments[] = sprintf('%s: %s! @eq', $fieldName, $field->name); break; } if (count($arguments) < 1) { return ''; } $queryName = lcfirst($typeName); $query = sprintf(' %s(%s)', $queryName, implode(', ', $arguments)); $query .= sprintf(': %1$s @find(model: "%1$s")', $typeName); if (config('lighthouse-utils.authorization')) { $permission = sprintf('find%1$s', $typeName); $query .= sprintf(' @can(if: "%1$s", model: "User")', $permission); } GraphQLSchema::register($queryName, $typeName, 'query', $permission ?? null); return $query; }
php
public static function generate(string $typeName, array $typeFields): string { $arguments = []; //Loop through fields to find the 'ID' field. foreach ($typeFields as $fieldName => $field) { if (false === ($field instanceof IDType)) { continue; } $arguments[] = sprintf('%s: %s! @eq', $fieldName, $field->name); break; } if (count($arguments) < 1) { return ''; } $queryName = lcfirst($typeName); $query = sprintf(' %s(%s)', $queryName, implode(', ', $arguments)); $query .= sprintf(': %1$s @find(model: "%1$s")', $typeName); if (config('lighthouse-utils.authorization')) { $permission = sprintf('find%1$s', $typeName); $query .= sprintf(' @can(if: "%1$s", model: "User")', $permission); } GraphQLSchema::register($queryName, $typeName, 'query', $permission ?? null); return $query; }
[ "public", "static", "function", "generate", "(", "string", "$", "typeName", ",", "array", "$", "typeFields", ")", ":", "string", "{", "$", "arguments", "=", "[", "]", ";", "//Loop through fields to find the 'ID' field.", "foreach", "(", "$", "typeFields", "as", "$", "fieldName", "=>", "$", "field", ")", "{", "if", "(", "false", "===", "(", "$", "field", "instanceof", "IDType", ")", ")", "{", "continue", ";", "}", "$", "arguments", "[", "]", "=", "sprintf", "(", "'%s: %s! @eq'", ",", "$", "fieldName", ",", "$", "field", "->", "name", ")", ";", "break", ";", "}", "if", "(", "count", "(", "$", "arguments", ")", "<", "1", ")", "{", "return", "''", ";", "}", "$", "queryName", "=", "lcfirst", "(", "$", "typeName", ")", ";", "$", "query", "=", "sprintf", "(", "' %s(%s)'", ",", "$", "queryName", ",", "implode", "(", "', '", ",", "$", "arguments", ")", ")", ";", "$", "query", ".=", "sprintf", "(", "': %1$s @find(model: \"%1$s\")'", ",", "$", "typeName", ")", ";", "if", "(", "config", "(", "'lighthouse-utils.authorization'", ")", ")", "{", "$", "permission", "=", "sprintf", "(", "'find%1$s'", ",", "$", "typeName", ")", ";", "$", "query", ".=", "sprintf", "(", "' @can(if: \"%1$s\", model: \"User\")'", ",", "$", "permission", ")", ";", "}", "GraphQLSchema", "::", "register", "(", "$", "queryName", ",", "$", "typeName", ",", "'query'", ",", "$", "permission", "??", "null", ")", ";", "return", "$", "query", ";", "}" ]
Generates a GraphQL query that returns one entity by ID @param string $typeName @param Type[] $typeFields @return string
[ "Generates", "a", "GraphQL", "query", "that", "returns", "one", "entity", "by", "ID" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/Queries/FindQueryGenerator.php#L18-L48
35,640
deInternetJongens/Lighthouse-Utils
src/Generators/Mutations/CreateMutationGenerator.php
CreateMutationGenerator.generate
public static function generate(string $typeName, array $typeFields): string { $mutationName = 'create' . $typeName; $arguments = RelationArgumentGenerator::generate($typeFields); $arguments = array_merge($arguments, InputFieldsArgumentGenerator::generate($typeFields)); if (count($arguments) < 1) { return ''; } $mutation = sprintf(' %s(%s)', $mutationName, implode(', ', $arguments)); $mutation .= sprintf(': %1$s @create(model: "%1$s")', $typeName); if (config('lighthouse-utils.authorization')) { $permission = sprintf('create%1$s', $typeName); $mutation .= sprintf(' @can(if: "%1$s", model: "User")', $permission); } GraphQLSchema::register($mutationName, $typeName, 'mutation', $permission ?? null); return $mutation; }
php
public static function generate(string $typeName, array $typeFields): string { $mutationName = 'create' . $typeName; $arguments = RelationArgumentGenerator::generate($typeFields); $arguments = array_merge($arguments, InputFieldsArgumentGenerator::generate($typeFields)); if (count($arguments) < 1) { return ''; } $mutation = sprintf(' %s(%s)', $mutationName, implode(', ', $arguments)); $mutation .= sprintf(': %1$s @create(model: "%1$s")', $typeName); if (config('lighthouse-utils.authorization')) { $permission = sprintf('create%1$s', $typeName); $mutation .= sprintf(' @can(if: "%1$s", model: "User")', $permission); } GraphQLSchema::register($mutationName, $typeName, 'mutation', $permission ?? null); return $mutation; }
[ "public", "static", "function", "generate", "(", "string", "$", "typeName", ",", "array", "$", "typeFields", ")", ":", "string", "{", "$", "mutationName", "=", "'create'", ".", "$", "typeName", ";", "$", "arguments", "=", "RelationArgumentGenerator", "::", "generate", "(", "$", "typeFields", ")", ";", "$", "arguments", "=", "array_merge", "(", "$", "arguments", ",", "InputFieldsArgumentGenerator", "::", "generate", "(", "$", "typeFields", ")", ")", ";", "if", "(", "count", "(", "$", "arguments", ")", "<", "1", ")", "{", "return", "''", ";", "}", "$", "mutation", "=", "sprintf", "(", "' %s(%s)'", ",", "$", "mutationName", ",", "implode", "(", "', '", ",", "$", "arguments", ")", ")", ";", "$", "mutation", ".=", "sprintf", "(", "': %1$s @create(model: \"%1$s\")'", ",", "$", "typeName", ")", ";", "if", "(", "config", "(", "'lighthouse-utils.authorization'", ")", ")", "{", "$", "permission", "=", "sprintf", "(", "'create%1$s'", ",", "$", "typeName", ")", ";", "$", "mutation", ".=", "sprintf", "(", "' @can(if: \"%1$s\", model: \"User\")'", ",", "$", "permission", ")", ";", "}", "GraphQLSchema", "::", "register", "(", "$", "mutationName", ",", "$", "typeName", ",", "'mutation'", ",", "$", "permission", "??", "null", ")", ";", "return", "$", "mutation", ";", "}" ]
Generates a GraphQL Mutation to create a record @param string $typeName @param Type[] $typeFields @return string
[ "Generates", "a", "GraphQL", "Mutation", "to", "create", "a", "record" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/Mutations/CreateMutationGenerator.php#L18-L40
35,641
deInternetJongens/Lighthouse-Utils
src/Generators/Mutations/UpdateMutationWithInputTypeGenerator.php
UpdateMutationWithInputTypeGenerator.generate
public static function generate(string $typeName, array $typeFields): MutationWithInput { $mutationName = 'update' . $typeName; $inputTypeName = sprintf('update%sInput', ucfirst($typeName)); $inputType = InputTypeArgumentGenerator::generate($inputTypeName, $typeFields, true); if (empty($inputType)) { return new MutationWithInput('', ''); } $mutation = sprintf(' %s(input: %s!)', $mutationName, $inputTypeName); $mutation .= sprintf(': %1$s @update(model: "%1$s", flatten: true)', $typeName); if (config('lighthouse-utils.authorization')) { $permission = sprintf('update%1$s', $typeName); $mutation .= sprintf(' @can(if: "%1$s", model: "User")', $permission); } GraphQLSchema::register($mutationName, $typeName, 'mutation', $permission ?? null); return new MutationWithInput($mutation, $inputType); }
php
public static function generate(string $typeName, array $typeFields): MutationWithInput { $mutationName = 'update' . $typeName; $inputTypeName = sprintf('update%sInput', ucfirst($typeName)); $inputType = InputTypeArgumentGenerator::generate($inputTypeName, $typeFields, true); if (empty($inputType)) { return new MutationWithInput('', ''); } $mutation = sprintf(' %s(input: %s!)', $mutationName, $inputTypeName); $mutation .= sprintf(': %1$s @update(model: "%1$s", flatten: true)', $typeName); if (config('lighthouse-utils.authorization')) { $permission = sprintf('update%1$s', $typeName); $mutation .= sprintf(' @can(if: "%1$s", model: "User")', $permission); } GraphQLSchema::register($mutationName, $typeName, 'mutation', $permission ?? null); return new MutationWithInput($mutation, $inputType); }
[ "public", "static", "function", "generate", "(", "string", "$", "typeName", ",", "array", "$", "typeFields", ")", ":", "MutationWithInput", "{", "$", "mutationName", "=", "'update'", ".", "$", "typeName", ";", "$", "inputTypeName", "=", "sprintf", "(", "'update%sInput'", ",", "ucfirst", "(", "$", "typeName", ")", ")", ";", "$", "inputType", "=", "InputTypeArgumentGenerator", "::", "generate", "(", "$", "inputTypeName", ",", "$", "typeFields", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "inputType", ")", ")", "{", "return", "new", "MutationWithInput", "(", "''", ",", "''", ")", ";", "}", "$", "mutation", "=", "sprintf", "(", "' %s(input: %s!)'", ",", "$", "mutationName", ",", "$", "inputTypeName", ")", ";", "$", "mutation", ".=", "sprintf", "(", "': %1$s @update(model: \"%1$s\", flatten: true)'", ",", "$", "typeName", ")", ";", "if", "(", "config", "(", "'lighthouse-utils.authorization'", ")", ")", "{", "$", "permission", "=", "sprintf", "(", "'update%1$s'", ",", "$", "typeName", ")", ";", "$", "mutation", ".=", "sprintf", "(", "' @can(if: \"%1$s\", model: \"User\")'", ",", "$", "permission", ")", ";", "}", "GraphQLSchema", "::", "register", "(", "$", "mutationName", ",", "$", "typeName", ",", "'mutation'", ",", "$", "permission", "??", "null", ")", ";", "return", "new", "MutationWithInput", "(", "$", "mutation", ",", "$", "inputType", ")", ";", "}" ]
Generates a GraphQL Mutation to update a record @param string $typeName @param Type[] $typeFields @return MutationWithInput
[ "Generates", "a", "GraphQL", "Mutation", "to", "update", "a", "record" ]
31cd7ffe225f4639f3ecf2fd40c4e6835a145dda
https://github.com/deInternetJongens/Lighthouse-Utils/blob/31cd7ffe225f4639f3ecf2fd40c4e6835a145dda/src/Generators/Mutations/UpdateMutationWithInputTypeGenerator.php#L18-L39
35,642
RWOverdijk/AssetManager
src/AssetManager/Service/MimeResolver.php
MimeResolver.getMimeType
public function getMimeType($filename) { $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (isset($this->mimeTypes[$extension])) { return $this->mimeTypes[$extension]; } return 'text/plain'; }
php
public function getMimeType($filename) { $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (isset($this->mimeTypes[$extension])) { return $this->mimeTypes[$extension]; } return 'text/plain'; }
[ "public", "function", "getMimeType", "(", "$", "filename", ")", "{", "$", "extension", "=", "strtolower", "(", "pathinfo", "(", "$", "filename", ",", "PATHINFO_EXTENSION", ")", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "mimeTypes", "[", "$", "extension", "]", ")", ")", "{", "return", "$", "this", "->", "mimeTypes", "[", "$", "extension", "]", ";", "}", "return", "'text/plain'", ";", "}" ]
Get the mime type from a file extension. @param string $filename @return string The mime type found. Falls back to text/plain.
[ "Get", "the", "mime", "type", "from", "a", "file", "extension", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Service/MimeResolver.php#L564-L573
35,643
RWOverdijk/AssetManager
src/AssetManager/Service/MimeResolver.php
MimeResolver.getExtension
public function getExtension($mimetype) { if (!($extension = array_search($mimetype, $this->mainMimeTypes))) { $extension = array_search($mimetype, $this->mimeTypes); } return !$extension ? null : $extension; }
php
public function getExtension($mimetype) { if (!($extension = array_search($mimetype, $this->mainMimeTypes))) { $extension = array_search($mimetype, $this->mimeTypes); } return !$extension ? null : $extension; }
[ "public", "function", "getExtension", "(", "$", "mimetype", ")", "{", "if", "(", "!", "(", "$", "extension", "=", "array_search", "(", "$", "mimetype", ",", "$", "this", "->", "mainMimeTypes", ")", ")", ")", "{", "$", "extension", "=", "array_search", "(", "$", "mimetype", ",", "$", "this", "->", "mimeTypes", ")", ";", "}", "return", "!", "$", "extension", "?", "null", ":", "$", "extension", ";", "}" ]
Get the extension that matches given mimetype. @param string $mimetype @return mixed null when not found, extension (string) when found.
[ "Get", "the", "extension", "that", "matches", "given", "mimetype", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Service/MimeResolver.php#L581-L588
35,644
loveorigami/yii2-notification-wrapper
src/Wrapper.php
Wrapper.init
public function init() { parent::init(); $this->url = Yii::$app->getUrlManager()->createUrl(['noty/default/index']); if (!$this->layerClass) { $this->layerClass = self::DEFAULT_LAYER; } }
php
public function init() { parent::init(); $this->url = Yii::$app->getUrlManager()->createUrl(['noty/default/index']); if (!$this->layerClass) { $this->layerClass = self::DEFAULT_LAYER; } }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "$", "this", "->", "url", "=", "Yii", "::", "$", "app", "->", "getUrlManager", "(", ")", "->", "createUrl", "(", "[", "'noty/default/index'", "]", ")", ";", "if", "(", "!", "$", "this", "->", "layerClass", ")", "{", "$", "this", "->", "layerClass", "=", "self", "::", "DEFAULT_LAYER", ";", "}", "}" ]
init layer class
[ "init", "layer", "class" ]
544c5a34b33799e0f0f0882e1163273bd12728e0
https://github.com/loveorigami/yii2-notification-wrapper/blob/544c5a34b33799e0f0f0882e1163273bd12728e0/src/Wrapper.php#L70-L79
35,645
loveorigami/yii2-notification-wrapper
src/Wrapper.php
Wrapper.registerJs
protected function registerJs() { $config['options'] = $this->options; $config['layerOptions'] = $this->layerOptions; $config['layerOptions']['layerId'] = $this->layer->getLayerId(); $config = Json::encode($config); $layerClass = Json::encode($this->layerClass); $this->view->registerJs(" $.ajaxSetup({ showNoty: true // default for all ajax calls }); $(document).ajaxComplete(function (event, xhr, settings) { if (settings.showNoty && (settings.type=='POST' || settings.container)) { $.ajax({ url: '$this->url', method: 'POST', cache: false, showNoty: false, global: false, data: { layerClass: '$layerClass', config: '$config' }, success: function(data) { $('#" . $this->layer->getLayerId() . "').html(data); } }); } }); ", View::POS_END); }
php
protected function registerJs() { $config['options'] = $this->options; $config['layerOptions'] = $this->layerOptions; $config['layerOptions']['layerId'] = $this->layer->getLayerId(); $config = Json::encode($config); $layerClass = Json::encode($this->layerClass); $this->view->registerJs(" $.ajaxSetup({ showNoty: true // default for all ajax calls }); $(document).ajaxComplete(function (event, xhr, settings) { if (settings.showNoty && (settings.type=='POST' || settings.container)) { $.ajax({ url: '$this->url', method: 'POST', cache: false, showNoty: false, global: false, data: { layerClass: '$layerClass', config: '$config' }, success: function(data) { $('#" . $this->layer->getLayerId() . "').html(data); } }); } }); ", View::POS_END); }
[ "protected", "function", "registerJs", "(", ")", "{", "$", "config", "[", "'options'", "]", "=", "$", "this", "->", "options", ";", "$", "config", "[", "'layerOptions'", "]", "=", "$", "this", "->", "layerOptions", ";", "$", "config", "[", "'layerOptions'", "]", "[", "'layerId'", "]", "=", "$", "this", "->", "layer", "->", "getLayerId", "(", ")", ";", "$", "config", "=", "Json", "::", "encode", "(", "$", "config", ")", ";", "$", "layerClass", "=", "Json", "::", "encode", "(", "$", "this", "->", "layerClass", ")", ";", "$", "this", "->", "view", "->", "registerJs", "(", "\"\n $.ajaxSetup({\n showNoty: true // default for all ajax calls\n });\n $(document).ajaxComplete(function (event, xhr, settings) {\n if (settings.showNoty && (settings.type=='POST' || settings.container)) {\n $.ajax({\n url: '$this->url',\n method: 'POST',\n cache: false,\n showNoty: false,\n global: false,\n data: {\n layerClass: '$layerClass',\n config: '$config'\n },\n success: function(data) {\n $('#\"", ".", "$", "this", "->", "layer", "->", "getLayerId", "(", ")", ".", "\"').html(data);\n }\n });\n }\n });\n \"", ",", "View", "::", "POS_END", ")", ";", "}" ]
Register js for ajax notifications
[ "Register", "js", "for", "ajax", "notifications" ]
544c5a34b33799e0f0f0882e1163273bd12728e0
https://github.com/loveorigami/yii2-notification-wrapper/blob/544c5a34b33799e0f0f0882e1163273bd12728e0/src/Wrapper.php#L157-L189
35,646
RWOverdijk/AssetManager
src/AssetManager/Service/AssetFilterManager.php
AssetFilterManager.ensureByService
protected function ensureByService(AssetInterface $asset, $service) { if (is_string($service)) { $this->ensureByFilter($asset, $this->getServiceLocator()->get($service)); } else { throw new Exception\RuntimeException( 'Unexpected service provided. Expected string or callback.' ); } }
php
protected function ensureByService(AssetInterface $asset, $service) { if (is_string($service)) { $this->ensureByFilter($asset, $this->getServiceLocator()->get($service)); } else { throw new Exception\RuntimeException( 'Unexpected service provided. Expected string or callback.' ); } }
[ "protected", "function", "ensureByService", "(", "AssetInterface", "$", "asset", ",", "$", "service", ")", "{", "if", "(", "is_string", "(", "$", "service", ")", ")", "{", "$", "this", "->", "ensureByFilter", "(", "$", "asset", ",", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "$", "service", ")", ")", ";", "}", "else", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "'Unexpected service provided. Expected string or callback.'", ")", ";", "}", "}" ]
Ensure that the filters as service are set. @param AssetInterface $asset @param string $service A valid service name. @throws Exception\RuntimeException
[ "Ensure", "that", "the", "filters", "as", "service", "are", "set", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Service/AssetFilterManager.php#L112-L121
35,647
RWOverdijk/AssetManager
src/AssetManager/Service/AssetFilterManager.php
AssetFilterManager.ensureByFilter
protected function ensureByFilter(AssetInterface $asset, $filter) { if ($filter instanceof FilterInterface) { $filterInstance = $filter; $asset->ensureFilter($filterInstance); return; } $filterClass = $filter; if (!is_subclass_of($filterClass, 'Assetic\Filter\FilterInterface', true)) { $filterClass .= (substr($filterClass, -6) === 'Filter') ? '' : 'Filter'; $filterClass = 'Assetic\Filter\\' . $filterClass; } if (!class_exists($filterClass)) { throw new Exception\RuntimeException( 'No filter found for ' . $filter ); } if (!isset($this->filterInstances[$filterClass])) { $this->filterInstances[$filterClass] = new $filterClass(); } $filterInstance = $this->filterInstances[$filterClass]; $asset->ensureFilter($filterInstance); }
php
protected function ensureByFilter(AssetInterface $asset, $filter) { if ($filter instanceof FilterInterface) { $filterInstance = $filter; $asset->ensureFilter($filterInstance); return; } $filterClass = $filter; if (!is_subclass_of($filterClass, 'Assetic\Filter\FilterInterface', true)) { $filterClass .= (substr($filterClass, -6) === 'Filter') ? '' : 'Filter'; $filterClass = 'Assetic\Filter\\' . $filterClass; } if (!class_exists($filterClass)) { throw new Exception\RuntimeException( 'No filter found for ' . $filter ); } if (!isset($this->filterInstances[$filterClass])) { $this->filterInstances[$filterClass] = new $filterClass(); } $filterInstance = $this->filterInstances[$filterClass]; $asset->ensureFilter($filterInstance); }
[ "protected", "function", "ensureByFilter", "(", "AssetInterface", "$", "asset", ",", "$", "filter", ")", "{", "if", "(", "$", "filter", "instanceof", "FilterInterface", ")", "{", "$", "filterInstance", "=", "$", "filter", ";", "$", "asset", "->", "ensureFilter", "(", "$", "filterInstance", ")", ";", "return", ";", "}", "$", "filterClass", "=", "$", "filter", ";", "if", "(", "!", "is_subclass_of", "(", "$", "filterClass", ",", "'Assetic\\Filter\\FilterInterface'", ",", "true", ")", ")", "{", "$", "filterClass", ".=", "(", "substr", "(", "$", "filterClass", ",", "-", "6", ")", "===", "'Filter'", ")", "?", "''", ":", "'Filter'", ";", "$", "filterClass", "=", "'Assetic\\Filter\\\\'", ".", "$", "filterClass", ";", "}", "if", "(", "!", "class_exists", "(", "$", "filterClass", ")", ")", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "'No filter found for '", ".", "$", "filter", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "filterInstances", "[", "$", "filterClass", "]", ")", ")", "{", "$", "this", "->", "filterInstances", "[", "$", "filterClass", "]", "=", "new", "$", "filterClass", "(", ")", ";", "}", "$", "filterInstance", "=", "$", "this", "->", "filterInstances", "[", "$", "filterClass", "]", ";", "$", "asset", "->", "ensureFilter", "(", "$", "filterInstance", ")", ";", "}" ]
Ensure that the filters as filter are set. @param AssetInterface $asset @param mixed $filter Either an instance of FilterInterface or a classname. @throws Exception\RuntimeException
[ "Ensure", "that", "the", "filters", "as", "filter", "are", "set", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Service/AssetFilterManager.php#L130-L159
35,648
loveorigami/yii2-notification-wrapper
src/layers/Layer.php
Layer.setTitle
public function setTitle() { switch ($this->type) { case self::TYPE_ERROR: $t = Yii::t('noty', 'Error'); break; case self::TYPE_INFO: $t = Yii::t('noty', 'Info'); break; case self::TYPE_WARNING: $t = Yii::t('noty', 'Warning'); break; case self::TYPE_SUCCESS: $t = Yii::t('noty', 'Success'); break; default: $t = ''; } $this->title = $this->showTitle ? $t : ''; }
php
public function setTitle() { switch ($this->type) { case self::TYPE_ERROR: $t = Yii::t('noty', 'Error'); break; case self::TYPE_INFO: $t = Yii::t('noty', 'Info'); break; case self::TYPE_WARNING: $t = Yii::t('noty', 'Warning'); break; case self::TYPE_SUCCESS: $t = Yii::t('noty', 'Success'); break; default: $t = ''; } $this->title = $this->showTitle ? $t : ''; }
[ "public", "function", "setTitle", "(", ")", "{", "switch", "(", "$", "this", "->", "type", ")", "{", "case", "self", "::", "TYPE_ERROR", ":", "$", "t", "=", "Yii", "::", "t", "(", "'noty'", ",", "'Error'", ")", ";", "break", ";", "case", "self", "::", "TYPE_INFO", ":", "$", "t", "=", "Yii", "::", "t", "(", "'noty'", ",", "'Info'", ")", ";", "break", ";", "case", "self", "::", "TYPE_WARNING", ":", "$", "t", "=", "Yii", "::", "t", "(", "'noty'", ",", "'Warning'", ")", ";", "break", ";", "case", "self", "::", "TYPE_SUCCESS", ":", "$", "t", "=", "Yii", "::", "t", "(", "'noty'", ",", "'Success'", ")", ";", "break", ";", "default", ":", "$", "t", "=", "''", ";", "}", "$", "this", "->", "title", "=", "$", "this", "->", "showTitle", "?", "$", "t", ":", "''", ";", "}" ]
set title by type
[ "set", "title", "by", "type" ]
544c5a34b33799e0f0f0882e1163273bd12728e0
https://github.com/loveorigami/yii2-notification-wrapper/blob/544c5a34b33799e0f0f0882e1163273bd12728e0/src/layers/Layer.php#L113-L133
35,649
RWOverdijk/AssetManager
src/AssetManager/Cache/FilePathCache.php
FilePathCache.cachedFile
protected function cachedFile() { if (null === $this->cachedFile) { $this->cachedFile = rtrim($this->dir, '/') . '/' . ltrim($this->filename, '/'); } return $this->cachedFile; }
php
protected function cachedFile() { if (null === $this->cachedFile) { $this->cachedFile = rtrim($this->dir, '/') . '/' . ltrim($this->filename, '/'); } return $this->cachedFile; }
[ "protected", "function", "cachedFile", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "cachedFile", ")", "{", "$", "this", "->", "cachedFile", "=", "rtrim", "(", "$", "this", "->", "dir", ",", "'/'", ")", ".", "'/'", ".", "ltrim", "(", "$", "this", "->", "filename", ",", "'/'", ")", ";", "}", "return", "$", "this", "->", "cachedFile", ";", "}" ]
Get the path-to-file. @return string Cache path
[ "Get", "the", "path", "-", "to", "-", "file", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Cache/FilePathCache.php#L122-L129
35,650
RWOverdijk/AssetManager
src/AssetManager/Service/AssetCacheManager.php
AssetCacheManager.getProvider
private function getProvider($path) { $cacheProvider = $this->getCacheProviderConfig($path); if (!$cacheProvider) { return null; } if (is_string($cacheProvider['cache']) && $this->serviceLocator->has($cacheProvider['cache']) ) { return $this->serviceLocator->get($cacheProvider['cache']); } // Left here for BC. Please consider defining a ZF2 service instead. if (is_callable($cacheProvider['cache'])) { return call_user_func($cacheProvider['cache'], $path); } $dir = ''; $class = $cacheProvider['cache']; if (!empty($cacheProvider['options']['dir'])) { $dir = $cacheProvider['options']['dir']; } $class = $this->classMapper($class); return new $class($dir, $path); }
php
private function getProvider($path) { $cacheProvider = $this->getCacheProviderConfig($path); if (!$cacheProvider) { return null; } if (is_string($cacheProvider['cache']) && $this->serviceLocator->has($cacheProvider['cache']) ) { return $this->serviceLocator->get($cacheProvider['cache']); } // Left here for BC. Please consider defining a ZF2 service instead. if (is_callable($cacheProvider['cache'])) { return call_user_func($cacheProvider['cache'], $path); } $dir = ''; $class = $cacheProvider['cache']; if (!empty($cacheProvider['options']['dir'])) { $dir = $cacheProvider['options']['dir']; } $class = $this->classMapper($class); return new $class($dir, $path); }
[ "private", "function", "getProvider", "(", "$", "path", ")", "{", "$", "cacheProvider", "=", "$", "this", "->", "getCacheProviderConfig", "(", "$", "path", ")", ";", "if", "(", "!", "$", "cacheProvider", ")", "{", "return", "null", ";", "}", "if", "(", "is_string", "(", "$", "cacheProvider", "[", "'cache'", "]", ")", "&&", "$", "this", "->", "serviceLocator", "->", "has", "(", "$", "cacheProvider", "[", "'cache'", "]", ")", ")", "{", "return", "$", "this", "->", "serviceLocator", "->", "get", "(", "$", "cacheProvider", "[", "'cache'", "]", ")", ";", "}", "// Left here for BC. Please consider defining a ZF2 service instead.", "if", "(", "is_callable", "(", "$", "cacheProvider", "[", "'cache'", "]", ")", ")", "{", "return", "call_user_func", "(", "$", "cacheProvider", "[", "'cache'", "]", ",", "$", "path", ")", ";", "}", "$", "dir", "=", "''", ";", "$", "class", "=", "$", "cacheProvider", "[", "'cache'", "]", ";", "if", "(", "!", "empty", "(", "$", "cacheProvider", "[", "'options'", "]", "[", "'dir'", "]", ")", ")", "{", "$", "dir", "=", "$", "cacheProvider", "[", "'options'", "]", "[", "'dir'", "]", ";", "}", "$", "class", "=", "$", "this", "->", "classMapper", "(", "$", "class", ")", ";", "return", "new", "$", "class", "(", "$", "dir", ",", "$", "path", ")", ";", "}" ]
Get the cache provider. First checks to see if the provider is callable, then will attempt to get it from the service locator, finally will fallback to a class mapper. @param $path @return array
[ "Get", "the", "cache", "provider", ".", "First", "checks", "to", "see", "if", "the", "provider", "is", "callable", "then", "will", "attempt", "to", "get", "it", "from", "the", "service", "locator", "finally", "will", "fallback", "to", "a", "class", "mapper", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Service/AssetCacheManager.php#L72-L100
35,651
RWOverdijk/AssetManager
src/AssetManager/Service/AssetCacheManager.php
AssetCacheManager.getCacheProviderConfig
private function getCacheProviderConfig($path) { $cacheProvider = null; if (!empty($this->config[$path]) && !empty($this->config[$path]['cache'])) { $cacheProvider = $this->config[$path]; } if (!$cacheProvider && !empty($this->config['default']) && !empty($this->config['default']['cache']) ) { $cacheProvider = $this->config['default']; } return $cacheProvider; }
php
private function getCacheProviderConfig($path) { $cacheProvider = null; if (!empty($this->config[$path]) && !empty($this->config[$path]['cache'])) { $cacheProvider = $this->config[$path]; } if (!$cacheProvider && !empty($this->config['default']) && !empty($this->config['default']['cache']) ) { $cacheProvider = $this->config['default']; } return $cacheProvider; }
[ "private", "function", "getCacheProviderConfig", "(", "$", "path", ")", "{", "$", "cacheProvider", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "config", "[", "$", "path", "]", ")", "&&", "!", "empty", "(", "$", "this", "->", "config", "[", "$", "path", "]", "[", "'cache'", "]", ")", ")", "{", "$", "cacheProvider", "=", "$", "this", "->", "config", "[", "$", "path", "]", ";", "}", "if", "(", "!", "$", "cacheProvider", "&&", "!", "empty", "(", "$", "this", "->", "config", "[", "'default'", "]", ")", "&&", "!", "empty", "(", "$", "this", "->", "config", "[", "'default'", "]", "[", "'cache'", "]", ")", ")", "{", "$", "cacheProvider", "=", "$", "this", "->", "config", "[", "'default'", "]", ";", "}", "return", "$", "cacheProvider", ";", "}" ]
Get the cache provider config. Use default values if defined. @param $path @return null|array Cache config definition. Returns null if not found in config.
[ "Get", "the", "cache", "provider", "config", ".", "Use", "default", "values", "if", "defined", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Service/AssetCacheManager.php#L110-L126
35,652
RWOverdijk/AssetManager
src/AssetManager/Module.php
Module.onDispatch
public function onDispatch(MvcEvent $event) { /* @var $response \Zend\Http\Response */ $response = $event->getResponse(); if (!method_exists($response, 'getStatusCode') || $response->getStatusCode() !== 404) { return; } $request = $event->getRequest(); $serviceManager = $event->getApplication()->getServiceManager(); $assetManager = $serviceManager->get(__NAMESPACE__ . '\Service\AssetManager'); if (!$assetManager->resolvesToAsset($request)) { return; } $response->setStatusCode(200); return $assetManager->setAssetOnResponse($response); }
php
public function onDispatch(MvcEvent $event) { /* @var $response \Zend\Http\Response */ $response = $event->getResponse(); if (!method_exists($response, 'getStatusCode') || $response->getStatusCode() !== 404) { return; } $request = $event->getRequest(); $serviceManager = $event->getApplication()->getServiceManager(); $assetManager = $serviceManager->get(__NAMESPACE__ . '\Service\AssetManager'); if (!$assetManager->resolvesToAsset($request)) { return; } $response->setStatusCode(200); return $assetManager->setAssetOnResponse($response); }
[ "public", "function", "onDispatch", "(", "MvcEvent", "$", "event", ")", "{", "/* @var $response \\Zend\\Http\\Response */", "$", "response", "=", "$", "event", "->", "getResponse", "(", ")", ";", "if", "(", "!", "method_exists", "(", "$", "response", ",", "'getStatusCode'", ")", "||", "$", "response", "->", "getStatusCode", "(", ")", "!==", "404", ")", "{", "return", ";", "}", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";", "$", "serviceManager", "=", "$", "event", "->", "getApplication", "(", ")", "->", "getServiceManager", "(", ")", ";", "$", "assetManager", "=", "$", "serviceManager", "->", "get", "(", "__NAMESPACE__", ".", "'\\Service\\AssetManager'", ")", ";", "if", "(", "!", "$", "assetManager", "->", "resolvesToAsset", "(", "$", "request", ")", ")", "{", "return", ";", "}", "$", "response", "->", "setStatusCode", "(", "200", ")", ";", "return", "$", "assetManager", "->", "setAssetOnResponse", "(", "$", "response", ")", ";", "}" ]
Callback method for dispatch and dispatch.error events. @param MvcEvent $event
[ "Callback", "method", "for", "dispatch", "and", "dispatch", ".", "error", "events", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Module.php#L52-L70
35,653
loveorigami/yii2-notification-wrapper
src/layers/Notie.php
Notie.overrideConfirm
public function overrideConfirm() { if ($this->overrideSystemConfirm) { $ok = Yii::t('noty', 'Ok'); $cancel = Yii::t('noty', 'Cancel'); $this->view->registerJs(" yii.confirm = function(message, ok, cancel) { notie.confirm(message, '$ok', '$cancel', function() { !ok || ok(); }); } "); } }
php
public function overrideConfirm() { if ($this->overrideSystemConfirm) { $ok = Yii::t('noty', 'Ok'); $cancel = Yii::t('noty', 'Cancel'); $this->view->registerJs(" yii.confirm = function(message, ok, cancel) { notie.confirm(message, '$ok', '$cancel', function() { !ok || ok(); }); } "); } }
[ "public", "function", "overrideConfirm", "(", ")", "{", "if", "(", "$", "this", "->", "overrideSystemConfirm", ")", "{", "$", "ok", "=", "Yii", "::", "t", "(", "'noty'", ",", "'Ok'", ")", ";", "$", "cancel", "=", "Yii", "::", "t", "(", "'noty'", ",", "'Cancel'", ")", ";", "$", "this", "->", "view", "->", "registerJs", "(", "\"\n yii.confirm = function(message, ok, cancel) {\n \n notie.confirm(message, '$ok', '$cancel', function() {\n !ok || ok();\n });\n \n }\n \"", ")", ";", "}", "}" ]
Override System Confirm
[ "Override", "System", "Confirm" ]
544c5a34b33799e0f0f0882e1163273bd12728e0
https://github.com/loveorigami/yii2-notification-wrapper/blob/544c5a34b33799e0f0f0882e1163273bd12728e0/src/layers/Notie.php#L100-L117
35,654
RWOverdijk/AssetManager
src/AssetManager/View/Helper/Asset.php
Asset.appendTimestamp
private function appendTimestamp($filename, $queryString, $timestamp = null) { // current timestamp as default $timestamp = $timestamp === null ? time() : $timestamp; return $filename . '?' . urlencode($queryString) . '=' . $timestamp; }
php
private function appendTimestamp($filename, $queryString, $timestamp = null) { // current timestamp as default $timestamp = $timestamp === null ? time() : $timestamp; return $filename . '?' . urlencode($queryString) . '=' . $timestamp; }
[ "private", "function", "appendTimestamp", "(", "$", "filename", ",", "$", "queryString", ",", "$", "timestamp", "=", "null", ")", "{", "// current timestamp as default", "$", "timestamp", "=", "$", "timestamp", "===", "null", "?", "time", "(", ")", ":", "$", "timestamp", ";", "return", "$", "filename", ".", "'?'", ".", "urlencode", "(", "$", "queryString", ")", ".", "'='", ".", "$", "timestamp", ";", "}" ]
Append timestamp as query param to the filename @param string $filename @param string $queryString @param int|null $timestamp @return string
[ "Append", "timestamp", "as", "query", "param", "to", "the", "filename" ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/View/Helper/Asset.php#L41-L47
35,655
RWOverdijk/AssetManager
src/AssetManager/View/Helper/Asset.php
Asset.elaborateFilePath
private function elaborateFilePath($filename, $queryString) { $asset = $this->assetManagerResolver->resolve($filename); if ($asset !== null) { // append last modified date to the filepath and use a custom query string return $this->appendTimestamp($filename, $queryString, $asset->getLastModified()); } return $filename; }
php
private function elaborateFilePath($filename, $queryString) { $asset = $this->assetManagerResolver->resolve($filename); if ($asset !== null) { // append last modified date to the filepath and use a custom query string return $this->appendTimestamp($filename, $queryString, $asset->getLastModified()); } return $filename; }
[ "private", "function", "elaborateFilePath", "(", "$", "filename", ",", "$", "queryString", ")", "{", "$", "asset", "=", "$", "this", "->", "assetManagerResolver", "->", "resolve", "(", "$", "filename", ")", ";", "if", "(", "$", "asset", "!==", "null", ")", "{", "// append last modified date to the filepath and use a custom query string", "return", "$", "this", "->", "appendTimestamp", "(", "$", "filename", ",", "$", "queryString", ",", "$", "asset", "->", "getLastModified", "(", ")", ")", ";", "}", "return", "$", "filename", ";", "}" ]
find the file and if it exists, append its unix modification time to the filename @param string $filename @param string $queryString @return string
[ "find", "the", "file", "and", "if", "it", "exists", "append", "its", "unix", "modification", "time", "to", "the", "filename" ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/View/Helper/Asset.php#L56-L66
35,656
RWOverdijk/AssetManager
src/AssetManager/View/Helper/Asset.php
Asset.getFilePathFromCache
private function getFilePathFromCache($filename, $queryString) { // return if cache not found if ($this->cache == null) { return null; } // cache key based on the filename $cacheKey = md5($filename); $itemIsFoundInCache = false; $filePath = $this->cache->getItem($cacheKey, $itemIsFoundInCache); // if there is no element in the cache, elaborate and cache it if ($itemIsFoundInCache === false || $filePath === null) { $filePath = $this->elaborateFilePath($filename, $queryString); $this->cache->setItem($cacheKey, $filePath); } return $filePath; }
php
private function getFilePathFromCache($filename, $queryString) { // return if cache not found if ($this->cache == null) { return null; } // cache key based on the filename $cacheKey = md5($filename); $itemIsFoundInCache = false; $filePath = $this->cache->getItem($cacheKey, $itemIsFoundInCache); // if there is no element in the cache, elaborate and cache it if ($itemIsFoundInCache === false || $filePath === null) { $filePath = $this->elaborateFilePath($filename, $queryString); $this->cache->setItem($cacheKey, $filePath); } return $filePath; }
[ "private", "function", "getFilePathFromCache", "(", "$", "filename", ",", "$", "queryString", ")", "{", "// return if cache not found", "if", "(", "$", "this", "->", "cache", "==", "null", ")", "{", "return", "null", ";", "}", "// cache key based on the filename", "$", "cacheKey", "=", "md5", "(", "$", "filename", ")", ";", "$", "itemIsFoundInCache", "=", "false", ";", "$", "filePath", "=", "$", "this", "->", "cache", "->", "getItem", "(", "$", "cacheKey", ",", "$", "itemIsFoundInCache", ")", ";", "// if there is no element in the cache, elaborate and cache it", "if", "(", "$", "itemIsFoundInCache", "===", "false", "||", "$", "filePath", "===", "null", ")", "{", "$", "filePath", "=", "$", "this", "->", "elaborateFilePath", "(", "$", "filename", ",", "$", "queryString", ")", ";", "$", "this", "->", "cache", "->", "setItem", "(", "$", "cacheKey", ",", "$", "filePath", ")", ";", "}", "return", "$", "filePath", ";", "}" ]
Use the cache to get the filePath @param string $filename @param string $queryString @return mixed|string
[ "Use", "the", "cache", "to", "get", "the", "filePath" ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/View/Helper/Asset.php#L76-L95
35,657
RWOverdijk/AssetManager
src/AssetManager/Resolver/AliasPathStackResolver.php
AliasPathStackResolver.addAlias
private function addAlias($alias, $path) { if (!is_string($path)) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid path provided; must be a string, received %s', gettype($path) )); } if (!is_string($alias)) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid alias provided; must be a string, received %s', gettype($alias) )); } $this->aliases[$alias] = $this->normalizePath($path); }
php
private function addAlias($alias, $path) { if (!is_string($path)) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid path provided; must be a string, received %s', gettype($path) )); } if (!is_string($alias)) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid alias provided; must be a string, received %s', gettype($alias) )); } $this->aliases[$alias] = $this->normalizePath($path); }
[ "private", "function", "addAlias", "(", "$", "alias", ",", "$", "path", ")", "{", "if", "(", "!", "is_string", "(", "$", "path", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Invalid path provided; must be a string, received %s'", ",", "gettype", "(", "$", "path", ")", ")", ")", ";", "}", "if", "(", "!", "is_string", "(", "$", "alias", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Invalid alias provided; must be a string, received %s'", ",", "gettype", "(", "$", "alias", ")", ")", ")", ";", "}", "$", "this", "->", "aliases", "[", "$", "alias", "]", "=", "$", "this", "->", "normalizePath", "(", "$", "path", ")", ";", "}" ]
Add a single alias to the stack @param string $alias @param string $path @throws Exception\InvalidArgumentException
[ "Add", "a", "single", "alias", "to", "the", "stack" ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Resolver/AliasPathStackResolver.php#L59-L76
35,658
RWOverdijk/AssetManager
src/AssetManager/Controller/ConsoleController.php
ConsoleController.warmupAction
public function warmupAction() { $request = $this->getRequest(); $purge = $request->getParam('purge', false); $verbose = $request->getParam('verbose', false) || $request->getParam('v', false); // purge cache for every configuration if ($purge) { $this->purgeCache($verbose); } $this->output('Collecting all assets...', $verbose); $collection = $this->assetManager->getResolver()->collect(); $this->output(sprintf('Collected %d assets, warming up...', count($collection)), $verbose); foreach ($collection as $path) { $asset = $this->assetManager->getResolver()->resolve($path); $this->assetManager->getAssetFilterManager()->setFilters($path, $asset); $this->assetManager->getAssetCacheManager()->setCache($path, $asset)->dump(); } $this->output(sprintf('Warming up finished...', $verbose)); }
php
public function warmupAction() { $request = $this->getRequest(); $purge = $request->getParam('purge', false); $verbose = $request->getParam('verbose', false) || $request->getParam('v', false); // purge cache for every configuration if ($purge) { $this->purgeCache($verbose); } $this->output('Collecting all assets...', $verbose); $collection = $this->assetManager->getResolver()->collect(); $this->output(sprintf('Collected %d assets, warming up...', count($collection)), $verbose); foreach ($collection as $path) { $asset = $this->assetManager->getResolver()->resolve($path); $this->assetManager->getAssetFilterManager()->setFilters($path, $asset); $this->assetManager->getAssetCacheManager()->setCache($path, $asset)->dump(); } $this->output(sprintf('Warming up finished...', $verbose)); }
[ "public", "function", "warmupAction", "(", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "purge", "=", "$", "request", "->", "getParam", "(", "'purge'", ",", "false", ")", ";", "$", "verbose", "=", "$", "request", "->", "getParam", "(", "'verbose'", ",", "false", ")", "||", "$", "request", "->", "getParam", "(", "'v'", ",", "false", ")", ";", "// purge cache for every configuration", "if", "(", "$", "purge", ")", "{", "$", "this", "->", "purgeCache", "(", "$", "verbose", ")", ";", "}", "$", "this", "->", "output", "(", "'Collecting all assets...'", ",", "$", "verbose", ")", ";", "$", "collection", "=", "$", "this", "->", "assetManager", "->", "getResolver", "(", ")", "->", "collect", "(", ")", ";", "$", "this", "->", "output", "(", "sprintf", "(", "'Collected %d assets, warming up...'", ",", "count", "(", "$", "collection", ")", ")", ",", "$", "verbose", ")", ";", "foreach", "(", "$", "collection", "as", "$", "path", ")", "{", "$", "asset", "=", "$", "this", "->", "assetManager", "->", "getResolver", "(", ")", "->", "resolve", "(", "$", "path", ")", ";", "$", "this", "->", "assetManager", "->", "getAssetFilterManager", "(", ")", "->", "setFilters", "(", "$", "path", ",", "$", "asset", ")", ";", "$", "this", "->", "assetManager", "->", "getAssetCacheManager", "(", ")", "->", "setCache", "(", "$", "path", ",", "$", "asset", ")", "->", "dump", "(", ")", ";", "}", "$", "this", "->", "output", "(", "sprintf", "(", "'Warming up finished...'", ",", "$", "verbose", ")", ")", ";", "}" ]
Dumps all assets to cache directories.
[ "Dumps", "all", "assets", "to", "cache", "directories", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Controller/ConsoleController.php#L66-L89
35,659
RWOverdijk/AssetManager
src/AssetManager/Controller/ConsoleController.php
ConsoleController.purgeCache
protected function purgeCache($verbose = false) { if (empty($this->appConfig['asset_manager']['caching'])) { return false; } foreach ($this->appConfig['asset_manager']['caching'] as $configName => $config) { if (empty($config['options']['dir'])) { continue; } $this->output(sprintf('Purging %s on "%s"...', $config['options']['dir'], $configName), $verbose); $node = $config['options']['dir']; if ($configName !== 'default') { $node .= '/'.$configName; } $this->recursiveRemove($node, $verbose); } return true; }
php
protected function purgeCache($verbose = false) { if (empty($this->appConfig['asset_manager']['caching'])) { return false; } foreach ($this->appConfig['asset_manager']['caching'] as $configName => $config) { if (empty($config['options']['dir'])) { continue; } $this->output(sprintf('Purging %s on "%s"...', $config['options']['dir'], $configName), $verbose); $node = $config['options']['dir']; if ($configName !== 'default') { $node .= '/'.$configName; } $this->recursiveRemove($node, $verbose); } return true; }
[ "protected", "function", "purgeCache", "(", "$", "verbose", "=", "false", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "appConfig", "[", "'asset_manager'", "]", "[", "'caching'", "]", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "this", "->", "appConfig", "[", "'asset_manager'", "]", "[", "'caching'", "]", "as", "$", "configName", "=>", "$", "config", ")", "{", "if", "(", "empty", "(", "$", "config", "[", "'options'", "]", "[", "'dir'", "]", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "output", "(", "sprintf", "(", "'Purging %s on \"%s\"...'", ",", "$", "config", "[", "'options'", "]", "[", "'dir'", "]", ",", "$", "configName", ")", ",", "$", "verbose", ")", ";", "$", "node", "=", "$", "config", "[", "'options'", "]", "[", "'dir'", "]", ";", "if", "(", "$", "configName", "!==", "'default'", ")", "{", "$", "node", ".=", "'/'", ".", "$", "configName", ";", "}", "$", "this", "->", "recursiveRemove", "(", "$", "node", ",", "$", "verbose", ")", ";", "}", "return", "true", ";", "}" ]
Purges all directories defined as AssetManager cache dir. @param bool $verbose verbose flag, default false @return bool false if caching is not set, otherwise true
[ "Purges", "all", "directories", "defined", "as", "AssetManager", "cache", "dir", "." ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Controller/ConsoleController.php#L96-L120
35,660
RWOverdijk/AssetManager
src/AssetManager/Resolver/PathStackResolver.php
PathStackResolver.addPath
public function addPath($path) { if (!is_string($path)) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid path provided; must be a string, received %s', gettype($path) )); } $this->paths[] = $this->normalizePath($path); }
php
public function addPath($path) { if (!is_string($path)) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid path provided; must be a string, received %s', gettype($path) )); } $this->paths[] = $this->normalizePath($path); }
[ "public", "function", "addPath", "(", "$", "path", ")", "{", "if", "(", "!", "is_string", "(", "$", "path", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Invalid path provided; must be a string, received %s'", ",", "gettype", "(", "$", "path", ")", ")", ")", ";", "}", "$", "this", "->", "paths", "[", "]", "=", "$", "this", "->", "normalizePath", "(", "$", "path", ")", ";", "}" ]
Add a single path to the stack @param string $path @throws Exception\InvalidArgumentException
[ "Add", "a", "single", "path", "to", "the", "stack" ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Resolver/PathStackResolver.php#L116-L126
35,661
RWOverdijk/AssetManager
src/AssetManager/Asset/AggregateAsset.php
AggregateAsset.processContent
private function processContent($content) { $this->mimetype = null; foreach ($content as $asset) { if (null === $this->mimetype) { $this->mimetype = $asset->mimetype; } if ($asset->mimetype !== $this->mimetype) { throw new Exception\RuntimeException( sprintf( 'Asset "%s" doesn\'t have the expected mime-type "%s".', $asset->getTargetPath(), $this->mimetype ) ); } $this->setLastModified( max( $asset->getLastModified(), $this->getLastModified() ) ); $this->setContent( $this->getContent() . $asset->dump() ); } }
php
private function processContent($content) { $this->mimetype = null; foreach ($content as $asset) { if (null === $this->mimetype) { $this->mimetype = $asset->mimetype; } if ($asset->mimetype !== $this->mimetype) { throw new Exception\RuntimeException( sprintf( 'Asset "%s" doesn\'t have the expected mime-type "%s".', $asset->getTargetPath(), $this->mimetype ) ); } $this->setLastModified( max( $asset->getLastModified(), $this->getLastModified() ) ); $this->setContent( $this->getContent() . $asset->dump() ); } }
[ "private", "function", "processContent", "(", "$", "content", ")", "{", "$", "this", "->", "mimetype", "=", "null", ";", "foreach", "(", "$", "content", "as", "$", "asset", ")", "{", "if", "(", "null", "===", "$", "this", "->", "mimetype", ")", "{", "$", "this", "->", "mimetype", "=", "$", "asset", "->", "mimetype", ";", "}", "if", "(", "$", "asset", "->", "mimetype", "!==", "$", "this", "->", "mimetype", ")", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "sprintf", "(", "'Asset \"%s\" doesn\\'t have the expected mime-type \"%s\".'", ",", "$", "asset", "->", "getTargetPath", "(", ")", ",", "$", "this", "->", "mimetype", ")", ")", ";", "}", "$", "this", "->", "setLastModified", "(", "max", "(", "$", "asset", "->", "getLastModified", "(", ")", ",", "$", "this", "->", "getLastModified", "(", ")", ")", ")", ";", "$", "this", "->", "setContent", "(", "$", "this", "->", "getContent", "(", ")", ".", "$", "asset", "->", "dump", "(", ")", ")", ";", "}", "}" ]
Loop through assets and merge content @param string $content @throws Exception\RuntimeException
[ "Loop", "through", "assets", "and", "merge", "content" ]
982e3b1802d76ec69b74f90c24154b37f460656f
https://github.com/RWOverdijk/AssetManager/blob/982e3b1802d76ec69b74f90c24154b37f460656f/src/AssetManager/Asset/AggregateAsset.php#L74-L102
35,662
ElForastero/Transliterate
src/Transliterator.php
Transliterator.make
public function make(string $text): string { $map = $this->getMap(); $transliterated = str_replace(array_keys($map), array_values($map), $text); if (true === config('transliterate.remove_accents', false)) { $transliterator = IntlTransliterator::create('Any-Latin; Latin-ASCII'); $transliterated = $transliterator->transliterate($transliterated); } return self::applyTransformers($transliterated); }
php
public function make(string $text): string { $map = $this->getMap(); $transliterated = str_replace(array_keys($map), array_values($map), $text); if (true === config('transliterate.remove_accents', false)) { $transliterator = IntlTransliterator::create('Any-Latin; Latin-ASCII'); $transliterated = $transliterator->transliterate($transliterated); } return self::applyTransformers($transliterated); }
[ "public", "function", "make", "(", "string", "$", "text", ")", ":", "string", "{", "$", "map", "=", "$", "this", "->", "getMap", "(", ")", ";", "$", "transliterated", "=", "str_replace", "(", "array_keys", "(", "$", "map", ")", ",", "array_values", "(", "$", "map", ")", ",", "$", "text", ")", ";", "if", "(", "true", "===", "config", "(", "'transliterate.remove_accents'", ",", "false", ")", ")", "{", "$", "transliterator", "=", "IntlTransliterator", "::", "create", "(", "'Any-Latin; Latin-ASCII'", ")", ";", "$", "transliterated", "=", "$", "transliterator", "->", "transliterate", "(", "$", "transliterated", ")", ";", "}", "return", "self", "::", "applyTransformers", "(", "$", "transliterated", ")", ";", "}" ]
Transliterate the given string. @param string $text @return string
[ "Transliterate", "the", "given", "string", "." ]
6f7d1d88440f7be3cc0f91f2a06b2374fece0832
https://github.com/ElForastero/Transliterate/blob/6f7d1d88440f7be3cc0f91f2a06b2374fece0832/src/Transliterator.php#L69-L80
35,663
ElForastero/Transliterate
src/Transliterator.php
Transliterator.slugify
public function slugify(string $text): string { $map = $this->getMap(); $text = str_replace(array_keys($map), array_values($map), trim($text)); $transliterator = IntlTransliterator::create('Any-Latin; Latin-ASCII; Lower()'); $text = $transliterator->transliterate($text); $text = str_replace('&', 'and', $text); return preg_replace( ['/[^\w\s]/', '/\s+/'], ['', '-'], $text ); }
php
public function slugify(string $text): string { $map = $this->getMap(); $text = str_replace(array_keys($map), array_values($map), trim($text)); $transliterator = IntlTransliterator::create('Any-Latin; Latin-ASCII; Lower()'); $text = $transliterator->transliterate($text); $text = str_replace('&', 'and', $text); return preg_replace( ['/[^\w\s]/', '/\s+/'], ['', '-'], $text ); }
[ "public", "function", "slugify", "(", "string", "$", "text", ")", ":", "string", "{", "$", "map", "=", "$", "this", "->", "getMap", "(", ")", ";", "$", "text", "=", "str_replace", "(", "array_keys", "(", "$", "map", ")", ",", "array_values", "(", "$", "map", ")", ",", "trim", "(", "$", "text", ")", ")", ";", "$", "transliterator", "=", "IntlTransliterator", "::", "create", "(", "'Any-Latin; Latin-ASCII; Lower()'", ")", ";", "$", "text", "=", "$", "transliterator", "->", "transliterate", "(", "$", "text", ")", ";", "$", "text", "=", "str_replace", "(", "'&'", ",", "'and'", ",", "$", "text", ")", ";", "return", "preg_replace", "(", "[", "'/[^\\w\\s]/'", ",", "'/\\s+/'", "]", ",", "[", "''", ",", "'-'", "]", ",", "$", "text", ")", ";", "}" ]
Create a slug by converting and removing all non-ascii characters. @param string $text @return string
[ "Create", "a", "slug", "by", "converting", "and", "removing", "all", "non", "-", "ascii", "characters", "." ]
6f7d1d88440f7be3cc0f91f2a06b2374fece0832
https://github.com/ElForastero/Transliterate/blob/6f7d1d88440f7be3cc0f91f2a06b2374fece0832/src/Transliterator.php#L89-L104
35,664
ElForastero/Transliterate
src/Transliterator.php
Transliterator.getMap
private function getMap(): array { $map = $this->map ?? config('transliterate.default_map'); $lang = $this->lang ?? config('transliterate.default_lang'); $customMaps = config('transliterate.custom_maps'); $vendorMapsPath = __DIR__.DIRECTORY_SEPARATOR.'maps'.DIRECTORY_SEPARATOR; $path = $customMaps[$lang][$map] ?? $vendorMapsPath.$lang.DIRECTORY_SEPARATOR.$map.'.php'; if (!file_exists($path)) { throw new \InvalidArgumentException("The transliteration map '${path}' doesn't exist"); } /* @noinspection PhpIncludeInspection */ return require $path; }
php
private function getMap(): array { $map = $this->map ?? config('transliterate.default_map'); $lang = $this->lang ?? config('transliterate.default_lang'); $customMaps = config('transliterate.custom_maps'); $vendorMapsPath = __DIR__.DIRECTORY_SEPARATOR.'maps'.DIRECTORY_SEPARATOR; $path = $customMaps[$lang][$map] ?? $vendorMapsPath.$lang.DIRECTORY_SEPARATOR.$map.'.php'; if (!file_exists($path)) { throw new \InvalidArgumentException("The transliteration map '${path}' doesn't exist"); } /* @noinspection PhpIncludeInspection */ return require $path; }
[ "private", "function", "getMap", "(", ")", ":", "array", "{", "$", "map", "=", "$", "this", "->", "map", "??", "config", "(", "'transliterate.default_map'", ")", ";", "$", "lang", "=", "$", "this", "->", "lang", "??", "config", "(", "'transliterate.default_lang'", ")", ";", "$", "customMaps", "=", "config", "(", "'transliterate.custom_maps'", ")", ";", "$", "vendorMapsPath", "=", "__DIR__", ".", "DIRECTORY_SEPARATOR", ".", "'maps'", ".", "DIRECTORY_SEPARATOR", ";", "$", "path", "=", "$", "customMaps", "[", "$", "lang", "]", "[", "$", "map", "]", "??", "$", "vendorMapsPath", ".", "$", "lang", ".", "DIRECTORY_SEPARATOR", ".", "$", "map", ".", "'.php'", ";", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"The transliteration map '${path}' doesn't exist\"", ")", ";", "}", "/* @noinspection PhpIncludeInspection */", "return", "require", "$", "path", ";", "}" ]
Get map array according to config file. @return array
[ "Get", "map", "array", "according", "to", "config", "file", "." ]
6f7d1d88440f7be3cc0f91f2a06b2374fece0832
https://github.com/ElForastero/Transliterate/blob/6f7d1d88440f7be3cc0f91f2a06b2374fece0832/src/Transliterator.php#L111-L126
35,665
ElForastero/Transliterate
src/Transliterator.php
Transliterator.applyTransformers
private function applyTransformers(string $string): string { foreach (Transformer::getAll() as $transformer) { $string = $transformer($string); } return $string; }
php
private function applyTransformers(string $string): string { foreach (Transformer::getAll() as $transformer) { $string = $transformer($string); } return $string; }
[ "private", "function", "applyTransformers", "(", "string", "$", "string", ")", ":", "string", "{", "foreach", "(", "Transformer", "::", "getAll", "(", ")", "as", "$", "transformer", ")", "{", "$", "string", "=", "$", "transformer", "(", "$", "string", ")", ";", "}", "return", "$", "string", ";", "}" ]
Apply a series of transformations defined as closures in the configuration file. @param string $string @return string
[ "Apply", "a", "series", "of", "transformations", "defined", "as", "closures", "in", "the", "configuration", "file", "." ]
6f7d1d88440f7be3cc0f91f2a06b2374fece0832
https://github.com/ElForastero/Transliterate/blob/6f7d1d88440f7be3cc0f91f2a06b2374fece0832/src/Transliterator.php#L135-L142
35,666
fabulator/endomondo-api
lib/Fabulator/Endomondo/EndomondoApi.php
EndomondoApi.generateCSRFToken
protected function generateCSRFToken() { try { parent::generateCSRFToken(); } catch (ClientException $e) { // too many request, sleep for a while if ($e->getCode() === 429) { throw new EndomondoApiException('Too many requests', $e->getCode(), $e); } throw new EndomondoApiException($e->getMessage(), $e->getCode(), $e); } }
php
protected function generateCSRFToken() { try { parent::generateCSRFToken(); } catch (ClientException $e) { // too many request, sleep for a while if ($e->getCode() === 429) { throw new EndomondoApiException('Too many requests', $e->getCode(), $e); } throw new EndomondoApiException($e->getMessage(), $e->getCode(), $e); } }
[ "protected", "function", "generateCSRFToken", "(", ")", "{", "try", "{", "parent", "::", "generateCSRFToken", "(", ")", ";", "}", "catch", "(", "ClientException", "$", "e", ")", "{", "// too many request, sleep for a while", "if", "(", "$", "e", "->", "getCode", "(", ")", "===", "429", ")", "{", "throw", "new", "EndomondoApiException", "(", "'Too many requests'", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "}", "throw", "new", "EndomondoApiException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "}", "}" ]
Generate csfr token. @return void @throws EndomondoApiException When generating fail
[ "Generate", "csfr", "token", "." ]
844b603a01b6237815fd186cfc11ee72594ae52b
https://github.com/fabulator/endomondo-api/blob/844b603a01b6237815fd186cfc11ee72594ae52b/lib/Fabulator/Endomondo/EndomondoApi.php#L31-L43
35,667
fabulator/endomondo-api
lib/Fabulator/Endomondo/EndomondoApi.php
EndomondoApi.getWorkoutBetween
public function getWorkoutBetween(\DateTime $from, \DateTime $to) { $workouts = $this->getWorkoutsUntil($to, 1); /* @var $workout Workout */ $workout = $workouts['workouts'][0]; if (!$workout) { return null; } if ($workout->getStart() > $from) { return $workout; } return null; }
php
public function getWorkoutBetween(\DateTime $from, \DateTime $to) { $workouts = $this->getWorkoutsUntil($to, 1); /* @var $workout Workout */ $workout = $workouts['workouts'][0]; if (!$workout) { return null; } if ($workout->getStart() > $from) { return $workout; } return null; }
[ "public", "function", "getWorkoutBetween", "(", "\\", "DateTime", "$", "from", ",", "\\", "DateTime", "$", "to", ")", "{", "$", "workouts", "=", "$", "this", "->", "getWorkoutsUntil", "(", "$", "to", ",", "1", ")", ";", "/* @var $workout Workout */", "$", "workout", "=", "$", "workouts", "[", "'workouts'", "]", "[", "0", "]", ";", "if", "(", "!", "$", "workout", ")", "{", "return", "null", ";", "}", "if", "(", "$", "workout", "->", "getStart", "(", ")", ">", "$", "from", ")", "{", "return", "$", "workout", ";", "}", "return", "null", ";", "}" ]
Try to find a single workout between two dates. @param \DateTime $from @param \DateTime $to @return Workout|null
[ "Try", "to", "find", "a", "single", "workout", "between", "two", "dates", "." ]
844b603a01b6237815fd186cfc11ee72594ae52b
https://github.com/fabulator/endomondo-api/blob/844b603a01b6237815fd186cfc11ee72594ae52b/lib/Fabulator/Endomondo/EndomondoApi.php#L208-L224
35,668
fabulator/endomondo-api
lib/Fabulator/Endomondo/EndomondoApi.php
EndomondoApi.getWorkoutsFromTo
public function getWorkoutsFromTo(\DateTime $from, \DateTime $to) { return $this->getWorkouts([ 'after' => $from->format('c'), 'before' => $to->format('c'), ]); }
php
public function getWorkoutsFromTo(\DateTime $from, \DateTime $to) { return $this->getWorkouts([ 'after' => $from->format('c'), 'before' => $to->format('c'), ]); }
[ "public", "function", "getWorkoutsFromTo", "(", "\\", "DateTime", "$", "from", ",", "\\", "DateTime", "$", "to", ")", "{", "return", "$", "this", "->", "getWorkouts", "(", "[", "'after'", "=>", "$", "from", "->", "format", "(", "'c'", ")", ",", "'before'", "=>", "$", "to", "->", "format", "(", "'c'", ")", ",", "]", ")", ";", "}" ]
Get all workouts between two dates. @param \DateTime $from @param \DateTime $to @return array $options { @var int $total Total found workout @var string $next Url for next workouts @var Workout[] $workout List of workouts }
[ "Get", "all", "workouts", "between", "two", "dates", "." ]
844b603a01b6237815fd186cfc11ee72594ae52b
https://github.com/fabulator/endomondo-api/blob/844b603a01b6237815fd186cfc11ee72594ae52b/lib/Fabulator/Endomondo/EndomondoApi.php#L237-L243
35,669
ahmedkhan847/mysqlwithelasticsearch
src/SearchElastic/Search.php
Search.search
public function search($query) { $this->validate($query); $client = $this->client->getClient(); $result = array(); // Change the match column name with the column name you want to search in it. $params = [ 'index' => $this->client->getIndex(), 'type' => $this->client->getType(), 'body' => [ 'query' => [ 'match' => [ $this->searchColumn => $query], ], ], ]; $query = $client->search($params); return $this->extractResult($query); }
php
public function search($query) { $this->validate($query); $client = $this->client->getClient(); $result = array(); // Change the match column name with the column name you want to search in it. $params = [ 'index' => $this->client->getIndex(), 'type' => $this->client->getType(), 'body' => [ 'query' => [ 'match' => [ $this->searchColumn => $query], ], ], ]; $query = $client->search($params); return $this->extractResult($query); }
[ "public", "function", "search", "(", "$", "query", ")", "{", "$", "this", "->", "validate", "(", "$", "query", ")", ";", "$", "client", "=", "$", "this", "->", "client", "->", "getClient", "(", ")", ";", "$", "result", "=", "array", "(", ")", ";", "// Change the match column name with the column name you want to search in it.", "$", "params", "=", "[", "'index'", "=>", "$", "this", "->", "client", "->", "getIndex", "(", ")", ",", "'type'", "=>", "$", "this", "->", "client", "->", "getType", "(", ")", ",", "'body'", "=>", "[", "'query'", "=>", "[", "'match'", "=>", "[", "$", "this", "->", "searchColumn", "=>", "$", "query", "]", ",", "]", ",", "]", ",", "]", ";", "$", "query", "=", "$", "client", "->", "search", "(", "$", "params", ")", ";", "return", "$", "this", "->", "extractResult", "(", "$", "query", ")", ";", "}" ]
Search in Elasticsearch. @param string $query @return Result from elasticsearch
[ "Search", "in", "Elasticsearch", "." ]
d30e169a0ae3ee04aac824d0037c53506b427be5
https://github.com/ahmedkhan847/mysqlwithelasticsearch/blob/d30e169a0ae3ee04aac824d0037c53506b427be5/src/SearchElastic/Search.php#L17-L35
35,670
ahmedkhan847/mysqlwithelasticsearch
src/ElasticSearchClient/Mapping.php
Mapping.createMapping
public function createMapping(array $map) { try { $elasticclient = $this->client->getClient(); $response = $elasticclient->indices()->create($map); return $response['acknowledged']; } catch (\Exception $ex) { return $ex->getMessage(); } }
php
public function createMapping(array $map) { try { $elasticclient = $this->client->getClient(); $response = $elasticclient->indices()->create($map); return $response['acknowledged']; } catch (\Exception $ex) { return $ex->getMessage(); } }
[ "public", "function", "createMapping", "(", "array", "$", "map", ")", "{", "try", "{", "$", "elasticclient", "=", "$", "this", "->", "client", "->", "getClient", "(", ")", ";", "$", "response", "=", "$", "elasticclient", "->", "indices", "(", ")", "->", "create", "(", "$", "map", ")", ";", "return", "$", "response", "[", "'acknowledged'", "]", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "return", "$", "ex", "->", "getMessage", "(", ")", ";", "}", "}" ]
Create mapping for Elasticsearch. @param array $map An array of elasticsearch mapping @return \ElasticSearchClient\ElasticSearchClient
[ "Create", "mapping", "for", "Elasticsearch", "." ]
d30e169a0ae3ee04aac824d0037c53506b427be5
https://github.com/ahmedkhan847/mysqlwithelasticsearch/blob/d30e169a0ae3ee04aac824d0037c53506b427be5/src/ElasticSearchClient/Mapping.php#L29-L38
35,671
ahmedkhan847/mysqlwithelasticsearch
src/ElasticSearchClient/Mapping.php
Mapping.deleteMapping
public function deleteMapping($index) { try { $elasticclient = $this->client->getClient(); $map = ['index' => $index]; $response = $elasticclient->indices()->delete($map); return $response['acknowledged']; } catch (\Exception $ex) { return $ex->getMessage(); } }
php
public function deleteMapping($index) { try { $elasticclient = $this->client->getClient(); $map = ['index' => $index]; $response = $elasticclient->indices()->delete($map); return $response['acknowledged']; } catch (\Exception $ex) { return $ex->getMessage(); } }
[ "public", "function", "deleteMapping", "(", "$", "index", ")", "{", "try", "{", "$", "elasticclient", "=", "$", "this", "->", "client", "->", "getClient", "(", ")", ";", "$", "map", "=", "[", "'index'", "=>", "$", "index", "]", ";", "$", "response", "=", "$", "elasticclient", "->", "indices", "(", ")", "->", "delete", "(", "$", "map", ")", ";", "return", "$", "response", "[", "'acknowledged'", "]", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "return", "$", "ex", "->", "getMessage", "(", ")", ";", "}", "}" ]
Delete the previous mapping by passing its name @param $index Name of an exisiting index to delete @return \ElasticSearchClient\ElasticSearchClient
[ "Delete", "the", "previous", "mapping", "by", "passing", "its", "name" ]
d30e169a0ae3ee04aac824d0037c53506b427be5
https://github.com/ahmedkhan847/mysqlwithelasticsearch/blob/d30e169a0ae3ee04aac824d0037c53506b427be5/src/ElasticSearchClient/Mapping.php#L46-L56
35,672
ahmedkhan847/mysqlwithelasticsearch
src/SearchElastic/SearchAbstract/SearchAbstract.php
SearchAbstract.extractResult
protected function extractResult($query) { $result = null; $i = 0; $hits = sizeof($query['hits']['hits']); $hit = $query['hits']['hits']; $result['searchfound'] = $hits; while ($i < $hits) { $result['result'][$i] = $query['hits']['hits'][$i]['_source']; $i++; } return $result; }
php
protected function extractResult($query) { $result = null; $i = 0; $hits = sizeof($query['hits']['hits']); $hit = $query['hits']['hits']; $result['searchfound'] = $hits; while ($i < $hits) { $result['result'][$i] = $query['hits']['hits'][$i]['_source']; $i++; } return $result; }
[ "protected", "function", "extractResult", "(", "$", "query", ")", "{", "$", "result", "=", "null", ";", "$", "i", "=", "0", ";", "$", "hits", "=", "sizeof", "(", "$", "query", "[", "'hits'", "]", "[", "'hits'", "]", ")", ";", "$", "hit", "=", "$", "query", "[", "'hits'", "]", "[", "'hits'", "]", ";", "$", "result", "[", "'searchfound'", "]", "=", "$", "hits", ";", "while", "(", "$", "i", "<", "$", "hits", ")", "{", "$", "result", "[", "'result'", "]", "[", "$", "i", "]", "=", "$", "query", "[", "'hits'", "]", "[", "'hits'", "]", "[", "$", "i", "]", "[", "'_source'", "]", ";", "$", "i", "++", ";", "}", "return", "$", "result", ";", "}" ]
Function to extract Search Result From ElasticSearch @param $query @return void
[ "Function", "to", "extract", "Search", "Result", "From", "ElasticSearch" ]
d30e169a0ae3ee04aac824d0037c53506b427be5
https://github.com/ahmedkhan847/mysqlwithelasticsearch/blob/d30e169a0ae3ee04aac824d0037c53506b427be5/src/SearchElastic/SearchAbstract/SearchAbstract.php#L62-L75
35,673
ahmedkhan847/mysqlwithelasticsearch
src/SearchElastic/SearchAbstract/SearchAbstract.php
SearchAbstract.validate
protected function validate($query) { if ($this->client->getIndex() == null) { throw new SearchException("Index cannot be null"); } if ($this->client->getType() == null) { throw new SearchException("Type cannot be null"); } if ($query == null) { throw new SearchException("Query can't be null"); } }
php
protected function validate($query) { if ($this->client->getIndex() == null) { throw new SearchException("Index cannot be null"); } if ($this->client->getType() == null) { throw new SearchException("Type cannot be null"); } if ($query == null) { throw new SearchException("Query can't be null"); } }
[ "protected", "function", "validate", "(", "$", "query", ")", "{", "if", "(", "$", "this", "->", "client", "->", "getIndex", "(", ")", "==", "null", ")", "{", "throw", "new", "SearchException", "(", "\"Index cannot be null\"", ")", ";", "}", "if", "(", "$", "this", "->", "client", "->", "getType", "(", ")", "==", "null", ")", "{", "throw", "new", "SearchException", "(", "\"Type cannot be null\"", ")", ";", "}", "if", "(", "$", "query", "==", "null", ")", "{", "throw", "new", "SearchException", "(", "\"Query can't be null\"", ")", ";", "}", "}" ]
Function to validate Search @param string $query @return void
[ "Function", "to", "validate", "Search" ]
d30e169a0ae3ee04aac824d0037c53506b427be5
https://github.com/ahmedkhan847/mysqlwithelasticsearch/blob/d30e169a0ae3ee04aac824d0037c53506b427be5/src/SearchElastic/SearchAbstract/SearchAbstract.php#L94-L105
35,674
apollopy/flysystem-aliyun-oss
src/AliyunOssAdapter.php
AliyunOssAdapter.putFile
public function putFile($path, $localFilePath, Config $config) { $object = $this->applyPathPrefix($path); $options = $this->getOptionsFromConfig($config); $options[OssClient::OSS_CHECK_MD5] = true; if (! isset($options[OssClient::OSS_CONTENT_TYPE])) { $options[OssClient::OSS_CONTENT_TYPE] = Util::guessMimeType($path, ''); } try { $this->client->uploadFile($this->bucket, $object, $localFilePath, $options); } catch (OssException $e) { return false; } $type = 'file'; $result = compact('type', 'path'); $result['mimetype'] = $options[OssClient::OSS_CONTENT_TYPE]; return $result; }
php
public function putFile($path, $localFilePath, Config $config) { $object = $this->applyPathPrefix($path); $options = $this->getOptionsFromConfig($config); $options[OssClient::OSS_CHECK_MD5] = true; if (! isset($options[OssClient::OSS_CONTENT_TYPE])) { $options[OssClient::OSS_CONTENT_TYPE] = Util::guessMimeType($path, ''); } try { $this->client->uploadFile($this->bucket, $object, $localFilePath, $options); } catch (OssException $e) { return false; } $type = 'file'; $result = compact('type', 'path'); $result['mimetype'] = $options[OssClient::OSS_CONTENT_TYPE]; return $result; }
[ "public", "function", "putFile", "(", "$", "path", ",", "$", "localFilePath", ",", "Config", "$", "config", ")", "{", "$", "object", "=", "$", "this", "->", "applyPathPrefix", "(", "$", "path", ")", ";", "$", "options", "=", "$", "this", "->", "getOptionsFromConfig", "(", "$", "config", ")", ";", "$", "options", "[", "OssClient", "::", "OSS_CHECK_MD5", "]", "=", "true", ";", "if", "(", "!", "isset", "(", "$", "options", "[", "OssClient", "::", "OSS_CONTENT_TYPE", "]", ")", ")", "{", "$", "options", "[", "OssClient", "::", "OSS_CONTENT_TYPE", "]", "=", "Util", "::", "guessMimeType", "(", "$", "path", ",", "''", ")", ";", "}", "try", "{", "$", "this", "->", "client", "->", "uploadFile", "(", "$", "this", "->", "bucket", ",", "$", "object", ",", "$", "localFilePath", ",", "$", "options", ")", ";", "}", "catch", "(", "OssException", "$", "e", ")", "{", "return", "false", ";", "}", "$", "type", "=", "'file'", ";", "$", "result", "=", "compact", "(", "'type'", ",", "'path'", ")", ";", "$", "result", "[", "'mimetype'", "]", "=", "$", "options", "[", "OssClient", "::", "OSS_CONTENT_TYPE", "]", ";", "return", "$", "result", ";", "}" ]
Write using a local file path. @param string $path @param string $localFilePath @param Config $config Config object @return array|false false on failure file meta data on success
[ "Write", "using", "a", "local", "file", "path", "." ]
08081796cef20984858e4a7cd0f708e0ca1b0bc9
https://github.com/apollopy/flysystem-aliyun-oss/blob/08081796cef20984858e4a7cd0f708e0ca1b0bc9/src/AliyunOssAdapter.php#L95-L117
35,675
apollopy/flysystem-aliyun-oss
src/AliyunOssAdapter.php
AliyunOssAdapter.getSignedDownloadUrl
public function getSignedDownloadUrl($path, $expires = 3600, $host_name = '', $use_ssl = false) { $object = $this->applyPathPrefix($path); $url = $this->client->signUrl($this->bucket, $object, $expires); if (! empty($host_name) || $use_ssl) { $parse_url = parse_url($url); if (! empty($host_name)) { $parse_url['host'] = $this->bucket.'.'.$host_name; } if ($use_ssl) { $parse_url['scheme'] = 'https'; } $url = (isset($parse_url['scheme']) ? $parse_url['scheme'].'://' : '') .( isset($parse_url['user']) ? $parse_url['user'].(isset($parse_url['pass']) ? ':'.$parse_url['pass'] : '').'@' : '' ) .(isset($parse_url['host']) ? $parse_url['host'] : '') .(isset($parse_url['port']) ? ':'.$parse_url['port'] : '') .(isset($parse_url['path']) ? $parse_url['path'] : '') .(isset($parse_url['query']) ? '?'.$parse_url['query'] : ''); } return $url; }
php
public function getSignedDownloadUrl($path, $expires = 3600, $host_name = '', $use_ssl = false) { $object = $this->applyPathPrefix($path); $url = $this->client->signUrl($this->bucket, $object, $expires); if (! empty($host_name) || $use_ssl) { $parse_url = parse_url($url); if (! empty($host_name)) { $parse_url['host'] = $this->bucket.'.'.$host_name; } if ($use_ssl) { $parse_url['scheme'] = 'https'; } $url = (isset($parse_url['scheme']) ? $parse_url['scheme'].'://' : '') .( isset($parse_url['user']) ? $parse_url['user'].(isset($parse_url['pass']) ? ':'.$parse_url['pass'] : '').'@' : '' ) .(isset($parse_url['host']) ? $parse_url['host'] : '') .(isset($parse_url['port']) ? ':'.$parse_url['port'] : '') .(isset($parse_url['path']) ? $parse_url['path'] : '') .(isset($parse_url['query']) ? '?'.$parse_url['query'] : ''); } return $url; }
[ "public", "function", "getSignedDownloadUrl", "(", "$", "path", ",", "$", "expires", "=", "3600", ",", "$", "host_name", "=", "''", ",", "$", "use_ssl", "=", "false", ")", "{", "$", "object", "=", "$", "this", "->", "applyPathPrefix", "(", "$", "path", ")", ";", "$", "url", "=", "$", "this", "->", "client", "->", "signUrl", "(", "$", "this", "->", "bucket", ",", "$", "object", ",", "$", "expires", ")", ";", "if", "(", "!", "empty", "(", "$", "host_name", ")", "||", "$", "use_ssl", ")", "{", "$", "parse_url", "=", "parse_url", "(", "$", "url", ")", ";", "if", "(", "!", "empty", "(", "$", "host_name", ")", ")", "{", "$", "parse_url", "[", "'host'", "]", "=", "$", "this", "->", "bucket", ".", "'.'", ".", "$", "host_name", ";", "}", "if", "(", "$", "use_ssl", ")", "{", "$", "parse_url", "[", "'scheme'", "]", "=", "'https'", ";", "}", "$", "url", "=", "(", "isset", "(", "$", "parse_url", "[", "'scheme'", "]", ")", "?", "$", "parse_url", "[", "'scheme'", "]", ".", "'://'", ":", "''", ")", ".", "(", "isset", "(", "$", "parse_url", "[", "'user'", "]", ")", "?", "$", "parse_url", "[", "'user'", "]", ".", "(", "isset", "(", "$", "parse_url", "[", "'pass'", "]", ")", "?", "':'", ".", "$", "parse_url", "[", "'pass'", "]", ":", "''", ")", ".", "'@'", ":", "''", ")", ".", "(", "isset", "(", "$", "parse_url", "[", "'host'", "]", ")", "?", "$", "parse_url", "[", "'host'", "]", ":", "''", ")", ".", "(", "isset", "(", "$", "parse_url", "[", "'port'", "]", ")", "?", "':'", ".", "$", "parse_url", "[", "'port'", "]", ":", "''", ")", ".", "(", "isset", "(", "$", "parse_url", "[", "'path'", "]", ")", "?", "$", "parse_url", "[", "'path'", "]", ":", "''", ")", ".", "(", "isset", "(", "$", "parse_url", "[", "'query'", "]", ")", "?", "'?'", ".", "$", "parse_url", "[", "'query'", "]", ":", "''", ")", ";", "}", "return", "$", "url", ";", "}" ]
Get the signed download url of a file. @param string $path @param int $expires @param string $host_name @param bool $use_ssl @return string
[ "Get", "the", "signed", "download", "url", "of", "a", "file", "." ]
08081796cef20984858e4a7cd0f708e0ca1b0bc9
https://github.com/apollopy/flysystem-aliyun-oss/blob/08081796cef20984858e4a7cd0f708e0ca1b0bc9/src/AliyunOssAdapter.php#L442-L469
35,676
nilportugues/php-backslasher
src/BackslashFixer/Fixer/FileEditor.php
FileEditor.removeUseFunctionsFromBackslashing
private function removeUseFunctionsFromBackslashing(FileGenerator $generator, array $functions) { foreach ($generator->getUses() as $namespacedFunction) { list($functionOrClass) = $namespacedFunction; if (\function_exists($functionOrClass)) { $function = \explode("\\", $functionOrClass); $function = \array_pop($function); if (!empty($functions[$function])) { unset($functions[$function]); } } } return $functions; }
php
private function removeUseFunctionsFromBackslashing(FileGenerator $generator, array $functions) { foreach ($generator->getUses() as $namespacedFunction) { list($functionOrClass) = $namespacedFunction; if (\function_exists($functionOrClass)) { $function = \explode("\\", $functionOrClass); $function = \array_pop($function); if (!empty($functions[$function])) { unset($functions[$function]); } } } return $functions; }
[ "private", "function", "removeUseFunctionsFromBackslashing", "(", "FileGenerator", "$", "generator", ",", "array", "$", "functions", ")", "{", "foreach", "(", "$", "generator", "->", "getUses", "(", ")", "as", "$", "namespacedFunction", ")", "{", "list", "(", "$", "functionOrClass", ")", "=", "$", "namespacedFunction", ";", "if", "(", "\\", "function_exists", "(", "$", "functionOrClass", ")", ")", "{", "$", "function", "=", "\\", "explode", "(", "\"\\\\\"", ",", "$", "functionOrClass", ")", ";", "$", "function", "=", "\\", "array_pop", "(", "$", "function", ")", ";", "if", "(", "!", "empty", "(", "$", "functions", "[", "$", "function", "]", ")", ")", "{", "unset", "(", "$", "functions", "[", "$", "function", "]", ")", ";", "}", "}", "}", "return", "$", "functions", ";", "}" ]
If a method exists under a namespace and has been aliased, or has been imported, don't replace. @param FileGenerator $generator @param array $functions @return array
[ "If", "a", "method", "exists", "under", "a", "namespace", "and", "has", "been", "aliased", "or", "has", "been", "imported", "don", "t", "replace", "." ]
e55984ef50b60c165b5f204a6ffb2756ee1592b2
https://github.com/nilportugues/php-backslasher/blob/e55984ef50b60c165b5f204a6ffb2756ee1592b2/src/BackslashFixer/Fixer/FileEditor.php#L103-L119
35,677
dunglas/php-torcontrol
src/TorControl.php
TorControl.detectAuthMethod
private function detectAuthMethod() { $data = $this->executeCommand('PROTOCOLINFO'); foreach ($data as $info) { if ('AUTH METHODS=NULL' === $info['message']) { $this->options['authmethod'] = static::AUTH_METHOD_NULL; return; } if ('AUTH METHODS=HASHEDPASSWORD' === $info['message']) { $this->options['authmethod'] = static::AUTH_METHOD_HASHEDPASSWORD; return; } if (preg_match('/^AUTH METHODS=(.*) COOKIEFILE="(.*)"/', $info['message'], $matches) === 1) { $this->options['authmethod'] = static::AUTH_METHOD_COOKIE; $this->options['cookiefile'] = $matches[2]; return; } } throw new Exception\ProtocolError('Auth method not supported'); }
php
private function detectAuthMethod() { $data = $this->executeCommand('PROTOCOLINFO'); foreach ($data as $info) { if ('AUTH METHODS=NULL' === $info['message']) { $this->options['authmethod'] = static::AUTH_METHOD_NULL; return; } if ('AUTH METHODS=HASHEDPASSWORD' === $info['message']) { $this->options['authmethod'] = static::AUTH_METHOD_HASHEDPASSWORD; return; } if (preg_match('/^AUTH METHODS=(.*) COOKIEFILE="(.*)"/', $info['message'], $matches) === 1) { $this->options['authmethod'] = static::AUTH_METHOD_COOKIE; $this->options['cookiefile'] = $matches[2]; return; } } throw new Exception\ProtocolError('Auth method not supported'); }
[ "private", "function", "detectAuthMethod", "(", ")", "{", "$", "data", "=", "$", "this", "->", "executeCommand", "(", "'PROTOCOLINFO'", ")", ";", "foreach", "(", "$", "data", "as", "$", "info", ")", "{", "if", "(", "'AUTH METHODS=NULL'", "===", "$", "info", "[", "'message'", "]", ")", "{", "$", "this", "->", "options", "[", "'authmethod'", "]", "=", "static", "::", "AUTH_METHOD_NULL", ";", "return", ";", "}", "if", "(", "'AUTH METHODS=HASHEDPASSWORD'", "===", "$", "info", "[", "'message'", "]", ")", "{", "$", "this", "->", "options", "[", "'authmethod'", "]", "=", "static", "::", "AUTH_METHOD_HASHEDPASSWORD", ";", "return", ";", "}", "if", "(", "preg_match", "(", "'/^AUTH METHODS=(.*) COOKIEFILE=\"(.*)\"/'", ",", "$", "info", "[", "'message'", "]", ",", "$", "matches", ")", "===", "1", ")", "{", "$", "this", "->", "options", "[", "'authmethod'", "]", "=", "static", "::", "AUTH_METHOD_COOKIE", ";", "$", "this", "->", "options", "[", "'cookiefile'", "]", "=", "$", "matches", "[", "2", "]", ";", "return", ";", "}", "}", "throw", "new", "Exception", "\\", "ProtocolError", "(", "'Auth method not supported'", ")", ";", "}" ]
Detects auth method using the PROTOCOLINFO command. @throws Exception\ProtocolError
[ "Detects", "auth", "method", "using", "the", "PROTOCOLINFO", "command", "." ]
ef908baf586acbc36dac4a2eed3a560894ffafee
https://github.com/dunglas/php-torcontrol/blob/ef908baf586acbc36dac4a2eed3a560894ffafee/src/TorControl.php#L79-L105
35,678
dunglas/php-torcontrol
src/TorControl.php
TorControl.connect
public function connect() { if ($this->connected) { return; } $this->socket = @fsockopen($this->options['hostname'], $this->options['port'], $errno, $errstr, $this->options['timeout']); if (!$this->socket) { throw new Exception\IOError($errno.' - '.$errstr); } $this->connected = true; return $this; }
php
public function connect() { if ($this->connected) { return; } $this->socket = @fsockopen($this->options['hostname'], $this->options['port'], $errno, $errstr, $this->options['timeout']); if (!$this->socket) { throw new Exception\IOError($errno.' - '.$errstr); } $this->connected = true; return $this; }
[ "public", "function", "connect", "(", ")", "{", "if", "(", "$", "this", "->", "connected", ")", "{", "return", ";", "}", "$", "this", "->", "socket", "=", "@", "fsockopen", "(", "$", "this", "->", "options", "[", "'hostname'", "]", ",", "$", "this", "->", "options", "[", "'port'", "]", ",", "$", "errno", ",", "$", "errstr", ",", "$", "this", "->", "options", "[", "'timeout'", "]", ")", ";", "if", "(", "!", "$", "this", "->", "socket", ")", "{", "throw", "new", "Exception", "\\", "IOError", "(", "$", "errno", ".", "' - '", ".", "$", "errstr", ")", ";", "}", "$", "this", "->", "connected", "=", "true", ";", "return", "$", "this", ";", "}" ]
Connects to the Tor server. @throws Exception\IOError @return \TorControl\TorControl
[ "Connects", "to", "the", "Tor", "server", "." ]
ef908baf586acbc36dac4a2eed3a560894ffafee
https://github.com/dunglas/php-torcontrol/blob/ef908baf586acbc36dac4a2eed3a560894ffafee/src/TorControl.php#L168-L182
35,679
dunglas/php-torcontrol
src/TorControl.php
TorControl.authenticate
public function authenticate() { if (static::AUTH_METHOD_NOT_SET === $this->options['authmethod']) { $this->detectAuthMethod(); } switch ($this->options['authmethod']) { case static::AUTH_METHOD_NULL: $this->executeCommand('AUTHENTICATE'); break; case static::AUTH_METHOD_HASHEDPASSWORD: $password = $this->getOption('password'); if (false === $password) { throw new \Exception('You must set a password option'); } $this->executeCommand('AUTHENTICATE '.static::quote($password)); break; case static::AUTH_METHOD_COOKIE: $cookieFile = $this->getOption('cookiefile'); if (false === $cookieFile) { throw new \Exception('You must set a cookiefile option'); } $cookie = file_get_contents($cookieFile); $this->executeCommand('AUTHENTICATE '.bin2hex($cookie)); break; } return $this; }
php
public function authenticate() { if (static::AUTH_METHOD_NOT_SET === $this->options['authmethod']) { $this->detectAuthMethod(); } switch ($this->options['authmethod']) { case static::AUTH_METHOD_NULL: $this->executeCommand('AUTHENTICATE'); break; case static::AUTH_METHOD_HASHEDPASSWORD: $password = $this->getOption('password'); if (false === $password) { throw new \Exception('You must set a password option'); } $this->executeCommand('AUTHENTICATE '.static::quote($password)); break; case static::AUTH_METHOD_COOKIE: $cookieFile = $this->getOption('cookiefile'); if (false === $cookieFile) { throw new \Exception('You must set a cookiefile option'); } $cookie = file_get_contents($cookieFile); $this->executeCommand('AUTHENTICATE '.bin2hex($cookie)); break; } return $this; }
[ "public", "function", "authenticate", "(", ")", "{", "if", "(", "static", "::", "AUTH_METHOD_NOT_SET", "===", "$", "this", "->", "options", "[", "'authmethod'", "]", ")", "{", "$", "this", "->", "detectAuthMethod", "(", ")", ";", "}", "switch", "(", "$", "this", "->", "options", "[", "'authmethod'", "]", ")", "{", "case", "static", "::", "AUTH_METHOD_NULL", ":", "$", "this", "->", "executeCommand", "(", "'AUTHENTICATE'", ")", ";", "break", ";", "case", "static", "::", "AUTH_METHOD_HASHEDPASSWORD", ":", "$", "password", "=", "$", "this", "->", "getOption", "(", "'password'", ")", ";", "if", "(", "false", "===", "$", "password", ")", "{", "throw", "new", "\\", "Exception", "(", "'You must set a password option'", ")", ";", "}", "$", "this", "->", "executeCommand", "(", "'AUTHENTICATE '", ".", "static", "::", "quote", "(", "$", "password", ")", ")", ";", "break", ";", "case", "static", "::", "AUTH_METHOD_COOKIE", ":", "$", "cookieFile", "=", "$", "this", "->", "getOption", "(", "'cookiefile'", ")", ";", "if", "(", "false", "===", "$", "cookieFile", ")", "{", "throw", "new", "\\", "Exception", "(", "'You must set a cookiefile option'", ")", ";", "}", "$", "cookie", "=", "file_get_contents", "(", "$", "cookieFile", ")", ";", "$", "this", "->", "executeCommand", "(", "'AUTHENTICATE '", ".", "bin2hex", "(", "$", "cookie", ")", ")", ";", "break", ";", "}", "return", "$", "this", ";", "}" ]
Authenticates to the Tor server. Autodetect authentication method if not set in options @throws \Exception @return \TorControl\TorControl
[ "Authenticates", "to", "the", "Tor", "server", "." ]
ef908baf586acbc36dac4a2eed3a560894ffafee
https://github.com/dunglas/php-torcontrol/blob/ef908baf586acbc36dac4a2eed3a560894ffafee/src/TorControl.php#L193-L225
35,680
dunglas/php-torcontrol
src/TorControl.php
TorControl.executeCommand
public function executeCommand($cmd) { $this->checkConnected(); $write = @fwrite($this->socket, "$cmd\r\n"); if (false === $write) { throw new Exception\IOError('Error while writing to the Tor server'); } $data = []; while (true) { $response = fread($this->socket, 1024); $multiline = false; $last_code = null; $last_separator = null; foreach (explode("\r\n", $response) as $line) { $code = substr($line, 0, 3); $separator = substr($line, 3, 1); $message = substr($line, 4); if ('+' === $separator) { $multiline = true; $last_code = $code; $last_separator = $separator; } if ($multiline) { $data[] = [ 'code' => $last_code, 'separator' => $last_separator, 'message' => $line, ]; } else { if (false === $code || false === $separator) { $e = new Exception\ProtocolError('Bad response format'); $e->setResponse($response); throw $e; } if (!in_array($separator, [' ', '+', '-'])) { $e = new Exception\ProtocolError('Unknown separator'); $e->setResponse($response); throw $e; } if (!in_array(substr($code, 0, 1), ['2', '6'])) { $e = new Exception\TorError($message, $code); $e->setResponse($response); return $e; } $data[] = [ 'code' => $code, 'separator' => $separator, 'message' => $message, ]; } if (' ' === $separator) { break 2; } } } return $data; }
php
public function executeCommand($cmd) { $this->checkConnected(); $write = @fwrite($this->socket, "$cmd\r\n"); if (false === $write) { throw new Exception\IOError('Error while writing to the Tor server'); } $data = []; while (true) { $response = fread($this->socket, 1024); $multiline = false; $last_code = null; $last_separator = null; foreach (explode("\r\n", $response) as $line) { $code = substr($line, 0, 3); $separator = substr($line, 3, 1); $message = substr($line, 4); if ('+' === $separator) { $multiline = true; $last_code = $code; $last_separator = $separator; } if ($multiline) { $data[] = [ 'code' => $last_code, 'separator' => $last_separator, 'message' => $line, ]; } else { if (false === $code || false === $separator) { $e = new Exception\ProtocolError('Bad response format'); $e->setResponse($response); throw $e; } if (!in_array($separator, [' ', '+', '-'])) { $e = new Exception\ProtocolError('Unknown separator'); $e->setResponse($response); throw $e; } if (!in_array(substr($code, 0, 1), ['2', '6'])) { $e = new Exception\TorError($message, $code); $e->setResponse($response); return $e; } $data[] = [ 'code' => $code, 'separator' => $separator, 'message' => $message, ]; } if (' ' === $separator) { break 2; } } } return $data; }
[ "public", "function", "executeCommand", "(", "$", "cmd", ")", "{", "$", "this", "->", "checkConnected", "(", ")", ";", "$", "write", "=", "@", "fwrite", "(", "$", "this", "->", "socket", ",", "\"$cmd\\r\\n\"", ")", ";", "if", "(", "false", "===", "$", "write", ")", "{", "throw", "new", "Exception", "\\", "IOError", "(", "'Error while writing to the Tor server'", ")", ";", "}", "$", "data", "=", "[", "]", ";", "while", "(", "true", ")", "{", "$", "response", "=", "fread", "(", "$", "this", "->", "socket", ",", "1024", ")", ";", "$", "multiline", "=", "false", ";", "$", "last_code", "=", "null", ";", "$", "last_separator", "=", "null", ";", "foreach", "(", "explode", "(", "\"\\r\\n\"", ",", "$", "response", ")", "as", "$", "line", ")", "{", "$", "code", "=", "substr", "(", "$", "line", ",", "0", ",", "3", ")", ";", "$", "separator", "=", "substr", "(", "$", "line", ",", "3", ",", "1", ")", ";", "$", "message", "=", "substr", "(", "$", "line", ",", "4", ")", ";", "if", "(", "'+'", "===", "$", "separator", ")", "{", "$", "multiline", "=", "true", ";", "$", "last_code", "=", "$", "code", ";", "$", "last_separator", "=", "$", "separator", ";", "}", "if", "(", "$", "multiline", ")", "{", "$", "data", "[", "]", "=", "[", "'code'", "=>", "$", "last_code", ",", "'separator'", "=>", "$", "last_separator", ",", "'message'", "=>", "$", "line", ",", "]", ";", "}", "else", "{", "if", "(", "false", "===", "$", "code", "||", "false", "===", "$", "separator", ")", "{", "$", "e", "=", "new", "Exception", "\\", "ProtocolError", "(", "'Bad response format'", ")", ";", "$", "e", "->", "setResponse", "(", "$", "response", ")", ";", "throw", "$", "e", ";", "}", "if", "(", "!", "in_array", "(", "$", "separator", ",", "[", "' '", ",", "'+'", ",", "'-'", "]", ")", ")", "{", "$", "e", "=", "new", "Exception", "\\", "ProtocolError", "(", "'Unknown separator'", ")", ";", "$", "e", "->", "setResponse", "(", "$", "response", ")", ";", "throw", "$", "e", ";", "}", "if", "(", "!", "in_array", "(", "substr", "(", "$", "code", ",", "0", ",", "1", ")", ",", "[", "'2'", ",", "'6'", "]", ")", ")", "{", "$", "e", "=", "new", "Exception", "\\", "TorError", "(", "$", "message", ",", "$", "code", ")", ";", "$", "e", "->", "setResponse", "(", "$", "response", ")", ";", "return", "$", "e", ";", "}", "$", "data", "[", "]", "=", "[", "'code'", "=>", "$", "code", ",", "'separator'", "=>", "$", "separator", ",", "'message'", "=>", "$", "message", ",", "]", ";", "}", "if", "(", "' '", "===", "$", "separator", ")", "{", "break", "2", ";", "}", "}", "}", "return", "$", "data", ";", "}" ]
Executes a command on the Tor server. @param string $cmd @throws Exception\IOError @throws Exception\ProtocolError @return array
[ "Executes", "a", "command", "on", "the", "Tor", "server", "." ]
ef908baf586acbc36dac4a2eed3a560894ffafee
https://github.com/dunglas/php-torcontrol/blob/ef908baf586acbc36dac4a2eed3a560894ffafee/src/TorControl.php#L237-L306
35,681
dunglas/php-torcontrol
src/TorControl.php
TorControl.quit
public function quit() { if ($this->connected && $this->socket) { $this->executeCommand('QUIT'); $close = @fclose($this->socket); if (!$close) { throw new Exception\IOError('Error while closing the connection to the Tor server'); } } $this->connected = false; }
php
public function quit() { if ($this->connected && $this->socket) { $this->executeCommand('QUIT'); $close = @fclose($this->socket); if (!$close) { throw new Exception\IOError('Error while closing the connection to the Tor server'); } } $this->connected = false; }
[ "public", "function", "quit", "(", ")", "{", "if", "(", "$", "this", "->", "connected", "&&", "$", "this", "->", "socket", ")", "{", "$", "this", "->", "executeCommand", "(", "'QUIT'", ")", ";", "$", "close", "=", "@", "fclose", "(", "$", "this", "->", "socket", ")", ";", "if", "(", "!", "$", "close", ")", "{", "throw", "new", "Exception", "\\", "IOError", "(", "'Error while closing the connection to the Tor server'", ")", ";", "}", "}", "$", "this", "->", "connected", "=", "false", ";", "}" ]
Closes the connection to the Tor server.
[ "Closes", "the", "connection", "to", "the", "Tor", "server", "." ]
ef908baf586acbc36dac4a2eed3a560894ffafee
https://github.com/dunglas/php-torcontrol/blob/ef908baf586acbc36dac4a2eed3a560894ffafee/src/TorControl.php#L311-L322
35,682
KnpLabs/rad-resource-resolver
src/Knp/Rad/ResourceResolver/RoutingNormalizer.php
RoutingNormalizer.normalizeDeclaration
public function normalizeDeclaration($declaration) { if (is_string($declaration)) { return $this->normalizeString($declaration); } // Normalize numerically indexed array if (array_keys($declaration) === array_keys(array_values($declaration))) { return $this->normalizeArray($declaration); } if (isset($declaration['arguments']) && !is_array($declaration['arguments'])) { throw new \InvalidArgumentException('The "arguments" parameter should be an array of arguments.'); } // Adds default value to associative array return array_merge(['method' => null, 'required' => true, 'arguments' => []], $declaration); }
php
public function normalizeDeclaration($declaration) { if (is_string($declaration)) { return $this->normalizeString($declaration); } // Normalize numerically indexed array if (array_keys($declaration) === array_keys(array_values($declaration))) { return $this->normalizeArray($declaration); } if (isset($declaration['arguments']) && !is_array($declaration['arguments'])) { throw new \InvalidArgumentException('The "arguments" parameter should be an array of arguments.'); } // Adds default value to associative array return array_merge(['method' => null, 'required' => true, 'arguments' => []], $declaration); }
[ "public", "function", "normalizeDeclaration", "(", "$", "declaration", ")", "{", "if", "(", "is_string", "(", "$", "declaration", ")", ")", "{", "return", "$", "this", "->", "normalizeString", "(", "$", "declaration", ")", ";", "}", "// Normalize numerically indexed array", "if", "(", "array_keys", "(", "$", "declaration", ")", "===", "array_keys", "(", "array_values", "(", "$", "declaration", ")", ")", ")", "{", "return", "$", "this", "->", "normalizeArray", "(", "$", "declaration", ")", ";", "}", "if", "(", "isset", "(", "$", "declaration", "[", "'arguments'", "]", ")", "&&", "!", "is_array", "(", "$", "declaration", "[", "'arguments'", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The \"arguments\" parameter should be an array of arguments.'", ")", ";", "}", "// Adds default value to associative array", "return", "array_merge", "(", "[", "'method'", "=>", "null", ",", "'required'", "=>", "true", ",", "'arguments'", "=>", "[", "]", "]", ",", "$", "declaration", ")", ";", "}" ]
Normalizes string and array declarations into associative array. @param string|array $declaration @return array
[ "Normalizes", "string", "and", "array", "declarations", "into", "associative", "array", "." ]
e4ece8d1fa8cbc984c98a27f6025002d3b449f56
https://github.com/KnpLabs/rad-resource-resolver/blob/e4ece8d1fa8cbc984c98a27f6025002d3b449f56/src/Knp/Rad/ResourceResolver/RoutingNormalizer.php#L14-L31
35,683
ouqiang/etcd-php
src/Client.php
Client.put
public function put($key, $value, array $options = []) { $params = [ 'key' => $key, 'value' => $value, ]; $params = $this->encode($params); $options = $this->encode($options); $body = $this->request(self::URI_PUT, $params, $options); $body = $this->decodeBodyForFields( $body, 'prev_kv', ['key', 'value',] ); if (isset($body['prev_kv']) && $this->pretty) { return $this->convertFields($body['prev_kv']); } return $body; }
php
public function put($key, $value, array $options = []) { $params = [ 'key' => $key, 'value' => $value, ]; $params = $this->encode($params); $options = $this->encode($options); $body = $this->request(self::URI_PUT, $params, $options); $body = $this->decodeBodyForFields( $body, 'prev_kv', ['key', 'value',] ); if (isset($body['prev_kv']) && $this->pretty) { return $this->convertFields($body['prev_kv']); } return $body; }
[ "public", "function", "put", "(", "$", "key", ",", "$", "value", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "[", "'key'", "=>", "$", "key", ",", "'value'", "=>", "$", "value", ",", "]", ";", "$", "params", "=", "$", "this", "->", "encode", "(", "$", "params", ")", ";", "$", "options", "=", "$", "this", "->", "encode", "(", "$", "options", ")", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_PUT", ",", "$", "params", ",", "$", "options", ")", ";", "$", "body", "=", "$", "this", "->", "decodeBodyForFields", "(", "$", "body", ",", "'prev_kv'", ",", "[", "'key'", ",", "'value'", ",", "]", ")", ";", "if", "(", "isset", "(", "$", "body", "[", "'prev_kv'", "]", ")", "&&", "$", "this", "->", "pretty", ")", "{", "return", "$", "this", "->", "convertFields", "(", "$", "body", "[", "'prev_kv'", "]", ")", ";", "}", "return", "$", "body", ";", "}" ]
Put puts the given key into the key-value store. A put request increments the revision of the key-value store\nand generates one event in the event history. @param string $key @param string $value @param array $options 可选参数 int64 lease bool prev_kv bool ignore_value bool ignore_lease @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "Put", "puts", "the", "given", "key", "into", "the", "key", "-", "value", "store", ".", "A", "put", "request", "increments", "the", "revision", "of", "the", "key", "-", "value", "store", "\\", "nand", "generates", "one", "event", "in", "the", "event", "history", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L127-L148
35,684
ouqiang/etcd-php
src/Client.php
Client.get
public function get($key, array $options = []) { $params = [ 'key' => $key, ]; $params = $this->encode($params); $options = $this->encode($options); $body = $this->request(self::URI_RANGE, $params, $options); $body = $this->decodeBodyForFields( $body, 'kvs', ['key', 'value',] ); if (isset($body['kvs']) && $this->pretty) { return $this->convertFields($body['kvs']); } return $body; }
php
public function get($key, array $options = []) { $params = [ 'key' => $key, ]; $params = $this->encode($params); $options = $this->encode($options); $body = $this->request(self::URI_RANGE, $params, $options); $body = $this->decodeBodyForFields( $body, 'kvs', ['key', 'value',] ); if (isset($body['kvs']) && $this->pretty) { return $this->convertFields($body['kvs']); } return $body; }
[ "public", "function", "get", "(", "$", "key", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "[", "'key'", "=>", "$", "key", ",", "]", ";", "$", "params", "=", "$", "this", "->", "encode", "(", "$", "params", ")", ";", "$", "options", "=", "$", "this", "->", "encode", "(", "$", "options", ")", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_RANGE", ",", "$", "params", ",", "$", "options", ")", ";", "$", "body", "=", "$", "this", "->", "decodeBodyForFields", "(", "$", "body", ",", "'kvs'", ",", "[", "'key'", ",", "'value'", ",", "]", ")", ";", "if", "(", "isset", "(", "$", "body", "[", "'kvs'", "]", ")", "&&", "$", "this", "->", "pretty", ")", "{", "return", "$", "this", "->", "convertFields", "(", "$", "body", "[", "'kvs'", "]", ")", ";", "}", "return", "$", "body", ";", "}" ]
Gets the key or a range of keys @param string $key @param array $options string range_end int limit int revision int sort_order int sort_target bool serializable bool keys_only bool count_only int64 min_mod_revision int64 max_mod_revision int64 min_create_revision int64 max_create_revision @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "Gets", "the", "key", "or", "a", "range", "of", "keys" ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L170-L189
35,685
ouqiang/etcd-php
src/Client.php
Client.getKeysWithPrefix
public function getKeysWithPrefix($prefix) { $prefix = trim($prefix); if (!$prefix) { return []; } $lastIndex = strlen($prefix) - 1; $lastChar = $prefix[$lastIndex]; $nextAsciiCode = ord($lastChar) + 1; $rangeEnd = $prefix; $rangeEnd[$lastIndex] = chr($nextAsciiCode); return $this->get($prefix, ['range_end' => $rangeEnd]); }
php
public function getKeysWithPrefix($prefix) { $prefix = trim($prefix); if (!$prefix) { return []; } $lastIndex = strlen($prefix) - 1; $lastChar = $prefix[$lastIndex]; $nextAsciiCode = ord($lastChar) + 1; $rangeEnd = $prefix; $rangeEnd[$lastIndex] = chr($nextAsciiCode); return $this->get($prefix, ['range_end' => $rangeEnd]); }
[ "public", "function", "getKeysWithPrefix", "(", "$", "prefix", ")", "{", "$", "prefix", "=", "trim", "(", "$", "prefix", ")", ";", "if", "(", "!", "$", "prefix", ")", "{", "return", "[", "]", ";", "}", "$", "lastIndex", "=", "strlen", "(", "$", "prefix", ")", "-", "1", ";", "$", "lastChar", "=", "$", "prefix", "[", "$", "lastIndex", "]", ";", "$", "nextAsciiCode", "=", "ord", "(", "$", "lastChar", ")", "+", "1", ";", "$", "rangeEnd", "=", "$", "prefix", ";", "$", "rangeEnd", "[", "$", "lastIndex", "]", "=", "chr", "(", "$", "nextAsciiCode", ")", ";", "return", "$", "this", "->", "get", "(", "$", "prefix", ",", "[", "'range_end'", "=>", "$", "rangeEnd", "]", ")", ";", "}" ]
get all keys with prefix @param string $prefix @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "get", "all", "keys", "with", "prefix" ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L209-L222
35,686
ouqiang/etcd-php
src/Client.php
Client.del
public function del($key, array $options = []) { $params = [ 'key' => $key, ]; $params = $this->encode($params); $options = $this->encode($options); $body = $this->request(self::URI_DELETE_RANGE, $params, $options); $body = $this->decodeBodyForFields( $body, 'prev_kvs', ['key', 'value',] ); if (isset($body['prev_kvs']) && $this->pretty) { return $this->convertFields($body['prev_kvs']); } return $body; }
php
public function del($key, array $options = []) { $params = [ 'key' => $key, ]; $params = $this->encode($params); $options = $this->encode($options); $body = $this->request(self::URI_DELETE_RANGE, $params, $options); $body = $this->decodeBodyForFields( $body, 'prev_kvs', ['key', 'value',] ); if (isset($body['prev_kvs']) && $this->pretty) { return $this->convertFields($body['prev_kvs']); } return $body; }
[ "public", "function", "del", "(", "$", "key", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "[", "'key'", "=>", "$", "key", ",", "]", ";", "$", "params", "=", "$", "this", "->", "encode", "(", "$", "params", ")", ";", "$", "options", "=", "$", "this", "->", "encode", "(", "$", "options", ")", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_DELETE_RANGE", ",", "$", "params", ",", "$", "options", ")", ";", "$", "body", "=", "$", "this", "->", "decodeBodyForFields", "(", "$", "body", ",", "'prev_kvs'", ",", "[", "'key'", ",", "'value'", ",", "]", ")", ";", "if", "(", "isset", "(", "$", "body", "[", "'prev_kvs'", "]", ")", "&&", "$", "this", "->", "pretty", ")", "{", "return", "$", "this", "->", "convertFields", "(", "$", "body", "[", "'prev_kvs'", "]", ")", ";", "}", "return", "$", "body", ";", "}" ]
Removes the specified key or range of keys @param string $key @param array $options string range_end bool prev_kv @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "Removes", "the", "specified", "key", "or", "range", "of", "keys" ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L234-L253
35,687
ouqiang/etcd-php
src/Client.php
Client.compaction
public function compaction($revision, $physical = false) { $params = [ 'revision' => $revision, 'physical' => $physical, ]; $body = $this->request(self::URI_COMPACTION, $params); return $body; }
php
public function compaction($revision, $physical = false) { $params = [ 'revision' => $revision, 'physical' => $physical, ]; $body = $this->request(self::URI_COMPACTION, $params); return $body; }
[ "public", "function", "compaction", "(", "$", "revision", ",", "$", "physical", "=", "false", ")", "{", "$", "params", "=", "[", "'revision'", "=>", "$", "revision", ",", "'physical'", "=>", "$", "physical", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_COMPACTION", ",", "$", "params", ")", ";", "return", "$", "body", ";", "}" ]
Compact compacts the event history in the etcd key-value store. The key-value\nstore should be periodically compacted or the event history will continue to grow\nindefinitely. @param int $revision @param bool|false $physical @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "Compact", "compacts", "the", "event", "history", "in", "the", "etcd", "key", "-", "value", "store", ".", "The", "key", "-", "value", "\\", "nstore", "should", "be", "periodically", "compacted", "or", "the", "event", "history", "will", "continue", "to", "grow", "\\", "nindefinitely", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L267-L277
35,688
ouqiang/etcd-php
src/Client.php
Client.grant
public function grant($ttl, $id = 0) { $params = [ 'TTL' => $ttl, 'ID' => $id, ]; $body = $this->request(self::URI_GRANT, $params); return $body; }
php
public function grant($ttl, $id = 0) { $params = [ 'TTL' => $ttl, 'ID' => $id, ]; $body = $this->request(self::URI_GRANT, $params); return $body; }
[ "public", "function", "grant", "(", "$", "ttl", ",", "$", "id", "=", "0", ")", "{", "$", "params", "=", "[", "'TTL'", "=>", "$", "ttl", ",", "'ID'", "=>", "$", "id", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_GRANT", ",", "$", "params", ")", ";", "return", "$", "body", ";", "}" ]
LeaseGrant creates a lease which expires if the server does not receive a keepAlive\nwithin a given time to live period. All keys attached to the lease will be expired and\ndeleted if the lease expires. Each expired key generates a delete event in the event history.", @param int $ttl TTL is the advisory time-to-live in seconds. @param int $id ID is the requested ID for the lease. If ID is set to 0, the lessor chooses an ID. @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "LeaseGrant", "creates", "a", "lease", "which", "expires", "if", "the", "server", "does", "not", "receive", "a", "keepAlive", "\\", "nwithin", "a", "given", "time", "to", "live", "period", ".", "All", "keys", "attached", "to", "the", "lease", "will", "be", "expired", "and", "\\", "ndeleted", "if", "the", "lease", "expires", ".", "Each", "expired", "key", "generates", "a", "delete", "event", "in", "the", "event", "history", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L295-L306
35,689
ouqiang/etcd-php
src/Client.php
Client.revoke
public function revoke($id) { $params = [ 'ID' => $id, ]; $body = $this->request(self::URI_REVOKE, $params); return $body; }
php
public function revoke($id) { $params = [ 'ID' => $id, ]; $body = $this->request(self::URI_REVOKE, $params); return $body; }
[ "public", "function", "revoke", "(", "$", "id", ")", "{", "$", "params", "=", "[", "'ID'", "=>", "$", "id", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_REVOKE", ",", "$", "params", ")", ";", "return", "$", "body", ";", "}" ]
revokes a lease. All keys attached to the lease will expire and be deleted. @param int $id ID is the lease ID to revoke. When the ID is revoked, all associated keys will be deleted. @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "revokes", "a", "lease", ".", "All", "keys", "attached", "to", "the", "lease", "will", "expire", "and", "be", "deleted", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L316-L325
35,690
ouqiang/etcd-php
src/Client.php
Client.keepAlive
public function keepAlive($id) { $params = [ 'ID' => $id, ]; $body = $this->request(self::URI_KEEPALIVE, $params); if (!isset($body['result'])) { return $body; } // response "result" field, etcd bug? return [ 'ID' => $body['result']['ID'], 'TTL' => $body['result']['TTL'], ]; }
php
public function keepAlive($id) { $params = [ 'ID' => $id, ]; $body = $this->request(self::URI_KEEPALIVE, $params); if (!isset($body['result'])) { return $body; } // response "result" field, etcd bug? return [ 'ID' => $body['result']['ID'], 'TTL' => $body['result']['TTL'], ]; }
[ "public", "function", "keepAlive", "(", "$", "id", ")", "{", "$", "params", "=", "[", "'ID'", "=>", "$", "id", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_KEEPALIVE", ",", "$", "params", ")", ";", "if", "(", "!", "isset", "(", "$", "body", "[", "'result'", "]", ")", ")", "{", "return", "$", "body", ";", "}", "// response \"result\" field, etcd bug?", "return", "[", "'ID'", "=>", "$", "body", "[", "'result'", "]", "[", "'ID'", "]", ",", "'TTL'", "=>", "$", "body", "[", "'result'", "]", "[", "'TTL'", "]", ",", "]", ";", "}" ]
keeps the lease alive by streaming keep alive requests from the client\nto the server and streaming keep alive responses from the server to the client. @param int $id ID is the lease ID for the lease to keep alive. @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "keeps", "the", "lease", "alive", "by", "streaming", "keep", "alive", "requests", "from", "the", "client", "\\", "nto", "the", "server", "and", "streaming", "keep", "alive", "responses", "from", "the", "server", "to", "the", "client", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L336-L352
35,691
ouqiang/etcd-php
src/Client.php
Client.timeToLive
public function timeToLive($id, $keys = false) { $params = [ 'ID' => $id, 'keys' => $keys, ]; $body = $this->request(self::URI_TIMETOLIVE, $params); if (isset($body['keys'])) { $body['keys'] = array_map(function($value) { return base64_decode($value); }, $body['keys']); } return $body; }
php
public function timeToLive($id, $keys = false) { $params = [ 'ID' => $id, 'keys' => $keys, ]; $body = $this->request(self::URI_TIMETOLIVE, $params); if (isset($body['keys'])) { $body['keys'] = array_map(function($value) { return base64_decode($value); }, $body['keys']); } return $body; }
[ "public", "function", "timeToLive", "(", "$", "id", ",", "$", "keys", "=", "false", ")", "{", "$", "params", "=", "[", "'ID'", "=>", "$", "id", ",", "'keys'", "=>", "$", "keys", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_TIMETOLIVE", ",", "$", "params", ")", ";", "if", "(", "isset", "(", "$", "body", "[", "'keys'", "]", ")", ")", "{", "$", "body", "[", "'keys'", "]", "=", "array_map", "(", "function", "(", "$", "value", ")", "{", "return", "base64_decode", "(", "$", "value", ")", ";", "}", ",", "$", "body", "[", "'keys'", "]", ")", ";", "}", "return", "$", "body", ";", "}" ]
retrieves lease information. @param int $id ID is the lease ID for the lease. @param bool|false $keys @return array @throws BadResponseException
[ "retrieves", "lease", "information", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L362-L378
35,692
ouqiang/etcd-php
src/Client.php
Client.addRole
public function addRole($name) { $params = [ 'name' => $name, ]; $body = $this->request(self::URI_AUTH_ROLE_ADD, $params); return $body; }
php
public function addRole($name) { $params = [ 'name' => $name, ]; $body = $this->request(self::URI_AUTH_ROLE_ADD, $params); return $body; }
[ "public", "function", "addRole", "(", "$", "name", ")", "{", "$", "params", "=", "[", "'name'", "=>", "$", "name", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_AUTH_ROLE_ADD", ",", "$", "params", ")", ";", "return", "$", "body", ";", "}" ]
add a new role. @param string $name @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "add", "a", "new", "role", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L440-L449
35,693
ouqiang/etcd-php
src/Client.php
Client.getRole
public function getRole($role) { $params = [ 'role' => $role, ]; $body = $this->request(self::URI_AUTH_ROLE_GET, $params); $body = $this->decodeBodyForFields( $body, 'perm', ['key', 'range_end',] ); if ($this->pretty && isset($body['perm'])) { return $body['perm']; } return $body; }
php
public function getRole($role) { $params = [ 'role' => $role, ]; $body = $this->request(self::URI_AUTH_ROLE_GET, $params); $body = $this->decodeBodyForFields( $body, 'perm', ['key', 'range_end',] ); if ($this->pretty && isset($body['perm'])) { return $body['perm']; } return $body; }
[ "public", "function", "getRole", "(", "$", "role", ")", "{", "$", "params", "=", "[", "'role'", "=>", "$", "role", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_AUTH_ROLE_GET", ",", "$", "params", ")", ";", "$", "body", "=", "$", "this", "->", "decodeBodyForFields", "(", "$", "body", ",", "'perm'", ",", "[", "'key'", ",", "'range_end'", ",", "]", ")", ";", "if", "(", "$", "this", "->", "pretty", "&&", "isset", "(", "$", "body", "[", "'perm'", "]", ")", ")", "{", "return", "$", "body", "[", "'perm'", "]", ";", "}", "return", "$", "body", ";", "}" ]
get detailed role information. @param string $role @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "get", "detailed", "role", "information", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L458-L475
35,694
ouqiang/etcd-php
src/Client.php
Client.deleteRole
public function deleteRole($role) { $params = [ 'role' => $role, ]; $body = $this->request(self::URI_AUTH_ROLE_DELETE, $params); return $body; }
php
public function deleteRole($role) { $params = [ 'role' => $role, ]; $body = $this->request(self::URI_AUTH_ROLE_DELETE, $params); return $body; }
[ "public", "function", "deleteRole", "(", "$", "role", ")", "{", "$", "params", "=", "[", "'role'", "=>", "$", "role", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_AUTH_ROLE_DELETE", ",", "$", "params", ")", ";", "return", "$", "body", ";", "}" ]
delete a specified role. @param string $role @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "delete", "a", "specified", "role", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L484-L493
35,695
ouqiang/etcd-php
src/Client.php
Client.roleList
public function roleList() { $body = $this->request(self::URI_AUTH_ROLE_LIST); if ($this->pretty && isset($body['roles'])) { return $body['roles']; } return $body; }
php
public function roleList() { $body = $this->request(self::URI_AUTH_ROLE_LIST); if ($this->pretty && isset($body['roles'])) { return $body['roles']; } return $body; }
[ "public", "function", "roleList", "(", ")", "{", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_AUTH_ROLE_LIST", ")", ";", "if", "(", "$", "this", "->", "pretty", "&&", "isset", "(", "$", "body", "[", "'roles'", "]", ")", ")", "{", "return", "$", "body", "[", "'roles'", "]", ";", "}", "return", "$", "body", ";", "}" ]
get lists of all roles @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "get", "lists", "of", "all", "roles" ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L501-L510
35,696
ouqiang/etcd-php
src/Client.php
Client.addUser
public function addUser($user, $password) { $params = [ 'name' => $user, 'password' => $password, ]; $body = $this->request(self::URI_AUTH_USER_ADD, $params); return $body; }
php
public function addUser($user, $password) { $params = [ 'name' => $user, 'password' => $password, ]; $body = $this->request(self::URI_AUTH_USER_ADD, $params); return $body; }
[ "public", "function", "addUser", "(", "$", "user", ",", "$", "password", ")", "{", "$", "params", "=", "[", "'name'", "=>", "$", "user", ",", "'password'", "=>", "$", "password", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_AUTH_USER_ADD", ",", "$", "params", ")", ";", "return", "$", "body", ";", "}" ]
add a new user @param string $user @param string $password @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "add", "a", "new", "user" ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L520-L530
35,697
ouqiang/etcd-php
src/Client.php
Client.getUser
public function getUser($user) { $params = [ 'name' => $user, ]; $body = $this->request(self::URI_AUTH_USER_GET, $params); if ($this->pretty && isset($body['roles'])) { return $body['roles']; } return $body; }
php
public function getUser($user) { $params = [ 'name' => $user, ]; $body = $this->request(self::URI_AUTH_USER_GET, $params); if ($this->pretty && isset($body['roles'])) { return $body['roles']; } return $body; }
[ "public", "function", "getUser", "(", "$", "user", ")", "{", "$", "params", "=", "[", "'name'", "=>", "$", "user", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_AUTH_USER_GET", ",", "$", "params", ")", ";", "if", "(", "$", "this", "->", "pretty", "&&", "isset", "(", "$", "body", "[", "'roles'", "]", ")", ")", "{", "return", "$", "body", "[", "'roles'", "]", ";", "}", "return", "$", "body", ";", "}" ]
get detailed user information @param string $user @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "get", "detailed", "user", "information" ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L539-L551
35,698
ouqiang/etcd-php
src/Client.php
Client.deleteUser
public function deleteUser($user) { $params = [ 'name' => $user, ]; $body = $this->request(self::URI_AUTH_USER_DELETE, $params); return $body; }
php
public function deleteUser($user) { $params = [ 'name' => $user, ]; $body = $this->request(self::URI_AUTH_USER_DELETE, $params); return $body; }
[ "public", "function", "deleteUser", "(", "$", "user", ")", "{", "$", "params", "=", "[", "'name'", "=>", "$", "user", ",", "]", ";", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_AUTH_USER_DELETE", ",", "$", "params", ")", ";", "return", "$", "body", ";", "}" ]
delete a specified user @param string $user @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "delete", "a", "specified", "user" ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L560-L569
35,699
ouqiang/etcd-php
src/Client.php
Client.userList
public function userList() { $body = $this->request(self::URI_AUTH_USER_LIST); if ($this->pretty && isset($body['users'])) { return $body['users']; } return $body; }
php
public function userList() { $body = $this->request(self::URI_AUTH_USER_LIST); if ($this->pretty && isset($body['users'])) { return $body['users']; } return $body; }
[ "public", "function", "userList", "(", ")", "{", "$", "body", "=", "$", "this", "->", "request", "(", "self", "::", "URI_AUTH_USER_LIST", ")", ";", "if", "(", "$", "this", "->", "pretty", "&&", "isset", "(", "$", "body", "[", "'users'", "]", ")", ")", "{", "return", "$", "body", "[", "'users'", "]", ";", "}", "return", "$", "body", ";", "}" ]
get a list of all users. @return array @throws \GuzzleHttp\Exception\BadResponseException
[ "get", "a", "list", "of", "all", "users", "." ]
8d16ee71fadb50e055b83509da78e21ff959fe2c
https://github.com/ouqiang/etcd-php/blob/8d16ee71fadb50e055b83509da78e21ff959fe2c/src/Client.php#L577-L585