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
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
12,300
factorio-item-browser/api-database
src/Repository/TranslationRepository.php
TranslationRepository.findDataByKeywords
public function findDataByKeywords(string $locale, array $keywords, array $modCombinationIds = []): array { $result = []; if (count($keywords) > 0) { $concat = 'LOWER(CONCAT(t.type, t.name, t.value, t.description))'; $priorityCase = 'CASE WHEN t.locale = :localePrimary THEN :priorityPrimary ' . 'WHEN t.locale = :localeSecondary THEN :prioritySecondary ELSE :priorityAny END'; $columns = [ 't.type AS type', 't.name AS name', 'MIN(' . $priorityCase . ') AS priority' ]; $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select($columns) ->from(Translation::class, 't') ->andWhere('t.type IN (:types)') ->addGroupBy('t.type') ->addGroupBy('t.name') ->setParameter('localePrimary', $locale) ->setParameter('localeSecondary', 'en') ->setParameter('priorityPrimary', SearchResultPriority::PRIMARY_LOCALE_MATCH) ->setParameter('prioritySecondary', SearchResultPriority::SECONDARY_LOCALE_MATCH) ->setParameter('priorityAny', SearchResultPriority::ANY_MATCH) ->setParameter('types', [ TranslationType::ITEM, TranslationType::FLUID, TranslationType::RECIPE ]); $index = 0; foreach ($keywords as $keyword) { $queryBuilder->andWhere($concat . ' LIKE :keyword' . $index) ->setParameter('keyword' . $index, '%' . addcslashes($keyword, '\\%_') . '%'); ++$index; } if (count($modCombinationIds) > 0) { $queryBuilder->innerJoin('t.modCombination', 'mc') ->andWhere('mc.id IN (:modCombinationIds)') ->setParameter('modCombinationIds', array_values($modCombinationIds)); } $result = $this->mapTranslationPriorityDataResult($queryBuilder->getQuery()->getResult()); } return $result; }
php
public function findDataByKeywords(string $locale, array $keywords, array $modCombinationIds = []): array { $result = []; if (count($keywords) > 0) { $concat = 'LOWER(CONCAT(t.type, t.name, t.value, t.description))'; $priorityCase = 'CASE WHEN t.locale = :localePrimary THEN :priorityPrimary ' . 'WHEN t.locale = :localeSecondary THEN :prioritySecondary ELSE :priorityAny END'; $columns = [ 't.type AS type', 't.name AS name', 'MIN(' . $priorityCase . ') AS priority' ]; $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select($columns) ->from(Translation::class, 't') ->andWhere('t.type IN (:types)') ->addGroupBy('t.type') ->addGroupBy('t.name') ->setParameter('localePrimary', $locale) ->setParameter('localeSecondary', 'en') ->setParameter('priorityPrimary', SearchResultPriority::PRIMARY_LOCALE_MATCH) ->setParameter('prioritySecondary', SearchResultPriority::SECONDARY_LOCALE_MATCH) ->setParameter('priorityAny', SearchResultPriority::ANY_MATCH) ->setParameter('types', [ TranslationType::ITEM, TranslationType::FLUID, TranslationType::RECIPE ]); $index = 0; foreach ($keywords as $keyword) { $queryBuilder->andWhere($concat . ' LIKE :keyword' . $index) ->setParameter('keyword' . $index, '%' . addcslashes($keyword, '\\%_') . '%'); ++$index; } if (count($modCombinationIds) > 0) { $queryBuilder->innerJoin('t.modCombination', 'mc') ->andWhere('mc.id IN (:modCombinationIds)') ->setParameter('modCombinationIds', array_values($modCombinationIds)); } $result = $this->mapTranslationPriorityDataResult($queryBuilder->getQuery()->getResult()); } return $result; }
[ "public", "function", "findDataByKeywords", "(", "string", "$", "locale", ",", "array", "$", "keywords", ",", "array", "$", "modCombinationIds", "=", "[", "]", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "if", "(", "count", "(", "$", "keywords", ")", ">", "0", ")", "{", "$", "concat", "=", "'LOWER(CONCAT(t.type, t.name, t.value, t.description))'", ";", "$", "priorityCase", "=", "'CASE WHEN t.locale = :localePrimary THEN :priorityPrimary '", ".", "'WHEN t.locale = :localeSecondary THEN :prioritySecondary ELSE :priorityAny END'", ";", "$", "columns", "=", "[", "'t.type AS type'", ",", "'t.name AS name'", ",", "'MIN('", ".", "$", "priorityCase", ".", "') AS priority'", "]", ";", "$", "queryBuilder", "=", "$", "this", "->", "entityManager", "->", "createQueryBuilder", "(", ")", ";", "$", "queryBuilder", "->", "select", "(", "$", "columns", ")", "->", "from", "(", "Translation", "::", "class", ",", "'t'", ")", "->", "andWhere", "(", "'t.type IN (:types)'", ")", "->", "addGroupBy", "(", "'t.type'", ")", "->", "addGroupBy", "(", "'t.name'", ")", "->", "setParameter", "(", "'localePrimary'", ",", "$", "locale", ")", "->", "setParameter", "(", "'localeSecondary'", ",", "'en'", ")", "->", "setParameter", "(", "'priorityPrimary'", ",", "SearchResultPriority", "::", "PRIMARY_LOCALE_MATCH", ")", "->", "setParameter", "(", "'prioritySecondary'", ",", "SearchResultPriority", "::", "SECONDARY_LOCALE_MATCH", ")", "->", "setParameter", "(", "'priorityAny'", ",", "SearchResultPriority", "::", "ANY_MATCH", ")", "->", "setParameter", "(", "'types'", ",", "[", "TranslationType", "::", "ITEM", ",", "TranslationType", "::", "FLUID", ",", "TranslationType", "::", "RECIPE", "]", ")", ";", "$", "index", "=", "0", ";", "foreach", "(", "$", "keywords", "as", "$", "keyword", ")", "{", "$", "queryBuilder", "->", "andWhere", "(", "$", "concat", ".", "' LIKE :keyword'", ".", "$", "index", ")", "->", "setParameter", "(", "'keyword'", ".", "$", "index", ",", "'%'", ".", "addcslashes", "(", "$", "keyword", ",", "'\\\\%_'", ")", ".", "'%'", ")", ";", "++", "$", "index", ";", "}", "if", "(", "count", "(", "$", "modCombinationIds", ")", ">", "0", ")", "{", "$", "queryBuilder", "->", "innerJoin", "(", "'t.modCombination'", ",", "'mc'", ")", "->", "andWhere", "(", "'mc.id IN (:modCombinationIds)'", ")", "->", "setParameter", "(", "'modCombinationIds'", ",", "array_values", "(", "$", "modCombinationIds", ")", ")", ";", "}", "$", "result", "=", "$", "this", "->", "mapTranslationPriorityDataResult", "(", "$", "queryBuilder", "->", "getQuery", "(", ")", "->", "getResult", "(", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Finds the types and names matching the specified keywords. @param string $locale @param array|string[] $keywords @param array|int[] $modCombinationIds @return array|TranslationPriorityData[]
[ "Finds", "the", "types", "and", "names", "matching", "the", "specified", "keywords", "." ]
c3a27e5673462a58b5afafc0ea0e0002f6db9803
https://github.com/factorio-item-browser/api-database/blob/c3a27e5673462a58b5afafc0ea0e0002f6db9803/src/Repository/TranslationRepository.php#L110-L157
12,301
factorio-item-browser/api-database
src/Repository/TranslationRepository.php
TranslationRepository.mapTranslationPriorityDataResult
protected function mapTranslationPriorityDataResult(array $translationPriorityData): array { $result = []; foreach ($translationPriorityData as $data) { $result[] = TranslationPriorityData::createFromArray($data); } return $result; }
php
protected function mapTranslationPriorityDataResult(array $translationPriorityData): array { $result = []; foreach ($translationPriorityData as $data) { $result[] = TranslationPriorityData::createFromArray($data); } return $result; }
[ "protected", "function", "mapTranslationPriorityDataResult", "(", "array", "$", "translationPriorityData", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "translationPriorityData", "as", "$", "data", ")", "{", "$", "result", "[", "]", "=", "TranslationPriorityData", "::", "createFromArray", "(", "$", "data", ")", ";", "}", "return", "$", "result", ";", "}" ]
Maps the query result to instances of TranslationPriorityData. @param array $translationPriorityData @return array|TranslationPriorityData[]
[ "Maps", "the", "query", "result", "to", "instances", "of", "TranslationPriorityData", "." ]
c3a27e5673462a58b5afafc0ea0e0002f6db9803
https://github.com/factorio-item-browser/api-database/blob/c3a27e5673462a58b5afafc0ea0e0002f6db9803/src/Repository/TranslationRepository.php#L164-L171
12,302
agalbourdin/agl-core
src/Data/Date.php
Date.toTz
public static function toTz($pDate, $pTimezone = NULL) { if ($pTimezone === NULL) { $pTimezone = Agl::app()->getConfig('main/global/timezone'); } $time_object = new DateTime($pDate, new DateTimeZone(self::DEFAULT_TZ)); $time_object->setTimezone(new DateTimeZone($pTimezone)); return $time_object->format(self::DATE_FORMAT); }
php
public static function toTz($pDate, $pTimezone = NULL) { if ($pTimezone === NULL) { $pTimezone = Agl::app()->getConfig('main/global/timezone'); } $time_object = new DateTime($pDate, new DateTimeZone(self::DEFAULT_TZ)); $time_object->setTimezone(new DateTimeZone($pTimezone)); return $time_object->format(self::DATE_FORMAT); }
[ "public", "static", "function", "toTz", "(", "$", "pDate", ",", "$", "pTimezone", "=", "NULL", ")", "{", "if", "(", "$", "pTimezone", "===", "NULL", ")", "{", "$", "pTimezone", "=", "Agl", "::", "app", "(", ")", "->", "getConfig", "(", "'main/global/timezone'", ")", ";", "}", "$", "time_object", "=", "new", "DateTime", "(", "$", "pDate", ",", "new", "DateTimeZone", "(", "self", "::", "DEFAULT_TZ", ")", ")", ";", "$", "time_object", "->", "setTimezone", "(", "new", "DateTimeZone", "(", "$", "pTimezone", ")", ")", ";", "return", "$", "time_object", "->", "format", "(", "self", "::", "DATE_FORMAT", ")", ";", "}" ]
convert a date from the default timezone to the application's timezone. @param $pDate @return string
[ "convert", "a", "date", "from", "the", "default", "timezone", "to", "the", "application", "s", "timezone", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Data/Date.php#L56-L65
12,303
agalbourdin/agl-core
src/Data/Date.php
Date.format
public static function format($pDate, $pFormat = 'short') { switch ($pFormat) { case 'short': return strftime('%x', strtotime($pDate)); break; case 'long': return strftime('%x %H:%M', strtotime($pDate)); break; case 'full': return strftime('%x %H:%M:%S', strtotime($pDate)); break; } throw new Exception("The requested date format is not correct"); }
php
public static function format($pDate, $pFormat = 'short') { switch ($pFormat) { case 'short': return strftime('%x', strtotime($pDate)); break; case 'long': return strftime('%x %H:%M', strtotime($pDate)); break; case 'full': return strftime('%x %H:%M:%S', strtotime($pDate)); break; } throw new Exception("The requested date format is not correct"); }
[ "public", "static", "function", "format", "(", "$", "pDate", ",", "$", "pFormat", "=", "'short'", ")", "{", "switch", "(", "$", "pFormat", ")", "{", "case", "'short'", ":", "return", "strftime", "(", "'%x'", ",", "strtotime", "(", "$", "pDate", ")", ")", ";", "break", ";", "case", "'long'", ":", "return", "strftime", "(", "'%x %H:%M'", ",", "strtotime", "(", "$", "pDate", ")", ")", ";", "break", ";", "case", "'full'", ":", "return", "strftime", "(", "'%x %H:%M:%S'", ",", "strtotime", "(", "$", "pDate", ")", ")", ";", "break", ";", "}", "throw", "new", "Exception", "(", "\"The requested date format is not correct\"", ")", ";", "}" ]
Format the date based on the locale and the requested format. @param string $pDate @param string $pFormat @return string
[ "Format", "the", "date", "based", "on", "the", "locale", "and", "the", "requested", "format", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Data/Date.php#L91-L106
12,304
OWeb/OWeb-Framework
OWeb/defaults/extensions/bbcode/JBBCode/Parser.php
Parser.loadDefaultCodes
public function loadDefaultCodes() { $this->addBBCode("b", "<strong>{param}</strong>"); $this->addBBCode("i", "<em>{param}</em>"); $this->addBBCode("u", "<u>{param}</u>"); $this->addBBCode("url", "<a href=\"{param}\">{param}</a>"); $this->addBBCode("url", "<a href=\"{option}\">{param}</a>", true); $this->addBBCode("img", "<img src=\"{param}\" alt=\"a user uploaded image\" />"); $this->addBBCode("img", "<img src=\"{param}\" alt=\"{option}\" />", true); $this->addBBCode("color", "<span style=\"color: {option}\">{param}</span>", true); }
php
public function loadDefaultCodes() { $this->addBBCode("b", "<strong>{param}</strong>"); $this->addBBCode("i", "<em>{param}</em>"); $this->addBBCode("u", "<u>{param}</u>"); $this->addBBCode("url", "<a href=\"{param}\">{param}</a>"); $this->addBBCode("url", "<a href=\"{option}\">{param}</a>", true); $this->addBBCode("img", "<img src=\"{param}\" alt=\"a user uploaded image\" />"); $this->addBBCode("img", "<img src=\"{param}\" alt=\"{option}\" />", true); $this->addBBCode("color", "<span style=\"color: {option}\">{param}</span>", true); }
[ "public", "function", "loadDefaultCodes", "(", ")", "{", "$", "this", "->", "addBBCode", "(", "\"b\"", ",", "\"<strong>{param}</strong>\"", ")", ";", "$", "this", "->", "addBBCode", "(", "\"i\"", ",", "\"<em>{param}</em>\"", ")", ";", "$", "this", "->", "addBBCode", "(", "\"u\"", ",", "\"<u>{param}</u>\"", ")", ";", "$", "this", "->", "addBBCode", "(", "\"url\"", ",", "\"<a href=\\\"{param}\\\">{param}</a>\"", ")", ";", "$", "this", "->", "addBBCode", "(", "\"url\"", ",", "\"<a href=\\\"{option}\\\">{param}</a>\"", ",", "true", ")", ";", "$", "this", "->", "addBBCode", "(", "\"img\"", ",", "\"<img src=\\\"{param}\\\" alt=\\\"a user uploaded image\\\" />\"", ")", ";", "$", "this", "->", "addBBCode", "(", "\"img\"", ",", "\"<img src=\\\"{param}\\\" alt=\\\"{option}\\\" />\"", ",", "true", ")", ";", "$", "this", "->", "addBBCode", "(", "\"color\"", ",", "\"<span style=\\\"color: {option}\\\">{param}</span>\"", ",", "true", ")", ";", "}" ]
Adds a set of default, standard bbcode definitions commonly used across the web.
[ "Adds", "a", "set", "of", "default", "standard", "bbcode", "definitions", "commonly", "used", "across", "the", "web", "." ]
fb441f51afb16860b0c946a55c36c789fbb125fa
https://github.com/OWeb/OWeb-Framework/blob/fb441f51afb16860b0c946a55c36c789fbb125fa/OWeb/defaults/extensions/bbcode/JBBCode/Parser.php#L265-L274
12,305
cyberspectrum/i18n-metamodels
src/MetaModelDictionary.php
MetaModelDictionary.getAttributeKeys
private function getAttributeKeys(): \Generator { foreach ($this->handlers as $attributeHandler) { /** @var MetaModelAttributeHandlerInterface $attributeHandler */ $prefix = $attributeHandler->getPrefix(); foreach ($this->idListGenerator() as $id) { yield $id . '.' . $prefix; } } }
php
private function getAttributeKeys(): \Generator { foreach ($this->handlers as $attributeHandler) { /** @var MetaModelAttributeHandlerInterface $attributeHandler */ $prefix = $attributeHandler->getPrefix(); foreach ($this->idListGenerator() as $id) { yield $id . '.' . $prefix; } } }
[ "private", "function", "getAttributeKeys", "(", ")", ":", "\\", "Generator", "{", "foreach", "(", "$", "this", "->", "handlers", "as", "$", "attributeHandler", ")", "{", "/** @var MetaModelAttributeHandlerInterface $attributeHandler */", "$", "prefix", "=", "$", "attributeHandler", "->", "getPrefix", "(", ")", ";", "foreach", "(", "$", "this", "->", "idListGenerator", "(", ")", "as", "$", "id", ")", "{", "yield", "$", "id", ".", "'.'", ".", "$", "prefix", ";", "}", "}", "}" ]
Obtain all attribute keys. @return \Generator
[ "Obtain", "all", "attribute", "keys", "." ]
5f36f24a3996eebd640c7f2bbbf20e6d9ff92365
https://github.com/cyberspectrum/i18n-metamodels/blob/5f36f24a3996eebd640c7f2bbbf20e6d9ff92365/src/MetaModelDictionary.php#L210-L219
12,306
cyberspectrum/i18n-metamodels
src/MetaModelDictionary.php
MetaModelDictionary.idListGenerator
private function idListGenerator(): \Generator { if (null === $this->ids) { $this->ids = $this->metaModel->getIdsFromFilter(null); } yield from $this->ids; }
php
private function idListGenerator(): \Generator { if (null === $this->ids) { $this->ids = $this->metaModel->getIdsFromFilter(null); } yield from $this->ids; }
[ "private", "function", "idListGenerator", "(", ")", ":", "\\", "Generator", "{", "if", "(", "null", "===", "$", "this", "->", "ids", ")", "{", "$", "this", "->", "ids", "=", "$", "this", "->", "metaModel", "->", "getIdsFromFilter", "(", "null", ")", ";", "}", "yield", "from", "$", "this", "->", "ids", ";", "}" ]
Obtain all ids in the MetaModel. @return \Generator
[ "Obtain", "all", "ids", "in", "the", "MetaModel", "." ]
5f36f24a3996eebd640c7f2bbbf20e6d9ff92365
https://github.com/cyberspectrum/i18n-metamodels/blob/5f36f24a3996eebd640c7f2bbbf20e6d9ff92365/src/MetaModelDictionary.php#L226-L233
12,307
lutsen/property-onetomany
src/Onetomany.php
Onetomany.read
public function read($bean, $property) { // NOTE: We're not executing the read method for each bean. Before I implement this I want to check potential performance issues. //return $bean->{ 'own'.ucfirst($property['name']).'List' }; // Set up child model to read properties $model_name = '\Lagan\Model\\' . ucfirst($property['name']); $child = new $model_name(); // All beans with this parent // Oder by position(s) if exits // NOTE: We're not executing the read method for each bean. Before I implement this I want to check potential performance issues. $add_to_query = ''; foreach($child->properties as $p) { if ( $p['type'] === '\\Lagan\\Property\\Position' ) { $add_to_query = $p['name'].' ASC, '; } } return \R::find( $property['name'], $bean->getMeta('type').'_id = :id ORDER BY '.$add_to_query.'title ASC ', [ ':id' => $bean->id ] ); }
php
public function read($bean, $property) { // NOTE: We're not executing the read method for each bean. Before I implement this I want to check potential performance issues. //return $bean->{ 'own'.ucfirst($property['name']).'List' }; // Set up child model to read properties $model_name = '\Lagan\Model\\' . ucfirst($property['name']); $child = new $model_name(); // All beans with this parent // Oder by position(s) if exits // NOTE: We're not executing the read method for each bean. Before I implement this I want to check potential performance issues. $add_to_query = ''; foreach($child->properties as $p) { if ( $p['type'] === '\\Lagan\\Property\\Position' ) { $add_to_query = $p['name'].' ASC, '; } } return \R::find( $property['name'], $bean->getMeta('type').'_id = :id ORDER BY '.$add_to_query.'title ASC ', [ ':id' => $bean->id ] ); }
[ "public", "function", "read", "(", "$", "bean", ",", "$", "property", ")", "{", "// NOTE: We're not executing the read method for each bean. Before I implement this I want to check potential performance issues.", "//return $bean->{ 'own'.ucfirst($property['name']).'List' };", "// Set up child model to read properties", "$", "model_name", "=", "'\\Lagan\\Model\\\\'", ".", "ucfirst", "(", "$", "property", "[", "'name'", "]", ")", ";", "$", "child", "=", "new", "$", "model_name", "(", ")", ";", "// All beans with this parent", "// Oder by position(s) if exits", "// NOTE: We're not executing the read method for each bean. Before I implement this I want to check potential performance issues.", "$", "add_to_query", "=", "''", ";", "foreach", "(", "$", "child", "->", "properties", "as", "$", "p", ")", "{", "if", "(", "$", "p", "[", "'type'", "]", "===", "'\\\\Lagan\\\\Property\\\\Position'", ")", "{", "$", "add_to_query", "=", "$", "p", "[", "'name'", "]", ".", "' ASC, '", ";", "}", "}", "return", "\\", "R", "::", "find", "(", "$", "property", "[", "'name'", "]", ",", "$", "bean", "->", "getMeta", "(", "'type'", ")", ".", "'_id = :id ORDER BY '", ".", "$", "add_to_query", ".", "'title ASC '", ",", "[", "':id'", "=>", "$", "bean", "->", "id", "]", ")", ";", "}" ]
The read method is executed each time a property with this type is read. @param bean $bean The Readbean bean object with this property. @param string[] $property Lagan model property arrray. @return bean[] Array with Redbean beans with a many-to-one relation with the object with this property.
[ "The", "read", "method", "is", "executed", "each", "time", "a", "property", "with", "this", "type", "is", "read", "." ]
5145b3f702f0a2ecf1ffe1344b52f730aa81c3de
https://github.com/lutsen/property-onetomany/blob/5145b3f702f0a2ecf1ffe1344b52f730aa81c3de/src/Onetomany.php#L127-L147
12,308
raidros/storer
src/Request.php
Request.getBody
public function getBody($keyChain) { if ($this->transformer) { $this->request[$keyChain] = $this->transformer->transformData($this->request[$keyChain]); } return $this->request; }
php
public function getBody($keyChain) { if ($this->transformer) { $this->request[$keyChain] = $this->transformer->transformData($this->request[$keyChain]); } return $this->request; }
[ "public", "function", "getBody", "(", "$", "keyChain", ")", "{", "if", "(", "$", "this", "->", "transformer", ")", "{", "$", "this", "->", "request", "[", "$", "keyChain", "]", "=", "$", "this", "->", "transformer", "->", "transformData", "(", "$", "this", "->", "request", "[", "$", "keyChain", "]", ")", ";", "}", "return", "$", "this", "->", "request", ";", "}" ]
return the transformed request body. @param string $keyChain @return array
[ "return", "the", "transformed", "request", "body", "." ]
e8ebea105b27888a9c42cbc5266e02e9e51324ee
https://github.com/raidros/storer/blob/e8ebea105b27888a9c42cbc5266e02e9e51324ee/src/Request.php#L29-L36
12,309
studyportals/Utils
src/HTML.php
HTML.getFilters
protected static function getFilters($set = self::S_MEDIA){ $tags = self::$_strict_tags; $tags_drop = self::$_strict_tags_drop; $attributes = self::$_strict_attributes; switch($set){ /** @noinspection PhpMissingBreakStatementInspection */ case self::S_MEDIA: $tags = array_merge_recursive( $tags, self::$_media_tags ); $tags_drop = array_merge_recursive( $tags_drop, self::$_media_tags_drop ); $attributes = array_merge_recursive( $attributes, self::$_media_attributes ); /** @noinspection PhpMissingBreakStatementInspection */ case self::S_LINK: $tags = array_merge_recursive( $tags, self::$_link_tags ); $tags_drop = array_merge_recursive( $tags_drop, self::$_link_tags_drop ); $attributes = array_merge_recursive( $attributes, self::$_link_attributes ); /** @noinspection PhpMissingBreakStatementInspection */ case self::S_BASIC: $tags = array_merge_recursive( $tags, self::$_basic_tags ); $tags_drop = array_merge_recursive( $tags_drop, self::$_basic_tags_drop ); $attributes = array_merge_recursive( $attributes, self::$_basic_attributes ); break; case self::S_LIMITED: // Limited is a bit special, it only consists of limited and // media. Therefore it doesn't need the fallthrough structure $tags = array_merge_recursive( static::$_limited_tags, static::$_media_tags ); $tags_drop = array_merge_recursive( static::$_limited_tags_drop, static::$_media_tags_drop ); $attributes = array_merge_recursive( static::$_limited_attributes, static::$_media_attributes ); break; default: break; } return [ 'tags' => $tags, 'tags_drop' => $tags_drop, 'attributes' => $attributes ]; }
php
protected static function getFilters($set = self::S_MEDIA){ $tags = self::$_strict_tags; $tags_drop = self::$_strict_tags_drop; $attributes = self::$_strict_attributes; switch($set){ /** @noinspection PhpMissingBreakStatementInspection */ case self::S_MEDIA: $tags = array_merge_recursive( $tags, self::$_media_tags ); $tags_drop = array_merge_recursive( $tags_drop, self::$_media_tags_drop ); $attributes = array_merge_recursive( $attributes, self::$_media_attributes ); /** @noinspection PhpMissingBreakStatementInspection */ case self::S_LINK: $tags = array_merge_recursive( $tags, self::$_link_tags ); $tags_drop = array_merge_recursive( $tags_drop, self::$_link_tags_drop ); $attributes = array_merge_recursive( $attributes, self::$_link_attributes ); /** @noinspection PhpMissingBreakStatementInspection */ case self::S_BASIC: $tags = array_merge_recursive( $tags, self::$_basic_tags ); $tags_drop = array_merge_recursive( $tags_drop, self::$_basic_tags_drop ); $attributes = array_merge_recursive( $attributes, self::$_basic_attributes ); break; case self::S_LIMITED: // Limited is a bit special, it only consists of limited and // media. Therefore it doesn't need the fallthrough structure $tags = array_merge_recursive( static::$_limited_tags, static::$_media_tags ); $tags_drop = array_merge_recursive( static::$_limited_tags_drop, static::$_media_tags_drop ); $attributes = array_merge_recursive( static::$_limited_attributes, static::$_media_attributes ); break; default: break; } return [ 'tags' => $tags, 'tags_drop' => $tags_drop, 'attributes' => $attributes ]; }
[ "protected", "static", "function", "getFilters", "(", "$", "set", "=", "self", "::", "S_MEDIA", ")", "{", "$", "tags", "=", "self", "::", "$", "_strict_tags", ";", "$", "tags_drop", "=", "self", "::", "$", "_strict_tags_drop", ";", "$", "attributes", "=", "self", "::", "$", "_strict_attributes", ";", "switch", "(", "$", "set", ")", "{", "/** @noinspection PhpMissingBreakStatementInspection */", "case", "self", "::", "S_MEDIA", ":", "$", "tags", "=", "array_merge_recursive", "(", "$", "tags", ",", "self", "::", "$", "_media_tags", ")", ";", "$", "tags_drop", "=", "array_merge_recursive", "(", "$", "tags_drop", ",", "self", "::", "$", "_media_tags_drop", ")", ";", "$", "attributes", "=", "array_merge_recursive", "(", "$", "attributes", ",", "self", "::", "$", "_media_attributes", ")", ";", "/** @noinspection PhpMissingBreakStatementInspection */", "case", "self", "::", "S_LINK", ":", "$", "tags", "=", "array_merge_recursive", "(", "$", "tags", ",", "self", "::", "$", "_link_tags", ")", ";", "$", "tags_drop", "=", "array_merge_recursive", "(", "$", "tags_drop", ",", "self", "::", "$", "_link_tags_drop", ")", ";", "$", "attributes", "=", "array_merge_recursive", "(", "$", "attributes", ",", "self", "::", "$", "_link_attributes", ")", ";", "/** @noinspection PhpMissingBreakStatementInspection */", "case", "self", "::", "S_BASIC", ":", "$", "tags", "=", "array_merge_recursive", "(", "$", "tags", ",", "self", "::", "$", "_basic_tags", ")", ";", "$", "tags_drop", "=", "array_merge_recursive", "(", "$", "tags_drop", ",", "self", "::", "$", "_basic_tags_drop", ")", ";", "$", "attributes", "=", "array_merge_recursive", "(", "$", "attributes", ",", "self", "::", "$", "_basic_attributes", ")", ";", "break", ";", "case", "self", "::", "S_LIMITED", ":", "// Limited is a bit special, it only consists of limited and", "// media. Therefore it doesn't need the fallthrough structure", "$", "tags", "=", "array_merge_recursive", "(", "static", "::", "$", "_limited_tags", ",", "static", "::", "$", "_media_tags", ")", ";", "$", "tags_drop", "=", "array_merge_recursive", "(", "static", "::", "$", "_limited_tags_drop", ",", "static", "::", "$", "_media_tags_drop", ")", ";", "$", "attributes", "=", "array_merge_recursive", "(", "static", "::", "$", "_limited_attributes", ",", "static", "::", "$", "_media_attributes", ")", ";", "break", ";", "default", ":", "break", ";", "}", "return", "[", "'tags'", "=>", "$", "tags", ",", "'tags_drop'", "=>", "$", "tags_drop", ",", "'attributes'", "=>", "$", "attributes", "]", ";", "}" ]
Get the filters. <p>Returns an array containing the default filters for the HTML library. The array consists of three elements:</p> <ul> <li><strong>tags:</strong> An array of valid tags that are allowed to remain inside the filtered HTML.</li> <li><strong>tags_drop:</strong> An array of tags that should be explicitly dropped from the output.<li> <li><strong>attributes:</strong> An array of allowed attributes.</li> </ul> @param string $set @return array
[ "Get", "the", "filters", "." ]
eab69ca10ce3261480164cf8108ae7020459c847
https://github.com/studyportals/Utils/blob/eab69ca10ce3261480164cf8108ae7020459c847/src/HTML.php#L157-L251
12,310
studyportals/Utils
src/HTML.php
HTML.cleanHTML
public static function cleanHTML($html, $filter_set = self::S_MEDIA){ $filters = self::getFilters($filter_set); // Pre-processing $html = preg_replace('/[\s]+/', ' ', $html); $html = str_replace('> <', '><', $html); $html = preg_replace('/(<br>)+/', '<br>', $html); $html = str_replace(['<br></', '><br>'], ['</', '>'], $html); // Clean HTML libxml_clear_errors(); $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'); $Document = new \DOMDocument(); @$Document->loadHTML($html); if(empty($Document)){ $libXMLError = libxml_get_last_error(); $xml_error = ''; if($libXMLError instanceof \LibXMLError){ $xml_error = ", libXML reports: {$libXMLError->message}"; } throw new HTMLException('Invalid HTML provided' . $xml_error); } $html = self::_cleanHTML($Document, $filters); // Post-processing $html = preg_replace('/[\s]+/', ' ', $html); $html = str_replace('> <', '><', $html); $html = preg_replace('/(<br>)+/', '<br>', $html); $html = str_replace(['<br></', '><br>'], ['</', '>'], $html); $html = Sanitize::replaceHttpsUrls($html); $html = trim($html); /** * Sometimes we just have some leftover attributes like an br. That the * text is not considered empty. But actually there is no visual content. * * Is the text without tags is empty we just return an empty string. * One exception are images cause they do not contain an textual value. */ if($html === '<br>'){ $html = ''; } return $html; }
php
public static function cleanHTML($html, $filter_set = self::S_MEDIA){ $filters = self::getFilters($filter_set); // Pre-processing $html = preg_replace('/[\s]+/', ' ', $html); $html = str_replace('> <', '><', $html); $html = preg_replace('/(<br>)+/', '<br>', $html); $html = str_replace(['<br></', '><br>'], ['</', '>'], $html); // Clean HTML libxml_clear_errors(); $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'); $Document = new \DOMDocument(); @$Document->loadHTML($html); if(empty($Document)){ $libXMLError = libxml_get_last_error(); $xml_error = ''; if($libXMLError instanceof \LibXMLError){ $xml_error = ", libXML reports: {$libXMLError->message}"; } throw new HTMLException('Invalid HTML provided' . $xml_error); } $html = self::_cleanHTML($Document, $filters); // Post-processing $html = preg_replace('/[\s]+/', ' ', $html); $html = str_replace('> <', '><', $html); $html = preg_replace('/(<br>)+/', '<br>', $html); $html = str_replace(['<br></', '><br>'], ['</', '>'], $html); $html = Sanitize::replaceHttpsUrls($html); $html = trim($html); /** * Sometimes we just have some leftover attributes like an br. That the * text is not considered empty. But actually there is no visual content. * * Is the text without tags is empty we just return an empty string. * One exception are images cause they do not contain an textual value. */ if($html === '<br>'){ $html = ''; } return $html; }
[ "public", "static", "function", "cleanHTML", "(", "$", "html", ",", "$", "filter_set", "=", "self", "::", "S_MEDIA", ")", "{", "$", "filters", "=", "self", "::", "getFilters", "(", "$", "filter_set", ")", ";", "// Pre-processing", "$", "html", "=", "preg_replace", "(", "'/[\\s]+/'", ",", "' '", ",", "$", "html", ")", ";", "$", "html", "=", "str_replace", "(", "'> <'", ",", "'><'", ",", "$", "html", ")", ";", "$", "html", "=", "preg_replace", "(", "'/(<br>)+/'", ",", "'<br>'", ",", "$", "html", ")", ";", "$", "html", "=", "str_replace", "(", "[", "'<br></'", ",", "'><br>'", "]", ",", "[", "'</'", ",", "'>'", "]", ",", "$", "html", ")", ";", "// Clean HTML", "libxml_clear_errors", "(", ")", ";", "$", "html", "=", "mb_convert_encoding", "(", "$", "html", ",", "'HTML-ENTITIES'", ",", "'UTF-8'", ")", ";", "$", "Document", "=", "new", "\\", "DOMDocument", "(", ")", ";", "@", "$", "Document", "->", "loadHTML", "(", "$", "html", ")", ";", "if", "(", "empty", "(", "$", "Document", ")", ")", "{", "$", "libXMLError", "=", "libxml_get_last_error", "(", ")", ";", "$", "xml_error", "=", "''", ";", "if", "(", "$", "libXMLError", "instanceof", "\\", "LibXMLError", ")", "{", "$", "xml_error", "=", "\", libXML reports: {$libXMLError->message}\"", ";", "}", "throw", "new", "HTMLException", "(", "'Invalid HTML provided'", ".", "$", "xml_error", ")", ";", "}", "$", "html", "=", "self", "::", "_cleanHTML", "(", "$", "Document", ",", "$", "filters", ")", ";", "// Post-processing", "$", "html", "=", "preg_replace", "(", "'/[\\s]+/'", ",", "' '", ",", "$", "html", ")", ";", "$", "html", "=", "str_replace", "(", "'> <'", ",", "'><'", ",", "$", "html", ")", ";", "$", "html", "=", "preg_replace", "(", "'/(<br>)+/'", ",", "'<br>'", ",", "$", "html", ")", ";", "$", "html", "=", "str_replace", "(", "[", "'<br></'", ",", "'><br>'", "]", ",", "[", "'</'", ",", "'>'", "]", ",", "$", "html", ")", ";", "$", "html", "=", "Sanitize", "::", "replaceHttpsUrls", "(", "$", "html", ")", ";", "$", "html", "=", "trim", "(", "$", "html", ")", ";", "/**\n\t\t * Sometimes we just have some leftover attributes like an br. That the\n\t\t * text is not considered empty. But actually there is no visual content.\n\t\t *\n\t\t * Is the text without tags is empty we just return an empty string.\n\t\t * One exception are images cause they do not contain an textual value.\n\t\t */", "if", "(", "$", "html", "===", "'<br>'", ")", "{", "$", "html", "=", "''", ";", "}", "return", "$", "html", ";", "}" ]
Thoroughly clean HTML based on a set of filters. <p>When the optional argument {@link $filters} is omitted a default, relatively restrictive, set of filter is used. For more information on the possible filters see {@link HTML::getDefaultFilters()}.</p> @param string $html @param string $filter_set @throws HTMLException @return string @see HTML::getDefaultFilters()
[ "Thoroughly", "clean", "HTML", "based", "on", "a", "set", "of", "filters", "." ]
eab69ca10ce3261480164cf8108ae7020459c847
https://github.com/studyportals/Utils/blob/eab69ca10ce3261480164cf8108ae7020459c847/src/HTML.php#L269-L330
12,311
studyportals/Utils
src/HTML.php
HTML._cleanHTML
private static function _cleanHTML(DOMNode $Node, array $filters){ $node_contents = ''; $tag_name = ''; if(isset($Node->tagName)){ $tag_name = strtolower(trim($Node->tagName)); } // Drop tags assert('isset($filters[\'tags_drop\']) && is_array($filters[\'tags_drop\'])'); if(!isset($filters['tags_drop']) || !is_array($filters['tags_drop'])){ $filters['tags_drop'] = []; } if($Node instanceof DOMComment || in_array($tag_name, $filters['tags_drop'])){ return ''; } // Clean node contents if(!isset($Node->childNodes) || $Node->childNodes->length == 0){ // As no charset conversion is needed, nodeValue can be directly used $node_contents = html_entity_decode($Node->nodeValue, ENT_QUOTES, DEFAULT_CHARSET); // Reduce every possible combination of whitespaces to a single space-character $node_contents = preg_replace('/\s+/', ' ', $node_contents); // Reapply HTML entities $node_contents = htmlentities($node_contents, ENT_QUOTES, DEFAULT_CHARSET); } else{ foreach($Node->childNodes as $Child){ $node_contents .= self::_cleanHTML($Child, $filters); } } // Nameless and disallowed nodes (return content only, no tags) assert('isset($filters[\'tags\']) && is_array($filters[\'tags\'])'); if(!isset($filters['tags']) || !is_array($filters['tags'])){ $filters['tags'] = []; } if($tag_name == '' || !in_array($tag_name, $filters['tags'])){ return $node_contents; } // Allowed nodes (return tag and content) else{ $node_attributes = self::_cleanAttributes($Node, $filters); // If (after filtering) "a" or "img" elements have no attributes, discard them if($node_attributes == '' && ($tag_name == 'a' || $tag_name == 'img')){ return $node_contents; } switch($tag_name){ // Empty elements (c.q. self-closing) case 'br': case 'hr': case 'input': case 'img': return "<$tag_name$node_attributes>"; break; // Elements with content default: // Empty "a" elements (c.q. page anchors) are allowed if(trim($node_contents) == '' && $tag_name != 'a') return ''; return "<$tag_name$node_attributes>$node_contents</$tag_name>"; } } }
php
private static function _cleanHTML(DOMNode $Node, array $filters){ $node_contents = ''; $tag_name = ''; if(isset($Node->tagName)){ $tag_name = strtolower(trim($Node->tagName)); } // Drop tags assert('isset($filters[\'tags_drop\']) && is_array($filters[\'tags_drop\'])'); if(!isset($filters['tags_drop']) || !is_array($filters['tags_drop'])){ $filters['tags_drop'] = []; } if($Node instanceof DOMComment || in_array($tag_name, $filters['tags_drop'])){ return ''; } // Clean node contents if(!isset($Node->childNodes) || $Node->childNodes->length == 0){ // As no charset conversion is needed, nodeValue can be directly used $node_contents = html_entity_decode($Node->nodeValue, ENT_QUOTES, DEFAULT_CHARSET); // Reduce every possible combination of whitespaces to a single space-character $node_contents = preg_replace('/\s+/', ' ', $node_contents); // Reapply HTML entities $node_contents = htmlentities($node_contents, ENT_QUOTES, DEFAULT_CHARSET); } else{ foreach($Node->childNodes as $Child){ $node_contents .= self::_cleanHTML($Child, $filters); } } // Nameless and disallowed nodes (return content only, no tags) assert('isset($filters[\'tags\']) && is_array($filters[\'tags\'])'); if(!isset($filters['tags']) || !is_array($filters['tags'])){ $filters['tags'] = []; } if($tag_name == '' || !in_array($tag_name, $filters['tags'])){ return $node_contents; } // Allowed nodes (return tag and content) else{ $node_attributes = self::_cleanAttributes($Node, $filters); // If (after filtering) "a" or "img" elements have no attributes, discard them if($node_attributes == '' && ($tag_name == 'a' || $tag_name == 'img')){ return $node_contents; } switch($tag_name){ // Empty elements (c.q. self-closing) case 'br': case 'hr': case 'input': case 'img': return "<$tag_name$node_attributes>"; break; // Elements with content default: // Empty "a" elements (c.q. page anchors) are allowed if(trim($node_contents) == '' && $tag_name != 'a') return ''; return "<$tag_name$node_attributes>$node_contents</$tag_name>"; } } }
[ "private", "static", "function", "_cleanHTML", "(", "DOMNode", "$", "Node", ",", "array", "$", "filters", ")", "{", "$", "node_contents", "=", "''", ";", "$", "tag_name", "=", "''", ";", "if", "(", "isset", "(", "$", "Node", "->", "tagName", ")", ")", "{", "$", "tag_name", "=", "strtolower", "(", "trim", "(", "$", "Node", "->", "tagName", ")", ")", ";", "}", "// Drop tags", "assert", "(", "'isset($filters[\\'tags_drop\\']) && is_array($filters[\\'tags_drop\\'])'", ")", ";", "if", "(", "!", "isset", "(", "$", "filters", "[", "'tags_drop'", "]", ")", "||", "!", "is_array", "(", "$", "filters", "[", "'tags_drop'", "]", ")", ")", "{", "$", "filters", "[", "'tags_drop'", "]", "=", "[", "]", ";", "}", "if", "(", "$", "Node", "instanceof", "DOMComment", "||", "in_array", "(", "$", "tag_name", ",", "$", "filters", "[", "'tags_drop'", "]", ")", ")", "{", "return", "''", ";", "}", "// Clean node contents", "if", "(", "!", "isset", "(", "$", "Node", "->", "childNodes", ")", "||", "$", "Node", "->", "childNodes", "->", "length", "==", "0", ")", "{", "// As no charset conversion is needed, nodeValue can be directly used", "$", "node_contents", "=", "html_entity_decode", "(", "$", "Node", "->", "nodeValue", ",", "ENT_QUOTES", ",", "DEFAULT_CHARSET", ")", ";", "// Reduce every possible combination of whitespaces to a single space-character", "$", "node_contents", "=", "preg_replace", "(", "'/\\s+/'", ",", "' '", ",", "$", "node_contents", ")", ";", "// Reapply HTML entities", "$", "node_contents", "=", "htmlentities", "(", "$", "node_contents", ",", "ENT_QUOTES", ",", "DEFAULT_CHARSET", ")", ";", "}", "else", "{", "foreach", "(", "$", "Node", "->", "childNodes", "as", "$", "Child", ")", "{", "$", "node_contents", ".=", "self", "::", "_cleanHTML", "(", "$", "Child", ",", "$", "filters", ")", ";", "}", "}", "// Nameless and disallowed nodes (return content only, no tags)", "assert", "(", "'isset($filters[\\'tags\\']) && is_array($filters[\\'tags\\'])'", ")", ";", "if", "(", "!", "isset", "(", "$", "filters", "[", "'tags'", "]", ")", "||", "!", "is_array", "(", "$", "filters", "[", "'tags'", "]", ")", ")", "{", "$", "filters", "[", "'tags'", "]", "=", "[", "]", ";", "}", "if", "(", "$", "tag_name", "==", "''", "||", "!", "in_array", "(", "$", "tag_name", ",", "$", "filters", "[", "'tags'", "]", ")", ")", "{", "return", "$", "node_contents", ";", "}", "// Allowed nodes (return tag and content)", "else", "{", "$", "node_attributes", "=", "self", "::", "_cleanAttributes", "(", "$", "Node", ",", "$", "filters", ")", ";", "// If (after filtering) \"a\" or \"img\" elements have no attributes, discard them", "if", "(", "$", "node_attributes", "==", "''", "&&", "(", "$", "tag_name", "==", "'a'", "||", "$", "tag_name", "==", "'img'", ")", ")", "{", "return", "$", "node_contents", ";", "}", "switch", "(", "$", "tag_name", ")", "{", "// Empty elements (c.q. self-closing)", "case", "'br'", ":", "case", "'hr'", ":", "case", "'input'", ":", "case", "'img'", ":", "return", "\"<$tag_name$node_attributes>\"", ";", "break", ";", "// Elements with content", "default", ":", "// Empty \"a\" elements (c.q. page anchors) are allowed", "if", "(", "trim", "(", "$", "node_contents", ")", "==", "''", "&&", "$", "tag_name", "!=", "'a'", ")", "return", "''", ";", "return", "\"<$tag_name$node_attributes>$node_contents</$tag_name>\"", ";", "}", "}", "}" ]
Clean the HTML of the provided DOM-node. <p>Reconstructs the HTML contents of the provided DOM-node in such a way that all invalid or disallowed HTML is removed from it.</p> @param DOMNode $Node @param array $filters @return string
[ "Clean", "the", "HTML", "of", "the", "provided", "DOM", "-", "node", "." ]
eab69ca10ce3261480164cf8108ae7020459c847
https://github.com/studyportals/Utils/blob/eab69ca10ce3261480164cf8108ae7020459c847/src/HTML.php#L344-L441
12,312
studyportals/Utils
src/HTML.php
HTML.convertToPlainText
public static function convertToPlainText($html, $strip_urls = false, $html_format = false){ $plain_text = $html; // Attempt to maintain some basic formatting $plain_text = str_replace('<li>', ' * ', $plain_text); $plain_text = str_replace(['</p>', '</h1>', '</h2>', '</h3>'], PHP_EOL . PHP_EOL, $plain_text); $plain_text = str_replace(['</ul>', '</ol>', '<br>', '</li>', '</h4>', '</h5>'], PHP_EOL, $plain_text); // Strip out all remaining HTML tags $plain_text = preg_replace('/<\/?.*>/iU', '', $plain_text); // Strip out everything that resembles a URL if($strip_urls){ $pattern = '/(?:(?:https?\:\/\/(?:www\.)?)|(?:www\.))\S+\s?/i'; $plain_text = preg_replace($pattern, '', $plain_text); } $plain_text = html_entity_decode($plain_text, ENT_QUOTES, DEFAULT_CHARSET); $plain_text = trim($plain_text); // Apply "HTML formatting" to the plain-text if($html_format){ $plain_text = htmlentities($plain_text, ENT_QUOTES, DEFAULT_CHARSET); $plain_text = str_replace(PHP_EOL, '<br>', $plain_text); $plain_text = "<p>$plain_text</p>"; } return $plain_text; }
php
public static function convertToPlainText($html, $strip_urls = false, $html_format = false){ $plain_text = $html; // Attempt to maintain some basic formatting $plain_text = str_replace('<li>', ' * ', $plain_text); $plain_text = str_replace(['</p>', '</h1>', '</h2>', '</h3>'], PHP_EOL . PHP_EOL, $plain_text); $plain_text = str_replace(['</ul>', '</ol>', '<br>', '</li>', '</h4>', '</h5>'], PHP_EOL, $plain_text); // Strip out all remaining HTML tags $plain_text = preg_replace('/<\/?.*>/iU', '', $plain_text); // Strip out everything that resembles a URL if($strip_urls){ $pattern = '/(?:(?:https?\:\/\/(?:www\.)?)|(?:www\.))\S+\s?/i'; $plain_text = preg_replace($pattern, '', $plain_text); } $plain_text = html_entity_decode($plain_text, ENT_QUOTES, DEFAULT_CHARSET); $plain_text = trim($plain_text); // Apply "HTML formatting" to the plain-text if($html_format){ $plain_text = htmlentities($plain_text, ENT_QUOTES, DEFAULT_CHARSET); $plain_text = str_replace(PHP_EOL, '<br>', $plain_text); $plain_text = "<p>$plain_text</p>"; } return $plain_text; }
[ "public", "static", "function", "convertToPlainText", "(", "$", "html", ",", "$", "strip_urls", "=", "false", ",", "$", "html_format", "=", "false", ")", "{", "$", "plain_text", "=", "$", "html", ";", "// Attempt to maintain some basic formatting", "$", "plain_text", "=", "str_replace", "(", "'<li>'", ",", "' * '", ",", "$", "plain_text", ")", ";", "$", "plain_text", "=", "str_replace", "(", "[", "'</p>'", ",", "'</h1>'", ",", "'</h2>'", ",", "'</h3>'", "]", ",", "PHP_EOL", ".", "PHP_EOL", ",", "$", "plain_text", ")", ";", "$", "plain_text", "=", "str_replace", "(", "[", "'</ul>'", ",", "'</ol>'", ",", "'<br>'", ",", "'</li>'", ",", "'</h4>'", ",", "'</h5>'", "]", ",", "PHP_EOL", ",", "$", "plain_text", ")", ";", "// Strip out all remaining HTML tags", "$", "plain_text", "=", "preg_replace", "(", "'/<\\/?.*>/iU'", ",", "''", ",", "$", "plain_text", ")", ";", "// Strip out everything that resembles a URL", "if", "(", "$", "strip_urls", ")", "{", "$", "pattern", "=", "'/(?:(?:https?\\:\\/\\/(?:www\\.)?)|(?:www\\.))\\S+\\s?/i'", ";", "$", "plain_text", "=", "preg_replace", "(", "$", "pattern", ",", "''", ",", "$", "plain_text", ")", ";", "}", "$", "plain_text", "=", "html_entity_decode", "(", "$", "plain_text", ",", "ENT_QUOTES", ",", "DEFAULT_CHARSET", ")", ";", "$", "plain_text", "=", "trim", "(", "$", "plain_text", ")", ";", "// Apply \"HTML formatting\" to the plain-text", "if", "(", "$", "html_format", ")", "{", "$", "plain_text", "=", "htmlentities", "(", "$", "plain_text", ",", "ENT_QUOTES", ",", "DEFAULT_CHARSET", ")", ";", "$", "plain_text", "=", "str_replace", "(", "PHP_EOL", ",", "'<br>'", ",", "$", "plain_text", ")", ";", "$", "plain_text", "=", "\"<p>$plain_text</p>\"", ";", "}", "return", "$", "plain_text", ";", "}" ]
Convert HTML to plain-text. <p>Convert (clean) HTML into plain-text. This method applies some very basic formatting to maintain a bit of the previous appearance. This method returns <em>pure</em> plain-text, including having all HTML entities decoded.</p> <p>This method <strong>only</strong> functions properly if it is fed proper HTML (c.q. passed through {@link HTML::cleanHTML()}).</p> <p>The optional argument {@link $strip_urls} is used to forcibly remove everything that looks like a URL (c.q. starts with "http://" or "www.") from the plain-text output.</p> <p>The optional argument {@link $html_format} is used to "HTML format" the returned plain-text. This entails all line-breaks are replaced with an HTML "br" element, HTML ntities are re-encoded and the entire string is wrapped in a single HTML paragraph element. This way the plain-text can be displayed (as plain-text) in an HTML document.</p> @param string $html @param boolean $strip_urls @param boolean $html_format @return string
[ "Convert", "HTML", "to", "plain", "-", "text", "." ]
eab69ca10ce3261480164cf8108ae7020459c847
https://github.com/studyportals/Utils/blob/eab69ca10ce3261480164cf8108ae7020459c847/src/HTML.php#L633-L670
12,313
yii2-tools/yii2-base
components/TypeValidator.php
TypeValidator.validateAttributeInternal
protected function validateAttributeInternal($model, $attribute) { $value = $model->{$attribute}; $result = ($this->type == FormatHelper::TYPE_LIST) ? $this->validateListValue($model, $value) : $this->validateValue($value); if (!empty($result)) { $this->addError($model, $attribute, $result[0], $result[1]); return; } Yii::info('Type validation success' . PHP_EOL . "Result value for '$attribute': {$this->filteredAttribute}", __METHOD__); $model->{$attribute} = $this->filteredAttribute; }
php
protected function validateAttributeInternal($model, $attribute) { $value = $model->{$attribute}; $result = ($this->type == FormatHelper::TYPE_LIST) ? $this->validateListValue($model, $value) : $this->validateValue($value); if (!empty($result)) { $this->addError($model, $attribute, $result[0], $result[1]); return; } Yii::info('Type validation success' . PHP_EOL . "Result value for '$attribute': {$this->filteredAttribute}", __METHOD__); $model->{$attribute} = $this->filteredAttribute; }
[ "protected", "function", "validateAttributeInternal", "(", "$", "model", ",", "$", "attribute", ")", "{", "$", "value", "=", "$", "model", "->", "{", "$", "attribute", "}", ";", "$", "result", "=", "(", "$", "this", "->", "type", "==", "FormatHelper", "::", "TYPE_LIST", ")", "?", "$", "this", "->", "validateListValue", "(", "$", "model", ",", "$", "value", ")", ":", "$", "this", "->", "validateValue", "(", "$", "value", ")", ";", "if", "(", "!", "empty", "(", "$", "result", ")", ")", "{", "$", "this", "->", "addError", "(", "$", "model", ",", "$", "attribute", ",", "$", "result", "[", "0", "]", ",", "$", "result", "[", "1", "]", ")", ";", "return", ";", "}", "Yii", "::", "info", "(", "'Type validation success'", ".", "PHP_EOL", ".", "\"Result value for '$attribute': {$this->filteredAttribute}\"", ",", "__METHOD__", ")", ";", "$", "model", "->", "{", "$", "attribute", "}", "=", "$", "this", "->", "filteredAttribute", ";", "}" ]
Model validation context @param $value
[ "Model", "validation", "context" ]
10f6bb6b0b9396c3d942e0f2ec06784fa9bbf72a
https://github.com/yii2-tools/yii2-base/blob/10f6bb6b0b9396c3d942e0f2ec06784fa9bbf72a/components/TypeValidator.php#L52-L69
12,314
bishopb/vanilla
applications/dashboard/models/class.localemodel.php
LocaleModel.WriteDefinitions
public static function WriteDefinitions($fp, $Definitions) { // Write the definitions. uksort($Definitions, 'strcasecmp'); $LastC = ''; foreach ($Definitions as $Key => $Value) { // Add a blank line between letters of the alphabet. if (isset($Key[0]) && strcasecmp($LastC, $Key[0]) != 0) { fwrite($fp, "\n"); $LastC = $Key[0]; } $Str = '$Definition['.var_export($Key, TRUE).'] = '.var_export($Value, TRUE).";\n"; fwrite($fp, $Str); } }
php
public static function WriteDefinitions($fp, $Definitions) { // Write the definitions. uksort($Definitions, 'strcasecmp'); $LastC = ''; foreach ($Definitions as $Key => $Value) { // Add a blank line between letters of the alphabet. if (isset($Key[0]) && strcasecmp($LastC, $Key[0]) != 0) { fwrite($fp, "\n"); $LastC = $Key[0]; } $Str = '$Definition['.var_export($Key, TRUE).'] = '.var_export($Value, TRUE).";\n"; fwrite($fp, $Str); } }
[ "public", "static", "function", "WriteDefinitions", "(", "$", "fp", ",", "$", "Definitions", ")", "{", "// Write the definitions.", "uksort", "(", "$", "Definitions", ",", "'strcasecmp'", ")", ";", "$", "LastC", "=", "''", ";", "foreach", "(", "$", "Definitions", "as", "$", "Key", "=>", "$", "Value", ")", "{", "// Add a blank line between letters of the alphabet.", "if", "(", "isset", "(", "$", "Key", "[", "0", "]", ")", "&&", "strcasecmp", "(", "$", "LastC", ",", "$", "Key", "[", "0", "]", ")", "!=", "0", ")", "{", "fwrite", "(", "$", "fp", ",", "\"\\n\"", ")", ";", "$", "LastC", "=", "$", "Key", "[", "0", "]", ";", "}", "$", "Str", "=", "'$Definition['", ".", "var_export", "(", "$", "Key", ",", "TRUE", ")", ".", "'] = '", ".", "var_export", "(", "$", "Value", ",", "TRUE", ")", ".", "\";\\n\"", ";", "fwrite", "(", "$", "fp", ",", "$", "Str", ")", ";", "}", "}" ]
Write a locale's definitions to a file. @param resource $fp The file to write to. @param array $Definitions The definitions to write.
[ "Write", "a", "locale", "s", "definitions", "to", "a", "file", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/applications/dashboard/models/class.localemodel.php#L176-L190
12,315
agalbourdin/agl-core
src/Data/Xml.php
Xml._getXPath
private function _getXPath() { if ($this->_xPath === NULL) { $this->_xPath = new DOMXPath($this->_domDoc); } return $this->_xPath; }
php
private function _getXPath() { if ($this->_xPath === NULL) { $this->_xPath = new DOMXPath($this->_domDoc); } return $this->_xPath; }
[ "private", "function", "_getXPath", "(", ")", "{", "if", "(", "$", "this", "->", "_xPath", "===", "NULL", ")", "{", "$", "this", "->", "_xPath", "=", "new", "DOMXPath", "(", "$", "this", "->", "_domDoc", ")", ";", "}", "return", "$", "this", "->", "_xPath", ";", "}" ]
Create a new DOMXPath. @return DOMXPath
[ "Create", "a", "new", "DOMXPath", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Data/Xml.php#L52-L59
12,316
agalbourdin/agl-core
src/Data/Xml.php
Xml.parseXPath
public function parseXPath($pPath) { $path = str_replace('@app', '/', $pPath); $path = preg_replace('#^@module\[([a-z0-9/]+)\]|@layout#', '', $path); $pathArr = explode('/', $path); foreach($pathArr as $key => $node) { if (preg_match('/^([a-zA-Z0-9\[\]@\'"=_-]+):([a-zA-Z0-9_-]+)$/', $node, $matches)) { $pathArr[$key] = $matches[1] . '/attribute::' . $matches[2]; } else if (preg_match('/^([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)=([a-zA-Z0-9_-]+)$/', $node, $matches)) { $pathArr[$key] = $matches[1] . '[@' . $matches[2] . '="' . $matches[3] . '"]'; } else if (preg_match('/^([a-zA-Z0-9_-]+)>([a-zA-Z0-9_-]+)=([a-zA-Z0-9_-]+)$/', $node, $matches)) { $pathArr[$key] = $matches[1] . '[' . $matches[2] . '="' . $matches[3] . '"]'; } } return '//' . implode('/', $pathArr); }
php
public function parseXPath($pPath) { $path = str_replace('@app', '/', $pPath); $path = preg_replace('#^@module\[([a-z0-9/]+)\]|@layout#', '', $path); $pathArr = explode('/', $path); foreach($pathArr as $key => $node) { if (preg_match('/^([a-zA-Z0-9\[\]@\'"=_-]+):([a-zA-Z0-9_-]+)$/', $node, $matches)) { $pathArr[$key] = $matches[1] . '/attribute::' . $matches[2]; } else if (preg_match('/^([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)=([a-zA-Z0-9_-]+)$/', $node, $matches)) { $pathArr[$key] = $matches[1] . '[@' . $matches[2] . '="' . $matches[3] . '"]'; } else if (preg_match('/^([a-zA-Z0-9_-]+)>([a-zA-Z0-9_-]+)=([a-zA-Z0-9_-]+)$/', $node, $matches)) { $pathArr[$key] = $matches[1] . '[' . $matches[2] . '="' . $matches[3] . '"]'; } } return '//' . implode('/', $pathArr); }
[ "public", "function", "parseXPath", "(", "$", "pPath", ")", "{", "$", "path", "=", "str_replace", "(", "'@app'", ",", "'/'", ",", "$", "pPath", ")", ";", "$", "path", "=", "preg_replace", "(", "'#^@module\\[([a-z0-9/]+)\\]|@layout#'", ",", "''", ",", "$", "path", ")", ";", "$", "pathArr", "=", "explode", "(", "'/'", ",", "$", "path", ")", ";", "foreach", "(", "$", "pathArr", "as", "$", "key", "=>", "$", "node", ")", "{", "if", "(", "preg_match", "(", "'/^([a-zA-Z0-9\\[\\]@\\'\"=_-]+):([a-zA-Z0-9_-]+)$/'", ",", "$", "node", ",", "$", "matches", ")", ")", "{", "$", "pathArr", "[", "$", "key", "]", "=", "$", "matches", "[", "1", "]", ".", "'/attribute::'", ".", "$", "matches", "[", "2", "]", ";", "}", "else", "if", "(", "preg_match", "(", "'/^([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)=([a-zA-Z0-9_-]+)$/'", ",", "$", "node", ",", "$", "matches", ")", ")", "{", "$", "pathArr", "[", "$", "key", "]", "=", "$", "matches", "[", "1", "]", ".", "'[@'", ".", "$", "matches", "[", "2", "]", ".", "'=\"'", ".", "$", "matches", "[", "3", "]", ".", "'\"]'", ";", "}", "else", "if", "(", "preg_match", "(", "'/^([a-zA-Z0-9_-]+)>([a-zA-Z0-9_-]+)=([a-zA-Z0-9_-]+)$/'", ",", "$", "node", ",", "$", "matches", ")", ")", "{", "$", "pathArr", "[", "$", "key", "]", "=", "$", "matches", "[", "1", "]", ".", "'['", ".", "$", "matches", "[", "2", "]", ".", "'=\"'", ".", "$", "matches", "[", "3", "]", ".", "'\"]'", ";", "}", "}", "return", "'//'", ".", "implode", "(", "'/'", ",", "$", "pathArr", ")", ";", "}" ]
Parse the required config path in order to convert the Agl syntax into a valid XPath query. @param string $pPath Requested path @return string XPath query
[ "Parse", "the", "required", "config", "path", "in", "order", "to", "convert", "the", "Agl", "syntax", "into", "a", "valid", "XPath", "query", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Data/Xml.php#L68-L86
12,317
agalbourdin/agl-core
src/Data/Xml.php
Xml.xPathQuery
public function xPathQuery($pQuery, $pNode = NULL) { $queryResult = $this->_getXPath()->query($pQuery, $pNode); if ($queryResult === false) { throw new Exception("Invalid XPath request"); } return $queryResult; }
php
public function xPathQuery($pQuery, $pNode = NULL) { $queryResult = $this->_getXPath()->query($pQuery, $pNode); if ($queryResult === false) { throw new Exception("Invalid XPath request"); } return $queryResult; }
[ "public", "function", "xPathQuery", "(", "$", "pQuery", ",", "$", "pNode", "=", "NULL", ")", "{", "$", "queryResult", "=", "$", "this", "->", "_getXPath", "(", ")", "->", "query", "(", "$", "pQuery", ",", "$", "pNode", ")", ";", "if", "(", "$", "queryResult", "===", "false", ")", "{", "throw", "new", "Exception", "(", "\"Invalid XPath request\"", ")", ";", "}", "return", "$", "queryResult", ";", "}" ]
Execute an XPath query. @param string $pQuery XPath query @return mixed
[ "Execute", "an", "XPath", "query", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Data/Xml.php#L196-L204
12,318
agalbourdin/agl-core
src/Data/Xml.php
Xml._getNodeAttributes
private function _getNodeAttributes(DOMElement $pNode) { $attributes = array(); if ($pNode->attributes->length) { foreach ($pNode->attributes as $key => $attr) { $attributes[$key] = $attr->value; } } return $attributes; }
php
private function _getNodeAttributes(DOMElement $pNode) { $attributes = array(); if ($pNode->attributes->length) { foreach ($pNode->attributes as $key => $attr) { $attributes[$key] = $attr->value; } } return $attributes; }
[ "private", "function", "_getNodeAttributes", "(", "DOMElement", "$", "pNode", ")", "{", "$", "attributes", "=", "array", "(", ")", ";", "if", "(", "$", "pNode", "->", "attributes", "->", "length", ")", "{", "foreach", "(", "$", "pNode", "->", "attributes", "as", "$", "key", "=>", "$", "attr", ")", "{", "$", "attributes", "[", "$", "key", "]", "=", "$", "attr", "->", "value", ";", "}", "}", "return", "$", "attributes", ";", "}" ]
Get the node attributes as array. @param DOMElement $pNode @return array
[ "Get", "the", "node", "attributes", "as", "array", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Data/Xml.php#L297-L307
12,319
toin0u/concise
src/Provider/Cache.php
Cache.transformUrl
protected function transformUrl($url, $transformation) { $cachedUrl = $this->pool->getItem(md5($url)); if ($cachedUrl->isMiss()) { $url = $this->provider->$transformation($url); $cachedUrl->set($url); } else { $url = $cachedUrl->get(); } return $url; }
php
protected function transformUrl($url, $transformation) { $cachedUrl = $this->pool->getItem(md5($url)); if ($cachedUrl->isMiss()) { $url = $this->provider->$transformation($url); $cachedUrl->set($url); } else { $url = $cachedUrl->get(); } return $url; }
[ "protected", "function", "transformUrl", "(", "$", "url", ",", "$", "transformation", ")", "{", "$", "cachedUrl", "=", "$", "this", "->", "pool", "->", "getItem", "(", "md5", "(", "$", "url", ")", ")", ";", "if", "(", "$", "cachedUrl", "->", "isMiss", "(", ")", ")", "{", "$", "url", "=", "$", "this", "->", "provider", "->", "$", "transformation", "(", "$", "url", ")", ";", "$", "cachedUrl", "->", "set", "(", "$", "url", ")", ";", "}", "else", "{", "$", "url", "=", "$", "cachedUrl", "->", "get", "(", ")", ";", "}", "return", "$", "url", ";", "}" ]
Shorten or expand a URL checking it in the cache first @param string $url @param string $transformation @return string
[ "Shorten", "or", "expand", "a", "URL", "checking", "it", "in", "the", "cache", "first" ]
3e38b8bb221ecedaa184cd98529d0d64f52c3f60
https://github.com/toin0u/concise/blob/3e38b8bb221ecedaa184cd98529d0d64f52c3f60/src/Provider/Cache.php#L67-L80
12,320
XTAIN/JoomlaBundle
Library/CMS/Module/Helper.php
Helper.cleanModuleList
public static function cleanModuleList($modules) { $app = \JFactory::getApplication(); // Apply negative selections and eliminate duplicates $Itemid = \JFactory::getApplication()->input->getInt('Itemid'); $negId = $Itemid ? -(int) $Itemid : false; $clean = array(); $dupes = array(); foreach ($modules as $i => $module) { // The module is excluded if there is an explicit prohibition $negHit = ($negId === (int) $module->menuid); if (isset($dupes[$module->id])) { // If this item has been excluded, keep the duplicate flag set, // but remove any item from the modules array. if ($negHit) { unset($clean[$module->id]); } continue; } $dupes[$module->id] = true; // Only accept modules without explicit exclusions. if ($negHit) { continue; } $module->name = substr($module->module, 4); $module->style = null; $module->position = strtolower($module->position); $clean[$module->id] = $module; } unset($dupes); // Do 3rd party stuff to manipulate module array. // Any plugins using this architecture may make alterations to the referenced $modules array. // To remove items you can do unset($modules[n]) or $modules[n]->published = false. // "onPrepareModuleList" may alter or add $modules, and does not need to return anything. // This should be used for module addition/deletion that the user would expect to happen at an // early stage. $app->triggerEvent( 'onPrepareModuleList', array( &$clean ) ); // "onAlterModuleList" may alter or add $modules, and does not need to return anything. $app->triggerEvent( 'onAlterModuleList', array( &$clean ) ); // "onPostProcessModuleList" allows a plugin to perform actions like parameter changes // on the completed list of modules and is guaranteed to occur *after* // the earlier plugins. $app->triggerEvent( 'onPostProcessModuleList', array( &$clean ) ); // Remove any that were marked as disabled during the preceding steps /*foreach ( $clean as $id => $module ) { if ( !isset( $module->published ) || $module->published == 0 ) { unset( $clean[$id] ); } }*/ // Return to simple indexing that matches the query order. return array_values($clean); }
php
public static function cleanModuleList($modules) { $app = \JFactory::getApplication(); // Apply negative selections and eliminate duplicates $Itemid = \JFactory::getApplication()->input->getInt('Itemid'); $negId = $Itemid ? -(int) $Itemid : false; $clean = array(); $dupes = array(); foreach ($modules as $i => $module) { // The module is excluded if there is an explicit prohibition $negHit = ($negId === (int) $module->menuid); if (isset($dupes[$module->id])) { // If this item has been excluded, keep the duplicate flag set, // but remove any item from the modules array. if ($negHit) { unset($clean[$module->id]); } continue; } $dupes[$module->id] = true; // Only accept modules without explicit exclusions. if ($negHit) { continue; } $module->name = substr($module->module, 4); $module->style = null; $module->position = strtolower($module->position); $clean[$module->id] = $module; } unset($dupes); // Do 3rd party stuff to manipulate module array. // Any plugins using this architecture may make alterations to the referenced $modules array. // To remove items you can do unset($modules[n]) or $modules[n]->published = false. // "onPrepareModuleList" may alter or add $modules, and does not need to return anything. // This should be used for module addition/deletion that the user would expect to happen at an // early stage. $app->triggerEvent( 'onPrepareModuleList', array( &$clean ) ); // "onAlterModuleList" may alter or add $modules, and does not need to return anything. $app->triggerEvent( 'onAlterModuleList', array( &$clean ) ); // "onPostProcessModuleList" allows a plugin to perform actions like parameter changes // on the completed list of modules and is guaranteed to occur *after* // the earlier plugins. $app->triggerEvent( 'onPostProcessModuleList', array( &$clean ) ); // Remove any that were marked as disabled during the preceding steps /*foreach ( $clean as $id => $module ) { if ( !isset( $module->published ) || $module->published == 0 ) { unset( $clean[$id] ); } }*/ // Return to simple indexing that matches the query order. return array_values($clean); }
[ "public", "static", "function", "cleanModuleList", "(", "$", "modules", ")", "{", "$", "app", "=", "\\", "JFactory", "::", "getApplication", "(", ")", ";", "// Apply negative selections and eliminate duplicates", "$", "Itemid", "=", "\\", "JFactory", "::", "getApplication", "(", ")", "->", "input", "->", "getInt", "(", "'Itemid'", ")", ";", "$", "negId", "=", "$", "Itemid", "?", "-", "(", "int", ")", "$", "Itemid", ":", "false", ";", "$", "clean", "=", "array", "(", ")", ";", "$", "dupes", "=", "array", "(", ")", ";", "foreach", "(", "$", "modules", "as", "$", "i", "=>", "$", "module", ")", "{", "// The module is excluded if there is an explicit prohibition", "$", "negHit", "=", "(", "$", "negId", "===", "(", "int", ")", "$", "module", "->", "menuid", ")", ";", "if", "(", "isset", "(", "$", "dupes", "[", "$", "module", "->", "id", "]", ")", ")", "{", "// If this item has been excluded, keep the duplicate flag set,", "// but remove any item from the modules array.", "if", "(", "$", "negHit", ")", "{", "unset", "(", "$", "clean", "[", "$", "module", "->", "id", "]", ")", ";", "}", "continue", ";", "}", "$", "dupes", "[", "$", "module", "->", "id", "]", "=", "true", ";", "// Only accept modules without explicit exclusions.", "if", "(", "$", "negHit", ")", "{", "continue", ";", "}", "$", "module", "->", "name", "=", "substr", "(", "$", "module", "->", "module", ",", "4", ")", ";", "$", "module", "->", "style", "=", "null", ";", "$", "module", "->", "position", "=", "strtolower", "(", "$", "module", "->", "position", ")", ";", "$", "clean", "[", "$", "module", "->", "id", "]", "=", "$", "module", ";", "}", "unset", "(", "$", "dupes", ")", ";", "// Do 3rd party stuff to manipulate module array.", "// Any plugins using this architecture may make alterations to the referenced $modules array.", "// To remove items you can do unset($modules[n]) or $modules[n]->published = false.", "// \"onPrepareModuleList\" may alter or add $modules, and does not need to return anything.", "// This should be used for module addition/deletion that the user would expect to happen at an", "// early stage.", "$", "app", "->", "triggerEvent", "(", "'onPrepareModuleList'", ",", "array", "(", "&", "$", "clean", ")", ")", ";", "// \"onAlterModuleList\" may alter or add $modules, and does not need to return anything.", "$", "app", "->", "triggerEvent", "(", "'onAlterModuleList'", ",", "array", "(", "&", "$", "clean", ")", ")", ";", "// \"onPostProcessModuleList\" allows a plugin to perform actions like parameter changes", "// on the completed list of modules and is guaranteed to occur *after*", "// the earlier plugins.", "$", "app", "->", "triggerEvent", "(", "'onPostProcessModuleList'", ",", "array", "(", "&", "$", "clean", ")", ")", ";", "// Remove any that were marked as disabled during the preceding steps", "/*foreach ( $clean as $id => $module )\n {\n if ( !isset( $module->published ) || $module->published == 0 )\n {\n unset( $clean[$id] );\n }\n }*/", "// Return to simple indexing that matches the query order.", "return", "array_values", "(", "$", "clean", ")", ";", "}" ]
Clean the module list @param array $modules Array with module objects @return array
[ "Clean", "the", "module", "list" ]
3d39e1278deba77c5a2197ad91973964ed2a38bd
https://github.com/XTAIN/JoomlaBundle/blob/3d39e1278deba77c5a2197ad91973964ed2a38bd/Library/CMS/Module/Helper.php#L198-L270
12,321
tenside/core
src/Composer/ComposerJson.php
ComposerJson.setLink
private function setLink($type, $name, $constraint) { $this->set($type . '/' . $this->escape($name), $constraint); return $this; }
php
private function setLink($type, $name, $constraint) { $this->set($type . '/' . $this->escape($name), $constraint); return $this; }
[ "private", "function", "setLink", "(", "$", "type", ",", "$", "name", ",", "$", "constraint", ")", "{", "$", "this", "->", "set", "(", "$", "type", ".", "'/'", ".", "$", "this", "->", "escape", "(", "$", "name", ")", ",", "$", "constraint", ")", ";", "return", "$", "this", ";", "}" ]
Set a link on a dependency to a constraint. @param string $type The link type (require, require-dev, provide, replace). @param string $name The package name. @param string $constraint The version constraint. @return ComposerJson
[ "Set", "a", "link", "on", "a", "dependency", "to", "a", "constraint", "." ]
56422fa8cdecf03cb431bb6654c2942ade39bf7b
https://github.com/tenside/core/blob/56422fa8cdecf03cb431bb6654c2942ade39bf7b/src/Composer/ComposerJson.php#L196-L201
12,322
tenside/core
src/Composer/ComposerJson.php
ComposerJson.setLock
public function setLock(PackageInterface $package, $state) { if ((bool) $state) { return $this->lockPackage($package); } return $this->unlockPackage($package); }
php
public function setLock(PackageInterface $package, $state) { if ((bool) $state) { return $this->lockPackage($package); } return $this->unlockPackage($package); }
[ "public", "function", "setLock", "(", "PackageInterface", "$", "package", ",", "$", "state", ")", "{", "if", "(", "(", "bool", ")", "$", "state", ")", "{", "return", "$", "this", "->", "lockPackage", "(", "$", "package", ")", ";", "}", "return", "$", "this", "->", "unlockPackage", "(", "$", "package", ")", ";", "}" ]
Set the locking state for the passed package. @param PackageInterface $package The package to lock. @param bool $state The desired state. @return ComposerJson
[ "Set", "the", "locking", "state", "for", "the", "passed", "package", "." ]
56422fa8cdecf03cb431bb6654c2942ade39bf7b
https://github.com/tenside/core/blob/56422fa8cdecf03cb431bb6654c2942ade39bf7b/src/Composer/ComposerJson.php#L315-L322
12,323
tenside/core
src/Composer/ComposerJson.php
ComposerJson.cleanEmptyArraysInPath
private function cleanEmptyArraysInPath($path) { $subs = $this->getEntries($path); if (!empty($subs)) { foreach ($subs as $subPath) { $this->cleanEmptyArraysInPath($subPath); } } if ([] === $this->get($path)) { $this->remove($path); } }
php
private function cleanEmptyArraysInPath($path) { $subs = $this->getEntries($path); if (!empty($subs)) { foreach ($subs as $subPath) { $this->cleanEmptyArraysInPath($subPath); } } if ([] === $this->get($path)) { $this->remove($path); } }
[ "private", "function", "cleanEmptyArraysInPath", "(", "$", "path", ")", "{", "$", "subs", "=", "$", "this", "->", "getEntries", "(", "$", "path", ")", ";", "if", "(", "!", "empty", "(", "$", "subs", ")", ")", "{", "foreach", "(", "$", "subs", "as", "$", "subPath", ")", "{", "$", "this", "->", "cleanEmptyArraysInPath", "(", "$", "subPath", ")", ";", "}", "}", "if", "(", "[", "]", "===", "$", "this", "->", "get", "(", "$", "path", ")", ")", "{", "$", "this", "->", "remove", "(", "$", "path", ")", ";", "}", "}" ]
Cleanup the array section at the given path by removing empty sub arrays. @param string $path The base path to remove empty elements from. @return void
[ "Cleanup", "the", "array", "section", "at", "the", "given", "path", "by", "removing", "empty", "sub", "arrays", "." ]
56422fa8cdecf03cb431bb6654c2942ade39bf7b
https://github.com/tenside/core/blob/56422fa8cdecf03cb431bb6654c2942ade39bf7b/src/Composer/ComposerJson.php#L331-L343
12,324
rocketphp/tweetnest
src/TweetNest.php
TweetNest.clear
public function clear() { $params = [ 'index' => $this->_esindex, 'type' => $this->_estype, 'body' => [ 'query' => [ 'match_all' => [] ] ] ]; $query = $this->_es->deleteByQuery($params); // return $query['_indices']['tweets']['_shards']['successful']; $result = true; return $result; }
php
public function clear() { $params = [ 'index' => $this->_esindex, 'type' => $this->_estype, 'body' => [ 'query' => [ 'match_all' => [] ] ] ]; $query = $this->_es->deleteByQuery($params); // return $query['_indices']['tweets']['_shards']['successful']; $result = true; return $result; }
[ "public", "function", "clear", "(", ")", "{", "$", "params", "=", "[", "'index'", "=>", "$", "this", "->", "_esindex", ",", "'type'", "=>", "$", "this", "->", "_estype", ",", "'body'", "=>", "[", "'query'", "=>", "[", "'match_all'", "=>", "[", "]", "]", "]", "]", ";", "$", "query", "=", "$", "this", "->", "_es", "->", "deleteByQuery", "(", "$", "params", ")", ";", "// return $query['_indices']['tweets']['_shards']['successful'];", "$", "result", "=", "true", ";", "return", "$", "result", ";", "}" ]
Clear tweets in elasticsearch @return bool
[ "Clear", "tweets", "in", "elasticsearch" ]
7aca76f95fb8eea503abab86935f767097a308e1
https://github.com/rocketphp/tweetnest/blob/7aca76f95fb8eea503abab86935f767097a308e1/src/TweetNest.php#L126-L141
12,325
rocketphp/tweetnest
src/TweetNest.php
TweetNest.save
public function save() { $result = null; $i = 0; foreach ( $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $this->_dir, RecursiveDirectoryIterator::SKIP_DOTS ), RecursiveIteratorIterator::SELF_FIRST ) as $item ) { if (!$item->isDir()) { $filename = $this->_dir . DIRECTORY_SEPARATOR . $iterator->getSubPathName(); $_tweet = file_get_contents($filename); $tweet = json_decode($_tweet, TRUE); $params = ['index' => $this->_esindex, 'type' => $this->_estype, 'body' => $tweet]; $result = $this->_es->index($params); $i++; } } return $i; }
php
public function save() { $result = null; $i = 0; foreach ( $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $this->_dir, RecursiveDirectoryIterator::SKIP_DOTS ), RecursiveIteratorIterator::SELF_FIRST ) as $item ) { if (!$item->isDir()) { $filename = $this->_dir . DIRECTORY_SEPARATOR . $iterator->getSubPathName(); $_tweet = file_get_contents($filename); $tweet = json_decode($_tweet, TRUE); $params = ['index' => $this->_esindex, 'type' => $this->_estype, 'body' => $tweet]; $result = $this->_es->index($params); $i++; } } return $i; }
[ "public", "function", "save", "(", ")", "{", "$", "result", "=", "null", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "iterator", "=", "new", "RecursiveIteratorIterator", "(", "new", "RecursiveDirectoryIterator", "(", "$", "this", "->", "_dir", ",", "RecursiveDirectoryIterator", "::", "SKIP_DOTS", ")", ",", "RecursiveIteratorIterator", "::", "SELF_FIRST", ")", "as", "$", "item", ")", "{", "if", "(", "!", "$", "item", "->", "isDir", "(", ")", ")", "{", "$", "filename", "=", "$", "this", "->", "_dir", ".", "DIRECTORY_SEPARATOR", ".", "$", "iterator", "->", "getSubPathName", "(", ")", ";", "$", "_tweet", "=", "file_get_contents", "(", "$", "filename", ")", ";", "$", "tweet", "=", "json_decode", "(", "$", "_tweet", ",", "TRUE", ")", ";", "$", "params", "=", "[", "'index'", "=>", "$", "this", "->", "_esindex", ",", "'type'", "=>", "$", "this", "->", "_estype", ",", "'body'", "=>", "$", "tweet", "]", ";", "$", "result", "=", "$", "this", "->", "_es", "->", "index", "(", "$", "params", ")", ";", "$", "i", "++", ";", "}", "}", "return", "$", "i", ";", "}" ]
Save tweets in elasticsearch @return int
[ "Save", "tweets", "in", "elasticsearch" ]
7aca76f95fb8eea503abab86935f767097a308e1
https://github.com/rocketphp/tweetnest/blob/7aca76f95fb8eea503abab86935f767097a308e1/src/TweetNest.php#L163-L190
12,326
rocketphp/tweetnest
src/TweetNest.php
TweetNest.tweets
public function tweets($limit = 1000) { $params = [ 'index' => $this->_esindex, 'type' => $this->_estype, 'size' => $limit, 'body' => [ 'query' => [ 'match_all' => [] ] ] ]; $query = $this->_es->search($params); if ($query['hits']['total'] >= 1) $result = $query['hits']['hits']; else $result = []; return $result; }
php
public function tweets($limit = 1000) { $params = [ 'index' => $this->_esindex, 'type' => $this->_estype, 'size' => $limit, 'body' => [ 'query' => [ 'match_all' => [] ] ] ]; $query = $this->_es->search($params); if ($query['hits']['total'] >= 1) $result = $query['hits']['hits']; else $result = []; return $result; }
[ "public", "function", "tweets", "(", "$", "limit", "=", "1000", ")", "{", "$", "params", "=", "[", "'index'", "=>", "$", "this", "->", "_esindex", ",", "'type'", "=>", "$", "this", "->", "_estype", ",", "'size'", "=>", "$", "limit", ",", "'body'", "=>", "[", "'query'", "=>", "[", "'match_all'", "=>", "[", "]", "]", "]", "]", ";", "$", "query", "=", "$", "this", "->", "_es", "->", "search", "(", "$", "params", ")", ";", "if", "(", "$", "query", "[", "'hits'", "]", "[", "'total'", "]", ">=", "1", ")", "$", "result", "=", "$", "query", "[", "'hits'", "]", "[", "'hits'", "]", ";", "else", "$", "result", "=", "[", "]", ";", "return", "$", "result", ";", "}" ]
Return all tweets @param int $limit Limit @return array
[ "Return", "all", "tweets" ]
7aca76f95fb8eea503abab86935f767097a308e1
https://github.com/rocketphp/tweetnest/blob/7aca76f95fb8eea503abab86935f767097a308e1/src/TweetNest.php#L198-L216
12,327
ideil/generic-file
src/GenericFile.php
GenericFile.moveUploadedFile
public function moveUploadedFile(File $file, $path_pattern = null) { // inperpolate path_pattern using $file // and get interpolator result object $interpolated = $this->interpolator->resolveStorePath( $path_pattern ?: $this->getConfig('store.path_pattern', ''), $file); // file will be moved to interpolated path // using configured public_path as root $target = $this->getStoreRootPath() . '/' . ltrim($interpolated, '/'); if ( ! file_exists($target)) { $file->move(dirname($target), basename($target)); } return $interpolated; }
php
public function moveUploadedFile(File $file, $path_pattern = null) { // inperpolate path_pattern using $file // and get interpolator result object $interpolated = $this->interpolator->resolveStorePath( $path_pattern ?: $this->getConfig('store.path_pattern', ''), $file); // file will be moved to interpolated path // using configured public_path as root $target = $this->getStoreRootPath() . '/' . ltrim($interpolated, '/'); if ( ! file_exists($target)) { $file->move(dirname($target), basename($target)); } return $interpolated; }
[ "public", "function", "moveUploadedFile", "(", "File", "$", "file", ",", "$", "path_pattern", "=", "null", ")", "{", "// inperpolate path_pattern using $file", "// and get interpolator result object", "$", "interpolated", "=", "$", "this", "->", "interpolator", "->", "resolveStorePath", "(", "$", "path_pattern", "?", ":", "$", "this", "->", "getConfig", "(", "'store.path_pattern'", ",", "''", ")", ",", "$", "file", ")", ";", "// file will be moved to interpolated path", "// using configured public_path as root", "$", "target", "=", "$", "this", "->", "getStoreRootPath", "(", ")", ".", "'/'", ".", "ltrim", "(", "$", "interpolated", ",", "'/'", ")", ";", "if", "(", "!", "file_exists", "(", "$", "target", ")", ")", "{", "$", "file", "->", "move", "(", "dirname", "(", "$", "target", ")", ",", "basename", "(", "$", "target", ")", ")", ";", "}", "return", "$", "interpolated", ";", "}" ]
Move uploaded file to path by pattern @param File $file @param string|null $path_pattern @return string|null
[ "Move", "uploaded", "file", "to", "path", "by", "pattern" ]
0506ab15dc88f2acbd59c99d6c679a670735d0f9
https://github.com/ideil/generic-file/blob/0506ab15dc88f2acbd59c99d6c679a670735d0f9/src/GenericFile.php#L118-L137
12,328
ideil/generic-file
src/GenericFile.php
GenericFile.makeUrlToUploadedFile
public function makeUrlToUploadedFile($model, $path_pattern = null, array $model_map = array(), $domain = null) { $pattern = $path_pattern ?: $this->getConfig('http.path_pattern', ''); if (is_null($domain)) { $domain = $this->getConfig('http.domain', ''); } $path = $this->interpolator->resolvePath($pattern, $model, $model_map)->getResult(); $path = rtrim($domain, '/') . '/' . ltrim($path, '/'); return $path; }
php
public function makeUrlToUploadedFile($model, $path_pattern = null, array $model_map = array(), $domain = null) { $pattern = $path_pattern ?: $this->getConfig('http.path_pattern', ''); if (is_null($domain)) { $domain = $this->getConfig('http.domain', ''); } $path = $this->interpolator->resolvePath($pattern, $model, $model_map)->getResult(); $path = rtrim($domain, '/') . '/' . ltrim($path, '/'); return $path; }
[ "public", "function", "makeUrlToUploadedFile", "(", "$", "model", ",", "$", "path_pattern", "=", "null", ",", "array", "$", "model_map", "=", "array", "(", ")", ",", "$", "domain", "=", "null", ")", "{", "$", "pattern", "=", "$", "path_pattern", "?", ":", "$", "this", "->", "getConfig", "(", "'http.path_pattern'", ",", "''", ")", ";", "if", "(", "is_null", "(", "$", "domain", ")", ")", "{", "$", "domain", "=", "$", "this", "->", "getConfig", "(", "'http.domain'", ",", "''", ")", ";", "}", "$", "path", "=", "$", "this", "->", "interpolator", "->", "resolvePath", "(", "$", "pattern", ",", "$", "model", ",", "$", "model_map", ")", "->", "getResult", "(", ")", ";", "$", "path", "=", "rtrim", "(", "$", "domain", ",", "'/'", ")", ".", "'/'", ".", "ltrim", "(", "$", "path", ",", "'/'", ")", ";", "return", "$", "path", ";", "}" ]
Make url to uploaded file @param array|object $model @param string|null $path_pattern @param array $model_map @return string
[ "Make", "url", "to", "uploaded", "file" ]
0506ab15dc88f2acbd59c99d6c679a670735d0f9
https://github.com/ideil/generic-file/blob/0506ab15dc88f2acbd59c99d6c679a670735d0f9/src/GenericFile.php#L202-L217
12,329
ideil/generic-file
src/GenericFile.php
GenericFile.makePathToUploadedFile
public function makePathToUploadedFile($model, $path_pattern = null, array $model_map = array()) { $pattern = $path_pattern ?: $this->getConfig('store.path_pattern', ''); $path = $this->interpolator->resolvePath($pattern, $model, $model_map)->getResult(); $path = $this->getStoreRootPath() . '/' . ltrim($path, '/'); return $path; }
php
public function makePathToUploadedFile($model, $path_pattern = null, array $model_map = array()) { $pattern = $path_pattern ?: $this->getConfig('store.path_pattern', ''); $path = $this->interpolator->resolvePath($pattern, $model, $model_map)->getResult(); $path = $this->getStoreRootPath() . '/' . ltrim($path, '/'); return $path; }
[ "public", "function", "makePathToUploadedFile", "(", "$", "model", ",", "$", "path_pattern", "=", "null", ",", "array", "$", "model_map", "=", "array", "(", ")", ")", "{", "$", "pattern", "=", "$", "path_pattern", "?", ":", "$", "this", "->", "getConfig", "(", "'store.path_pattern'", ",", "''", ")", ";", "$", "path", "=", "$", "this", "->", "interpolator", "->", "resolvePath", "(", "$", "pattern", ",", "$", "model", ",", "$", "model_map", ")", "->", "getResult", "(", ")", ";", "$", "path", "=", "$", "this", "->", "getStoreRootPath", "(", ")", ".", "'/'", ".", "ltrim", "(", "$", "path", ",", "'/'", ")", ";", "return", "$", "path", ";", "}" ]
Full path to uploaded file @param array|object $model @param string|null $path_pattern @param array $model_map @return string
[ "Full", "path", "to", "uploaded", "file" ]
0506ab15dc88f2acbd59c99d6c679a670735d0f9
https://github.com/ideil/generic-file/blob/0506ab15dc88f2acbd59c99d6c679a670735d0f9/src/GenericFile.php#L228-L237
12,330
ideil/generic-file
src/GenericFile.php
GenericFile.deleteUploadedFile
public function deleteUploadedFile($model, $path_pattern = null) { if ( ! $this->canRemoveFiles()) { return null; } $filepath = $this->path($model, $path_pattern); if ($filepath && file_exists($filepath)) { return unlink($filepath); } return false; }
php
public function deleteUploadedFile($model, $path_pattern = null) { if ( ! $this->canRemoveFiles()) { return null; } $filepath = $this->path($model, $path_pattern); if ($filepath && file_exists($filepath)) { return unlink($filepath); } return false; }
[ "public", "function", "deleteUploadedFile", "(", "$", "model", ",", "$", "path_pattern", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "canRemoveFiles", "(", ")", ")", "{", "return", "null", ";", "}", "$", "filepath", "=", "$", "this", "->", "path", "(", "$", "model", ",", "$", "path_pattern", ")", ";", "if", "(", "$", "filepath", "&&", "file_exists", "(", "$", "filepath", ")", ")", "{", "return", "unlink", "(", "$", "filepath", ")", ";", "}", "return", "false", ";", "}" ]
Delete uploaded file @param array|Illuminate\Database\Eloquent\Model $model @param string|null $path_pattern @return string
[ "Delete", "uploaded", "file" ]
0506ab15dc88f2acbd59c99d6c679a670735d0f9
https://github.com/ideil/generic-file/blob/0506ab15dc88f2acbd59c99d6c679a670735d0f9/src/GenericFile.php#L247-L262
12,331
Archi-Strasbourg/archi-wiki
includes/framework/config.class.php
ArchiConfig.getUrlRacine
public function getUrlRacine() { $protocol = empty($_SERVER["HTTPS"])?"http":"https"; if (isset($_SERVER["SERVER_NAME"])) { $dirname=dirname($_SERVER["PHP_SELF"]); if (basename($dirname)=="script") { $dirname = dirname($dirname); } } else { $dirname=""; } $url =$protocol."://".$this->getNomServeur(). $dirname; if ($dirname!="/") { $url.="/"; } return $url; }
php
public function getUrlRacine() { $protocol = empty($_SERVER["HTTPS"])?"http":"https"; if (isset($_SERVER["SERVER_NAME"])) { $dirname=dirname($_SERVER["PHP_SELF"]); if (basename($dirname)=="script") { $dirname = dirname($dirname); } } else { $dirname=""; } $url =$protocol."://".$this->getNomServeur(). $dirname; if ($dirname!="/") { $url.="/"; } return $url; }
[ "public", "function", "getUrlRacine", "(", ")", "{", "$", "protocol", "=", "empty", "(", "$", "_SERVER", "[", "\"HTTPS\"", "]", ")", "?", "\"http\"", ":", "\"https\"", ";", "if", "(", "isset", "(", "$", "_SERVER", "[", "\"SERVER_NAME\"", "]", ")", ")", "{", "$", "dirname", "=", "dirname", "(", "$", "_SERVER", "[", "\"PHP_SELF\"", "]", ")", ";", "if", "(", "basename", "(", "$", "dirname", ")", "==", "\"script\"", ")", "{", "$", "dirname", "=", "dirname", "(", "$", "dirname", ")", ";", "}", "}", "else", "{", "$", "dirname", "=", "\"\"", ";", "}", "$", "url", "=", "$", "protocol", ".", "\"://\"", ".", "$", "this", "->", "getNomServeur", "(", ")", ".", "$", "dirname", ";", "if", "(", "$", "dirname", "!=", "\"/\"", ")", "{", "$", "url", ".=", "\"/\"", ";", "}", "return", "$", "url", ";", "}" ]
Renvoit la racine de l'URL @return string
[ "Renvoit", "la", "racine", "de", "l", "URL" ]
b9fb39f43a78409890a7de96426c1f6c49d5c323
https://github.com/Archi-Strasbourg/archi-wiki/blob/b9fb39f43a78409890a7de96426c1f6c49d5c323/includes/framework/config.class.php#L242-L259
12,332
Archi-Strasbourg/archi-wiki
includes/framework/config.class.php
ArchiConfig.getUrlImage
public function getUrlImage($size = "", $name = "") { if (!empty($size)) { $size.="/"; } return $this->getUrlRacine()."images/".$size.$name; }
php
public function getUrlImage($size = "", $name = "") { if (!empty($size)) { $size.="/"; } return $this->getUrlRacine()."images/".$size.$name; }
[ "public", "function", "getUrlImage", "(", "$", "size", "=", "\"\"", ",", "$", "name", "=", "\"\"", ")", "{", "if", "(", "!", "empty", "(", "$", "size", ")", ")", "{", "$", "size", ".=", "\"/\"", ";", "}", "return", "$", "this", "->", "getUrlRacine", "(", ")", ".", "\"images/\"", ".", "$", "size", ".", "$", "name", ";", "}" ]
Permet d'obtenir l'URL du dossier d'une image @param string $size Taille de l'image (mini, moyen, grand ou originaux) @param string $name Nom de l'image (avec son extension) @return string
[ "Permet", "d", "obtenir", "l", "URL", "du", "dossier", "d", "une", "image" ]
b9fb39f43a78409890a7de96426c1f6c49d5c323
https://github.com/Archi-Strasbourg/archi-wiki/blob/b9fb39f43a78409890a7de96426c1f6c49d5c323/includes/framework/config.class.php#L293-L299
12,333
nours/TableBundle
Factory/TableFactory.php
TableFactory.createBuilder
protected function createBuilder(ResolvedType $type, array $options) { $builder = new TableBuilder($type, $this, $options); $extensions = $this->getExtensionsForType($type); // Extensions build pass foreach ($extensions as $extension) { $extension->buildTable($builder, $options); } // And build the fields $type->buildTable($builder, $options); // Extensions build pass foreach ($extensions as $extension) { $extension->finishTable($builder, $options); } return $builder; }
php
protected function createBuilder(ResolvedType $type, array $options) { $builder = new TableBuilder($type, $this, $options); $extensions = $this->getExtensionsForType($type); // Extensions build pass foreach ($extensions as $extension) { $extension->buildTable($builder, $options); } // And build the fields $type->buildTable($builder, $options); // Extensions build pass foreach ($extensions as $extension) { $extension->finishTable($builder, $options); } return $builder; }
[ "protected", "function", "createBuilder", "(", "ResolvedType", "$", "type", ",", "array", "$", "options", ")", "{", "$", "builder", "=", "new", "TableBuilder", "(", "$", "type", ",", "$", "this", ",", "$", "options", ")", ";", "$", "extensions", "=", "$", "this", "->", "getExtensionsForType", "(", "$", "type", ")", ";", "// Extensions build pass", "foreach", "(", "$", "extensions", "as", "$", "extension", ")", "{", "$", "extension", "->", "buildTable", "(", "$", "builder", ",", "$", "options", ")", ";", "}", "// And build the fields", "$", "type", "->", "buildTable", "(", "$", "builder", ",", "$", "options", ")", ";", "// Extensions build pass", "foreach", "(", "$", "extensions", "as", "$", "extension", ")", "{", "$", "extension", "->", "finishTable", "(", "$", "builder", ",", "$", "options", ")", ";", "}", "return", "$", "builder", ";", "}" ]
Creates the table builder for a table type. @param ResolvedType $type @param array $options @return TableBuilder
[ "Creates", "the", "table", "builder", "for", "a", "table", "type", "." ]
0fb5bd7cc13008fb7890037b1a1ccb02d047c329
https://github.com/nours/TableBundle/blob/0fb5bd7cc13008fb7890037b1a1ccb02d047c329/Factory/TableFactory.php#L124-L143
12,334
nours/TableBundle
Factory/TableFactory.php
TableFactory.findExtensions
private function findExtensions(&$extensions, $name) { $extension = $this->getExtension($name); // Put deps first foreach ((array)$extension->getDependency() as $dep) { if (!isset($extensions[$dep])) { $this->findExtensions($extensions, $dep); } } $extensions[$name] = $extension; }
php
private function findExtensions(&$extensions, $name) { $extension = $this->getExtension($name); // Put deps first foreach ((array)$extension->getDependency() as $dep) { if (!isset($extensions[$dep])) { $this->findExtensions($extensions, $dep); } } $extensions[$name] = $extension; }
[ "private", "function", "findExtensions", "(", "&", "$", "extensions", ",", "$", "name", ")", "{", "$", "extension", "=", "$", "this", "->", "getExtension", "(", "$", "name", ")", ";", "// Put deps first", "foreach", "(", "(", "array", ")", "$", "extension", "->", "getDependency", "(", ")", "as", "$", "dep", ")", "{", "if", "(", "!", "isset", "(", "$", "extensions", "[", "$", "dep", "]", ")", ")", "{", "$", "this", "->", "findExtensions", "(", "$", "extensions", ",", "$", "dep", ")", ";", "}", "}", "$", "extensions", "[", "$", "name", "]", "=", "$", "extension", ";", "}" ]
Find extnesions recursively @param $extensions @param $name
[ "Find", "extnesions", "recursively" ]
0fb5bd7cc13008fb7890037b1a1ccb02d047c329
https://github.com/nours/TableBundle/blob/0fb5bd7cc13008fb7890037b1a1ccb02d047c329/Factory/TableFactory.php#L281-L293
12,335
nours/TableBundle
Factory/TableFactory.php
TableFactory.sortExtensions
private function sortExtensions() { // Ensure extensions are loaded in order $this->sortedExtensions = array(); foreach ($this->extensions as $extension) { $this->addExtensionToSorted($extension); } }
php
private function sortExtensions() { // Ensure extensions are loaded in order $this->sortedExtensions = array(); foreach ($this->extensions as $extension) { $this->addExtensionToSorted($extension); } }
[ "private", "function", "sortExtensions", "(", ")", "{", "// Ensure extensions are loaded in order", "$", "this", "->", "sortedExtensions", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "extensions", "as", "$", "extension", ")", "{", "$", "this", "->", "addExtensionToSorted", "(", "$", "extension", ")", ";", "}", "}" ]
Sort the extensions by dependency
[ "Sort", "the", "extensions", "by", "dependency" ]
0fb5bd7cc13008fb7890037b1a1ccb02d047c329
https://github.com/nours/TableBundle/blob/0fb5bd7cc13008fb7890037b1a1ccb02d047c329/Factory/TableFactory.php#L323-L330
12,336
osflab/view
Helper/Bootstrap/AbstractViewHelper.php
AbstractViewHelper.getPercentageColor
public static function getPercentageColor(int $percentage, int $redLimit = 30, int $orangeLimit = 70):string { return $percentage < $redLimit ? self::COLOR_RED : ( $percentage < $orangeLimit ? self::COLOR_ORANGE : self::COLOR_GREEN); }
php
public static function getPercentageColor(int $percentage, int $redLimit = 30, int $orangeLimit = 70):string { return $percentage < $redLimit ? self::COLOR_RED : ( $percentage < $orangeLimit ? self::COLOR_ORANGE : self::COLOR_GREEN); }
[ "public", "static", "function", "getPercentageColor", "(", "int", "$", "percentage", ",", "int", "$", "redLimit", "=", "30", ",", "int", "$", "orangeLimit", "=", "70", ")", ":", "string", "{", "return", "$", "percentage", "<", "$", "redLimit", "?", "self", "::", "COLOR_RED", ":", "(", "$", "percentage", "<", "$", "orangeLimit", "?", "self", "::", "COLOR_ORANGE", ":", "self", "::", "COLOR_GREEN", ")", ";", "}" ]
Get a color related to a percentage @param int $percentage @param int $redLimit @param int $orangeLimit @return string
[ "Get", "a", "color", "related", "to", "a", "percentage" ]
e06601013e8ec86dc2055e000e58dffd963c78e2
https://github.com/osflab/view/blob/e06601013e8ec86dc2055e000e58dffd963c78e2/Helper/Bootstrap/AbstractViewHelper.php#L44-L49
12,337
hemio-ev/form
src/Trait_/MaintainsTransformations.php
MaintainsTransformations.withTransformations
public function withTransformations($value) { // null for not provided remains untouched if ($value === null) return null; foreach ($this->valueTransformations as $f) $value = $f($value); return $value; }
php
public function withTransformations($value) { // null for not provided remains untouched if ($value === null) return null; foreach ($this->valueTransformations as $f) $value = $f($value); return $value; }
[ "public", "function", "withTransformations", "(", "$", "value", ")", "{", "// null for not provided remains untouched", "if", "(", "$", "value", "===", "null", ")", "return", "null", ";", "foreach", "(", "$", "this", "->", "valueTransformations", "as", "$", "f", ")", "$", "value", "=", "$", "f", "(", "$", "value", ")", ";", "return", "$", "value", ";", "}" ]
Returns the given value with all transformations applied @param mixed $value
[ "Returns", "the", "given", "value", "with", "all", "transformations", "applied" ]
b4de29c90ca6ec0c58e8e2a1a7db79926b38831d
https://github.com/hemio-ev/form/blob/b4de29c90ca6ec0c58e8e2a1a7db79926b38831d/src/Trait_/MaintainsTransformations.php#L27-L36
12,338
devbr/pack-blog
Ajax.php
Ajax.checkLink
function checkLink() { if (!isset($_POST['link'])) { $this->sendError(); } $link = strtolower(str_replace([" ",'"',"'",';','.',','], ["-",""], preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities(trim($_POST['link']))))); $base = new Model\Base; $status = $base->checkLink($link, $_POST['aID']) === false ? 'ok' : 'error'; $this->send(['status'=>$status,'link'=>$link]); }
php
function checkLink() { if (!isset($_POST['link'])) { $this->sendError(); } $link = strtolower(str_replace([" ",'"',"'",';','.',','], ["-",""], preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities(trim($_POST['link']))))); $base = new Model\Base; $status = $base->checkLink($link, $_POST['aID']) === false ? 'ok' : 'error'; $this->send(['status'=>$status,'link'=>$link]); }
[ "function", "checkLink", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "_POST", "[", "'link'", "]", ")", ")", "{", "$", "this", "->", "sendError", "(", ")", ";", "}", "$", "link", "=", "strtolower", "(", "str_replace", "(", "[", "\" \"", ",", "'\"'", ",", "\"'\"", ",", "';'", ",", "'.'", ",", "','", "]", ",", "[", "\"-\"", ",", "\"\"", "]", ",", "preg_replace", "(", "\"/&([a-z])[a-z]+;/i\"", ",", "\"$1\"", ",", "htmlentities", "(", "trim", "(", "$", "_POST", "[", "'link'", "]", ")", ")", ")", ")", ")", ";", "$", "base", "=", "new", "Model", "\\", "Base", ";", "$", "status", "=", "$", "base", "->", "checkLink", "(", "$", "link", ",", "$", "_POST", "[", "'aID'", "]", ")", "===", "false", "?", "'ok'", ":", "'error'", ";", "$", "this", "->", "send", "(", "[", "'status'", "=>", "$", "status", ",", "'link'", "=>", "$", "link", "]", ")", ";", "}" ]
Check if "link" is "in use" @return void Send data to javascript (Json)
[ "Check", "if", "link", "is", "in", "use" ]
4693e36521ee3d08077f0db3e013afb99785cc9d
https://github.com/devbr/pack-blog/blob/4693e36521ee3d08077f0db3e013afb99785cc9d/Ajax.php#L99-L111
12,339
web-operational-kit/uri
src/Components/Path.php
Path.getSegments
public function getSegments() { if(!isset($this->segments)) $this->segments = explode('/', $this->path); return $this->segments; }
php
public function getSegments() { if(!isset($this->segments)) $this->segments = explode('/', $this->path); return $this->segments; }
[ "public", "function", "getSegments", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "segments", ")", ")", "$", "this", "->", "segments", "=", "explode", "(", "'/'", ",", "$", "this", "->", "path", ")", ";", "return", "$", "this", "->", "segments", ";", "}" ]
Get path segments @return array Returns path segments
[ "Get", "path", "segments" ]
5712ca924109a0ac6a443c1fe9f497514bd48768
https://github.com/web-operational-kit/uri/blob/5712ca924109a0ac6a443c1fe9f497514bd48768/src/Components/Path.php#L70-L77
12,340
asika32764/joomla-framework-console
Console.php
Console.register
public function register($name) { return $this->addCommand(new Command($name, $this->input, $this->output)); }
php
public function register($name) { return $this->addCommand(new Command($name, $this->input, $this->output)); }
[ "public", "function", "register", "(", "$", "name", ")", "{", "return", "$", "this", "->", "addCommand", "(", "new", "Command", "(", "$", "name", ",", "$", "this", "->", "input", ",", "$", "this", "->", "output", ")", ")", ";", "}" ]
Register a new Console. @param string $name The command name. @return AbstractCommand The created commend. @since 1.0
[ "Register", "a", "new", "Console", "." ]
fe28cf9e1c694049e015121e2bd041268e814249
https://github.com/asika32764/joomla-framework-console/blob/fe28cf9e1c694049e015121e2bd041268e814249/Console.php#L199-L202
12,341
vpg/titon.common
src/Titon/Common/Traits/Cacheable.php
Cacheable.createCacheKey
public function createCacheKey($keys) { if (is_array($keys)) { $key = array_shift($keys); if ($keys) { foreach ($keys as $value) { if (is_array($value)) { $key .= '-' . md5(json_encode($value)); } else if ($value) { $key .= '-' . $value; } } } } else { $key = $keys; } return (string) $key; }
php
public function createCacheKey($keys) { if (is_array($keys)) { $key = array_shift($keys); if ($keys) { foreach ($keys as $value) { if (is_array($value)) { $key .= '-' . md5(json_encode($value)); } else if ($value) { $key .= '-' . $value; } } } } else { $key = $keys; } return (string) $key; }
[ "public", "function", "createCacheKey", "(", "$", "keys", ")", "{", "if", "(", "is_array", "(", "$", "keys", ")", ")", "{", "$", "key", "=", "array_shift", "(", "$", "keys", ")", ";", "if", "(", "$", "keys", ")", "{", "foreach", "(", "$", "keys", "as", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "key", ".=", "'-'", ".", "md5", "(", "json_encode", "(", "$", "value", ")", ")", ";", "}", "else", "if", "(", "$", "value", ")", "{", "$", "key", ".=", "'-'", ".", "$", "value", ";", "}", "}", "}", "}", "else", "{", "$", "key", "=", "$", "keys", ";", "}", "return", "(", "string", ")", "$", "key", ";", "}" ]
Generate a cache key. If an array is passed, drill down and form a key. @param string|array $keys @return string
[ "Generate", "a", "cache", "key", ".", "If", "an", "array", "is", "passed", "drill", "down", "and", "form", "a", "key", "." ]
41fe62bd5134bf76db3ff9caa16f280d9d534ef9
https://github.com/vpg/titon.common/blob/41fe62bd5134bf76db3ff9caa16f280d9d534ef9/src/Titon/Common/Traits/Cacheable.php#L75-L93
12,342
vpg/titon.common
src/Titon/Common/Traits/Cacheable.php
Cacheable.setCache
public function setCache($key, $value) { $this->_cache[$this->createCacheKey($key)] = $value; return $value; }
php
public function setCache($key, $value) { $this->_cache[$this->createCacheKey($key)] = $value; return $value; }
[ "public", "function", "setCache", "(", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "_cache", "[", "$", "this", "->", "createCacheKey", "(", "$", "key", ")", "]", "=", "$", "value", ";", "return", "$", "value", ";", "}" ]
Set a value to the cache with the defined key. This will overwrite any data with the same key. The value being saved will be returned. @param string|array $key @param mixed $value @return mixed
[ "Set", "a", "value", "to", "the", "cache", "with", "the", "defined", "key", ".", "This", "will", "overwrite", "any", "data", "with", "the", "same", "key", ".", "The", "value", "being", "saved", "will", "be", "returned", "." ]
41fe62bd5134bf76db3ff9caa16f280d9d534ef9
https://github.com/vpg/titon.common/blob/41fe62bd5134bf76db3ff9caa16f280d9d534ef9/src/Titon/Common/Traits/Cacheable.php#L157-L161
12,343
b01/interception
src/StreamWrappers/Http.php
Http.stream_close
public function stream_close() { if ( !\is_resource($this->resource) ) { return; } // Close the resource. if ( $this->resourceType === static::RESOURCE_TYPE_FILE ) { \fclose( $this->resource ); } else if ( $this->ssl ) { \fclose( $this->resource ); // Only save the file when not loaded locally. $saveFile = $this->getSaveFile(); \file_put_contents( $saveFile, $this->content ); } else if ( $this->resourceType === static::RESOURCE_TYPE_SOCKET ) { // This could throw errors if the socket is not connected on some systems. @\socket_shutdown( $this->resource ); \socket_close( $this->resource ); // Only save the file when not loaded locally. $saveFile = $this->getSaveFile(); \file_put_contents( $saveFile, $this->content ); } // Leave the resource for garbage clean-up. $this->resource = NULL; // Reset so we do not overwrite a file unintentionally for the next request. static::clearSaveFile(); }
php
public function stream_close() { if ( !\is_resource($this->resource) ) { return; } // Close the resource. if ( $this->resourceType === static::RESOURCE_TYPE_FILE ) { \fclose( $this->resource ); } else if ( $this->ssl ) { \fclose( $this->resource ); // Only save the file when not loaded locally. $saveFile = $this->getSaveFile(); \file_put_contents( $saveFile, $this->content ); } else if ( $this->resourceType === static::RESOURCE_TYPE_SOCKET ) { // This could throw errors if the socket is not connected on some systems. @\socket_shutdown( $this->resource ); \socket_close( $this->resource ); // Only save the file when not loaded locally. $saveFile = $this->getSaveFile(); \file_put_contents( $saveFile, $this->content ); } // Leave the resource for garbage clean-up. $this->resource = NULL; // Reset so we do not overwrite a file unintentionally for the next request. static::clearSaveFile(); }
[ "public", "function", "stream_close", "(", ")", "{", "if", "(", "!", "\\", "is_resource", "(", "$", "this", "->", "resource", ")", ")", "{", "return", ";", "}", "// Close the resource.", "if", "(", "$", "this", "->", "resourceType", "===", "static", "::", "RESOURCE_TYPE_FILE", ")", "{", "\\", "fclose", "(", "$", "this", "->", "resource", ")", ";", "}", "else", "if", "(", "$", "this", "->", "ssl", ")", "{", "\\", "fclose", "(", "$", "this", "->", "resource", ")", ";", "// Only save the file when not loaded locally.", "$", "saveFile", "=", "$", "this", "->", "getSaveFile", "(", ")", ";", "\\", "file_put_contents", "(", "$", "saveFile", ",", "$", "this", "->", "content", ")", ";", "}", "else", "if", "(", "$", "this", "->", "resourceType", "===", "static", "::", "RESOURCE_TYPE_SOCKET", ")", "{", "// This could throw errors if the socket is not connected on some systems.", "@", "\\", "socket_shutdown", "(", "$", "this", "->", "resource", ")", ";", "\\", "socket_close", "(", "$", "this", "->", "resource", ")", ";", "// Only save the file when not loaded locally.", "$", "saveFile", "=", "$", "this", "->", "getSaveFile", "(", ")", ";", "\\", "file_put_contents", "(", "$", "saveFile", ",", "$", "this", "->", "content", ")", ";", "}", "// Leave the resource for garbage clean-up.", "$", "this", "->", "resource", "=", "NULL", ";", "// Reset so we do not overwrite a file unintentionally for the next request.", "static", "::", "clearSaveFile", "(", ")", ";", "}" ]
Close the resource. @return void
[ "Close", "the", "resource", "." ]
fe508529a49d97d5f24fa835cdbb6e4a67137be3
https://github.com/b01/interception/blob/fe508529a49d97d5f24fa835cdbb6e4a67137be3/src/StreamWrappers/Http.php#L113-L147
12,344
b01/interception
src/StreamWrappers/Http.php
Http.isValidFilename
static private function isValidFilename( $pFilename ) { // A filename must not contain the following chars: $invalidChars = [ ',', '<', '>', '*', '?', '|', '\\', '/', "'", '"', ':' ]; // Build regular expression. $invalidCharRegExPatter = '@'. implode( $invalidChars ) . '@'; // Notify the developer when a filename contains invalid characters. if ( \preg_match($invalidCharRegExPatter, $pFilename) === 1 ) { \trigger_error( 'A filename cannot contain the following characters: ' . implode('', $invalidChars) ); // When trigger errors are silenced. return FALSE; } return TRUE; }
php
static private function isValidFilename( $pFilename ) { // A filename must not contain the following chars: $invalidChars = [ ',', '<', '>', '*', '?', '|', '\\', '/', "'", '"', ':' ]; // Build regular expression. $invalidCharRegExPatter = '@'. implode( $invalidChars ) . '@'; // Notify the developer when a filename contains invalid characters. if ( \preg_match($invalidCharRegExPatter, $pFilename) === 1 ) { \trigger_error( 'A filename cannot contain the following characters: ' . implode('', $invalidChars) ); // When trigger errors are silenced. return FALSE; } return TRUE; }
[ "static", "private", "function", "isValidFilename", "(", "$", "pFilename", ")", "{", "// A filename must not contain the following chars:", "$", "invalidChars", "=", "[", "','", ",", "'<'", ",", "'>'", ",", "'*'", ",", "'?'", ",", "'|'", ",", "'\\\\'", ",", "'/'", ",", "\"'\"", ",", "'\"'", ",", "':'", "]", ";", "// Build regular expression.", "$", "invalidCharRegExPatter", "=", "'@'", ".", "implode", "(", "$", "invalidChars", ")", ".", "'@'", ";", "// Notify the developer when a filename contains invalid characters.", "if", "(", "\\", "preg_match", "(", "$", "invalidCharRegExPatter", ",", "$", "pFilename", ")", "===", "1", ")", "{", "\\", "trigger_error", "(", "'A filename cannot contain the following characters: '", ".", "implode", "(", "''", ",", "$", "invalidChars", ")", ")", ";", "// When trigger errors are silenced.", "return", "FALSE", ";", "}", "return", "TRUE", ";", "}" ]
Validate a name filename. @param $pFilename @return bool
[ "Validate", "a", "name", "filename", "." ]
fe508529a49d97d5f24fa835cdbb6e4a67137be3
https://github.com/b01/interception/blob/fe508529a49d97d5f24fa835cdbb6e4a67137be3/src/StreamWrappers/Http.php#L453-L467
12,345
b01/interception
src/StreamWrappers/Http.php
Http.getSaveFile
private function getSaveFile() { $filename = static::getSaveFilename() . static::persistSuffix(); // When not set. if ( empty($filename) ) { throw new InterceptionException( InterceptionException::NO_FILENAME ); } $ext = '.rsd'; // Build file path. return static::getSaveDir() . DIRECTORY_SEPARATOR . $filename . $ext; }
php
private function getSaveFile() { $filename = static::getSaveFilename() . static::persistSuffix(); // When not set. if ( empty($filename) ) { throw new InterceptionException( InterceptionException::NO_FILENAME ); } $ext = '.rsd'; // Build file path. return static::getSaveDir() . DIRECTORY_SEPARATOR . $filename . $ext; }
[ "private", "function", "getSaveFile", "(", ")", "{", "$", "filename", "=", "static", "::", "getSaveFilename", "(", ")", ".", "static", "::", "persistSuffix", "(", ")", ";", "// When not set.", "if", "(", "empty", "(", "$", "filename", ")", ")", "{", "throw", "new", "InterceptionException", "(", "InterceptionException", "::", "NO_FILENAME", ")", ";", "}", "$", "ext", "=", "'.rsd'", ";", "// Build file path.", "return", "static", "::", "getSaveDir", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "$", "filename", ".", "$", "ext", ";", "}" ]
Get the full file path by generating one from the URL, or the one set by the developer. @return bool @throws InterceptionException
[ "Get", "the", "full", "file", "path", "by", "generating", "one", "from", "the", "URL", "or", "the", "one", "set", "by", "the", "developer", "." ]
fe508529a49d97d5f24fa835cdbb6e4a67137be3
https://github.com/b01/interception/blob/fe508529a49d97d5f24fa835cdbb6e4a67137be3/src/StreamWrappers/Http.php#L542-L554
12,346
b01/interception
src/StreamWrappers/Http.php
Http.populateResponseHeaders
private function populateResponseHeaders() { $done = FALSE; $line = NULL; $header = ''; $buffer = NULL; // When using a file stream. if ( $this->resourceType === static::RESOURCE_TYPE_FILE ) { $done = \feof( $this->resource ); } // Read the headers from the resource. while ( !$done ) { $buffer = $this->readFromResource( 1 ); // Update stream $this->content .= $buffer; $header = \strstr( $this->content, "\r\n\r\n", TRUE ); // When you reach the end of the header, then exit the loop. if ( $buffer === '' || $header !== FALSE ) { break; } } // Update cursor position. $this->position += \strlen( $this->content ); // Parse header. if ( strlen(trim($header)) > 0 ) { // Set header $this->wrapperData = explode( "\r\n", $header ); } }
php
private function populateResponseHeaders() { $done = FALSE; $line = NULL; $header = ''; $buffer = NULL; // When using a file stream. if ( $this->resourceType === static::RESOURCE_TYPE_FILE ) { $done = \feof( $this->resource ); } // Read the headers from the resource. while ( !$done ) { $buffer = $this->readFromResource( 1 ); // Update stream $this->content .= $buffer; $header = \strstr( $this->content, "\r\n\r\n", TRUE ); // When you reach the end of the header, then exit the loop. if ( $buffer === '' || $header !== FALSE ) { break; } } // Update cursor position. $this->position += \strlen( $this->content ); // Parse header. if ( strlen(trim($header)) > 0 ) { // Set header $this->wrapperData = explode( "\r\n", $header ); } }
[ "private", "function", "populateResponseHeaders", "(", ")", "{", "$", "done", "=", "FALSE", ";", "$", "line", "=", "NULL", ";", "$", "header", "=", "''", ";", "$", "buffer", "=", "NULL", ";", "// When using a file stream.", "if", "(", "$", "this", "->", "resourceType", "===", "static", "::", "RESOURCE_TYPE_FILE", ")", "{", "$", "done", "=", "\\", "feof", "(", "$", "this", "->", "resource", ")", ";", "}", "// Read the headers from the resource.", "while", "(", "!", "$", "done", ")", "{", "$", "buffer", "=", "$", "this", "->", "readFromResource", "(", "1", ")", ";", "// Update stream", "$", "this", "->", "content", ".=", "$", "buffer", ";", "$", "header", "=", "\\", "strstr", "(", "$", "this", "->", "content", ",", "\"\\r\\n\\r\\n\"", ",", "TRUE", ")", ";", "// When you reach the end of the header, then exit the loop.", "if", "(", "$", "buffer", "===", "''", "||", "$", "header", "!==", "FALSE", ")", "{", "break", ";", "}", "}", "// Update cursor position.", "$", "this", "->", "position", "+=", "\\", "strlen", "(", "$", "this", "->", "content", ")", ";", "// Parse header.", "if", "(", "strlen", "(", "trim", "(", "$", "header", ")", ")", ">", "0", ")", "{", "// Set header", "$", "this", "->", "wrapperData", "=", "explode", "(", "\"\\r\\n\"", ",", "$", "header", ")", ";", "}", "}" ]
Parse the content for the headers.
[ "Parse", "the", "content", "for", "the", "headers", "." ]
fe508529a49d97d5f24fa835cdbb6e4a67137be3
https://github.com/b01/interception/blob/fe508529a49d97d5f24fa835cdbb6e4a67137be3/src/StreamWrappers/Http.php#L559-L593
12,347
b01/interception
src/StreamWrappers/Http.php
Http.triggerSocketError
private function triggerSocketError() { $errorNo = \socket_last_error( $this->resource ); $errorStr = \socket_strerror( $errorNo ); \trigger_error( '\\Kshabazz\\Interception\\StreamWrappers\\Http ' . $errorStr ); }
php
private function triggerSocketError() { $errorNo = \socket_last_error( $this->resource ); $errorStr = \socket_strerror( $errorNo ); \trigger_error( '\\Kshabazz\\Interception\\StreamWrappers\\Http ' . $errorStr ); }
[ "private", "function", "triggerSocketError", "(", ")", "{", "$", "errorNo", "=", "\\", "socket_last_error", "(", "$", "this", "->", "resource", ")", ";", "$", "errorStr", "=", "\\", "socket_strerror", "(", "$", "errorNo", ")", ";", "\\", "trigger_error", "(", "'\\\\Kshabazz\\\\Interception\\\\StreamWrappers\\\\Http '", ".", "$", "errorStr", ")", ";", "}" ]
Trigger socket error.
[ "Trigger", "socket", "error", "." ]
fe508529a49d97d5f24fa835cdbb6e4a67137be3
https://github.com/b01/interception/blob/fe508529a49d97d5f24fa835cdbb6e4a67137be3/src/StreamWrappers/Http.php#L649-L654
12,348
herzcthu/kanaung-converter
src/Converter/Converter.php
Converter.convert
public function convert($content) { $result = strtr($content, $this->rules); return $this->correct($result); }
php
public function convert($content) { $result = strtr($content, $this->rules); return $this->correct($result); }
[ "public", "function", "convert", "(", "$", "content", ")", "{", "$", "result", "=", "strtr", "(", "$", "content", ",", "$", "this", "->", "rules", ")", ";", "return", "$", "this", "->", "correct", "(", "$", "result", ")", ";", "}" ]
Convert content from one encoding to another @param string $content Content of text to convert @return string Converted text
[ "Convert", "content", "from", "one", "encoding", "to", "another" ]
eccd2b7fba8d9d04d26602657527715eb8844e8c
https://github.com/herzcthu/kanaung-converter/blob/eccd2b7fba8d9d04d26602657527715eb8844e8c/src/Converter/Converter.php#L16-L20
12,349
herzcthu/kanaung-converter
src/Converter/Converter.php
Converter.correct
protected function correct($content) { $corrections = $this->corrections; if (!empty($corrections)) { foreach ($corrections as $pattern => $replacement) { $reg_count = 0; /** * @var $content * reassign $content to corrected $content as long as corrections * rules array loop */ $content = preg_replace('/' . $pattern . '/us', $replacement, $content, -1, $reg_count); } } return $content; }
php
protected function correct($content) { $corrections = $this->corrections; if (!empty($corrections)) { foreach ($corrections as $pattern => $replacement) { $reg_count = 0; /** * @var $content * reassign $content to corrected $content as long as corrections * rules array loop */ $content = preg_replace('/' . $pattern . '/us', $replacement, $content, -1, $reg_count); } } return $content; }
[ "protected", "function", "correct", "(", "$", "content", ")", "{", "$", "corrections", "=", "$", "this", "->", "corrections", ";", "if", "(", "!", "empty", "(", "$", "corrections", ")", ")", "{", "foreach", "(", "$", "corrections", "as", "$", "pattern", "=>", "$", "replacement", ")", "{", "$", "reg_count", "=", "0", ";", "/**\n * @var $content\n * reassign $content to corrected $content as long as corrections\n * rules array loop\n */", "$", "content", "=", "preg_replace", "(", "'/'", ".", "$", "pattern", ".", "'/us'", ",", "$", "replacement", ",", "$", "content", ",", "-", "1", ",", "$", "reg_count", ")", ";", "}", "}", "return", "$", "content", ";", "}" ]
Correct any ordering or encoding error using regular expression @param string $content Content of text to correct @return string Corrected text
[ "Correct", "any", "ordering", "or", "encoding", "error", "using", "regular", "expression" ]
eccd2b7fba8d9d04d26602657527715eb8844e8c
https://github.com/herzcthu/kanaung-converter/blob/eccd2b7fba8d9d04d26602657527715eb8844e8c/src/Converter/Converter.php#L49-L67
12,350
gnkam/univ-savoie-edt
src/Gnkam/Univ/Savoie/Edt/Formalizer.php
Formalizer.serviceGroup
public function serviceGroup($group) { # Check if empty $group = intval($group); if(empty($group)) { return array(); } $json = $this->service('group', $group); return $json; }
php
public function serviceGroup($group) { # Check if empty $group = intval($group); if(empty($group)) { return array(); } $json = $this->service('group', $group); return $json; }
[ "public", "function", "serviceGroup", "(", "$", "group", ")", "{", "# Check if empty", "$", "group", "=", "intval", "(", "$", "group", ")", ";", "if", "(", "empty", "(", "$", "group", ")", ")", "{", "return", "array", "(", ")", ";", "}", "$", "json", "=", "$", "this", "->", "service", "(", "'group'", ",", "$", "group", ")", ";", "return", "$", "json", ";", "}" ]
Call service for Group @param integer $group Group to call @return array Group Data
[ "Call", "service", "for", "Group" ]
5a9eb6d1fa76cbcfdfb47f1802dce819c83961a4
https://github.com/gnkam/univ-savoie-edt/blob/5a9eb6d1fa76cbcfdfb47f1802dce819c83961a4/src/Gnkam/Univ/Savoie/Edt/Formalizer.php#L56-L67
12,351
gnkam/univ-savoie-edt
src/Gnkam/Univ/Savoie/Edt/Formalizer.php
Formalizer.serviceTree
public function serviceTree($node = null) { $node = ($node === null) ? -1 : $node; $json = $this->service('tree', $node); return $json; }
php
public function serviceTree($node = null) { $node = ($node === null) ? -1 : $node; $json = $this->service('tree', $node); return $json; }
[ "public", "function", "serviceTree", "(", "$", "node", "=", "null", ")", "{", "$", "node", "=", "(", "$", "node", "===", "null", ")", "?", "-", "1", ":", "$", "node", ";", "$", "json", "=", "$", "this", "->", "service", "(", "'tree'", ",", "$", "node", ")", ";", "return", "$", "json", ";", "}" ]
Call service for Tree @param integer $node Node to call @return array Node Data
[ "Call", "service", "for", "Tree" ]
5a9eb6d1fa76cbcfdfb47f1802dce819c83961a4
https://github.com/gnkam/univ-savoie-edt/blob/5a9eb6d1fa76cbcfdfb47f1802dce819c83961a4/src/Gnkam/Univ/Savoie/Edt/Formalizer.php#L85-L90
12,352
gnkam/univ-savoie-edt
src/Gnkam/Univ/Savoie/Edt/Formalizer.php
Formalizer.treeData
public function treeData($tree) { $receiver = new TreeReceiver($this->getCacheLink(), $this->projectId); return $receiver->getArrayData($tree); }
php
public function treeData($tree) { $receiver = new TreeReceiver($this->getCacheLink(), $this->projectId); return $receiver->getArrayData($tree); }
[ "public", "function", "treeData", "(", "$", "tree", ")", "{", "$", "receiver", "=", "new", "TreeReceiver", "(", "$", "this", "->", "getCacheLink", "(", ")", ",", "$", "this", "->", "projectId", ")", ";", "return", "$", "receiver", "->", "getArrayData", "(", "$", "tree", ")", ";", "}" ]
Receive group data @param integer $node Node id to call @return array Node Data
[ "Receive", "group", "data" ]
5a9eb6d1fa76cbcfdfb47f1802dce819c83961a4
https://github.com/gnkam/univ-savoie-edt/blob/5a9eb6d1fa76cbcfdfb47f1802dce819c83961a4/src/Gnkam/Univ/Savoie/Edt/Formalizer.php#L97-L101
12,353
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.concat
public static function concat($one, $other) { Arguments::define( Boa::either( Boa::lst(), Boa::string() ), Boa::either( Boa::lst(), Boa::string() ) )->check($one, $other); $oneType = TypeHound::fetch($one); $twoType = TypeHound::fetch($other); if ($oneType !== $twoType) { throw new MismatchedArgumentTypesException( __FUNCTION__, $one, $other ); } if ($oneType === ScalarTypes::SCALAR_STRING) { return $one . $other; } return ArrayMap::of($one)->append(ArrayMap::of($other))->toArray(); }
php
public static function concat($one, $other) { Arguments::define( Boa::either( Boa::lst(), Boa::string() ), Boa::either( Boa::lst(), Boa::string() ) )->check($one, $other); $oneType = TypeHound::fetch($one); $twoType = TypeHound::fetch($other); if ($oneType !== $twoType) { throw new MismatchedArgumentTypesException( __FUNCTION__, $one, $other ); } if ($oneType === ScalarTypes::SCALAR_STRING) { return $one . $other; } return ArrayMap::of($one)->append(ArrayMap::of($other))->toArray(); }
[ "public", "static", "function", "concat", "(", "$", "one", ",", "$", "other", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "either", "(", "Boa", "::", "lst", "(", ")", ",", "Boa", "::", "string", "(", ")", ")", ",", "Boa", "::", "either", "(", "Boa", "::", "lst", "(", ")", ",", "Boa", "::", "string", "(", ")", ")", ")", "->", "check", "(", "$", "one", ",", "$", "other", ")", ";", "$", "oneType", "=", "TypeHound", "::", "fetch", "(", "$", "one", ")", ";", "$", "twoType", "=", "TypeHound", "::", "fetch", "(", "$", "other", ")", ";", "if", "(", "$", "oneType", "!==", "$", "twoType", ")", "{", "throw", "new", "MismatchedArgumentTypesException", "(", "__FUNCTION__", ",", "$", "one", ",", "$", "other", ")", ";", "}", "if", "(", "$", "oneType", "===", "ScalarTypes", "::", "SCALAR_STRING", ")", "{", "return", "$", "one", ".", "$", "other", ";", "}", "return", "ArrayMap", "::", "of", "(", "$", "one", ")", "->", "append", "(", "ArrayMap", "::", "of", "(", "$", "other", ")", ")", "->", "toArray", "(", ")", ";", "}" ]
Concatenate the two provided values. @param string|array|Traversable $one @param string|array|Traversable $other @throws MismatchedArgumentTypesException @throws InvalidArgumentException @return mixed
[ "Concatenate", "the", "two", "provided", "values", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L71-L100
12,354
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.each
public static function each(callable $function, $input) { if ($input instanceof FoldableInterface) { $input->foldl(function ($acc, $x) use ($function) { $function($x); }, null); return; } elseif ($input instanceof LeftFoldableInterface) { $input->foldl(function ($x) use ($function) { $function($x); }, null); return; } static::map($function, $input); }
php
public static function each(callable $function, $input) { if ($input instanceof FoldableInterface) { $input->foldl(function ($acc, $x) use ($function) { $function($x); }, null); return; } elseif ($input instanceof LeftFoldableInterface) { $input->foldl(function ($x) use ($function) { $function($x); }, null); return; } static::map($function, $input); }
[ "public", "static", "function", "each", "(", "callable", "$", "function", ",", "$", "input", ")", "{", "if", "(", "$", "input", "instanceof", "FoldableInterface", ")", "{", "$", "input", "->", "foldl", "(", "function", "(", "$", "acc", ",", "$", "x", ")", "use", "(", "$", "function", ")", "{", "$", "function", "(", "$", "x", ")", ";", "}", ",", "null", ")", ";", "return", ";", "}", "elseif", "(", "$", "input", "instanceof", "LeftFoldableInterface", ")", "{", "$", "input", "->", "foldl", "(", "function", "(", "$", "x", ")", "use", "(", "$", "function", ")", "{", "$", "function", "(", "$", "x", ")", ";", "}", ",", "null", ")", ";", "return", ";", "}", "static", "::", "map", "(", "$", "function", ",", "$", "input", ")", ";", "}" ]
Call the provided function on each element. @param callable $function @param array|Traversable|FoldableInterface|LeftFoldableInterface $input @throws InvalidArgumentException
[ "Call", "the", "provided", "function", "on", "each", "element", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L180-L197
12,355
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.within
public static function within($min, $max, $value) { Arguments::define( Boa::either(Boa::integer(), Boa::float()), Boa::either(Boa::integer(), Boa::float()), Boa::either(Boa::integer(), Boa::float()) )->check($min, $max, $value); if ($min > $max) { throw new LackOfCoffeeException( 'Max value is less than the min value.' ); } return ($min <= $value && $max >= $value); }
php
public static function within($min, $max, $value) { Arguments::define( Boa::either(Boa::integer(), Boa::float()), Boa::either(Boa::integer(), Boa::float()), Boa::either(Boa::integer(), Boa::float()) )->check($min, $max, $value); if ($min > $max) { throw new LackOfCoffeeException( 'Max value is less than the min value.' ); } return ($min <= $value && $max >= $value); }
[ "public", "static", "function", "within", "(", "$", "min", ",", "$", "max", ",", "$", "value", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "either", "(", "Boa", "::", "integer", "(", ")", ",", "Boa", "::", "float", "(", ")", ")", ",", "Boa", "::", "either", "(", "Boa", "::", "integer", "(", ")", ",", "Boa", "::", "float", "(", ")", ")", ",", "Boa", "::", "either", "(", "Boa", "::", "integer", "(", ")", ",", "Boa", "::", "float", "(", ")", ")", ")", "->", "check", "(", "$", "min", ",", "$", "max", ",", "$", "value", ")", ";", "if", "(", "$", "min", ">", "$", "max", ")", "{", "throw", "new", "LackOfCoffeeException", "(", "'Max value is less than the min value.'", ")", ";", "}", "return", "(", "$", "min", "<=", "$", "value", "&&", "$", "max", ">=", "$", "value", ")", ";", "}" ]
Check if a value is between two other values. @param int|float $min @param int|float $max @param int|float $value @throws LackOfCoffeeException @return bool
[ "Check", "if", "a", "value", "is", "between", "two", "other", "values", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L227-L242
12,356
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.rope
public static function rope($string, $encoding = null) { Arguments::define(Boa::string(), Boa::maybe(Boa::string())) ->check($string, $encoding); return new Rope($string, $encoding); }
php
public static function rope($string, $encoding = null) { Arguments::define(Boa::string(), Boa::maybe(Boa::string())) ->check($string, $encoding); return new Rope($string, $encoding); }
[ "public", "static", "function", "rope", "(", "$", "string", ",", "$", "encoding", "=", "null", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "string", "(", ")", ",", "Boa", "::", "maybe", "(", "Boa", "::", "string", "(", ")", ")", ")", "->", "check", "(", "$", "string", ",", "$", "encoding", ")", ";", "return", "new", "Rope", "(", "$", "string", ",", "$", "encoding", ")", ";", "}" ]
Create a new instance of a rope. @param string $string @param string|null $encoding @return Rope
[ "Create", "a", "new", "instance", "of", "a", "rope", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L252-L258
12,357
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.esc
public static function esc($string) { Arguments::define(Boa::string())->check($string); return htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); }
php
public static function esc($string) { Arguments::define(Boa::string())->check($string); return htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); }
[ "public", "static", "function", "esc", "(", "$", "string", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "string", "(", ")", ")", "->", "check", "(", "$", "string", ")", ";", "return", "htmlspecialchars", "(", "$", "string", ",", "ENT_QUOTES", ",", "'UTF-8'", ")", ";", "}" ]
Escape the provided input for HTML. @param string $string @return string
[ "Escape", "the", "provided", "input", "for", "HTML", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L267-L272
12,358
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.callSetters
public static function callSetters( $object, array $input, array $allowed = null ) { $filtered = ArrayMap::of($input); if ($allowed !== null) { $filtered = $filtered->only($allowed); } $filtered->each(function ($value, $key) use (&$object) { $setterName = 'set' . Str::studly($key); $object->$setterName($value); }); }
php
public static function callSetters( $object, array $input, array $allowed = null ) { $filtered = ArrayMap::of($input); if ($allowed !== null) { $filtered = $filtered->only($allowed); } $filtered->each(function ($value, $key) use (&$object) { $setterName = 'set' . Str::studly($key); $object->$setterName($value); }); }
[ "public", "static", "function", "callSetters", "(", "$", "object", ",", "array", "$", "input", ",", "array", "$", "allowed", "=", "null", ")", "{", "$", "filtered", "=", "ArrayMap", "::", "of", "(", "$", "input", ")", ";", "if", "(", "$", "allowed", "!==", "null", ")", "{", "$", "filtered", "=", "$", "filtered", "->", "only", "(", "$", "allowed", ")", ";", "}", "$", "filtered", "->", "each", "(", "function", "(", "$", "value", ",", "$", "key", ")", "use", "(", "&", "$", "object", ")", "{", "$", "setterName", "=", "'set'", ".", "Str", "::", "studly", "(", "$", "key", ")", ";", "$", "object", "->", "$", "setterName", "(", "$", "value", ")", ";", "}", ")", ";", "}" ]
Set properties of an object by only calling setters of array keys that are set in the input array. Useful for parsing API responses into entities. @param object $object @param array $input @param string[]|null $allowed
[ "Set", "properties", "of", "an", "object", "by", "only", "calling", "setters", "of", "array", "keys", "that", "are", "set", "in", "the", "input", "array", ".", "Useful", "for", "parsing", "API", "responses", "into", "entities", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L283-L299
12,359
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.firstBias
public static function firstBias($biased, $one, $other) { Arguments::define(Boa::boolean(), Boa::any(), Boa::any()) ->check($biased, $one, $other); if ($biased) { return static::thunk($one); } return static::thunk($other); }
php
public static function firstBias($biased, $one, $other) { Arguments::define(Boa::boolean(), Boa::any(), Boa::any()) ->check($biased, $one, $other); if ($biased) { return static::thunk($one); } return static::thunk($other); }
[ "public", "static", "function", "firstBias", "(", "$", "biased", ",", "$", "one", ",", "$", "other", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "boolean", "(", ")", ",", "Boa", "::", "any", "(", ")", ",", "Boa", "::", "any", "(", ")", ")", "->", "check", "(", "$", "biased", ",", "$", "one", ",", "$", "other", ")", ";", "if", "(", "$", "biased", ")", "{", "return", "static", "::", "thunk", "(", "$", "one", ")", ";", "}", "return", "static", "::", "thunk", "(", "$", "other", ")", ";", "}" ]
Return the first value if the condition is true, otherwise, return the second. @param bool $biased @param mixed|Closure $one @param mixed|Closure $other @return mixed
[ "Return", "the", "first", "value", "if", "the", "condition", "is", "true", "otherwise", "return", "the", "second", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L311-L321
12,360
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.foldr
public static function foldr(callable $function, $initial, $foldable) { Arguments::define(Boa::func(), Boa::any(), Boa::foldable()) ->check($function, $initial, $foldable); return ComplexFactory::toFoldable($foldable) ->foldr($function, $initial); }
php
public static function foldr(callable $function, $initial, $foldable) { Arguments::define(Boa::func(), Boa::any(), Boa::foldable()) ->check($function, $initial, $foldable); return ComplexFactory::toFoldable($foldable) ->foldr($function, $initial); }
[ "public", "static", "function", "foldr", "(", "callable", "$", "function", ",", "$", "initial", ",", "$", "foldable", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "func", "(", ")", ",", "Boa", "::", "any", "(", ")", ",", "Boa", "::", "foldable", "(", ")", ")", "->", "check", "(", "$", "function", ",", "$", "initial", ",", "$", "foldable", ")", ";", "return", "ComplexFactory", "::", "toFoldable", "(", "$", "foldable", ")", "->", "foldr", "(", "$", "function", ",", "$", "initial", ")", ";", "}" ]
Same as foldl but it works from right to left. @param callable $function @param mixed $initial @param array|FoldableInterface $foldable @return mixed
[ "Same", "as", "foldl", "but", "it", "works", "from", "right", "to", "left", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L372-L379
12,361
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.map
public static function map(callable $function, $traversable) { $aggregation = []; foreach ($traversable as $key => $value) { $aggregation[$key] = $function($value, $key); } return $aggregation; }
php
public static function map(callable $function, $traversable) { $aggregation = []; foreach ($traversable as $key => $value) { $aggregation[$key] = $function($value, $key); } return $aggregation; }
[ "public", "static", "function", "map", "(", "callable", "$", "function", ",", "$", "traversable", ")", "{", "$", "aggregation", "=", "[", "]", ";", "foreach", "(", "$", "traversable", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "aggregation", "[", "$", "key", "]", "=", "$", "function", "(", "$", "value", ",", "$", "key", ")", ";", "}", "return", "$", "aggregation", ";", "}" ]
Call a function on every item in a list and return the resulting list. @param callable $function @param array|Traversable $traversable @return array
[ "Call", "a", "function", "on", "every", "item", "in", "a", "list", "and", "return", "the", "resulting", "list", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L454-L463
12,362
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.filter
public static function filter(callable $function, $traversable) { Arguments::define(Boa::func(), Boa::traversable()) ->check($function, $traversable); $aggregation = []; foreach ($traversable as $key => $value) { if ($function($value, $key)) { $aggregation[$key] = $value; } } return $aggregation; }
php
public static function filter(callable $function, $traversable) { Arguments::define(Boa::func(), Boa::traversable()) ->check($function, $traversable); $aggregation = []; foreach ($traversable as $key => $value) { if ($function($value, $key)) { $aggregation[$key] = $value; } } return $aggregation; }
[ "public", "static", "function", "filter", "(", "callable", "$", "function", ",", "$", "traversable", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "func", "(", ")", ",", "Boa", "::", "traversable", "(", ")", ")", "->", "check", "(", "$", "function", ",", "$", "traversable", ")", ";", "$", "aggregation", "=", "[", "]", ";", "foreach", "(", "$", "traversable", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "function", "(", "$", "value", ",", "$", "key", ")", ")", "{", "$", "aggregation", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "aggregation", ";", "}" ]
Filter a list by calling a callback on each element. If the callback returns true, then the element will be added to the resulting array. Otherwise, it will be skipped. Also, unlike array_filter, this function preserves indexes. @param callable $function @param array|Traversable $traversable @return array
[ "Filter", "a", "list", "by", "calling", "a", "callback", "on", "each", "element", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L478-L492
12,363
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.curryArgs
public static function curryArgs(callable $function, $args) { Arguments::define(Boa::func(), Boa::arr())->check($function, $args); // Counts required parameters. $required = function () use ($function) { return (new ReflectionFunction($function)) ->getNumberOfRequiredParameters(); }; $isFulfilled = function (callable $function, $args) use ($required) { return count($args) >= $required($function); }; if ($isFulfilled($function, $args)) { return static::apply($function, $args); } return function (...$funcArgs) use ( $function, $args, $required, $isFulfilled ) { $newArgs = ArrayList::of($args) ->append(ArrayList::of($funcArgs)) ->toArray(); if ($isFulfilled($function, $newArgs)) { return static::apply($function, $newArgs); } return static::curryArgs($function, $newArgs); }; }
php
public static function curryArgs(callable $function, $args) { Arguments::define(Boa::func(), Boa::arr())->check($function, $args); // Counts required parameters. $required = function () use ($function) { return (new ReflectionFunction($function)) ->getNumberOfRequiredParameters(); }; $isFulfilled = function (callable $function, $args) use ($required) { return count($args) >= $required($function); }; if ($isFulfilled($function, $args)) { return static::apply($function, $args); } return function (...$funcArgs) use ( $function, $args, $required, $isFulfilled ) { $newArgs = ArrayList::of($args) ->append(ArrayList::of($funcArgs)) ->toArray(); if ($isFulfilled($function, $newArgs)) { return static::apply($function, $newArgs); } return static::curryArgs($function, $newArgs); }; }
[ "public", "static", "function", "curryArgs", "(", "callable", "$", "function", ",", "$", "args", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "func", "(", ")", ",", "Boa", "::", "arr", "(", ")", ")", "->", "check", "(", "$", "function", ",", "$", "args", ")", ";", "// Counts required parameters.", "$", "required", "=", "function", "(", ")", "use", "(", "$", "function", ")", "{", "return", "(", "new", "ReflectionFunction", "(", "$", "function", ")", ")", "->", "getNumberOfRequiredParameters", "(", ")", ";", "}", ";", "$", "isFulfilled", "=", "function", "(", "callable", "$", "function", ",", "$", "args", ")", "use", "(", "$", "required", ")", "{", "return", "count", "(", "$", "args", ")", ">=", "$", "required", "(", "$", "function", ")", ";", "}", ";", "if", "(", "$", "isFulfilled", "(", "$", "function", ",", "$", "args", ")", ")", "{", "return", "static", "::", "apply", "(", "$", "function", ",", "$", "args", ")", ";", "}", "return", "function", "(", "...", "$", "funcArgs", ")", "use", "(", "$", "function", ",", "$", "args", ",", "$", "required", ",", "$", "isFulfilled", ")", "{", "$", "newArgs", "=", "ArrayList", "::", "of", "(", "$", "args", ")", "->", "append", "(", "ArrayList", "::", "of", "(", "$", "funcArgs", ")", ")", "->", "toArray", "(", ")", ";", "if", "(", "$", "isFulfilled", "(", "$", "function", ",", "$", "newArgs", ")", ")", "{", "return", "static", "::", "apply", "(", "$", "function", ",", "$", "newArgs", ")", ";", "}", "return", "static", "::", "curryArgs", "(", "$", "function", ",", "$", "newArgs", ")", ";", "}", ";", "}" ]
Left-curry the provided function with the provided array of arguments. @param callable $function @param mixed[] $args @return Closure|mixed
[ "Left", "-", "curry", "the", "provided", "function", "with", "the", "provided", "array", "of", "arguments", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L515-L549
12,364
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.poll
public static function poll(callable $function, $times) { Arguments::define(Boa::func(), Boa::integer()) ->check($function, $times); for ($ii = 0; $ii < $times; $ii++) { static::call($function, $ii); } }
php
public static function poll(callable $function, $times) { Arguments::define(Boa::func(), Boa::integer()) ->check($function, $times); for ($ii = 0; $ii < $times; $ii++) { static::call($function, $ii); } }
[ "public", "static", "function", "poll", "(", "callable", "$", "function", ",", "$", "times", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "func", "(", ")", ",", "Boa", "::", "integer", "(", ")", ")", "->", "check", "(", "$", "function", ",", "$", "times", ")", ";", "for", "(", "$", "ii", "=", "0", ";", "$", "ii", "<", "$", "times", ";", "$", "ii", "++", ")", "{", "static", "::", "call", "(", "$", "function", ",", "$", "ii", ")", ";", "}", "}" ]
Call a function N times. This covers one of the most frequent case for using for-loops. @param callable $function @param int $times
[ "Call", "a", "function", "N", "times", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L572-L580
12,365
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.retry
public static function retry(callable $function, $attempts) { Arguments::define(Boa::func(), Boa::integer()) ->check($function, $attempts); for ($ii = 0; $ii < $attempts; $ii++) { try { $result = static::call($function, $ii); return $result; } catch (Exception $e) { continue; } } return null; }
php
public static function retry(callable $function, $attempts) { Arguments::define(Boa::func(), Boa::integer()) ->check($function, $attempts); for ($ii = 0; $ii < $attempts; $ii++) { try { $result = static::call($function, $ii); return $result; } catch (Exception $e) { continue; } } return null; }
[ "public", "static", "function", "retry", "(", "callable", "$", "function", ",", "$", "attempts", ")", "{", "Arguments", "::", "define", "(", "Boa", "::", "func", "(", ")", ",", "Boa", "::", "integer", "(", ")", ")", "->", "check", "(", "$", "function", ",", "$", "attempts", ")", ";", "for", "(", "$", "ii", "=", "0", ";", "$", "ii", "<", "$", "attempts", ";", "$", "ii", "++", ")", "{", "try", "{", "$", "result", "=", "static", "::", "call", "(", "$", "function", ",", "$", "ii", ")", ";", "return", "$", "result", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "continue", ";", "}", "}", "return", "null", ";", "}" ]
Attempt call the provided function a number of times until it no longer throws an exception. @param callable $function @param int $attempts @return mixed|null @throws InvalidArgumentException
[ "Attempt", "call", "the", "provided", "function", "a", "number", "of", "times", "until", "it", "no", "longer", "throws", "an", "exception", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L592-L608
12,366
sellerlabs/nucleus
src/SellerLabs/Nucleus/Support/Std.php
Std.castToBool
public static function castToBool($mixed) { if (is_string($mixed) || $mixed instanceof Rope) { $lower = Rope::of($mixed)->toLower(); if ($lower->equals(Rope::of('true'))) { return true; } elseif ($lower->equals(Rope::of('false'))) { return false; } throw new CoreException('Unable to cast into a bool.'); } elseif (is_int($mixed)) { if ($mixed === 1) { return true; } elseif ($mixed === 0) { return false; } throw new CoreException('Unable to cast into a bool.'); } elseif (is_float($mixed)) { if ($mixed === 1.0) { return true; } elseif ($mixed === 0.0) { return false; } throw new CoreException('Unable to cast into a bool.'); } elseif (is_bool($mixed)) { return $mixed; } throw new CoreException('Unable to cast into a bool.'); }
php
public static function castToBool($mixed) { if (is_string($mixed) || $mixed instanceof Rope) { $lower = Rope::of($mixed)->toLower(); if ($lower->equals(Rope::of('true'))) { return true; } elseif ($lower->equals(Rope::of('false'))) { return false; } throw new CoreException('Unable to cast into a bool.'); } elseif (is_int($mixed)) { if ($mixed === 1) { return true; } elseif ($mixed === 0) { return false; } throw new CoreException('Unable to cast into a bool.'); } elseif (is_float($mixed)) { if ($mixed === 1.0) { return true; } elseif ($mixed === 0.0) { return false; } throw new CoreException('Unable to cast into a bool.'); } elseif (is_bool($mixed)) { return $mixed; } throw new CoreException('Unable to cast into a bool.'); }
[ "public", "static", "function", "castToBool", "(", "$", "mixed", ")", "{", "if", "(", "is_string", "(", "$", "mixed", ")", "||", "$", "mixed", "instanceof", "Rope", ")", "{", "$", "lower", "=", "Rope", "::", "of", "(", "$", "mixed", ")", "->", "toLower", "(", ")", ";", "if", "(", "$", "lower", "->", "equals", "(", "Rope", "::", "of", "(", "'true'", ")", ")", ")", "{", "return", "true", ";", "}", "elseif", "(", "$", "lower", "->", "equals", "(", "Rope", "::", "of", "(", "'false'", ")", ")", ")", "{", "return", "false", ";", "}", "throw", "new", "CoreException", "(", "'Unable to cast into a bool.'", ")", ";", "}", "elseif", "(", "is_int", "(", "$", "mixed", ")", ")", "{", "if", "(", "$", "mixed", "===", "1", ")", "{", "return", "true", ";", "}", "elseif", "(", "$", "mixed", "===", "0", ")", "{", "return", "false", ";", "}", "throw", "new", "CoreException", "(", "'Unable to cast into a bool.'", ")", ";", "}", "elseif", "(", "is_float", "(", "$", "mixed", ")", ")", "{", "if", "(", "$", "mixed", "===", "1.0", ")", "{", "return", "true", ";", "}", "elseif", "(", "$", "mixed", "===", "0.0", ")", "{", "return", "false", ";", "}", "throw", "new", "CoreException", "(", "'Unable to cast into a bool.'", ")", ";", "}", "elseif", "(", "is_bool", "(", "$", "mixed", ")", ")", "{", "return", "$", "mixed", ";", "}", "throw", "new", "CoreException", "(", "'Unable to cast into a bool.'", ")", ";", "}" ]
Attempt to cast a value into a bool. @param mixed $mixed @return bool @throws CoreException
[ "Attempt", "to", "cast", "a", "value", "into", "a", "bool", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Support/Std.php#L618-L651
12,367
phox-pro/pulsar-core
src/app/Logic/Front/Generators/BodyGenerator.php
BodyGenerator.render
public function render() : string { $html = '<div id="app">'; $html .= ' <transition name="fade" mode="out-in"> <router-view></router-view> </transition>'; $html .= '</div>'; $title = env('APP_NAME'); $html .= '<script src="/assets/application.js"></script>'; $html .= $this->scripts(); return '<body>' . $html . '</body>'; }
php
public function render() : string { $html = '<div id="app">'; $html .= ' <transition name="fade" mode="out-in"> <router-view></router-view> </transition>'; $html .= '</div>'; $title = env('APP_NAME'); $html .= '<script src="/assets/application.js"></script>'; $html .= $this->scripts(); return '<body>' . $html . '</body>'; }
[ "public", "function", "render", "(", ")", ":", "string", "{", "$", "html", "=", "'<div id=\"app\">'", ";", "$", "html", ".=", "'\n <transition name=\"fade\" mode=\"out-in\">\n <router-view></router-view>\n </transition>'", ";", "$", "html", ".=", "'</div>'", ";", "$", "title", "=", "env", "(", "'APP_NAME'", ")", ";", "$", "html", ".=", "'<script src=\"/assets/application.js\"></script>'", ";", "$", "html", ".=", "$", "this", "->", "scripts", "(", ")", ";", "return", "'<body>'", ".", "$", "html", ".", "'</body>'", ";", "}" ]
Function for return rendered body html @return string
[ "Function", "for", "return", "rendered", "body", "html" ]
fa9c66f6578180253a65c91edf422fc3c51b32ba
https://github.com/phox-pro/pulsar-core/blob/fa9c66f6578180253a65c91edf422fc3c51b32ba/src/app/Logic/Front/Generators/BodyGenerator.php#L15-L27
12,368
bishopb/vanilla
applications/dashboard/controllers/class.dashboardcontroller.php
DashboardController.AddSideMenu
public function AddSideMenu($CurrentUrl = FALSE) { if(!$CurrentUrl) $CurrentUrl = strtolower($this->SelfUrl); // Only add to the assets if this is not a view-only request if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { // Configure SideMenu module $SideMenu = new SideMenuModule($this); $SideMenu->EventName = 'GetAppSettingsMenuItems'; $SideMenu->HtmlId = ''; $SideMenu->HighlightRoute($CurrentUrl); $SideMenu->Sort = C('Garden.DashboardMenu.Sort'); // Hook for adding to menu // $this->EventArguments['SideMenu'] = &$SideMenu; // $this->FireEvent('GetAppSettingsMenuItems'); // Add the module $this->AddModule($SideMenu, 'Panel'); } }
php
public function AddSideMenu($CurrentUrl = FALSE) { if(!$CurrentUrl) $CurrentUrl = strtolower($this->SelfUrl); // Only add to the assets if this is not a view-only request if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { // Configure SideMenu module $SideMenu = new SideMenuModule($this); $SideMenu->EventName = 'GetAppSettingsMenuItems'; $SideMenu->HtmlId = ''; $SideMenu->HighlightRoute($CurrentUrl); $SideMenu->Sort = C('Garden.DashboardMenu.Sort'); // Hook for adding to menu // $this->EventArguments['SideMenu'] = &$SideMenu; // $this->FireEvent('GetAppSettingsMenuItems'); // Add the module $this->AddModule($SideMenu, 'Panel'); } }
[ "public", "function", "AddSideMenu", "(", "$", "CurrentUrl", "=", "FALSE", ")", "{", "if", "(", "!", "$", "CurrentUrl", ")", "$", "CurrentUrl", "=", "strtolower", "(", "$", "this", "->", "SelfUrl", ")", ";", "// Only add to the assets if this is not a view-only request", "if", "(", "$", "this", "->", "_DeliveryType", "==", "DELIVERY_TYPE_ALL", ")", "{", "// Configure SideMenu module", "$", "SideMenu", "=", "new", "SideMenuModule", "(", "$", "this", ")", ";", "$", "SideMenu", "->", "EventName", "=", "'GetAppSettingsMenuItems'", ";", "$", "SideMenu", "->", "HtmlId", "=", "''", ";", "$", "SideMenu", "->", "HighlightRoute", "(", "$", "CurrentUrl", ")", ";", "$", "SideMenu", "->", "Sort", "=", "C", "(", "'Garden.DashboardMenu.Sort'", ")", ";", "// Hook for adding to menu", "// $this->EventArguments['SideMenu'] = &$SideMenu;", "// $this->FireEvent('GetAppSettingsMenuItems');", "// Add the module", "$", "this", "->", "AddModule", "(", "$", "SideMenu", ",", "'Panel'", ")", ";", "}", "}" ]
Build and add the Dashboard's side navigation menu. @since 2.0.0 @access public @param string $CurrentUrl Used to highlight correct route in menu.
[ "Build", "and", "add", "the", "Dashboard", "s", "side", "navigation", "menu", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/applications/dashboard/controllers/class.dashboardcontroller.php#L71-L91
12,369
uthando-cms/uthando-common
src/UthandoCommon/View/FlashMessenger.php
FlashMessenger.fetchMessagesFromNamespace
protected function fetchMessagesFromNamespace($namespace) { $this->setNamespace($namespace); if ($this->hasMessages()) { $messages = $this->getMessagesFromNamespace($namespace); // reset namespace $this->setNamespace(); return $this->buildMessage($namespace, $messages); } return ''; }
php
protected function fetchMessagesFromNamespace($namespace) { $this->setNamespace($namespace); if ($this->hasMessages()) { $messages = $this->getMessagesFromNamespace($namespace); // reset namespace $this->setNamespace(); return $this->buildMessage($namespace, $messages); } return ''; }
[ "protected", "function", "fetchMessagesFromNamespace", "(", "$", "namespace", ")", "{", "$", "this", "->", "setNamespace", "(", "$", "namespace", ")", ";", "if", "(", "$", "this", "->", "hasMessages", "(", ")", ")", "{", "$", "messages", "=", "$", "this", "->", "getMessagesFromNamespace", "(", "$", "namespace", ")", ";", "// reset namespace", "$", "this", "->", "setNamespace", "(", ")", ";", "return", "$", "this", "->", "buildMessage", "(", "$", "namespace", ",", "$", "messages", ")", ";", "}", "return", "''", ";", "}" ]
Gets messages from flash messenger plugin namespace @param string $namespace @return string
[ "Gets", "messages", "from", "flash", "messenger", "plugin", "namespace" ]
feb915da5d26b60f536282e1bc3ad5c22e53f485
https://github.com/uthando-cms/uthando-common/blob/feb915da5d26b60f536282e1bc3ad5c22e53f485/src/UthandoCommon/View/FlashMessenger.php#L117-L130
12,370
uthando-cms/uthando-common
src/UthandoCommon/View/FlashMessenger.php
FlashMessenger.getAlert
protected function getAlert($namespace, $message, $title = null, $titleTag = 'h4', $isBlock = false) { $namespace = $this->classMessages[$namespace]; $html = ($title) ? sprintf($this->titleFormat, $titleTag, $title, $titleTag) : ''; $html .= $message . PHP_EOL; $alert = $this->getAlertHelper()->$namespace($html, $isBlock); return $alert; }
php
protected function getAlert($namespace, $message, $title = null, $titleTag = 'h4', $isBlock = false) { $namespace = $this->classMessages[$namespace]; $html = ($title) ? sprintf($this->titleFormat, $titleTag, $title, $titleTag) : ''; $html .= $message . PHP_EOL; $alert = $this->getAlertHelper()->$namespace($html, $isBlock); return $alert; }
[ "protected", "function", "getAlert", "(", "$", "namespace", ",", "$", "message", ",", "$", "title", "=", "null", ",", "$", "titleTag", "=", "'h4'", ",", "$", "isBlock", "=", "false", ")", "{", "$", "namespace", "=", "$", "this", "->", "classMessages", "[", "$", "namespace", "]", ";", "$", "html", "=", "(", "$", "title", ")", "?", "sprintf", "(", "$", "this", "->", "titleFormat", ",", "$", "titleTag", ",", "$", "title", ",", "$", "titleTag", ")", ":", "''", ";", "$", "html", ".=", "$", "message", ".", "PHP_EOL", ";", "$", "alert", "=", "$", "this", "->", "getAlertHelper", "(", ")", "->", "$", "namespace", "(", "$", "html", ",", "$", "isBlock", ")", ";", "return", "$", "alert", ";", "}" ]
Get the alert string @param string $namespace @return string $alert
[ "Get", "the", "alert", "string" ]
feb915da5d26b60f536282e1bc3ad5c22e53f485
https://github.com/uthando-cms/uthando-common/blob/feb915da5d26b60f536282e1bc3ad5c22e53f485/src/UthandoCommon/View/FlashMessenger.php#L189-L199
12,371
uthando-cms/uthando-common
src/UthandoCommon/View/FlashMessenger.php
FlashMessenger.getAlertHelper
protected function getAlertHelper() { if ($this->alertHelper) { return $this->alertHelper; } $this->alertHelper = $this->view->plugin('tbAlert'); return $this->alertHelper; }
php
protected function getAlertHelper() { if ($this->alertHelper) { return $this->alertHelper; } $this->alertHelper = $this->view->plugin('tbAlert'); return $this->alertHelper; }
[ "protected", "function", "getAlertHelper", "(", ")", "{", "if", "(", "$", "this", "->", "alertHelper", ")", "{", "return", "$", "this", "->", "alertHelper", ";", "}", "$", "this", "->", "alertHelper", "=", "$", "this", "->", "view", "->", "plugin", "(", "'tbAlert'", ")", ";", "return", "$", "this", "->", "alertHelper", ";", "}" ]
Retrieve the alert helper @return Alert
[ "Retrieve", "the", "alert", "helper" ]
feb915da5d26b60f536282e1bc3ad5c22e53f485
https://github.com/uthando-cms/uthando-common/blob/feb915da5d26b60f536282e1bc3ad5c22e53f485/src/UthandoCommon/View/FlashMessenger.php#L206-L215
12,372
uthando-cms/uthando-common
src/UthandoCommon/View/FlashMessenger.php
FlashMessenger.getPluginFlashMessenger
public function getPluginFlashMessenger() { if ($this->pluginFlashMessenger) { return $this->pluginFlashMessenger; } $this->pluginFlashMessenger = new PluginFlashMessenger(); return $this->pluginFlashMessenger; }
php
public function getPluginFlashMessenger() { if ($this->pluginFlashMessenger) { return $this->pluginFlashMessenger; } $this->pluginFlashMessenger = new PluginFlashMessenger(); return $this->pluginFlashMessenger; }
[ "public", "function", "getPluginFlashMessenger", "(", ")", "{", "if", "(", "$", "this", "->", "pluginFlashMessenger", ")", "{", "return", "$", "this", "->", "pluginFlashMessenger", ";", "}", "$", "this", "->", "pluginFlashMessenger", "=", "new", "PluginFlashMessenger", "(", ")", ";", "return", "$", "this", "->", "pluginFlashMessenger", ";", "}" ]
Retrieve the flash messenger plugin @return \Zend\Mvc\Controller\Plugin\FlashMessenger
[ "Retrieve", "the", "flash", "messenger", "plugin" ]
feb915da5d26b60f536282e1bc3ad5c22e53f485
https://github.com/uthando-cms/uthando-common/blob/feb915da5d26b60f536282e1bc3ad5c22e53f485/src/UthandoCommon/View/FlashMessenger.php#L238-L247
12,373
CampusUnion/Sked
src/Database/SkeModel.php
SkeModel.fetch
public function fetch(string $strDate) { // Filter input $this->validateDate($strDate); $strDateStart = $strDate . ' 00:00:00'; if ($this->iTimezoneOffset) { $strDateStart = date( 'Y-m-d H:i:s', strtotime( $strDateStart . ($this->iTimezoneOffset < 0 ? ' +' : ' ') . -$this->iTimezoneOffset . ' hours' ) ); } $strDateEnd = date('Y-m-d H:i:s', strtotime($strDateStart . ' + 1 day - 1 second')); // Get results and sort by time $aResults = $this->queryDay($strDateStart, $strDateEnd); usort($aResults, function($aResult1, $aResult2) { return $aResult1['session_at'] <=> $aResult2['session_at'] ?: $aResult1['starts_at'] <=> $aResult2['starts_at']; }); return $aResults; }
php
public function fetch(string $strDate) { // Filter input $this->validateDate($strDate); $strDateStart = $strDate . ' 00:00:00'; if ($this->iTimezoneOffset) { $strDateStart = date( 'Y-m-d H:i:s', strtotime( $strDateStart . ($this->iTimezoneOffset < 0 ? ' +' : ' ') . -$this->iTimezoneOffset . ' hours' ) ); } $strDateEnd = date('Y-m-d H:i:s', strtotime($strDateStart . ' + 1 day - 1 second')); // Get results and sort by time $aResults = $this->queryDay($strDateStart, $strDateEnd); usort($aResults, function($aResult1, $aResult2) { return $aResult1['session_at'] <=> $aResult2['session_at'] ?: $aResult1['starts_at'] <=> $aResult2['starts_at']; }); return $aResults; }
[ "public", "function", "fetch", "(", "string", "$", "strDate", ")", "{", "// Filter input", "$", "this", "->", "validateDate", "(", "$", "strDate", ")", ";", "$", "strDateStart", "=", "$", "strDate", ".", "' 00:00:00'", ";", "if", "(", "$", "this", "->", "iTimezoneOffset", ")", "{", "$", "strDateStart", "=", "date", "(", "'Y-m-d H:i:s'", ",", "strtotime", "(", "$", "strDateStart", ".", "(", "$", "this", "->", "iTimezoneOffset", "<", "0", "?", "' +'", ":", "' '", ")", ".", "-", "$", "this", "->", "iTimezoneOffset", ".", "' hours'", ")", ")", ";", "}", "$", "strDateEnd", "=", "date", "(", "'Y-m-d H:i:s'", ",", "strtotime", "(", "$", "strDateStart", ".", "' + 1 day - 1 second'", ")", ")", ";", "// Get results and sort by time", "$", "aResults", "=", "$", "this", "->", "queryDay", "(", "$", "strDateStart", ",", "$", "strDateEnd", ")", ";", "usort", "(", "$", "aResults", ",", "function", "(", "$", "aResult1", ",", "$", "aResult2", ")", "{", "return", "$", "aResult1", "[", "'session_at'", "]", "<=>", "$", "aResult2", "[", "'session_at'", "]", "?", ":", "$", "aResult1", "[", "'starts_at'", "]", "<=>", "$", "aResult2", "[", "'starts_at'", "]", ";", "}", ")", ";", "return", "$", "aResults", ";", "}" ]
Fetch today's event sessions from the database. @param string $strDate Date of event sessions to fetch. @return array
[ "Fetch", "today", "s", "event", "sessions", "from", "the", "database", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/Database/SkeModel.php#L127-L150
12,374
CampusUnion/Sked
src/Database/SkeModel.php
SkeModel.save
public function save(SkeVent &$skeVent) { $mReturn = false; // Validate if ($this->validateEvent($skeVent)) { $aValues = $skeVent->toArray(false); unset($aValues['lead_time_num'], $aValues['lead_time_unit']); // Run transaction $this->beginTransaction(); try { $mReturn = $this->saveEvent($aValues); $this->saveEventTags($mReturn, $skeVent->getTags()); $this->saveEventMembers($mReturn, $skeVent->getMembers()); } catch (\Exception $e) { $mReturn = false; $skeVent->addError(2, $e->getMessage()); } $this->endTransaction((bool)$mReturn); } return $mReturn; }
php
public function save(SkeVent &$skeVent) { $mReturn = false; // Validate if ($this->validateEvent($skeVent)) { $aValues = $skeVent->toArray(false); unset($aValues['lead_time_num'], $aValues['lead_time_unit']); // Run transaction $this->beginTransaction(); try { $mReturn = $this->saveEvent($aValues); $this->saveEventTags($mReturn, $skeVent->getTags()); $this->saveEventMembers($mReturn, $skeVent->getMembers()); } catch (\Exception $e) { $mReturn = false; $skeVent->addError(2, $e->getMessage()); } $this->endTransaction((bool)$mReturn); } return $mReturn; }
[ "public", "function", "save", "(", "SkeVent", "&", "$", "skeVent", ")", "{", "$", "mReturn", "=", "false", ";", "// Validate", "if", "(", "$", "this", "->", "validateEvent", "(", "$", "skeVent", ")", ")", "{", "$", "aValues", "=", "$", "skeVent", "->", "toArray", "(", "false", ")", ";", "unset", "(", "$", "aValues", "[", "'lead_time_num'", "]", ",", "$", "aValues", "[", "'lead_time_unit'", "]", ")", ";", "// Run transaction", "$", "this", "->", "beginTransaction", "(", ")", ";", "try", "{", "$", "mReturn", "=", "$", "this", "->", "saveEvent", "(", "$", "aValues", ")", ";", "$", "this", "->", "saveEventTags", "(", "$", "mReturn", ",", "$", "skeVent", "->", "getTags", "(", ")", ")", ";", "$", "this", "->", "saveEventMembers", "(", "$", "mReturn", ",", "$", "skeVent", "->", "getMembers", "(", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "mReturn", "=", "false", ";", "$", "skeVent", "->", "addError", "(", "2", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "$", "this", "->", "endTransaction", "(", "(", "bool", ")", "$", "mReturn", ")", ";", "}", "return", "$", "mReturn", ";", "}" ]
Persist data to the database. @param CampusUnion\Sked\SkeVent $skeVent Passed by reference. @return int|bool Success/failure.
[ "Persist", "data", "to", "the", "database", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/Database/SkeModel.php#L206-L229
12,375
CampusUnion/Sked
src/Database/SkeModel.php
SkeModel.validateEvent
protected function validateEvent(SkeVent &$skeVent) { $bValid = true; $skeVent->resetErrors(); $aData = $skeVent->toArray(); // Check required fields && valid options foreach (Sked::form()->getFieldDefinitions() as $strKey => $aDefinition) { // Required if (!isset($aData[$strKey]) && ($aDefinition['required'] ?? false) && !isset($aData['id'])) { $bValid = false; $skeVent->addError( $strKey, 'The "' . $aDefinition['attribs']['label'] . '" field is required.' ); // Valid option } elseif (!$this->validateOption($aData[$strKey] ?? null, $aDefinition['options'] ?? null)) { $bValid = false; $skeVent->addError( $strKey, 'An invalid ' . $strKey . ' option was given.' ); } } // Check reminder fields - should both be present, or neither if (isset($aData['lead_time_num']) || isset($aData['lead_time_unit'])) { // one is set if (!isset($aData['lead_time_num']) || !isset($aData['lead_time_unit'])) { // but not both $bValid = false; $skeVent->addError( isset($aData['lead_time_num']) ? 'lead_time_unit' : 'lead_time_num', 'Both Reminder fields should be filled out (or clear them both).' ); } } // Check recurring-event fields if (isset($aData['ends_at'])) { if (!isset($aData['frequency'])) { $bValid = false; $skeVent->addError( 'frequency', 'A frequency is required for recurring events.' ); } if (!isset($aData['interval']) || SkeVent::INTERVAL_ONCE === $aData['interval']) { $bValid = false; $skeVent->addError( 'interval', 'An interval (daily, weekly, etc.) is required for recurring events.' ); } } if (isset($aData['frequency']) && !isset($aData['interval'])) { $bValid = false; $skeVent->addError( 'interval', 'An interval (daily, weekly, etc.) is required when a frequency is selected.' ); } if (isset($aData['interval'])) { if (SkeVent::INTERVAL_DAILY === $aData['interval'] && isset($aData['weekdays'])) { $bValid = false; $skeVent->addError( 'weekdays', 'A day of the week cannot be selected for daily events.' ); } } return $bValid; }
php
protected function validateEvent(SkeVent &$skeVent) { $bValid = true; $skeVent->resetErrors(); $aData = $skeVent->toArray(); // Check required fields && valid options foreach (Sked::form()->getFieldDefinitions() as $strKey => $aDefinition) { // Required if (!isset($aData[$strKey]) && ($aDefinition['required'] ?? false) && !isset($aData['id'])) { $bValid = false; $skeVent->addError( $strKey, 'The "' . $aDefinition['attribs']['label'] . '" field is required.' ); // Valid option } elseif (!$this->validateOption($aData[$strKey] ?? null, $aDefinition['options'] ?? null)) { $bValid = false; $skeVent->addError( $strKey, 'An invalid ' . $strKey . ' option was given.' ); } } // Check reminder fields - should both be present, or neither if (isset($aData['lead_time_num']) || isset($aData['lead_time_unit'])) { // one is set if (!isset($aData['lead_time_num']) || !isset($aData['lead_time_unit'])) { // but not both $bValid = false; $skeVent->addError( isset($aData['lead_time_num']) ? 'lead_time_unit' : 'lead_time_num', 'Both Reminder fields should be filled out (or clear them both).' ); } } // Check recurring-event fields if (isset($aData['ends_at'])) { if (!isset($aData['frequency'])) { $bValid = false; $skeVent->addError( 'frequency', 'A frequency is required for recurring events.' ); } if (!isset($aData['interval']) || SkeVent::INTERVAL_ONCE === $aData['interval']) { $bValid = false; $skeVent->addError( 'interval', 'An interval (daily, weekly, etc.) is required for recurring events.' ); } } if (isset($aData['frequency']) && !isset($aData['interval'])) { $bValid = false; $skeVent->addError( 'interval', 'An interval (daily, weekly, etc.) is required when a frequency is selected.' ); } if (isset($aData['interval'])) { if (SkeVent::INTERVAL_DAILY === $aData['interval'] && isset($aData['weekdays'])) { $bValid = false; $skeVent->addError( 'weekdays', 'A day of the week cannot be selected for daily events.' ); } } return $bValid; }
[ "protected", "function", "validateEvent", "(", "SkeVent", "&", "$", "skeVent", ")", "{", "$", "bValid", "=", "true", ";", "$", "skeVent", "->", "resetErrors", "(", ")", ";", "$", "aData", "=", "$", "skeVent", "->", "toArray", "(", ")", ";", "// Check required fields && valid options", "foreach", "(", "Sked", "::", "form", "(", ")", "->", "getFieldDefinitions", "(", ")", "as", "$", "strKey", "=>", "$", "aDefinition", ")", "{", "// Required", "if", "(", "!", "isset", "(", "$", "aData", "[", "$", "strKey", "]", ")", "&&", "(", "$", "aDefinition", "[", "'required'", "]", "??", "false", ")", "&&", "!", "isset", "(", "$", "aData", "[", "'id'", "]", ")", ")", "{", "$", "bValid", "=", "false", ";", "$", "skeVent", "->", "addError", "(", "$", "strKey", ",", "'The \"'", ".", "$", "aDefinition", "[", "'attribs'", "]", "[", "'label'", "]", ".", "'\" field is required.'", ")", ";", "// Valid option", "}", "elseif", "(", "!", "$", "this", "->", "validateOption", "(", "$", "aData", "[", "$", "strKey", "]", "??", "null", ",", "$", "aDefinition", "[", "'options'", "]", "??", "null", ")", ")", "{", "$", "bValid", "=", "false", ";", "$", "skeVent", "->", "addError", "(", "$", "strKey", ",", "'An invalid '", ".", "$", "strKey", ".", "' option was given.'", ")", ";", "}", "}", "// Check reminder fields - should both be present, or neither", "if", "(", "isset", "(", "$", "aData", "[", "'lead_time_num'", "]", ")", "||", "isset", "(", "$", "aData", "[", "'lead_time_unit'", "]", ")", ")", "{", "// one is set", "if", "(", "!", "isset", "(", "$", "aData", "[", "'lead_time_num'", "]", ")", "||", "!", "isset", "(", "$", "aData", "[", "'lead_time_unit'", "]", ")", ")", "{", "// but not both", "$", "bValid", "=", "false", ";", "$", "skeVent", "->", "addError", "(", "isset", "(", "$", "aData", "[", "'lead_time_num'", "]", ")", "?", "'lead_time_unit'", ":", "'lead_time_num'", ",", "'Both Reminder fields should be filled out (or clear them both).'", ")", ";", "}", "}", "// Check recurring-event fields", "if", "(", "isset", "(", "$", "aData", "[", "'ends_at'", "]", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "aData", "[", "'frequency'", "]", ")", ")", "{", "$", "bValid", "=", "false", ";", "$", "skeVent", "->", "addError", "(", "'frequency'", ",", "'A frequency is required for recurring events.'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "aData", "[", "'interval'", "]", ")", "||", "SkeVent", "::", "INTERVAL_ONCE", "===", "$", "aData", "[", "'interval'", "]", ")", "{", "$", "bValid", "=", "false", ";", "$", "skeVent", "->", "addError", "(", "'interval'", ",", "'An interval (daily, weekly, etc.) is required for recurring events.'", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "aData", "[", "'frequency'", "]", ")", "&&", "!", "isset", "(", "$", "aData", "[", "'interval'", "]", ")", ")", "{", "$", "bValid", "=", "false", ";", "$", "skeVent", "->", "addError", "(", "'interval'", ",", "'An interval (daily, weekly, etc.) is required when a frequency is selected.'", ")", ";", "}", "if", "(", "isset", "(", "$", "aData", "[", "'interval'", "]", ")", ")", "{", "if", "(", "SkeVent", "::", "INTERVAL_DAILY", "===", "$", "aData", "[", "'interval'", "]", "&&", "isset", "(", "$", "aData", "[", "'weekdays'", "]", ")", ")", "{", "$", "bValid", "=", "false", ";", "$", "skeVent", "->", "addError", "(", "'weekdays'", ",", "'A day of the week cannot be selected for daily events.'", ")", ";", "}", "}", "return", "$", "bValid", ";", "}" ]
Validate the event data. If errors are found, adds them to the SkeVent object. @param CampusUnion\Sked\SkeVent $skeVent Passed by reference. @return bool Valid/invalid.
[ "Validate", "the", "event", "data", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/Database/SkeModel.php#L239-L312
12,376
CampusUnion/Sked
src/Database/SkeModel.php
SkeModel.validateOption
protected function validateOption($mValue, array $aOptions = null) { return is_null($mValue) || is_null($aOptions) || array_key_exists($mValue, $aOptions); }
php
protected function validateOption($mValue, array $aOptions = null) { return is_null($mValue) || is_null($aOptions) || array_key_exists($mValue, $aOptions); }
[ "protected", "function", "validateOption", "(", "$", "mValue", ",", "array", "$", "aOptions", "=", "null", ")", "{", "return", "is_null", "(", "$", "mValue", ")", "||", "is_null", "(", "$", "aOptions", ")", "||", "array_key_exists", "(", "$", "mValue", ",", "$", "aOptions", ")", ";", "}" ]
Check if value is a valid option. If either value or options is null, return true (no validation rules). @param int|string $mValue The value in question. @param array $aOptions The list of valid options. @return bool
[ "Check", "if", "value", "is", "a", "valid", "option", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/Database/SkeModel.php#L323-L327
12,377
kaecyra/app-common
src/Addon/AddonManager.php
AddonManager.scanSourceFolders
public function scanSourceFolders() { $this->addons = []; foreach ($this->sources as $sourceDir) { $this->scanSource($sourceDir); } }
php
public function scanSourceFolders() { $this->addons = []; foreach ($this->sources as $sourceDir) { $this->scanSource($sourceDir); } }
[ "public", "function", "scanSourceFolders", "(", ")", "{", "$", "this", "->", "addons", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "sources", "as", "$", "sourceDir", ")", "{", "$", "this", "->", "scanSource", "(", "$", "sourceDir", ")", ";", "}", "}" ]
Scan all source folders @return void
[ "Scan", "all", "source", "folders" ]
8dbcf70c575fb587614b45da8ec02d098e3e843b
https://github.com/kaecyra/app-common/blob/8dbcf70c575fb587614b45da8ec02d098e3e843b/src/Addon/AddonManager.php#L123-L128
12,378
kaecyra/app-common
src/Addon/AddonManager.php
AddonManager.scanSource
public function scanSource($sourceDir) { $this->log(LogLevel::INFO, "Scanning addon source: {$sourceDir}"); $addonsCandidates = scandir($sourceDir); foreach ($addonsCandidates as $addonCandidate) { // Ignore hidden files and directory traversal links $char = substr($addonCandidate, 0, 1); if ($char == '.') { continue; } // Search for addon definition file $definitionFile = paths($sourceDir, $addonCandidate, "addon.json"); if (!file_exists($definitionFile)) { continue; } try { $addon = new Addon(realpath($definitionFile)); } catch (\Exception $ex) { $this->log(LogLevel::WARNING, " failed loading addon '{definition}': {message}", [ 'definition' => $definitionFile, 'message' => $ex->getMessage() ]); continue; } // Addon loaded $this->log(LogLevel::INFO, " found addon: {name} v{version} (provides {classes} classes from {path})", [ 'name' => $addon->getInfo('name'), 'version' => $addon->getInfo('version'), 'path' => $addon->getPath(), 'classes' => count($addon->getClasses()) ]); $this->addons[$addon->getInfo('name')] = $addon; } }
php
public function scanSource($sourceDir) { $this->log(LogLevel::INFO, "Scanning addon source: {$sourceDir}"); $addonsCandidates = scandir($sourceDir); foreach ($addonsCandidates as $addonCandidate) { // Ignore hidden files and directory traversal links $char = substr($addonCandidate, 0, 1); if ($char == '.') { continue; } // Search for addon definition file $definitionFile = paths($sourceDir, $addonCandidate, "addon.json"); if (!file_exists($definitionFile)) { continue; } try { $addon = new Addon(realpath($definitionFile)); } catch (\Exception $ex) { $this->log(LogLevel::WARNING, " failed loading addon '{definition}': {message}", [ 'definition' => $definitionFile, 'message' => $ex->getMessage() ]); continue; } // Addon loaded $this->log(LogLevel::INFO, " found addon: {name} v{version} (provides {classes} classes from {path})", [ 'name' => $addon->getInfo('name'), 'version' => $addon->getInfo('version'), 'path' => $addon->getPath(), 'classes' => count($addon->getClasses()) ]); $this->addons[$addon->getInfo('name')] = $addon; } }
[ "public", "function", "scanSource", "(", "$", "sourceDir", ")", "{", "$", "this", "->", "log", "(", "LogLevel", "::", "INFO", ",", "\"Scanning addon source: {$sourceDir}\"", ")", ";", "$", "addonsCandidates", "=", "scandir", "(", "$", "sourceDir", ")", ";", "foreach", "(", "$", "addonsCandidates", "as", "$", "addonCandidate", ")", "{", "// Ignore hidden files and directory traversal links", "$", "char", "=", "substr", "(", "$", "addonCandidate", ",", "0", ",", "1", ")", ";", "if", "(", "$", "char", "==", "'.'", ")", "{", "continue", ";", "}", "// Search for addon definition file", "$", "definitionFile", "=", "paths", "(", "$", "sourceDir", ",", "$", "addonCandidate", ",", "\"addon.json\"", ")", ";", "if", "(", "!", "file_exists", "(", "$", "definitionFile", ")", ")", "{", "continue", ";", "}", "try", "{", "$", "addon", "=", "new", "Addon", "(", "realpath", "(", "$", "definitionFile", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "$", "this", "->", "log", "(", "LogLevel", "::", "WARNING", ",", "\" failed loading addon '{definition}': {message}\"", ",", "[", "'definition'", "=>", "$", "definitionFile", ",", "'message'", "=>", "$", "ex", "->", "getMessage", "(", ")", "]", ")", ";", "continue", ";", "}", "// Addon loaded", "$", "this", "->", "log", "(", "LogLevel", "::", "INFO", ",", "\" found addon: {name} v{version} (provides {classes} classes from {path})\"", ",", "[", "'name'", "=>", "$", "addon", "->", "getInfo", "(", "'name'", ")", ",", "'version'", "=>", "$", "addon", "->", "getInfo", "(", "'version'", ")", ",", "'path'", "=>", "$", "addon", "->", "getPath", "(", ")", ",", "'classes'", "=>", "count", "(", "$", "addon", "->", "getClasses", "(", ")", ")", "]", ")", ";", "$", "this", "->", "addons", "[", "$", "addon", "->", "getInfo", "(", "'name'", ")", "]", "=", "$", "addon", ";", "}", "}" ]
Scan source dir for addons @param string $sourceDir
[ "Scan", "source", "dir", "for", "addons" ]
8dbcf70c575fb587614b45da8ec02d098e3e843b
https://github.com/kaecyra/app-common/blob/8dbcf70c575fb587614b45da8ec02d098e3e843b/src/Addon/AddonManager.php#L135-L172
12,379
kaecyra/app-common
src/Addon/AddonManager.php
AddonManager.startAddon
public function startAddon($addonName, $level = 0) { $nest = str_repeat(' ', $level); $this->log(LogLevel::NOTICE, "{$nest} start addon: {addon}", [ 'addon' => $addonName ]); // Short circuit if already started if ($this->isStarted($addonName)) { $this->log(LogLevel::INFO, "{$nest} already started"); return true; } // Check if we've got an addon called this $addon = $this->getAddon($addonName); if (!$addon) { $this->log(LogLevel::WARNING, "{$nest} unknown addon, not loaded"); return false; } // Check requirements $requiredAddons = $addon->getInfo('requires') ?? []; // If we have requirements, try to load them if (count($requiredAddons)) { $txtRequirements = implode(',', $requiredAddons); $this->log(LogLevel::INFO, "{$nest} addon has requirements: {requirements}", [ 'requirements' => $txtRequirements ]); // Check if the requirements are all available $missing = []; foreach ($requiredAddons as $requiredAddon) { if (!$this->isAvailable($requiredAddon)) { $missing[] = $requiredAddon; } } if (count($missing)) { $txtMissing = implode(',', $missing); $this->log(LogLevel::WARNING, "{$nest} missing requirements: {missing}", [ 'missing' => $txtMissing ]); return false; } // Keep track of which requirements we've loaded so we can unload if things went wrong $startedRequirements = []; // Loop over requirements and load each one in turn $loadedAllRequirements = true; foreach ($requiredAddons as $requiredAddon) { if (!$this->isStarted($requiredAddon)) { // Try to load addon if available $loadedRequirement = false; if ($this->isAvailable($requiredAddon)) { $loadedRequirement = $this->startAddon($requiredAddon, $level+1); } $loadedAllRequirements &= $loadedRequirement; if (!$loadedRequirement) { $this->log(LogLevel::WARNING, "{$nest} failed starting required addon: {addon}", [ 'addon' => $requiredAddon ]); return false; } $startedRequirements[] = $requiredAddon; } } } // Cache autoload info $this->autoload = array_merge($this->autoload, $addon->getClasses()); $addonClass = $addon->getAddonClass(); if ($addonClass) { $this->log(LogLevel::INFO, "{$nest} creating addon instance: {$addonClass}"); // Get instance $instance = $this->di->getArgs($addonClass, [ new Reference([AbstractConfig::class, "addons.addon.{$addonName}"]) ]); $instance->setAddon($addon); $this->instances[$addonName] = $instance; $instance->start(); } $this->enabled[$addonName] = true; return true; }
php
public function startAddon($addonName, $level = 0) { $nest = str_repeat(' ', $level); $this->log(LogLevel::NOTICE, "{$nest} start addon: {addon}", [ 'addon' => $addonName ]); // Short circuit if already started if ($this->isStarted($addonName)) { $this->log(LogLevel::INFO, "{$nest} already started"); return true; } // Check if we've got an addon called this $addon = $this->getAddon($addonName); if (!$addon) { $this->log(LogLevel::WARNING, "{$nest} unknown addon, not loaded"); return false; } // Check requirements $requiredAddons = $addon->getInfo('requires') ?? []; // If we have requirements, try to load them if (count($requiredAddons)) { $txtRequirements = implode(',', $requiredAddons); $this->log(LogLevel::INFO, "{$nest} addon has requirements: {requirements}", [ 'requirements' => $txtRequirements ]); // Check if the requirements are all available $missing = []; foreach ($requiredAddons as $requiredAddon) { if (!$this->isAvailable($requiredAddon)) { $missing[] = $requiredAddon; } } if (count($missing)) { $txtMissing = implode(',', $missing); $this->log(LogLevel::WARNING, "{$nest} missing requirements: {missing}", [ 'missing' => $txtMissing ]); return false; } // Keep track of which requirements we've loaded so we can unload if things went wrong $startedRequirements = []; // Loop over requirements and load each one in turn $loadedAllRequirements = true; foreach ($requiredAddons as $requiredAddon) { if (!$this->isStarted($requiredAddon)) { // Try to load addon if available $loadedRequirement = false; if ($this->isAvailable($requiredAddon)) { $loadedRequirement = $this->startAddon($requiredAddon, $level+1); } $loadedAllRequirements &= $loadedRequirement; if (!$loadedRequirement) { $this->log(LogLevel::WARNING, "{$nest} failed starting required addon: {addon}", [ 'addon' => $requiredAddon ]); return false; } $startedRequirements[] = $requiredAddon; } } } // Cache autoload info $this->autoload = array_merge($this->autoload, $addon->getClasses()); $addonClass = $addon->getAddonClass(); if ($addonClass) { $this->log(LogLevel::INFO, "{$nest} creating addon instance: {$addonClass}"); // Get instance $instance = $this->di->getArgs($addonClass, [ new Reference([AbstractConfig::class, "addons.addon.{$addonName}"]) ]); $instance->setAddon($addon); $this->instances[$addonName] = $instance; $instance->start(); } $this->enabled[$addonName] = true; return true; }
[ "public", "function", "startAddon", "(", "$", "addonName", ",", "$", "level", "=", "0", ")", "{", "$", "nest", "=", "str_repeat", "(", "' '", ",", "$", "level", ")", ";", "$", "this", "->", "log", "(", "LogLevel", "::", "NOTICE", ",", "\"{$nest} start addon: {addon}\"", ",", "[", "'addon'", "=>", "$", "addonName", "]", ")", ";", "// Short circuit if already started", "if", "(", "$", "this", "->", "isStarted", "(", "$", "addonName", ")", ")", "{", "$", "this", "->", "log", "(", "LogLevel", "::", "INFO", ",", "\"{$nest} already started\"", ")", ";", "return", "true", ";", "}", "// Check if we've got an addon called this", "$", "addon", "=", "$", "this", "->", "getAddon", "(", "$", "addonName", ")", ";", "if", "(", "!", "$", "addon", ")", "{", "$", "this", "->", "log", "(", "LogLevel", "::", "WARNING", ",", "\"{$nest} unknown addon, not loaded\"", ")", ";", "return", "false", ";", "}", "// Check requirements", "$", "requiredAddons", "=", "$", "addon", "->", "getInfo", "(", "'requires'", ")", "??", "[", "]", ";", "// If we have requirements, try to load them", "if", "(", "count", "(", "$", "requiredAddons", ")", ")", "{", "$", "txtRequirements", "=", "implode", "(", "','", ",", "$", "requiredAddons", ")", ";", "$", "this", "->", "log", "(", "LogLevel", "::", "INFO", ",", "\"{$nest} addon has requirements: {requirements}\"", ",", "[", "'requirements'", "=>", "$", "txtRequirements", "]", ")", ";", "// Check if the requirements are all available", "$", "missing", "=", "[", "]", ";", "foreach", "(", "$", "requiredAddons", "as", "$", "requiredAddon", ")", "{", "if", "(", "!", "$", "this", "->", "isAvailable", "(", "$", "requiredAddon", ")", ")", "{", "$", "missing", "[", "]", "=", "$", "requiredAddon", ";", "}", "}", "if", "(", "count", "(", "$", "missing", ")", ")", "{", "$", "txtMissing", "=", "implode", "(", "','", ",", "$", "missing", ")", ";", "$", "this", "->", "log", "(", "LogLevel", "::", "WARNING", ",", "\"{$nest} missing requirements: {missing}\"", ",", "[", "'missing'", "=>", "$", "txtMissing", "]", ")", ";", "return", "false", ";", "}", "// Keep track of which requirements we've loaded so we can unload if things went wrong", "$", "startedRequirements", "=", "[", "]", ";", "// Loop over requirements and load each one in turn", "$", "loadedAllRequirements", "=", "true", ";", "foreach", "(", "$", "requiredAddons", "as", "$", "requiredAddon", ")", "{", "if", "(", "!", "$", "this", "->", "isStarted", "(", "$", "requiredAddon", ")", ")", "{", "// Try to load addon if available", "$", "loadedRequirement", "=", "false", ";", "if", "(", "$", "this", "->", "isAvailable", "(", "$", "requiredAddon", ")", ")", "{", "$", "loadedRequirement", "=", "$", "this", "->", "startAddon", "(", "$", "requiredAddon", ",", "$", "level", "+", "1", ")", ";", "}", "$", "loadedAllRequirements", "&=", "$", "loadedRequirement", ";", "if", "(", "!", "$", "loadedRequirement", ")", "{", "$", "this", "->", "log", "(", "LogLevel", "::", "WARNING", ",", "\"{$nest} failed starting required addon: {addon}\"", ",", "[", "'addon'", "=>", "$", "requiredAddon", "]", ")", ";", "return", "false", ";", "}", "$", "startedRequirements", "[", "]", "=", "$", "requiredAddon", ";", "}", "}", "}", "// Cache autoload info", "$", "this", "->", "autoload", "=", "array_merge", "(", "$", "this", "->", "autoload", ",", "$", "addon", "->", "getClasses", "(", ")", ")", ";", "$", "addonClass", "=", "$", "addon", "->", "getAddonClass", "(", ")", ";", "if", "(", "$", "addonClass", ")", "{", "$", "this", "->", "log", "(", "LogLevel", "::", "INFO", ",", "\"{$nest} creating addon instance: {$addonClass}\"", ")", ";", "// Get instance", "$", "instance", "=", "$", "this", "->", "di", "->", "getArgs", "(", "$", "addonClass", ",", "[", "new", "Reference", "(", "[", "AbstractConfig", "::", "class", ",", "\"addons.addon.{$addonName}\"", "]", ")", "]", ")", ";", "$", "instance", "->", "setAddon", "(", "$", "addon", ")", ";", "$", "this", "->", "instances", "[", "$", "addonName", "]", "=", "$", "instance", ";", "$", "instance", "->", "start", "(", ")", ";", "}", "$", "this", "->", "enabled", "[", "$", "addonName", "]", "=", "true", ";", "return", "true", ";", "}" ]
Start an addon @param string $addonName addon name @return boolean load success status
[ "Start", "an", "addon" ]
8dbcf70c575fb587614b45da8ec02d098e3e843b
https://github.com/kaecyra/app-common/blob/8dbcf70c575fb587614b45da8ec02d098e3e843b/src/Addon/AddonManager.php#L206-L301
12,380
kaecyra/app-common
src/Addon/AddonManager.php
AddonManager.getInstance
public function getInstance($addonName) { if (!$this->isStarted($addonName)) { throw new \Exception("Tried to get instance of inactive addon '{$addonName}'"); } if (!array_key_exists($addonName, $this->instances) || !($this->instances[$addonName] instanceof AddonInterface)) { throw new \Exception("Addon '{$addonName}' has no instance"); } return $this->instances[$addonName]; }
php
public function getInstance($addonName) { if (!$this->isStarted($addonName)) { throw new \Exception("Tried to get instance of inactive addon '{$addonName}'"); } if (!array_key_exists($addonName, $this->instances) || !($this->instances[$addonName] instanceof AddonInterface)) { throw new \Exception("Addon '{$addonName}' has no instance"); } return $this->instances[$addonName]; }
[ "public", "function", "getInstance", "(", "$", "addonName", ")", "{", "if", "(", "!", "$", "this", "->", "isStarted", "(", "$", "addonName", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Tried to get instance of inactive addon '{$addonName}'\"", ")", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "addonName", ",", "$", "this", "->", "instances", ")", "||", "!", "(", "$", "this", "->", "instances", "[", "$", "addonName", "]", "instanceof", "AddonInterface", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Addon '{$addonName}' has no instance\"", ")", ";", "}", "return", "$", "this", "->", "instances", "[", "$", "addonName", "]", ";", "}" ]
Get addon instance @param string $addonName @throws \Exception @return AddonInterface
[ "Get", "addon", "instance" ]
8dbcf70c575fb587614b45da8ec02d098e3e843b
https://github.com/kaecyra/app-common/blob/8dbcf70c575fb587614b45da8ec02d098e3e843b/src/Addon/AddonManager.php#L365-L375
12,381
tokenly/counterparty-transaction-parser
src/Parser.php
Parser.lookupCounterpartyTransactionType
public function lookupCounterpartyTransactionType(array $tx, $protocol_version=null) { $data = $this->parseBitcoinTransaction($tx, $protocol_version); if ($data === null) { return null; } return $data['type']; }
php
public function lookupCounterpartyTransactionType(array $tx, $protocol_version=null) { $data = $this->parseBitcoinTransaction($tx, $protocol_version); if ($data === null) { return null; } return $data['type']; }
[ "public", "function", "lookupCounterpartyTransactionType", "(", "array", "$", "tx", ",", "$", "protocol_version", "=", "null", ")", "{", "$", "data", "=", "$", "this", "->", "parseBitcoinTransaction", "(", "$", "tx", ",", "$", "protocol_version", ")", ";", "if", "(", "$", "data", "===", "null", ")", "{", "return", "null", ";", "}", "return", "$", "data", "[", "'type'", "]", ";", "}" ]
parses a transaction and determines the counterparty transaction type @param array $tx Transaction data from bitcoind @param int|null $protocol_version the procol version. Leave blank for the latest protocol. @return string|null Counterparty transaction type
[ "parses", "a", "transaction", "and", "determines", "the", "counterparty", "transaction", "type" ]
dd39cba0f595948e3c99d1ab7bc134d3f9a88bec
https://github.com/tokenly/counterparty-transaction-parser/blob/dd39cba0f595948e3c99d1ab7bc134d3f9a88bec/src/Parser.php#L29-L33
12,382
tokenly/counterparty-transaction-parser
src/Parser.php
Parser.parseBitcoinTransaction
public function parseBitcoinTransaction(array $tx, $protocol_version=null) { if ($protocol_version === null) { $protocol_version = self::DEFAULT_PROTOCOL_VERSION; } switch ($protocol_version) { case 1: return $this->parseBitcoinTransactionVersion1($tx); case 2: return $this->parseBitcoinTransactionVersion2($tx); default: throw new Exception("Unknown protocol version", 1); } }
php
public function parseBitcoinTransaction(array $tx, $protocol_version=null) { if ($protocol_version === null) { $protocol_version = self::DEFAULT_PROTOCOL_VERSION; } switch ($protocol_version) { case 1: return $this->parseBitcoinTransactionVersion1($tx); case 2: return $this->parseBitcoinTransactionVersion2($tx); default: throw new Exception("Unknown protocol version", 1); } }
[ "public", "function", "parseBitcoinTransaction", "(", "array", "$", "tx", ",", "$", "protocol_version", "=", "null", ")", "{", "if", "(", "$", "protocol_version", "===", "null", ")", "{", "$", "protocol_version", "=", "self", "::", "DEFAULT_PROTOCOL_VERSION", ";", "}", "switch", "(", "$", "protocol_version", ")", "{", "case", "1", ":", "return", "$", "this", "->", "parseBitcoinTransactionVersion1", "(", "$", "tx", ")", ";", "case", "2", ":", "return", "$", "this", "->", "parseBitcoinTransactionVersion2", "(", "$", "tx", ")", ";", "default", ":", "throw", "new", "Exception", "(", "\"Unknown protocol version\"", ",", "1", ")", ";", "}", "}" ]
parses a transaction and returns the raw counterparty data @param array $tx Transaction data from bitcoind @param int|null $protocol_version the procol version. Leave blank for the latest protocol. @return array transaction data including type, destination, asset and quantity
[ "parses", "a", "transaction", "and", "returns", "the", "raw", "counterparty", "data" ]
dd39cba0f595948e3c99d1ab7bc134d3f9a88bec
https://github.com/tokenly/counterparty-transaction-parser/blob/dd39cba0f595948e3c99d1ab7bc134d3f9a88bec/src/Parser.php#L51-L63
12,383
tokenly/counterparty-transaction-parser
src/Parser.php
Parser.typeIDToType
protected static function typeIDToType($type_id) { if ($type_id === 0) { return 'send'; } else if ($type_id === 2) { return 'enhanced_send'; } else if ($type_id === 10) { return 'order'; } else if ($type_id === 11) { return 'btcpay'; } else if ($type_id === 20) { return 'issuance'; } else if ($type_id === 30) { return 'broadcast'; } else if ($type_id === 40) { return 'bet'; } else if ($type_id === 50) { return 'dividend'; } else if ($type_id === 70) { return 'cancel'; } else if ($type_id === 21) { return 'callback'; } else if ($type_id === 80) { return 'rps'; } else if ($type_id === 81) { return 'rpsresolve'; } return null; }
php
protected static function typeIDToType($type_id) { if ($type_id === 0) { return 'send'; } else if ($type_id === 2) { return 'enhanced_send'; } else if ($type_id === 10) { return 'order'; } else if ($type_id === 11) { return 'btcpay'; } else if ($type_id === 20) { return 'issuance'; } else if ($type_id === 30) { return 'broadcast'; } else if ($type_id === 40) { return 'bet'; } else if ($type_id === 50) { return 'dividend'; } else if ($type_id === 70) { return 'cancel'; } else if ($type_id === 21) { return 'callback'; } else if ($type_id === 80) { return 'rps'; } else if ($type_id === 81) { return 'rpsresolve'; } return null; }
[ "protected", "static", "function", "typeIDToType", "(", "$", "type_id", ")", "{", "if", "(", "$", "type_id", "===", "0", ")", "{", "return", "'send'", ";", "}", "else", "if", "(", "$", "type_id", "===", "2", ")", "{", "return", "'enhanced_send'", ";", "}", "else", "if", "(", "$", "type_id", "===", "10", ")", "{", "return", "'order'", ";", "}", "else", "if", "(", "$", "type_id", "===", "11", ")", "{", "return", "'btcpay'", ";", "}", "else", "if", "(", "$", "type_id", "===", "20", ")", "{", "return", "'issuance'", ";", "}", "else", "if", "(", "$", "type_id", "===", "30", ")", "{", "return", "'broadcast'", ";", "}", "else", "if", "(", "$", "type_id", "===", "40", ")", "{", "return", "'bet'", ";", "}", "else", "if", "(", "$", "type_id", "===", "50", ")", "{", "return", "'dividend'", ";", "}", "else", "if", "(", "$", "type_id", "===", "70", ")", "{", "return", "'cancel'", ";", "}", "else", "if", "(", "$", "type_id", "===", "21", ")", "{", "return", "'callback'", ";", "}", "else", "if", "(", "$", "type_id", "===", "80", ")", "{", "return", "'rps'", ";", "}", "else", "if", "(", "$", "type_id", "===", "81", ")", "{", "return", "'rpsresolve'", ";", "}", "return", "null", ";", "}" ]
map type id number to counterparty transaction type @param int $type_id The type id @return string|null the type
[ "map", "type", "id", "number", "to", "counterparty", "transaction", "type" ]
dd39cba0f595948e3c99d1ab7bc134d3f9a88bec
https://github.com/tokenly/counterparty-transaction-parser/blob/dd39cba0f595948e3c99d1ab7bc134d3f9a88bec/src/Parser.php#L387-L415
12,384
Apatis/Handler-Response
src/NotAllowedHandler.php
NotAllowedHandler.renderPlainText
protected function renderPlainText( ServerRequestInterface $request, ResponseInterface $response, array $allowedMethods ) { printf("Method %s is not allowed\r\n", $request->getMethod()); if ($this->isDisplayError()) { printf("Request method must be one of: (%s).\r\n", implode(', ', $allowedMethods)); } }
php
protected function renderPlainText( ServerRequestInterface $request, ResponseInterface $response, array $allowedMethods ) { printf("Method %s is not allowed\r\n", $request->getMethod()); if ($this->isDisplayError()) { printf("Request method must be one of: (%s).\r\n", implode(', ', $allowedMethods)); } }
[ "protected", "function", "renderPlainText", "(", "ServerRequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ",", "array", "$", "allowedMethods", ")", "{", "printf", "(", "\"Method %s is not allowed\\r\\n\"", ",", "$", "request", "->", "getMethod", "(", ")", ")", ";", "if", "(", "$", "this", "->", "isDisplayError", "(", ")", ")", "{", "printf", "(", "\"Request method must be one of: (%s).\\r\\n\"", ",", "implode", "(", "', '", ",", "$", "allowedMethods", ")", ")", ";", "}", "}" ]
Render Plain Text Output @param ServerRequestInterface $request @param ResponseInterface $response just for reference @param array $allowedMethods @return void
[ "Render", "Plain", "Text", "Output" ]
289941fdeb82dd8d89b20857accd96b017cd6053
https://github.com/Apatis/Handler-Response/blob/289941fdeb82dd8d89b20857accd96b017cd6053/src/NotAllowedHandler.php#L57-L66
12,385
Apatis/Handler-Response
src/NotAllowedHandler.php
NotAllowedHandler.renderXML
protected function renderXML( ServerRequestInterface $request, ResponseInterface $response, array $allowedMethods ) { $message = sprintf('Method %s is not allowed', $request->getMethod()); $baseSep = str_repeat(' ', 4); $sep = str_repeat($baseSep, 2); $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . "<root>\n" . "{$baseSep}<error>\n" . "{$sep}<message>{$message}</message>\n"; if ($this->isDisplayError()) { $method = htmlentities($request->getMethod()); $allowedMethodXML = ''; foreach ($allowedMethods as $value) { $value = htmlentities($value); $allowedMethodXML .= "{$baseSep}<method>{$value}</method>\n{$sep}"; } $xml .= "{$sep}<request_method>{$method}</request_method>\n"; $xml .= "{$sep}<allowed_methods>\n{$sep}{$allowedMethodXML}</allowed_methods>\n"; } $xml .= "{$baseSep}</error>\n</root>"; echo $xml; }
php
protected function renderXML( ServerRequestInterface $request, ResponseInterface $response, array $allowedMethods ) { $message = sprintf('Method %s is not allowed', $request->getMethod()); $baseSep = str_repeat(' ', 4); $sep = str_repeat($baseSep, 2); $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . "<root>\n" . "{$baseSep}<error>\n" . "{$sep}<message>{$message}</message>\n"; if ($this->isDisplayError()) { $method = htmlentities($request->getMethod()); $allowedMethodXML = ''; foreach ($allowedMethods as $value) { $value = htmlentities($value); $allowedMethodXML .= "{$baseSep}<method>{$value}</method>\n{$sep}"; } $xml .= "{$sep}<request_method>{$method}</request_method>\n"; $xml .= "{$sep}<allowed_methods>\n{$sep}{$allowedMethodXML}</allowed_methods>\n"; } $xml .= "{$baseSep}</error>\n</root>"; echo $xml; }
[ "protected", "function", "renderXML", "(", "ServerRequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ",", "array", "$", "allowedMethods", ")", "{", "$", "message", "=", "sprintf", "(", "'Method %s is not allowed'", ",", "$", "request", "->", "getMethod", "(", ")", ")", ";", "$", "baseSep", "=", "str_repeat", "(", "' '", ",", "4", ")", ";", "$", "sep", "=", "str_repeat", "(", "$", "baseSep", ",", "2", ")", ";", "$", "xml", "=", "\"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\\n\"", ".", "\"<root>\\n\"", ".", "\"{$baseSep}<error>\\n\"", ".", "\"{$sep}<message>{$message}</message>\\n\"", ";", "if", "(", "$", "this", "->", "isDisplayError", "(", ")", ")", "{", "$", "method", "=", "htmlentities", "(", "$", "request", "->", "getMethod", "(", ")", ")", ";", "$", "allowedMethodXML", "=", "''", ";", "foreach", "(", "$", "allowedMethods", "as", "$", "value", ")", "{", "$", "value", "=", "htmlentities", "(", "$", "value", ")", ";", "$", "allowedMethodXML", ".=", "\"{$baseSep}<method>{$value}</method>\\n{$sep}\"", ";", "}", "$", "xml", ".=", "\"{$sep}<request_method>{$method}</request_method>\\n\"", ";", "$", "xml", ".=", "\"{$sep}<allowed_methods>\\n{$sep}{$allowedMethodXML}</allowed_methods>\\n\"", ";", "}", "$", "xml", ".=", "\"{$baseSep}</error>\\n</root>\"", ";", "echo", "$", "xml", ";", "}" ]
Render XML Output @param ServerRequestInterface $request @param ResponseInterface $response just for reference @param array $allowedMethods @return void
[ "Render", "XML", "Output" ]
289941fdeb82dd8d89b20857accd96b017cd6053
https://github.com/Apatis/Handler-Response/blob/289941fdeb82dd8d89b20857accd96b017cd6053/src/NotAllowedHandler.php#L77-L104
12,386
fphammerle/php-helpers
colors/RGBA.php
RGBA.setAlpha
public function setAlpha($alpha) { $alpha = (float)$alpha; if($alpha < 0 || $alpha > 1) { throw new \UnexpectedValueException('value must be within [0, 1]'); } $this->_alpha = $alpha; }
php
public function setAlpha($alpha) { $alpha = (float)$alpha; if($alpha < 0 || $alpha > 1) { throw new \UnexpectedValueException('value must be within [0, 1]'); } $this->_alpha = $alpha; }
[ "public", "function", "setAlpha", "(", "$", "alpha", ")", "{", "$", "alpha", "=", "(", "float", ")", "$", "alpha", ";", "if", "(", "$", "alpha", "<", "0", "||", "$", "alpha", ">", "1", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'value must be within [0, 1]'", ")", ";", "}", "$", "this", "->", "_alpha", "=", "$", "alpha", ";", "}" ]
alpha 0 => 100% transparency alpha 1 => opaque, 0% transparency
[ "alpha", "0", "=", ">", "100%", "transparency", "alpha", "1", "=", ">", "opaque", "0%", "transparency" ]
ef4d5708080bad2d0474c86445293c04448da257
https://github.com/fphammerle/php-helpers/blob/ef4d5708080bad2d0474c86445293c04448da257/colors/RGBA.php#L26-L33
12,387
slickframework/orm
src/Mapper/Relation/AbstractRelation.php
AbstractRelation.getParentEntityDescriptor
public function getParentEntityDescriptor() { if (is_null($this->parentEntityDescriptor)) { $this->setParentEntityDescriptor( EntityDescriptorRegistry::getInstance() ->getDescriptorFor($this->parentEntity) ); } return $this->parentEntityDescriptor; }
php
public function getParentEntityDescriptor() { if (is_null($this->parentEntityDescriptor)) { $this->setParentEntityDescriptor( EntityDescriptorRegistry::getInstance() ->getDescriptorFor($this->parentEntity) ); } return $this->parentEntityDescriptor; }
[ "public", "function", "getParentEntityDescriptor", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "parentEntityDescriptor", ")", ")", "{", "$", "this", "->", "setParentEntityDescriptor", "(", "EntityDescriptorRegistry", "::", "getInstance", "(", ")", "->", "getDescriptorFor", "(", "$", "this", "->", "parentEntity", ")", ")", ";", "}", "return", "$", "this", "->", "parentEntityDescriptor", ";", "}" ]
Gets the parent or related entity descriptor @return EntityDescriptorInterface
[ "Gets", "the", "parent", "or", "related", "entity", "descriptor" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Mapper/Relation/AbstractRelation.php#L125-L134
12,388
slickframework/orm
src/Mapper/Relation/AbstractRelation.php
AbstractRelation.normalizeFieldName
protected function normalizeFieldName($tableName) { $tableName = Text::camelCaseToSeparator($tableName, '#'); $parts = explode('#', $tableName); $lastName = array_pop($parts); $lastName = Text::singular(strtolower($lastName)); array_push($parts, ucfirst($lastName)); return lcfirst(implode('', $parts)); }
php
protected function normalizeFieldName($tableName) { $tableName = Text::camelCaseToSeparator($tableName, '#'); $parts = explode('#', $tableName); $lastName = array_pop($parts); $lastName = Text::singular(strtolower($lastName)); array_push($parts, ucfirst($lastName)); return lcfirst(implode('', $parts)); }
[ "protected", "function", "normalizeFieldName", "(", "$", "tableName", ")", "{", "$", "tableName", "=", "Text", "::", "camelCaseToSeparator", "(", "$", "tableName", ",", "'#'", ")", ";", "$", "parts", "=", "explode", "(", "'#'", ",", "$", "tableName", ")", ";", "$", "lastName", "=", "array_pop", "(", "$", "parts", ")", ";", "$", "lastName", "=", "Text", "::", "singular", "(", "strtolower", "(", "$", "lastName", ")", ")", ";", "array_push", "(", "$", "parts", ",", "ucfirst", "(", "$", "lastName", ")", ")", ";", "return", "lcfirst", "(", "implode", "(", "''", ",", "$", "parts", ")", ")", ";", "}" ]
Normalizes the key field by convention @param string $tableName @return string
[ "Normalizes", "the", "key", "field", "by", "convention" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Mapper/Relation/AbstractRelation.php#L169-L177
12,389
slickframework/orm
src/Mapper/Relation/AbstractRelation.php
AbstractRelation.registerEntity
protected function registerEntity($entity) { Orm::getRepository($this->getParentEntity()) ->getIdentityMap() ->set($entity); return $entity; }
php
protected function registerEntity($entity) { Orm::getRepository($this->getParentEntity()) ->getIdentityMap() ->set($entity); return $entity; }
[ "protected", "function", "registerEntity", "(", "$", "entity", ")", "{", "Orm", "::", "getRepository", "(", "$", "this", "->", "getParentEntity", "(", ")", ")", "->", "getIdentityMap", "(", ")", "->", "set", "(", "$", "entity", ")", ";", "return", "$", "entity", ";", "}" ]
Register the retrieved entities in the repository identity map @param EntityInterface|EntityCollection $entity @return EntityInterface|EntityCollection
[ "Register", "the", "retrieved", "entities", "in", "the", "repository", "identity", "map" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Mapper/Relation/AbstractRelation.php#L186-L193
12,390
slickframework/orm
src/Mapper/Relation/AbstractRelation.php
AbstractRelation.getAdapter
public function getAdapter() { if (null == $this->adapter) { $className = $this->getEntityDescriptor()->className(); $repository = Orm::getRepository($className); $this->setAdapter($repository->getAdapter()); } return $this->adapter; }
php
public function getAdapter() { if (null == $this->adapter) { $className = $this->getEntityDescriptor()->className(); $repository = Orm::getRepository($className); $this->setAdapter($repository->getAdapter()); } return $this->adapter; }
[ "public", "function", "getAdapter", "(", ")", "{", "if", "(", "null", "==", "$", "this", "->", "adapter", ")", "{", "$", "className", "=", "$", "this", "->", "getEntityDescriptor", "(", ")", "->", "className", "(", ")", ";", "$", "repository", "=", "Orm", "::", "getRepository", "(", "$", "className", ")", ";", "$", "this", "->", "setAdapter", "(", "$", "repository", "->", "getAdapter", "(", ")", ")", ";", "}", "return", "$", "this", "->", "adapter", ";", "}" ]
Gets relation adapter @return AdapterInterface
[ "Gets", "relation", "adapter" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Mapper/Relation/AbstractRelation.php#L212-L220
12,391
sasedev/extra-tools-bundle
src/Sasedev/ExtraToolsBundle/Util/DateFormatter.php
DateFormatter.parse
public function parse($date, $locale = null) { $result = new \DateTime(); $result->setTimestamp($this->parseTimestamp($date, $locale)); return $result; }
php
public function parse($date, $locale = null) { $result = new \DateTime(); $result->setTimestamp($this->parseTimestamp($date, $locale)); return $result; }
[ "public", "function", "parse", "(", "$", "date", ",", "$", "locale", "=", "null", ")", "{", "$", "result", "=", "new", "\\", "DateTime", "(", ")", ";", "$", "result", "->", "setTimestamp", "(", "$", "this", "->", "parseTimestamp", "(", "$", "date", ",", "$", "locale", ")", ")", ";", "return", "$", "result", ";", "}" ]
Parse a string representation of a date to a \DateTime @param string $date @param string $locale @return \DateTime datetime @throws \Exception If fails parsing the string
[ "Parse", "a", "string", "representation", "of", "a", "date", "to", "a", "\\", "DateTime" ]
14037d6b5c8ba9520ffe33f26057e2e53bea7a75
https://github.com/sasedev/extra-tools-bundle/blob/14037d6b5c8ba9520ffe33f26057e2e53bea7a75/src/Sasedev/ExtraToolsBundle/Util/DateFormatter.php#L29-L35
12,392
sasedev/extra-tools-bundle
src/Sasedev/ExtraToolsBundle/Util/DateFormatter.php
DateFormatter.parseTimestamp
private function parseTimestamp($date, $locale = null) { // try time default formats foreach ($this->formats as $timeFormat) { // try date default formats foreach($this->formats as $dateFormat) { $dateFormater = \IntlDateFormatter::create($locale ?: \Locale::getDefault(), $dateFormat, $timeFormat, date_default_timezone_get()); $timestamp = $dateFormater->parse($date); if ($dateFormater->getErrorCode() == 0) { return $timestamp; } } } // try other custom formats $formats = array( 'MMMM yyyy', // november 2011 - nov. 2011 ); foreach($formats as $format) { $dateFormater = \IntlDateFormatter::create($locale ?: \Locale::getDefault(), $this->formats['none'], $this->formats['none'], date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, $format); $timestamp = $dateFormater->parse($date); if ($dateFormater->getErrorCode() == 0) { return $timestamp; } } throw new \Exception('"'.$date.'" could not be converted to \DateTime'); }
php
private function parseTimestamp($date, $locale = null) { // try time default formats foreach ($this->formats as $timeFormat) { // try date default formats foreach($this->formats as $dateFormat) { $dateFormater = \IntlDateFormatter::create($locale ?: \Locale::getDefault(), $dateFormat, $timeFormat, date_default_timezone_get()); $timestamp = $dateFormater->parse($date); if ($dateFormater->getErrorCode() == 0) { return $timestamp; } } } // try other custom formats $formats = array( 'MMMM yyyy', // november 2011 - nov. 2011 ); foreach($formats as $format) { $dateFormater = \IntlDateFormatter::create($locale ?: \Locale::getDefault(), $this->formats['none'], $this->formats['none'], date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, $format); $timestamp = $dateFormater->parse($date); if ($dateFormater->getErrorCode() == 0) { return $timestamp; } } throw new \Exception('"'.$date.'" could not be converted to \DateTime'); }
[ "private", "function", "parseTimestamp", "(", "$", "date", ",", "$", "locale", "=", "null", ")", "{", "// try time default formats", "foreach", "(", "$", "this", "->", "formats", "as", "$", "timeFormat", ")", "{", "// try date default formats", "foreach", "(", "$", "this", "->", "formats", "as", "$", "dateFormat", ")", "{", "$", "dateFormater", "=", "\\", "IntlDateFormatter", "::", "create", "(", "$", "locale", "?", ":", "\\", "Locale", "::", "getDefault", "(", ")", ",", "$", "dateFormat", ",", "$", "timeFormat", ",", "date_default_timezone_get", "(", ")", ")", ";", "$", "timestamp", "=", "$", "dateFormater", "->", "parse", "(", "$", "date", ")", ";", "if", "(", "$", "dateFormater", "->", "getErrorCode", "(", ")", "==", "0", ")", "{", "return", "$", "timestamp", ";", "}", "}", "}", "// try other custom formats", "$", "formats", "=", "array", "(", "'MMMM yyyy'", ",", "// november 2011 - nov. 2011", ")", ";", "foreach", "(", "$", "formats", "as", "$", "format", ")", "{", "$", "dateFormater", "=", "\\", "IntlDateFormatter", "::", "create", "(", "$", "locale", "?", ":", "\\", "Locale", "::", "getDefault", "(", ")", ",", "$", "this", "->", "formats", "[", "'none'", "]", ",", "$", "this", "->", "formats", "[", "'none'", "]", ",", "date_default_timezone_get", "(", ")", ",", "\\", "IntlDateFormatter", "::", "GREGORIAN", ",", "$", "format", ")", ";", "$", "timestamp", "=", "$", "dateFormater", "->", "parse", "(", "$", "date", ")", ";", "if", "(", "$", "dateFormater", "->", "getErrorCode", "(", ")", "==", "0", ")", "{", "return", "$", "timestamp", ";", "}", "}", "throw", "new", "\\", "Exception", "(", "'\"'", ".", "$", "date", ".", "'\" could not be converted to \\DateTime'", ")", ";", "}" ]
Parse a string representation of a date to a timestamp. @param string $date @param string $locale @return int Timestamp @throws \Exception If fails parsing the string
[ "Parse", "a", "string", "representation", "of", "a", "date", "to", "a", "timestamp", "." ]
14037d6b5c8ba9520ffe33f26057e2e53bea7a75
https://github.com/sasedev/extra-tools-bundle/blob/14037d6b5c8ba9520ffe33f26057e2e53bea7a75/src/Sasedev/ExtraToolsBundle/Util/DateFormatter.php#L72-L100
12,393
sellerlabs/nucleus
src/SellerLabs/Nucleus/Validation/Validator.php
Validator.spec
public static function spec( $constraints, $defaults = [], $required = [], $messages = [] ) { return new static( Spec::define($constraints, $defaults, $required), $messages ); }
php
public static function spec( $constraints, $defaults = [], $required = [], $messages = [] ) { return new static( Spec::define($constraints, $defaults, $required), $messages ); }
[ "public", "static", "function", "spec", "(", "$", "constraints", ",", "$", "defaults", "=", "[", "]", ",", "$", "required", "=", "[", "]", ",", "$", "messages", "=", "[", "]", ")", "{", "return", "new", "static", "(", "Spec", "::", "define", "(", "$", "constraints", ",", "$", "defaults", ",", "$", "required", ")", ",", "$", "messages", ")", ";", "}" ]
Shortcut for defining a validator using a Spec. @param array $constraints @param array $defaults @param array $required @param array $messages @return static
[ "Shortcut", "for", "defining", "a", "validator", "using", "a", "Spec", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Validation/Validator.php#L97-L107
12,394
sellerlabs/nucleus
src/SellerLabs/Nucleus/Validation/Validator.php
Validator.check
public function check(array $input) { $result = $this->spec->check($input); return new SpecResult( $result->getMissing(), Arr::walkCopy( $result->getFailed(), function ($key, $value, &$array, $path) { $array[$key] = Std::coalesce( Std::firstBias( Arr::dotGet( $this->messages, Std::nonempty($path, $key) ) !== null, [Arr::dotGet( $this->messages, Std::nonempty($path, $key) )], null ), Std::firstBias( $value instanceof AbstractConstraint, function () use ($value) { return $value->getDescription(); }, null ), Std::firstBias( is_array($value), function () use ($value) { return array_map( function (AbstractConstraint $item) { return $item->getDescription(); }, $value ); }, $value ) ); }, true, '', false ), $result->getStatus() ); }
php
public function check(array $input) { $result = $this->spec->check($input); return new SpecResult( $result->getMissing(), Arr::walkCopy( $result->getFailed(), function ($key, $value, &$array, $path) { $array[$key] = Std::coalesce( Std::firstBias( Arr::dotGet( $this->messages, Std::nonempty($path, $key) ) !== null, [Arr::dotGet( $this->messages, Std::nonempty($path, $key) )], null ), Std::firstBias( $value instanceof AbstractConstraint, function () use ($value) { return $value->getDescription(); }, null ), Std::firstBias( is_array($value), function () use ($value) { return array_map( function (AbstractConstraint $item) { return $item->getDescription(); }, $value ); }, $value ) ); }, true, '', false ), $result->getStatus() ); }
[ "public", "function", "check", "(", "array", "$", "input", ")", "{", "$", "result", "=", "$", "this", "->", "spec", "->", "check", "(", "$", "input", ")", ";", "return", "new", "SpecResult", "(", "$", "result", "->", "getMissing", "(", ")", ",", "Arr", "::", "walkCopy", "(", "$", "result", "->", "getFailed", "(", ")", ",", "function", "(", "$", "key", ",", "$", "value", ",", "&", "$", "array", ",", "$", "path", ")", "{", "$", "array", "[", "$", "key", "]", "=", "Std", "::", "coalesce", "(", "Std", "::", "firstBias", "(", "Arr", "::", "dotGet", "(", "$", "this", "->", "messages", ",", "Std", "::", "nonempty", "(", "$", "path", ",", "$", "key", ")", ")", "!==", "null", ",", "[", "Arr", "::", "dotGet", "(", "$", "this", "->", "messages", ",", "Std", "::", "nonempty", "(", "$", "path", ",", "$", "key", ")", ")", "]", ",", "null", ")", ",", "Std", "::", "firstBias", "(", "$", "value", "instanceof", "AbstractConstraint", ",", "function", "(", ")", "use", "(", "$", "value", ")", "{", "return", "$", "value", "->", "getDescription", "(", ")", ";", "}", ",", "null", ")", ",", "Std", "::", "firstBias", "(", "is_array", "(", "$", "value", ")", ",", "function", "(", ")", "use", "(", "$", "value", ")", "{", "return", "array_map", "(", "function", "(", "AbstractConstraint", "$", "item", ")", "{", "return", "$", "item", "->", "getDescription", "(", ")", ";", "}", ",", "$", "value", ")", ";", "}", ",", "$", "value", ")", ")", ";", "}", ",", "true", ",", "''", ",", "false", ")", ",", "$", "result", "->", "getStatus", "(", ")", ")", ";", "}" ]
Check that the spec matches and overlay help messaged. The resulting SpecResult instance should have more user-friendly messages. This allows one to use Specs for validation on a website or even an API. @param array $input @return SpecResult
[ "Check", "that", "the", "spec", "matches", "and", "overlay", "help", "messaged", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Validation/Validator.php#L136-L184
12,395
judus/minimal-minimal
src/Providers/AbstractProvider.php
AbstractProvider.register
public function register() { $bindings = $this->bindings(); count($bindings) > 0 && App::bind($bindings); $providers = $this->providers(); count($providers) > 0 && App::register($providers); $config = $this->config(); count($config) > 0 && Config::push($config); $subscribers = $this->subscribers(); count($subscribers) > 0 && Event::register($subscribers); $this->routes(); }
php
public function register() { $bindings = $this->bindings(); count($bindings) > 0 && App::bind($bindings); $providers = $this->providers(); count($providers) > 0 && App::register($providers); $config = $this->config(); count($config) > 0 && Config::push($config); $subscribers = $this->subscribers(); count($subscribers) > 0 && Event::register($subscribers); $this->routes(); }
[ "public", "function", "register", "(", ")", "{", "$", "bindings", "=", "$", "this", "->", "bindings", "(", ")", ";", "count", "(", "$", "bindings", ")", ">", "0", "&&", "App", "::", "bind", "(", "$", "bindings", ")", ";", "$", "providers", "=", "$", "this", "->", "providers", "(", ")", ";", "count", "(", "$", "providers", ")", ">", "0", "&&", "App", "::", "register", "(", "$", "providers", ")", ";", "$", "config", "=", "$", "this", "->", "config", "(", ")", ";", "count", "(", "$", "config", ")", ">", "0", "&&", "Config", "::", "push", "(", "$", "config", ")", ";", "$", "subscribers", "=", "$", "this", "->", "subscribers", "(", ")", ";", "count", "(", "$", "subscribers", ")", ">", "0", "&&", "Event", "::", "register", "(", "$", "subscribers", ")", ";", "$", "this", "->", "routes", "(", ")", ";", "}" ]
Called after pushing a service provider to the container
[ "Called", "after", "pushing", "a", "service", "provider", "to", "the", "container" ]
36db55c537175cead2ab412f166bf2574d0f9597
https://github.com/judus/minimal-minimal/blob/36db55c537175cead2ab412f166bf2574d0f9597/src/Providers/AbstractProvider.php#L19-L34
12,396
judus/minimal-minimal
src/Providers/AbstractProvider.php
AbstractProvider.singleton
public function singleton($name, $object) { if (IOC::hasSingleton($name)) { return IOC::singleton($name); } else { IOC::singleton($name, $object); return $object; } }
php
public function singleton($name, $object) { if (IOC::hasSingleton($name)) { return IOC::singleton($name); } else { IOC::singleton($name, $object); return $object; } }
[ "public", "function", "singleton", "(", "$", "name", ",", "$", "object", ")", "{", "if", "(", "IOC", "::", "hasSingleton", "(", "$", "name", ")", ")", "{", "return", "IOC", "::", "singleton", "(", "$", "name", ")", ";", "}", "else", "{", "IOC", "::", "singleton", "(", "$", "name", ",", "$", "object", ")", ";", "return", "$", "object", ";", "}", "}" ]
Tells the container the service should be a singleton @param $name @param $object @return mixed
[ "Tells", "the", "container", "the", "service", "should", "be", "a", "singleton" ]
36db55c537175cead2ab412f166bf2574d0f9597
https://github.com/judus/minimal-minimal/blob/36db55c537175cead2ab412f166bf2574d0f9597/src/Providers/AbstractProvider.php#L74-L82
12,397
gamernetwork/yolk-core
src/helpers/DateTimeHelper.php
DateTimeHelper.makeTimestamp
public static function makeTimestamp( $time ) { if( is_numeric($time) ) return (int) $time; elseif( $time instanceof \DateTime ) return $time->getTimestamp(); $ts = strtotime($time); if( $ts === false ) throw new \LogicException("Unable convert {$time} to a valid timestamp"); return $ts; }
php
public static function makeTimestamp( $time ) { if( is_numeric($time) ) return (int) $time; elseif( $time instanceof \DateTime ) return $time->getTimestamp(); $ts = strtotime($time); if( $ts === false ) throw new \LogicException("Unable convert {$time} to a valid timestamp"); return $ts; }
[ "public", "static", "function", "makeTimestamp", "(", "$", "time", ")", "{", "if", "(", "is_numeric", "(", "$", "time", ")", ")", "return", "(", "int", ")", "$", "time", ";", "elseif", "(", "$", "time", "instanceof", "\\", "DateTime", ")", "return", "$", "time", "->", "getTimestamp", "(", ")", ";", "$", "ts", "=", "strtotime", "(", "$", "time", ")", ";", "if", "(", "$", "ts", "===", "false", ")", "throw", "new", "\\", "LogicException", "(", "\"Unable convert {$time} to a valid timestamp\"", ")", ";", "return", "$", "ts", ";", "}" ]
Convert a value to a timestamp. @param mixed $time @return integer
[ "Convert", "a", "value", "to", "a", "timestamp", "." ]
d9567dd55c51507dd34a55fd335a7b333e3db269
https://github.com/gamernetwork/yolk-core/blob/d9567dd55c51507dd34a55fd335a7b333e3db269/src/helpers/DateTimeHelper.php#L21-L36
12,398
PytoCryto/PytoTPL
src/Compiler.php
Compiler.tryCompile
private function tryCompile($string, \Closure $afterEvents = null, $flags = null) // todo: after events + flags (?) { foreach ($this->compilers as $compiler => $priority) { if (! class_exists($compiler)) { throw new NotFoundException("PytoTPL compiler ({$compiler}) couldn't be found!"); } elseif (! is_subclass_of($compiler, "PytoTPL\Compilers\AbstractCompiler")) { throw new InvalidCompilerException("Compiler ({$compiler}) must extend (PytoTPL\Compilers\AbstractCompiler)!"); } $string = $this->run($compiler, $string); } return $string; }
php
private function tryCompile($string, \Closure $afterEvents = null, $flags = null) // todo: after events + flags (?) { foreach ($this->compilers as $compiler => $priority) { if (! class_exists($compiler)) { throw new NotFoundException("PytoTPL compiler ({$compiler}) couldn't be found!"); } elseif (! is_subclass_of($compiler, "PytoTPL\Compilers\AbstractCompiler")) { throw new InvalidCompilerException("Compiler ({$compiler}) must extend (PytoTPL\Compilers\AbstractCompiler)!"); } $string = $this->run($compiler, $string); } return $string; }
[ "private", "function", "tryCompile", "(", "$", "string", ",", "\\", "Closure", "$", "afterEvents", "=", "null", ",", "$", "flags", "=", "null", ")", "// todo: after events + flags (?)", "{", "foreach", "(", "$", "this", "->", "compilers", "as", "$", "compiler", "=>", "$", "priority", ")", "{", "if", "(", "!", "class_exists", "(", "$", "compiler", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"PytoTPL compiler ({$compiler}) couldn't be found!\"", ")", ";", "}", "elseif", "(", "!", "is_subclass_of", "(", "$", "compiler", ",", "\"PytoTPL\\Compilers\\AbstractCompiler\"", ")", ")", "{", "throw", "new", "InvalidCompilerException", "(", "\"Compiler ({$compiler}) must extend (PytoTPL\\Compilers\\AbstractCompiler)!\"", ")", ";", "}", "$", "string", "=", "$", "this", "->", "run", "(", "$", "compiler", ",", "$", "string", ")", ";", "}", "return", "$", "string", ";", "}" ]
Load all the available compilers and run each one @param string $string @param \Closure|null $afterEvents @param mixed $flags @return type
[ "Load", "all", "the", "available", "compilers", "and", "run", "each", "one" ]
a130fb26d57b888871a5b047fba970a5fafd4131
https://github.com/PytoCryto/PytoTPL/blob/a130fb26d57b888871a5b047fba970a5fafd4131/src/Compiler.php#L103-L116
12,399
PytoCryto/PytoTPL
src/Compiler.php
Compiler.run
private function run($compiler, $string) { $compiler = $this->getCompilerInstance($compiler); return preg_replace_callback($compiler->getPattern(), function ($matches) use ($compiler) { return $compiler->compile($matches); }, $string); }
php
private function run($compiler, $string) { $compiler = $this->getCompilerInstance($compiler); return preg_replace_callback($compiler->getPattern(), function ($matches) use ($compiler) { return $compiler->compile($matches); }, $string); }
[ "private", "function", "run", "(", "$", "compiler", ",", "$", "string", ")", "{", "$", "compiler", "=", "$", "this", "->", "getCompilerInstance", "(", "$", "compiler", ")", ";", "return", "preg_replace_callback", "(", "$", "compiler", "->", "getPattern", "(", ")", ",", "function", "(", "$", "matches", ")", "use", "(", "$", "compiler", ")", "{", "return", "$", "compiler", "->", "compile", "(", "$", "matches", ")", ";", "}", ",", "$", "string", ")", ";", "}" ]
Run the compiler @param string $compiler @param string $string @return mixed
[ "Run", "the", "compiler" ]
a130fb26d57b888871a5b047fba970a5fafd4131
https://github.com/PytoCryto/PytoTPL/blob/a130fb26d57b888871a5b047fba970a5fafd4131/src/Compiler.php#L125-L132