repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
perryflynn/PerrysLambda
src/PerrysLambda/Sortable.php
Sortable.startOrder
public static function startOrder(ArrayList $list, $order) { $order = LambdaUtils::toSelectCallable($order); $temp = new static($list, $order, self::ORDER_ASC); $temp->thenBy($order); return $temp; }
php
public static function startOrder(ArrayList $list, $order) { $order = LambdaUtils::toSelectCallable($order); $temp = new static($list, $order, self::ORDER_ASC); $temp->thenBy($order); return $temp; }
[ "public", "static", "function", "startOrder", "(", "ArrayList", "$", "list", ",", "$", "order", ")", "{", "$", "order", "=", "LambdaUtils", "::", "toSelectCallable", "(", "$", "order", ")", ";", "$", "temp", "=", "new", "static", "(", "$", "list", ",", "$", "order", ",", "self", "::", "ORDER_ASC", ")", ";", "$", "temp", "->", "thenBy", "(", "$", "order", ")", ";", "return", "$", "temp", ";", "}" ]
Create asc order instance @param \PerrysLambda\ArrayList $list @param callable|string|null $order @return \PerrysLambda\Sortable
[ "Create", "asc", "order", "instance" ]
9f1734ae4689d73278b887f9354dfd31428e96de
https://github.com/perryflynn/PerrysLambda/blob/9f1734ae4689d73278b887f9354dfd31428e96de/src/PerrysLambda/Sortable.php#L21-L27
train
perryflynn/PerrysLambda
src/PerrysLambda/Sortable.php
Sortable.startOrderDesc
public static function startOrderDesc(ArrayList $list, $order) { $order = LambdaUtils::toSelectCallable($order); $temp = new static($list, $order, self::ORDER_DESC); $temp->thenByDesc($order); return $temp; }
php
public static function startOrderDesc(ArrayList $list, $order) { $order = LambdaUtils::toSelectCallable($order); $temp = new static($list, $order, self::ORDER_DESC); $temp->thenByDesc($order); return $temp; }
[ "public", "static", "function", "startOrderDesc", "(", "ArrayList", "$", "list", ",", "$", "order", ")", "{", "$", "order", "=", "LambdaUtils", "::", "toSelectCallable", "(", "$", "order", ")", ";", "$", "temp", "=", "new", "static", "(", "$", "list", ",", "$", "order", ",", "self", "::", "ORDER_DESC", ")", ";", "$", "temp", "->", "thenByDesc", "(", "$", "order", ")", ";", "return", "$", "temp", ";", "}" ]
Create desc order instance @param \PerrysLambda\ArrayList $list @param callable|string|null $order @return \PerrysLambda\Sortable
[ "Create", "desc", "order", "instance" ]
9f1734ae4689d73278b887f9354dfd31428e96de
https://github.com/perryflynn/PerrysLambda/blob/9f1734ae4689d73278b887f9354dfd31428e96de/src/PerrysLambda/Sortable.php#L35-L41
train
perryflynn/PerrysLambda
src/PerrysLambda/Sortable.php
Sortable.thenBy
public function thenBy($order) { $order = LambdaUtils::toSelectCallable($order); $this->orders[] = array("property" => $order, "direction" => self::ORDER_ASC); return $this; }
php
public function thenBy($order) { $order = LambdaUtils::toSelectCallable($order); $this->orders[] = array("property" => $order, "direction" => self::ORDER_ASC); return $this; }
[ "public", "function", "thenBy", "(", "$", "order", ")", "{", "$", "order", "=", "LambdaUtils", "::", "toSelectCallable", "(", "$", "order", ")", ";", "$", "this", "->", "orders", "[", "]", "=", "array", "(", "\"property\"", "=>", "$", "order", ",", "\"direction\"", "=>", "self", "::", "ORDER_ASC", ")", ";", "return", "$", "this", ";", "}" ]
New asc order rule @param callable|string|null $order @return \PerrysLambda\Sortable
[ "New", "asc", "order", "rule" ]
9f1734ae4689d73278b887f9354dfd31428e96de
https://github.com/perryflynn/PerrysLambda/blob/9f1734ae4689d73278b887f9354dfd31428e96de/src/PerrysLambda/Sortable.php#L55-L60
train
perryflynn/PerrysLambda
src/PerrysLambda/Sortable.php
Sortable.thenByDesc
public function thenByDesc($order) { $order = LambdaUtils::toSelectCallable($order); $this->orders[] = array("property" => $order, "direction" => self::ORDER_DESC); return $this; }
php
public function thenByDesc($order) { $order = LambdaUtils::toSelectCallable($order); $this->orders[] = array("property" => $order, "direction" => self::ORDER_DESC); return $this; }
[ "public", "function", "thenByDesc", "(", "$", "order", ")", "{", "$", "order", "=", "LambdaUtils", "::", "toSelectCallable", "(", "$", "order", ")", ";", "$", "this", "->", "orders", "[", "]", "=", "array", "(", "\"property\"", "=>", "$", "order", ",", "\"direction\"", "=>", "self", "::", "ORDER_DESC", ")", ";", "return", "$", "this", ";", "}" ]
New desc order rule @param callable|string|null $order @return \PerrysLambda\Sortable
[ "New", "desc", "order", "rule" ]
9f1734ae4689d73278b887f9354dfd31428e96de
https://github.com/perryflynn/PerrysLambda/blob/9f1734ae4689d73278b887f9354dfd31428e96de/src/PerrysLambda/Sortable.php#L67-L72
train
perryflynn/PerrysLambda
src/PerrysLambda/Sortable.php
Sortable.setDefaultComparator
protected function setDefaultComparator() { $func = function($a, $b) { $temp = 0; $cmpres = null; foreach($this->orders as $order) { $valuea = call_user_func($order['property'], $a); $valueb = call_user_func($order['property'], $b); if($valuea instanceof \DateTime || $valueb instanceof \DateTime || is_numeric($valuea) || is_numeric($valueb)) { if(is_numeric($valuea) || is_numeric($valueb)) { $valuea = ((double)$valuea); $valueb = ((double)$valueb); } $cmpres = ($valuea < $valueb ? -1 : ($valuea > $valueb ? 1 : 0)); } else { $cmpres = strcmp($valuea, $valueb); } $temp = (($order['direction'] == self::ORDER_DESC) ? -1 : 1) * $cmpres; if($temp!=0) { break; } } return $temp; }; $this->setComparator($func); }
php
protected function setDefaultComparator() { $func = function($a, $b) { $temp = 0; $cmpres = null; foreach($this->orders as $order) { $valuea = call_user_func($order['property'], $a); $valueb = call_user_func($order['property'], $b); if($valuea instanceof \DateTime || $valueb instanceof \DateTime || is_numeric($valuea) || is_numeric($valueb)) { if(is_numeric($valuea) || is_numeric($valueb)) { $valuea = ((double)$valuea); $valueb = ((double)$valueb); } $cmpres = ($valuea < $valueb ? -1 : ($valuea > $valueb ? 1 : 0)); } else { $cmpres = strcmp($valuea, $valueb); } $temp = (($order['direction'] == self::ORDER_DESC) ? -1 : 1) * $cmpres; if($temp!=0) { break; } } return $temp; }; $this->setComparator($func); }
[ "protected", "function", "setDefaultComparator", "(", ")", "{", "$", "func", "=", "function", "(", "$", "a", ",", "$", "b", ")", "{", "$", "temp", "=", "0", ";", "$", "cmpres", "=", "null", ";", "foreach", "(", "$", "this", "->", "orders", "as", "$", "order", ")", "{", "$", "valuea", "=", "call_user_func", "(", "$", "order", "[", "'property'", "]", ",", "$", "a", ")", ";", "$", "valueb", "=", "call_user_func", "(", "$", "order", "[", "'property'", "]", ",", "$", "b", ")", ";", "if", "(", "$", "valuea", "instanceof", "\\", "DateTime", "||", "$", "valueb", "instanceof", "\\", "DateTime", "||", "is_numeric", "(", "$", "valuea", ")", "||", "is_numeric", "(", "$", "valueb", ")", ")", "{", "if", "(", "is_numeric", "(", "$", "valuea", ")", "||", "is_numeric", "(", "$", "valueb", ")", ")", "{", "$", "valuea", "=", "(", "(", "double", ")", "$", "valuea", ")", ";", "$", "valueb", "=", "(", "(", "double", ")", "$", "valueb", ")", ";", "}", "$", "cmpres", "=", "(", "$", "valuea", "<", "$", "valueb", "?", "-", "1", ":", "(", "$", "valuea", ">", "$", "valueb", "?", "1", ":", "0", ")", ")", ";", "}", "else", "{", "$", "cmpres", "=", "strcmp", "(", "$", "valuea", ",", "$", "valueb", ")", ";", "}", "$", "temp", "=", "(", "(", "$", "order", "[", "'direction'", "]", "==", "self", "::", "ORDER_DESC", ")", "?", "-", "1", ":", "1", ")", "*", "$", "cmpres", ";", "if", "(", "$", "temp", "!=", "0", ")", "{", "break", ";", "}", "}", "return", "$", "temp", ";", "}", ";", "$", "this", "->", "setComparator", "(", "$", "func", ")", ";", "}" ]
Set the default compare method
[ "Set", "the", "default", "compare", "method" ]
9f1734ae4689d73278b887f9354dfd31428e96de
https://github.com/perryflynn/PerrysLambda/blob/9f1734ae4689d73278b887f9354dfd31428e96de/src/PerrysLambda/Sortable.php#L97-L133
train
perryflynn/PerrysLambda
src/PerrysLambda/Sortable.php
Sortable.toList
public function toList() { $data = $this->list->getData(); usort($data, $this->getComparator()); $newlist = $this->list->newInstance(); $newlist->setData($data); return $newlist; }
php
public function toList() { $data = $this->list->getData(); usort($data, $this->getComparator()); $newlist = $this->list->newInstance(); $newlist->setData($data); return $newlist; }
[ "public", "function", "toList", "(", ")", "{", "$", "data", "=", "$", "this", "->", "list", "->", "getData", "(", ")", ";", "usort", "(", "$", "data", ",", "$", "this", "->", "getComparator", "(", ")", ")", ";", "$", "newlist", "=", "$", "this", "->", "list", "->", "newInstance", "(", ")", ";", "$", "newlist", "->", "setData", "(", "$", "data", ")", ";", "return", "$", "newlist", ";", "}" ]
Sort and get the result @return \PerrysLambda\ArrayList
[ "Sort", "and", "get", "the", "result" ]
9f1734ae4689d73278b887f9354dfd31428e96de
https://github.com/perryflynn/PerrysLambda/blob/9f1734ae4689d73278b887f9354dfd31428e96de/src/PerrysLambda/Sortable.php#L139-L148
train
rawphp/RawSession
src/RawPHP/RawSession/Handler/FileHandler.php
FileHandler.getFileContents
protected function getFileContents() { $json = file_get_contents( $this->sessionPath ); $this->items = json_decode( $json, TRUE ); }
php
protected function getFileContents() { $json = file_get_contents( $this->sessionPath ); $this->items = json_decode( $json, TRUE ); }
[ "protected", "function", "getFileContents", "(", ")", "{", "$", "json", "=", "file_get_contents", "(", "$", "this", "->", "sessionPath", ")", ";", "$", "this", "->", "items", "=", "json_decode", "(", "$", "json", ",", "TRUE", ")", ";", "}" ]
Get file contents from file.
[ "Get", "file", "contents", "from", "file", "." ]
1e410e1def1d6d61acfade3bd31478464c70aea3
https://github.com/rawphp/RawSession/blob/1e410e1def1d6d61acfade3bd31478464c70aea3/src/RawPHP/RawSession/Handler/FileHandler.php#L151-L156
train
betasyntax/Betasyntax-Framework-Core
src/Betasyntax/Core/Application.php
Application.getEnvironment
private function getEnvironment() { $env = new \Dotenv\Dotenv($this->basePath); $env->load(); $this->env['env'] = getenv('APP_ENV'); $this->env['debug'] = getenv('APP_DEBUG'); $this->env['appSecret'] = getenv('APP_KEY'); }
php
private function getEnvironment() { $env = new \Dotenv\Dotenv($this->basePath); $env->load(); $this->env['env'] = getenv('APP_ENV'); $this->env['debug'] = getenv('APP_DEBUG'); $this->env['appSecret'] = getenv('APP_KEY'); }
[ "private", "function", "getEnvironment", "(", ")", "{", "$", "env", "=", "new", "\\", "Dotenv", "\\", "Dotenv", "(", "$", "this", "->", "basePath", ")", ";", "$", "env", "->", "load", "(", ")", ";", "$", "this", "->", "env", "[", "'env'", "]", "=", "getenv", "(", "'APP_ENV'", ")", ";", "$", "this", "->", "env", "[", "'debug'", "]", "=", "getenv", "(", "'APP_DEBUG'", ")", ";", "$", "this", "->", "env", "[", "'appSecret'", "]", "=", "getenv", "(", "'APP_KEY'", ")", ";", "}" ]
Loads the environment from your .env file @return array
[ "Loads", "the", "environment", "from", "your", ".", "env", "file" ]
2d135ec1f7dd98e6ef21512a069ac2595f1eb78e
https://github.com/betasyntax/Betasyntax-Framework-Core/blob/2d135ec1f7dd98e6ef21512a069ac2595f1eb78e/src/Betasyntax/Core/Application.php#L210-L217
train
betasyntax/Betasyntax-Framework-Core
src/Betasyntax/Core/Application.php
Application.boot
public function boot() { //start the session $this->session = Session::getInstance(); // create the container instance $this->container = new AppContainer; //boot the app and registers any middlewhere $this->container->addServiceProvider(new ServiceProvider($this)); }
php
public function boot() { //start the session $this->session = Session::getInstance(); // create the container instance $this->container = new AppContainer; //boot the app and registers any middlewhere $this->container->addServiceProvider(new ServiceProvider($this)); }
[ "public", "function", "boot", "(", ")", "{", "//start the session", "$", "this", "->", "session", "=", "Session", "::", "getInstance", "(", ")", ";", "// create the container instance", "$", "this", "->", "container", "=", "new", "AppContainer", ";", "//boot the app and registers any middlewhere", "$", "this", "->", "container", "->", "addServiceProvider", "(", "new", "ServiceProvider", "(", "$", "this", ")", ")", ";", "}" ]
Application boot method. Loads the app providers and sets some default application variables @return void
[ "Application", "boot", "method", ".", "Loads", "the", "app", "providers", "and", "sets", "some", "default", "application", "variables" ]
2d135ec1f7dd98e6ef21512a069ac2595f1eb78e
https://github.com/betasyntax/Betasyntax-Framework-Core/blob/2d135ec1f7dd98e6ef21512a069ac2595f1eb78e/src/Betasyntax/Core/Application.php#L259-L267
train
WellBloud/sovacore-core
src/model/AdminModule/facade/BaseFacade.php
BaseFacade.getParentsForBreadcrumbs
public function getParentsForBreadcrumbs( $entity, &$parents = [] ) { array_push($parents, $entity); if ($entity->parent !== null) { $this->getParentsForBreadcrumbs($entity->parent, $parents); } return array_reverse($parents); }
php
public function getParentsForBreadcrumbs( $entity, &$parents = [] ) { array_push($parents, $entity); if ($entity->parent !== null) { $this->getParentsForBreadcrumbs($entity->parent, $parents); } return array_reverse($parents); }
[ "public", "function", "getParentsForBreadcrumbs", "(", "$", "entity", ",", "&", "$", "parents", "=", "[", "]", ")", "{", "array_push", "(", "$", "parents", ",", "$", "entity", ")", ";", "if", "(", "$", "entity", "->", "parent", "!==", "null", ")", "{", "$", "this", "->", "getParentsForBreadcrumbs", "(", "$", "entity", "->", "parent", ",", "$", "parents", ")", ";", "}", "return", "array_reverse", "(", "$", "parents", ")", ";", "}" ]
Finds all parents of the entity @param type $entity @param array $parents @return array
[ "Finds", "all", "parents", "of", "the", "entity" ]
1816a0d7cd3ec4a90d64e301fc2469d171ad217f
https://github.com/WellBloud/sovacore-core/blob/1816a0d7cd3ec4a90d64e301fc2469d171ad217f/src/model/AdminModule/facade/BaseFacade.php#L55-L65
train
WellBloud/sovacore-core
src/model/AdminModule/facade/BaseFacade.php
BaseFacade.deleteItem
public function deleteItem($id = null) { if ($id === null) { throw new ItemNotSelectedException; } $entity = $this->getById($id); $this->deleteEntity($entity); }
php
public function deleteItem($id = null) { if ($id === null) { throw new ItemNotSelectedException; } $entity = $this->getById($id); $this->deleteEntity($entity); }
[ "public", "function", "deleteItem", "(", "$", "id", "=", "null", ")", "{", "if", "(", "$", "id", "===", "null", ")", "{", "throw", "new", "ItemNotSelectedException", ";", "}", "$", "entity", "=", "$", "this", "->", "getById", "(", "$", "id", ")", ";", "$", "this", "->", "deleteEntity", "(", "$", "entity", ")", ";", "}" ]
Method for deleting an item @param type $id @throws ItemNotSelectedException
[ "Method", "for", "deleting", "an", "item" ]
1816a0d7cd3ec4a90d64e301fc2469d171ad217f
https://github.com/WellBloud/sovacore-core/blob/1816a0d7cd3ec4a90d64e301fc2469d171ad217f/src/model/AdminModule/facade/BaseFacade.php#L72-L79
train
WellBloud/sovacore-core
src/model/AdminModule/facade/BaseFacade.php
BaseFacade.publishUnpublish
public function publishUnpublish($id, User $userEntity ) { if ($id === null) { throw new ItemNotSelectedException; } $entity = $this->getById($id); $entity->published = !$entity->published; $entity->modifiedOn = new DateTime(); $entity->modifiedBy = $userEntity; $this->repository->saveItem($entity); }
php
public function publishUnpublish($id, User $userEntity ) { if ($id === null) { throw new ItemNotSelectedException; } $entity = $this->getById($id); $entity->published = !$entity->published; $entity->modifiedOn = new DateTime(); $entity->modifiedBy = $userEntity; $this->repository->saveItem($entity); }
[ "public", "function", "publishUnpublish", "(", "$", "id", ",", "User", "$", "userEntity", ")", "{", "if", "(", "$", "id", "===", "null", ")", "{", "throw", "new", "ItemNotSelectedException", ";", "}", "$", "entity", "=", "$", "this", "->", "getById", "(", "$", "id", ")", ";", "$", "entity", "->", "published", "=", "!", "$", "entity", "->", "published", ";", "$", "entity", "->", "modifiedOn", "=", "new", "DateTime", "(", ")", ";", "$", "entity", "->", "modifiedBy", "=", "$", "userEntity", ";", "$", "this", "->", "repository", "->", "saveItem", "(", "$", "entity", ")", ";", "}" ]
Method for publishing and unpublishing entity @param integer $id @param User $userEntity @throws ItemNotSelectedException
[ "Method", "for", "publishing", "and", "unpublishing", "entity" ]
1816a0d7cd3ec4a90d64e301fc2469d171ad217f
https://github.com/WellBloud/sovacore-core/blob/1816a0d7cd3ec4a90d64e301fc2469d171ad217f/src/model/AdminModule/facade/BaseFacade.php#L119-L131
train
WellBloud/sovacore-core
src/model/AdminModule/facade/BaseFacade.php
BaseFacade.getDefaultValues
public function getDefaultValues($id = null) { if ($id === null) { return array(); } $entity = $this->getById($id); $values = $this->getDefaultFormValues($entity); return $values; }
php
public function getDefaultValues($id = null) { if ($id === null) { return array(); } $entity = $this->getById($id); $values = $this->getDefaultFormValues($entity); return $values; }
[ "public", "function", "getDefaultValues", "(", "$", "id", "=", "null", ")", "{", "if", "(", "$", "id", "===", "null", ")", "{", "return", "array", "(", ")", ";", "}", "$", "entity", "=", "$", "this", "->", "getById", "(", "$", "id", ")", ";", "$", "values", "=", "$", "this", "->", "getDefaultFormValues", "(", "$", "entity", ")", ";", "return", "$", "values", ";", "}" ]
Method for passing default values for form @param type $id @return type
[ "Method", "for", "passing", "default", "values", "for", "form" ]
1816a0d7cd3ec4a90d64e301fc2469d171ad217f
https://github.com/WellBloud/sovacore-core/blob/1816a0d7cd3ec4a90d64e301fc2469d171ad217f/src/model/AdminModule/facade/BaseFacade.php#L148-L156
train
WellBloud/sovacore-core
src/model/AdminModule/facade/BaseFacade.php
BaseFacade.getUniqueAlias
public function getUniqueAlias($entity, string $titleProperty = 'title', string $titleValue = null, string $aliasColumn = 'seoTitle' ): string { return $this->repository->getUniqueAlias($entity, trim($titleProperty), $titleValue, $aliasColumn); }
php
public function getUniqueAlias($entity, string $titleProperty = 'title', string $titleValue = null, string $aliasColumn = 'seoTitle' ): string { return $this->repository->getUniqueAlias($entity, trim($titleProperty), $titleValue, $aliasColumn); }
[ "public", "function", "getUniqueAlias", "(", "$", "entity", ",", "string", "$", "titleProperty", "=", "'title'", ",", "string", "$", "titleValue", "=", "null", ",", "string", "$", "aliasColumn", "=", "'seoTitle'", ")", ":", "string", "{", "return", "$", "this", "->", "repository", "->", "getUniqueAlias", "(", "$", "entity", ",", "trim", "(", "$", "titleProperty", ")", ",", "$", "titleValue", ",", "$", "aliasColumn", ")", ";", "}" ]
Returns unique alias for SEF URL @param type $entity @param string $titleProperty entity property with title (or name) @param string $titleValue @param string $aliasColumn @return string
[ "Returns", "unique", "alias", "for", "SEF", "URL" ]
1816a0d7cd3ec4a90d64e301fc2469d171ad217f
https://github.com/WellBloud/sovacore-core/blob/1816a0d7cd3ec4a90d64e301fc2469d171ad217f/src/model/AdminModule/facade/BaseFacade.php#L166-L173
train
kambalabs/KmbDomain
src/KmbDomain/Model/Environment.php
Environment.getNormalizedName
public function getNormalizedName() { if ($this->normalizedName === null) { $this->normalizedName = implode('_', $this->getAncestorsNames()); } return $this->normalizedName; }
php
public function getNormalizedName() { if ($this->normalizedName === null) { $this->normalizedName = implode('_', $this->getAncestorsNames()); } return $this->normalizedName; }
[ "public", "function", "getNormalizedName", "(", ")", "{", "if", "(", "$", "this", "->", "normalizedName", "===", "null", ")", "{", "$", "this", "->", "normalizedName", "=", "implode", "(", "'_'", ",", "$", "this", "->", "getAncestorsNames", "(", ")", ")", ";", "}", "return", "$", "this", "->", "normalizedName", ";", "}" ]
Get NormalizedName. @return string
[ "Get", "NormalizedName", "." ]
b1631bd936c6c6798076b51dfaebd706e1bdc8c2
https://github.com/kambalabs/KmbDomain/blob/b1631bd936c6c6798076b51dfaebd706e1bdc8c2/src/KmbDomain/Model/Environment.php#L113-L119
train
bseddon/XPath20
DOM/DOMSchemaType.php
DOMSchemaType.fromSchemaType
public static function fromSchemaType( $qname ) { $types = SchemaTypes::getInstance(); $type = $types->getType( "{$qname->prefix}:{$qname->localName}" ); if ( ! $type ) return null; $datatype = new DOMSchemaDatatype( "{$qname->prefix}:{$qname->localName}" ); $result = new DOMSchemaSimpleType( $qname, $datatype ); return $result; }
php
public static function fromSchemaType( $qname ) { $types = SchemaTypes::getInstance(); $type = $types->getType( "{$qname->prefix}:{$qname->localName}" ); if ( ! $type ) return null; $datatype = new DOMSchemaDatatype( "{$qname->prefix}:{$qname->localName}" ); $result = new DOMSchemaSimpleType( $qname, $datatype ); return $result; }
[ "public", "static", "function", "fromSchemaType", "(", "$", "qname", ")", "{", "$", "types", "=", "SchemaTypes", "::", "getInstance", "(", ")", ";", "$", "type", "=", "$", "types", "->", "getType", "(", "\"{$qname->prefix}:{$qname->localName}\"", ")", ";", "if", "(", "!", "$", "type", ")", "return", "null", ";", "$", "datatype", "=", "new", "DOMSchemaDatatype", "(", "\"{$qname->prefix}:{$qname->localName}\"", ")", ";", "$", "result", "=", "new", "DOMSchemaSimpleType", "(", "$", "qname", ",", "$", "datatype", ")", ";", "return", "$", "result", ";", "}" ]
Create an instance for a type in the SchemaTypes types list if there is one @param QName $qname @return DOMSchemaSimpleType
[ "Create", "an", "instance", "for", "a", "type", "in", "the", "SchemaTypes", "types", "list", "if", "there", "is", "one" ]
69882b6efffaa5470a819d5fdd2f6473ddeb046d
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/DOM/DOMSchemaType.php#L66-L76
train
bseddon/XPath20
DOM/DOMSchemaType.php
DOMSchemaType.GetBuiltInComplexTypeByTypeCode
public static function GetBuiltInComplexTypeByTypeCode( $typeCode ) { // The $typeCode must be valid (one of the items in XmlTypeCode) $type = XmlTypeCode::getTypeForCode( $typeCode ); if ( $type === false) { throw new \InvalidArgumentException( "The typecode passed to DOMSchemaType::GetBuiltInComplexTypeByTypeCode is not valid" ); } return DOMSchemaType::GetBuiltInComplexTypeByQName( $type ); }
php
public static function GetBuiltInComplexTypeByTypeCode( $typeCode ) { // The $typeCode must be valid (one of the items in XmlTypeCode) $type = XmlTypeCode::getTypeForCode( $typeCode ); if ( $type === false) { throw new \InvalidArgumentException( "The typecode passed to DOMSchemaType::GetBuiltInComplexTypeByTypeCode is not valid" ); } return DOMSchemaType::GetBuiltInComplexTypeByQName( $type ); }
[ "public", "static", "function", "GetBuiltInComplexTypeByTypeCode", "(", "$", "typeCode", ")", "{", "// The $typeCode must be valid (one of the items in XmlTypeCode)\r", "$", "type", "=", "XmlTypeCode", "::", "getTypeForCode", "(", "$", "typeCode", ")", ";", "if", "(", "$", "type", "===", "false", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"The typecode passed to DOMSchemaType::GetBuiltInComplexTypeByTypeCode is not valid\"", ")", ";", "}", "return", "DOMSchemaType", "::", "GetBuiltInComplexTypeByQName", "(", "$", "type", ")", ";", "}" ]
Returns an XmlSchemaComplexType that represents the built-in complex type of the complex type specified. @param XmlTypeCode $typeCode One of the XmlTypeCode values representing the complex type. @throws \InvalidArgumentException @return XmlSchemaComplexType The type that represents the built-in complex type.
[ "Returns", "an", "XmlSchemaComplexType", "that", "represents", "the", "built", "-", "in", "complex", "type", "of", "the", "complex", "type", "specified", "." ]
69882b6efffaa5470a819d5fdd2f6473ddeb046d
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/DOM/DOMSchemaType.php#L86-L97
train
bseddon/XPath20
DOM/DOMSchemaType.php
DOMSchemaType.GetBuiltInComplexTypeByQName
public static function GetBuiltInComplexTypeByQName( $qualifiedName ) { // The $qualifiedName cannot be null if ( is_null( $qualifiedName ) ) throw new \lyquidity\xml\exceptions\ArgumentNullException( "The QName passed to DOMSchemaType::GetBuiltInComplexTypeByQName cannot be null" ); $type = ""; if ( $qualifiedName instanceof QName ) { $type = "{$qualifiedName->prefix}:{$qualifiedName->localName}"; } else if ( is_string( $qualifiedName ) ) { $type = $qualifiedName; $qualifiedName = \lyquidity\xml\qname( $qualifiedName, array( SCHEMA_PREFIX => SCHEMA_NAMESPACE ) + SchemaTypes::getInstance()->getProcessedSchemas() ); } else { throw new \InvalidArgumentException( "The qualified name passed to DOMSchemaType::GetBuiltInSimpleTypeByQName MUST be a string or QName"); } // The only valid built-in complex type is xs:anyType. if ( $type != "xs:anyType" ) { // return null; } $dataType = new DOMSchemaDatatype( $type ); return new DOMSchemaComplexType( $qualifiedName, $dataType ); }
php
public static function GetBuiltInComplexTypeByQName( $qualifiedName ) { // The $qualifiedName cannot be null if ( is_null( $qualifiedName ) ) throw new \lyquidity\xml\exceptions\ArgumentNullException( "The QName passed to DOMSchemaType::GetBuiltInComplexTypeByQName cannot be null" ); $type = ""; if ( $qualifiedName instanceof QName ) { $type = "{$qualifiedName->prefix}:{$qualifiedName->localName}"; } else if ( is_string( $qualifiedName ) ) { $type = $qualifiedName; $qualifiedName = \lyquidity\xml\qname( $qualifiedName, array( SCHEMA_PREFIX => SCHEMA_NAMESPACE ) + SchemaTypes::getInstance()->getProcessedSchemas() ); } else { throw new \InvalidArgumentException( "The qualified name passed to DOMSchemaType::GetBuiltInSimpleTypeByQName MUST be a string or QName"); } // The only valid built-in complex type is xs:anyType. if ( $type != "xs:anyType" ) { // return null; } $dataType = new DOMSchemaDatatype( $type ); return new DOMSchemaComplexType( $qualifiedName, $dataType ); }
[ "public", "static", "function", "GetBuiltInComplexTypeByQName", "(", "$", "qualifiedName", ")", "{", "// The $qualifiedName cannot be null\r", "if", "(", "is_null", "(", "$", "qualifiedName", ")", ")", "throw", "new", "\\", "lyquidity", "\\", "xml", "\\", "exceptions", "\\", "ArgumentNullException", "(", "\"The QName passed to DOMSchemaType::GetBuiltInComplexTypeByQName cannot be null\"", ")", ";", "$", "type", "=", "\"\"", ";", "if", "(", "$", "qualifiedName", "instanceof", "QName", ")", "{", "$", "type", "=", "\"{$qualifiedName->prefix}:{$qualifiedName->localName}\"", ";", "}", "else", "if", "(", "is_string", "(", "$", "qualifiedName", ")", ")", "{", "$", "type", "=", "$", "qualifiedName", ";", "$", "qualifiedName", "=", "\\", "lyquidity", "\\", "xml", "\\", "qname", "(", "$", "qualifiedName", ",", "array", "(", "SCHEMA_PREFIX", "=>", "SCHEMA_NAMESPACE", ")", "+", "SchemaTypes", "::", "getInstance", "(", ")", "->", "getProcessedSchemas", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"The qualified name passed to DOMSchemaType::GetBuiltInSimpleTypeByQName MUST be a string or QName\"", ")", ";", "}", "// The only valid built-in complex type is xs:anyType.\r", "if", "(", "$", "type", "!=", "\"xs:anyType\"", ")", "{", "// return null;\r", "}", "$", "dataType", "=", "new", "DOMSchemaDatatype", "(", "$", "type", ")", ";", "return", "new", "DOMSchemaComplexType", "(", "$", "qualifiedName", ",", "$", "dataType", ")", ";", "}" ]
Returns an XmlSchemaComplexType that represents the built-in complex type of the complex type specified by qualified name. @param QName|string $qualifiedName The QName of the complex type. @return The XmlSchemaComplexType that represents the built-in complex type. @except \lyquidity\xml\exceptions\ArgumentNullException The XmlQualifiedName parameter is null.
[ "Returns", "an", "XmlSchemaComplexType", "that", "represents", "the", "built", "-", "in", "complex", "type", "of", "the", "complex", "type", "specified", "by", "qualified", "name", "." ]
69882b6efffaa5470a819d5fdd2f6473ddeb046d
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/DOM/DOMSchemaType.php#L109-L136
train
bseddon/XPath20
DOM/DOMSchemaType.php
DOMSchemaType.getSchemaType
public static function getSchemaType( $domNode ) { try { $types = SchemaTypes::getInstance(); $type = $types->getTypeForDOMNode( $domNode ); if ( $type ) { // TODO Kludge alert!! The XBRL_Types class wrongly used the prefix 'xsd' instead of 'xs' // This needs to be fixed but for now convert 'xs' to 'xsd' // BMS 2018-04-09 This can be retired // if ( strpos( $type, "xs:" ) === 0 ) $type = str_replace( "xs:", "xsd:", $type ); $resolves = SchemaTypes::getInstance()->resolvesToBaseType( $type, array( "xs:anySimpleType", "xsd:anySimpleType" ) ); if ( $resolves ) { return DOMSchemaType::GetBuiltInSimpleTypeByQName( $type ); } } return XmlSchema::$AnyType; } catch ( SchemaException $ex ) {} return XmlSchema::$UntypedAtomic; }
php
public static function getSchemaType( $domNode ) { try { $types = SchemaTypes::getInstance(); $type = $types->getTypeForDOMNode( $domNode ); if ( $type ) { // TODO Kludge alert!! The XBRL_Types class wrongly used the prefix 'xsd' instead of 'xs' // This needs to be fixed but for now convert 'xs' to 'xsd' // BMS 2018-04-09 This can be retired // if ( strpos( $type, "xs:" ) === 0 ) $type = str_replace( "xs:", "xsd:", $type ); $resolves = SchemaTypes::getInstance()->resolvesToBaseType( $type, array( "xs:anySimpleType", "xsd:anySimpleType" ) ); if ( $resolves ) { return DOMSchemaType::GetBuiltInSimpleTypeByQName( $type ); } } return XmlSchema::$AnyType; } catch ( SchemaException $ex ) {} return XmlSchema::$UntypedAtomic; }
[ "public", "static", "function", "getSchemaType", "(", "$", "domNode", ")", "{", "try", "{", "$", "types", "=", "SchemaTypes", "::", "getInstance", "(", ")", ";", "$", "type", "=", "$", "types", "->", "getTypeForDOMNode", "(", "$", "domNode", ")", ";", "if", "(", "$", "type", ")", "{", "// TODO Kludge alert!! The XBRL_Types class wrongly used the prefix 'xsd' instead of 'xs'\r", "// This needs to be fixed but for now convert 'xs' to 'xsd'\r", "// BMS 2018-04-09 This can be retired\r", "// if ( strpos( $type, \"xs:\" ) === 0 ) $type = str_replace( \"xs:\", \"xsd:\", $type );\r", "$", "resolves", "=", "SchemaTypes", "::", "getInstance", "(", ")", "->", "resolvesToBaseType", "(", "$", "type", ",", "array", "(", "\"xs:anySimpleType\"", ",", "\"xsd:anySimpleType\"", ")", ")", ";", "if", "(", "$", "resolves", ")", "{", "return", "DOMSchemaType", "::", "GetBuiltInSimpleTypeByQName", "(", "$", "type", ")", ";", "}", "}", "return", "XmlSchema", "::", "$", "AnyType", ";", "}", "catch", "(", "SchemaException", "$", "ex", ")", "{", "}", "return", "XmlSchema", "::", "$", "UntypedAtomic", ";", "}" ]
Create a DOMSchemaType instance from a DOMNode @param DOMXPathItem $domNode @return XmlSchemaType
[ "Create", "a", "DOMSchemaType", "instance", "from", "a", "DOMNode" ]
69882b6efffaa5470a819d5fdd2f6473ddeb046d
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/DOM/DOMSchemaType.php#L268-L295
train
SCLInternet/SclRequestResponse
src/SclRequestResponse/AbstractRequestResponse.php
AbstractRequestResponse.processRequest
public function processRequest(RequestInterface $request) { $this->response = $this->communicator->getResponse($request); return $this->response; }
php
public function processRequest(RequestInterface $request) { $this->response = $this->communicator->getResponse($request); return $this->response; }
[ "public", "function", "processRequest", "(", "RequestInterface", "$", "request", ")", "{", "$", "this", "->", "response", "=", "$", "this", "->", "communicator", "->", "getResponse", "(", "$", "request", ")", ";", "return", "$", "this", "->", "response", ";", "}" ]
Sends the request to the server and hands back the response. @param RequestInterface $request @return ResponseInterface
[ "Sends", "the", "request", "to", "the", "server", "and", "hands", "back", "the", "response", "." ]
40e5e24288c70be6c7e4e54992069aba969f562c
https://github.com/SCLInternet/SclRequestResponse/blob/40e5e24288c70be6c7e4e54992069aba969f562c/src/SclRequestResponse/AbstractRequestResponse.php#L54-L59
train
AlexyaFramework/Tools
Alexya/Tools/Session/Results.php
Results.initialize
public static function initialize(Session $session) : void { static::$_session = $session; if(!static::$_session->keyExists("_RESULTS")) { static::$_session->set("_RESULTS", []); } }
php
public static function initialize(Session $session) : void { static::$_session = $session; if(!static::$_session->keyExists("_RESULTS")) { static::$_session->set("_RESULTS", []); } }
[ "public", "static", "function", "initialize", "(", "Session", "$", "session", ")", ":", "void", "{", "static", "::", "$", "_session", "=", "$", "session", ";", "if", "(", "!", "static", "::", "$", "_session", "->", "keyExists", "(", "\"_RESULTS\"", ")", ")", "{", "static", "::", "$", "_session", "->", "set", "(", "\"_RESULTS\"", ",", "[", "]", ")", ";", "}", "}" ]
Sets session object. @param Session $session Session where results will be saved.
[ "Sets", "session", "object", "." ]
2ae7c91cde0517579b926dd872eaf7ea324fd1e4
https://github.com/AlexyaFramework/Tools/blob/2ae7c91cde0517579b926dd872eaf7ea324fd1e4/Alexya/Tools/Session/Results.php#L41-L48
train
AlexyaFramework/Tools
Alexya/Tools/Session/Results.php
Results.flash
public static function flash(string $name, $result) : void { $results = static::$_session->get("_RESULTS"); $results[$name] = [ "type" => "flash", "result" => $result ]; static::$_session->set("_RESULTS", $results); }
php
public static function flash(string $name, $result) : void { $results = static::$_session->get("_RESULTS"); $results[$name] = [ "type" => "flash", "result" => $result ]; static::$_session->set("_RESULTS", $results); }
[ "public", "static", "function", "flash", "(", "string", "$", "name", ",", "$", "result", ")", ":", "void", "{", "$", "results", "=", "static", "::", "$", "_session", "->", "get", "(", "\"_RESULTS\"", ")", ";", "$", "results", "[", "$", "name", "]", "=", "[", "\"type\"", "=>", "\"flash\"", ",", "\"result\"", "=>", "$", "result", "]", ";", "static", "::", "$", "_session", "->", "set", "(", "\"_RESULTS\"", ",", "$", "results", ")", ";", "}" ]
Adds a flash result. @param string $name Result name. @param mixed $result Result to add.
[ "Adds", "a", "flash", "result", "." ]
2ae7c91cde0517579b926dd872eaf7ea324fd1e4
https://github.com/AlexyaFramework/Tools/blob/2ae7c91cde0517579b926dd872eaf7ea324fd1e4/Alexya/Tools/Session/Results.php#L74-L84
train
AlexyaFramework/Tools
Alexya/Tools/Session/Results.php
Results.delete
public static function delete(string $name) : void { $results = static::$_session->get("_RESULTS"); unset($results[$name]); static::$_session->set("_RESULTS", $results); }
php
public static function delete(string $name) : void { $results = static::$_session->get("_RESULTS"); unset($results[$name]); static::$_session->set("_RESULTS", $results); }
[ "public", "static", "function", "delete", "(", "string", "$", "name", ")", ":", "void", "{", "$", "results", "=", "static", "::", "$", "_session", "->", "get", "(", "\"_RESULTS\"", ")", ";", "unset", "(", "$", "results", "[", "$", "name", "]", ")", ";", "static", "::", "$", "_session", "->", "set", "(", "\"_RESULTS\"", ",", "$", "results", ")", ";", "}" ]
Deletes a result. @param string $name Result name.
[ "Deletes", "a", "result", "." ]
2ae7c91cde0517579b926dd872eaf7ea324fd1e4
https://github.com/AlexyaFramework/Tools/blob/2ae7c91cde0517579b926dd872eaf7ea324fd1e4/Alexya/Tools/Session/Results.php#L91-L98
train
AlexyaFramework/Tools
Alexya/Tools/Session/Results.php
Results.get
public static function get($length = -1, int $offset = 0) : array { $ret = []; $results = static::$_session->get("_RESULTS"); if( !is_numeric($length) && isset($results[$length]) ) { $ret = $results[$length]["result"]; if($results[$length]["type"] === "flash") { unset($results[$length]); static::$_session->set("_RESULTS", $results); } return $ret; } foreach($results as $key => $value) { if($offset > 0) { $offset--; continue; } $ret[$key] = $$value["result"]; if($value["type"] == "flash") { unset($results[$key]); } if($length-- == 0) { break; } } static::$_session->set("_RESULTS", $results); return $ret; }
php
public static function get($length = -1, int $offset = 0) : array { $ret = []; $results = static::$_session->get("_RESULTS"); if( !is_numeric($length) && isset($results[$length]) ) { $ret = $results[$length]["result"]; if($results[$length]["type"] === "flash") { unset($results[$length]); static::$_session->set("_RESULTS", $results); } return $ret; } foreach($results as $key => $value) { if($offset > 0) { $offset--; continue; } $ret[$key] = $$value["result"]; if($value["type"] == "flash") { unset($results[$key]); } if($length-- == 0) { break; } } static::$_session->set("_RESULTS", $results); return $ret; }
[ "public", "static", "function", "get", "(", "$", "length", "=", "-", "1", ",", "int", "$", "offset", "=", "0", ")", ":", "array", "{", "$", "ret", "=", "[", "]", ";", "$", "results", "=", "static", "::", "$", "_session", "->", "get", "(", "\"_RESULTS\"", ")", ";", "if", "(", "!", "is_numeric", "(", "$", "length", ")", "&&", "isset", "(", "$", "results", "[", "$", "length", "]", ")", ")", "{", "$", "ret", "=", "$", "results", "[", "$", "length", "]", "[", "\"result\"", "]", ";", "if", "(", "$", "results", "[", "$", "length", "]", "[", "\"type\"", "]", "===", "\"flash\"", ")", "{", "unset", "(", "$", "results", "[", "$", "length", "]", ")", ";", "static", "::", "$", "_session", "->", "set", "(", "\"_RESULTS\"", ",", "$", "results", ")", ";", "}", "return", "$", "ret", ";", "}", "foreach", "(", "$", "results", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "offset", ">", "0", ")", "{", "$", "offset", "--", ";", "continue", ";", "}", "$", "ret", "[", "$", "key", "]", "=", "$", "$", "value", "[", "\"result\"", "]", ";", "if", "(", "$", "value", "[", "\"type\"", "]", "==", "\"flash\"", ")", "{", "unset", "(", "$", "results", "[", "$", "key", "]", ")", ";", "}", "if", "(", "$", "length", "--", "==", "0", ")", "{", "break", ";", "}", "}", "static", "::", "$", "_session", "->", "set", "(", "\"_RESULTS\"", ",", "$", "results", ")", ";", "return", "$", "ret", ";", "}" ]
Returns the results. @param int|string $length Length of the array to return, if string, the name of the result. @param int $offset Array offset. @return array Array with `$length` results.
[ "Returns", "the", "results", "." ]
2ae7c91cde0517579b926dd872eaf7ea324fd1e4
https://github.com/AlexyaFramework/Tools/blob/2ae7c91cde0517579b926dd872eaf7ea324fd1e4/Alexya/Tools/Session/Results.php#L108-L148
train
AnonymPHP/Anonym-Route
Matchers/RegexChecker.php
RegexChecker.match
public function match($url = null) { $match = parent::match($url); $regex = $this->getRegex($this->getMatchUrl()); if ($regex !== ' ') { if (preg_match("@" . ltrim($regex) . "@si", $this->getRequestedUrl(), $matches) || true === $match) { unset($matches[0]); ParameterBag::setParameters($matches); return true; } else { return false; } } else { return false; } }
php
public function match($url = null) { $match = parent::match($url); $regex = $this->getRegex($this->getMatchUrl()); if ($regex !== ' ') { if (preg_match("@" . ltrim($regex) . "@si", $this->getRequestedUrl(), $matches) || true === $match) { unset($matches[0]); ParameterBag::setParameters($matches); return true; } else { return false; } } else { return false; } }
[ "public", "function", "match", "(", "$", "url", "=", "null", ")", "{", "$", "match", "=", "parent", "::", "match", "(", "$", "url", ")", ";", "$", "regex", "=", "$", "this", "->", "getRegex", "(", "$", "this", "->", "getMatchUrl", "(", ")", ")", ";", "if", "(", "$", "regex", "!==", "' '", ")", "{", "if", "(", "preg_match", "(", "\"@\"", ".", "ltrim", "(", "$", "regex", ")", ".", "\"@si\"", ",", "$", "this", "->", "getRequestedUrl", "(", ")", ",", "$", "matches", ")", "||", "true", "===", "$", "match", ")", "{", "unset", "(", "$", "matches", "[", "0", "]", ")", ";", "ParameterBag", "::", "setParameters", "(", "$", "matches", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}" ]
Regex kontrolu yapar @param string|null $url @return bool
[ "Regex", "kontrolu", "yapar" ]
bb7f8004fbbd2998af8b0061f404f026f11466ab
https://github.com/AnonymPHP/Anonym-Route/blob/bb7f8004fbbd2998af8b0061f404f026f11466ab/Matchers/RegexChecker.php#L38-L55
train
mossphp/moss-storage
Moss/Storage/Query/AbstractEntityValueQuery.php
AbstractEntityValueQuery.getValueFromReferencedEntity
protected function getValueFromReferencedEntity(FieldInterface $field) { $references = $this->model->referredIn($field->name()); foreach ($references as $foreign => $reference) { $entity = $this->accessor->getPropertyValue($this->instance, $reference->container()); if ($entity === null) { continue; } $value = $this->accessor->getPropertyValue($entity, $foreign); $this->accessor->setPropertyValue($this->instance, $field->name(), $value); break; } }
php
protected function getValueFromReferencedEntity(FieldInterface $field) { $references = $this->model->referredIn($field->name()); foreach ($references as $foreign => $reference) { $entity = $this->accessor->getPropertyValue($this->instance, $reference->container()); if ($entity === null) { continue; } $value = $this->accessor->getPropertyValue($entity, $foreign); $this->accessor->setPropertyValue($this->instance, $field->name(), $value); break; } }
[ "protected", "function", "getValueFromReferencedEntity", "(", "FieldInterface", "$", "field", ")", "{", "$", "references", "=", "$", "this", "->", "model", "->", "referredIn", "(", "$", "field", "->", "name", "(", ")", ")", ";", "foreach", "(", "$", "references", "as", "$", "foreign", "=>", "$", "reference", ")", "{", "$", "entity", "=", "$", "this", "->", "accessor", "->", "getPropertyValue", "(", "$", "this", "->", "instance", ",", "$", "reference", "->", "container", "(", ")", ")", ";", "if", "(", "$", "entity", "===", "null", ")", "{", "continue", ";", "}", "$", "value", "=", "$", "this", "->", "accessor", "->", "getPropertyValue", "(", "$", "entity", ",", "$", "foreign", ")", ";", "$", "this", "->", "accessor", "->", "setPropertyValue", "(", "$", "this", "->", "instance", ",", "$", "field", "->", "name", "(", ")", ",", "$", "value", ")", ";", "break", ";", "}", "}" ]
Gets value from first referenced entity that has it @param FieldInterface $field
[ "Gets", "value", "from", "first", "referenced", "entity", "that", "has", "it" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/AbstractEntityValueQuery.php#L83-L97
train
WideFocus/Feed-Writer
src/WriterField.php
WriterField.getValue
public function getValue(ArrayAccess $item): string { $value = $item->offsetExists($this->name) ? $item->offsetGet($this->name) : ''; if (is_callable($this->filter)) { if ($this->filter instanceof ContextAwareFilterInterface) { $this->filter->setContext(clone $item); } $value = call_user_func($this->filter, $value); } return $value; }
php
public function getValue(ArrayAccess $item): string { $value = $item->offsetExists($this->name) ? $item->offsetGet($this->name) : ''; if (is_callable($this->filter)) { if ($this->filter instanceof ContextAwareFilterInterface) { $this->filter->setContext(clone $item); } $value = call_user_func($this->filter, $value); } return $value; }
[ "public", "function", "getValue", "(", "ArrayAccess", "$", "item", ")", ":", "string", "{", "$", "value", "=", "$", "item", "->", "offsetExists", "(", "$", "this", "->", "name", ")", "?", "$", "item", "->", "offsetGet", "(", "$", "this", "->", "name", ")", ":", "''", ";", "if", "(", "is_callable", "(", "$", "this", "->", "filter", ")", ")", "{", "if", "(", "$", "this", "->", "filter", "instanceof", "ContextAwareFilterInterface", ")", "{", "$", "this", "->", "filter", "->", "setContext", "(", "clone", "$", "item", ")", ";", "}", "$", "value", "=", "call_user_func", "(", "$", "this", "->", "filter", ",", "$", "value", ")", ";", "}", "return", "$", "value", ";", "}" ]
Get the value from a data object, the filter is applied. @param ArrayAccess $item @return string
[ "Get", "the", "value", "from", "a", "data", "object", "the", "filter", "is", "applied", "." ]
c2698394645c75db06962e5e9d638f0cabe69fe3
https://github.com/WideFocus/Feed-Writer/blob/c2698394645c75db06962e5e9d638f0cabe69fe3/src/WriterField.php#L76-L91
train
squareproton/Bond
src/Bond/Pg/Catalog/Repository/Attribute.php
Attribute.getIndexes
public function getIndexes( $oid ) { // load primary keys $query = new Query( "SELECT string_to_array( indkey::text, ' ') AS keys, * FROM pg_index WHERE indrelid = %oid:int%", array( 'oid' => $this->get('oid') ) ); $indexes = $this->db->query( $query )->fetch(Result::TYPE_DETECT); foreach( $this->indexes as &$index ) { $index['columns'] = array(); foreach( $index['keys'] as $columnIndex ) { $index['columns'][] = sprintf( '%s.%s', $oid, $columnIndex ); } } return $indexes; }
php
public function getIndexes( $oid ) { // load primary keys $query = new Query( "SELECT string_to_array( indkey::text, ' ') AS keys, * FROM pg_index WHERE indrelid = %oid:int%", array( 'oid' => $this->get('oid') ) ); $indexes = $this->db->query( $query )->fetch(Result::TYPE_DETECT); foreach( $this->indexes as &$index ) { $index['columns'] = array(); foreach( $index['keys'] as $columnIndex ) { $index['columns'][] = sprintf( '%s.%s', $oid, $columnIndex ); } } return $indexes; }
[ "public", "function", "getIndexes", "(", "$", "oid", ")", "{", "// load primary keys", "$", "query", "=", "new", "Query", "(", "\"SELECT string_to_array( indkey::text, ' ') AS keys, * FROM pg_index WHERE indrelid = %oid:int%\"", ",", "array", "(", "'oid'", "=>", "$", "this", "->", "get", "(", "'oid'", ")", ")", ")", ";", "$", "indexes", "=", "$", "this", "->", "db", "->", "query", "(", "$", "query", ")", "->", "fetch", "(", "Result", "::", "TYPE_DETECT", ")", ";", "foreach", "(", "$", "this", "->", "indexes", "as", "&", "$", "index", ")", "{", "$", "index", "[", "'columns'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "index", "[", "'keys'", "]", "as", "$", "columnIndex", ")", "{", "$", "index", "[", "'columns'", "]", "[", "]", "=", "sprintf", "(", "'%s.%s'", ",", "$", "oid", ",", "$", "columnIndex", ")", ";", "}", "}", "return", "$", "indexes", ";", "}" ]
Get relation indexes from a oid @param String $oid @return array()
[ "Get", "relation", "indexes", "from", "a", "oid" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Pg/Catalog/Repository/Attribute.php#L203-L230
train
squareproton/Bond
src/Bond/Pg/Catalog/Repository/Attribute.php
Attribute.findByIdentifier
public function findByIdentifier( $identifier ) { $identifier = explode('.', $identifier); if( count( $identifier) < 2 ) { throw new \InvalidArgumentException("yeah, not a table.column level identifier"); } $columnName = array_pop( $identifier ); $tableName = implode('.',$identifier ); $table = new Query( <<<SQL SELECT a.attrelid::text || '.' || a.attnum AS key FROM pg_attribute AS a WHERE a.attrelid = quote_ident(%tableName:%)::regclass::oid AND attname = %columnName:% AND a.attnum > 0 SQL , array( 'tableName' => $tableName, 'columnName' => $columnName, ) ); try { $columnKey = $this->db->query( $table )->fetch( Result::FETCH_SINGLE ); } catch( \Exception $e ) { return null; } return $this->find( $columnKey ); }
php
public function findByIdentifier( $identifier ) { $identifier = explode('.', $identifier); if( count( $identifier) < 2 ) { throw new \InvalidArgumentException("yeah, not a table.column level identifier"); } $columnName = array_pop( $identifier ); $tableName = implode('.',$identifier ); $table = new Query( <<<SQL SELECT a.attrelid::text || '.' || a.attnum AS key FROM pg_attribute AS a WHERE a.attrelid = quote_ident(%tableName:%)::regclass::oid AND attname = %columnName:% AND a.attnum > 0 SQL , array( 'tableName' => $tableName, 'columnName' => $columnName, ) ); try { $columnKey = $this->db->query( $table )->fetch( Result::FETCH_SINGLE ); } catch( \Exception $e ) { return null; } return $this->find( $columnKey ); }
[ "public", "function", "findByIdentifier", "(", "$", "identifier", ")", "{", "$", "identifier", "=", "explode", "(", "'.'", ",", "$", "identifier", ")", ";", "if", "(", "count", "(", "$", "identifier", ")", "<", "2", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"yeah, not a table.column level identifier\"", ")", ";", "}", "$", "columnName", "=", "array_pop", "(", "$", "identifier", ")", ";", "$", "tableName", "=", "implode", "(", "'.'", ",", "$", "identifier", ")", ";", "$", "table", "=", "new", "Query", "(", " <<<SQL\nSELECT\n a.attrelid::text || '.' || a.attnum AS key\nFROM\n pg_attribute AS a\nWHERE\n a.attrelid = quote_ident(%tableName:%)::regclass::oid AND\n attname = %columnName:% AND\n a.attnum > 0\nSQL", ",", "array", "(", "'tableName'", "=>", "$", "tableName", ",", "'columnName'", "=>", "$", "columnName", ",", ")", ")", ";", "try", "{", "$", "columnKey", "=", "$", "this", "->", "db", "->", "query", "(", "$", "table", ")", "->", "fetch", "(", "Result", "::", "FETCH_SINGLE", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "find", "(", "$", "columnKey", ")", ";", "}" ]
Initalise a attribute by a schema.table.column or table.column identifier AFAICT due to the ambiguity of the identifier this is probably best doen with a round trip to the database. It isn't slow. @return
[ "Initalise", "a", "attribute", "by", "a", "schema", ".", "table", ".", "column", "or", "table", ".", "column", "identifier", "AFAICT", "due", "to", "the", "ambiguity", "of", "the", "identifier", "this", "is", "probably", "best", "doen", "with", "a", "round", "trip", "to", "the", "database", ".", "It", "isn", "t", "slow", "." ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Pg/Catalog/Repository/Attribute.php#L237-L274
train
squareproton/Bond
src/Bond/Pg/Catalog/Repository/Attribute.php
Attribute.buildComments
protected function buildComments() { if( is_null( $this->comments ) ) { $this->comments = array(); } else { return; } $sql = <<<SQL SELECT a.attrelid::text || '.' || a.attnum AS key, d.description AS text FROM pg_attribute AS a INNER JOIN pg_description AS d ON a.attrelid = d.objoid AND a.attnum = d.objsubid AND d.classoid = 'pg_class'::regclass::oid WHERE a.attnum > 0 ; SQL ; $comments = $this->db->query( new Query( $sql ) )->fetch(); // key the array and populate static cache foreach( $comments as $comment ) { $this->comments[$comment['key']] = $comment['text']; } }
php
protected function buildComments() { if( is_null( $this->comments ) ) { $this->comments = array(); } else { return; } $sql = <<<SQL SELECT a.attrelid::text || '.' || a.attnum AS key, d.description AS text FROM pg_attribute AS a INNER JOIN pg_description AS d ON a.attrelid = d.objoid AND a.attnum = d.objsubid AND d.classoid = 'pg_class'::regclass::oid WHERE a.attnum > 0 ; SQL ; $comments = $this->db->query( new Query( $sql ) )->fetch(); // key the array and populate static cache foreach( $comments as $comment ) { $this->comments[$comment['key']] = $comment['text']; } }
[ "protected", "function", "buildComments", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "comments", ")", ")", "{", "$", "this", "->", "comments", "=", "array", "(", ")", ";", "}", "else", "{", "return", ";", "}", "$", "sql", "=", " <<<SQL\nSELECT\n a.attrelid::text || '.' || a.attnum AS key,\n d.description AS text\nFROM\n pg_attribute AS a\nINNER JOIN\n pg_description AS d ON\n a.attrelid = d.objoid AND\n a.attnum = d.objsubid AND\n d.classoid = 'pg_class'::regclass::oid\nWHERE\n a.attnum > 0\n;\nSQL", ";", "$", "comments", "=", "$", "this", "->", "db", "->", "query", "(", "new", "Query", "(", "$", "sql", ")", ")", "->", "fetch", "(", ")", ";", "// key the array and populate static cache", "foreach", "(", "$", "comments", "as", "$", "comment", ")", "{", "$", "this", "->", "comments", "[", "$", "comment", "[", "'key'", "]", "]", "=", "$", "comment", "[", "'text'", "]", ";", "}", "}" ]
It's a hassle complicating all the column source queries with a join to pg_description. This is a lazy load comment solution. Midly hacky.
[ "It", "s", "a", "hassle", "complicating", "all", "the", "column", "source", "queries", "with", "a", "join", "to", "pg_description", ".", "This", "is", "a", "lazy", "load", "comment", "solution", ".", "Midly", "hacky", "." ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Pg/Catalog/Repository/Attribute.php#L316-L349
train
t-kanstantsin/fileupload
src/formatter/adapter/Watermark.php
Watermark.getWatermark
private function getWatermark(ImagineInterface $imagine): ?ImageInterface { $resource = null; if ($this->getMarkFilepath() !== null) { $resource = fopen($this->getMarkFilepath(), 'rb'); } elseif (\is_string($this->markContent)) { $resource = 'a'; // TODO: create resource. } elseif (\is_resource($this->markContent)) { $resource = $this->markContent; } if ($resource === null) { return null; } return $imagine->read($resource); }
php
private function getWatermark(ImagineInterface $imagine): ?ImageInterface { $resource = null; if ($this->getMarkFilepath() !== null) { $resource = fopen($this->getMarkFilepath(), 'rb'); } elseif (\is_string($this->markContent)) { $resource = 'a'; // TODO: create resource. } elseif (\is_resource($this->markContent)) { $resource = $this->markContent; } if ($resource === null) { return null; } return $imagine->read($resource); }
[ "private", "function", "getWatermark", "(", "ImagineInterface", "$", "imagine", ")", ":", "?", "ImageInterface", "{", "$", "resource", "=", "null", ";", "if", "(", "$", "this", "->", "getMarkFilepath", "(", ")", "!==", "null", ")", "{", "$", "resource", "=", "fopen", "(", "$", "this", "->", "getMarkFilepath", "(", ")", ",", "'rb'", ")", ";", "}", "elseif", "(", "\\", "is_string", "(", "$", "this", "->", "markContent", ")", ")", "{", "$", "resource", "=", "'a'", ";", "// TODO: create resource.", "}", "elseif", "(", "\\", "is_resource", "(", "$", "this", "->", "markContent", ")", ")", "{", "$", "resource", "=", "$", "this", "->", "markContent", ";", "}", "if", "(", "$", "resource", "===", "null", ")", "{", "return", "null", ";", "}", "return", "$", "imagine", "->", "read", "(", "$", "resource", ")", ";", "}" ]
Get watermark image @param ImagineInterface $imagine @return ImageInterface|null @throws \Imagine\Exception\RuntimeException @throws \UnexpectedValueException @throws \ErrorException
[ "Get", "watermark", "image" ]
d6317a9b9b36d992f09affe3900ef7d7ddfd855f
https://github.com/t-kanstantsin/fileupload/blob/d6317a9b9b36d992f09affe3900ef7d7ddfd855f/src/formatter/adapter/Watermark.php#L119-L135
train
rafflesargentina/l5-filterable-sortable
src/QueryFilters.php
QueryFilters.getAppliedFilters
public static function getAppliedFilters() { $classMethods = get_class_methods(get_class()); $calledClassMethods = get_class_methods(get_called_class()); $filteredMethods = array_filter( $calledClassMethods, function ($calledClassMethod) use ($classMethods) { return !in_array($calledClassMethod, $classMethods, true); } ); return \Illuminate\Support\Facades\Request::only($filteredMethods); }
php
public static function getAppliedFilters() { $classMethods = get_class_methods(get_class()); $calledClassMethods = get_class_methods(get_called_class()); $filteredMethods = array_filter( $calledClassMethods, function ($calledClassMethod) use ($classMethods) { return !in_array($calledClassMethod, $classMethods, true); } ); return \Illuminate\Support\Facades\Request::only($filteredMethods); }
[ "public", "static", "function", "getAppliedFilters", "(", ")", "{", "$", "classMethods", "=", "get_class_methods", "(", "get_class", "(", ")", ")", ";", "$", "calledClassMethods", "=", "get_class_methods", "(", "get_called_class", "(", ")", ")", ";", "$", "filteredMethods", "=", "array_filter", "(", "$", "calledClassMethods", ",", "function", "(", "$", "calledClassMethod", ")", "use", "(", "$", "classMethods", ")", "{", "return", "!", "in_array", "(", "$", "calledClassMethod", ",", "$", "classMethods", ",", "true", ")", ";", "}", ")", ";", "return", "\\", "Illuminate", "\\", "Support", "\\", "Facades", "\\", "Request", "::", "only", "(", "$", "filteredMethods", ")", ";", "}" ]
Get applied filters from request. @return array
[ "Get", "applied", "filters", "from", "request", "." ]
eb3ecf399145ec7c5241ba2134ed0bea2057e6c3
https://github.com/rafflesargentina/l5-filterable-sortable/blob/eb3ecf399145ec7c5241ba2134ed0bea2057e6c3/src/QueryFilters.php#L71-L83
train
Mohiohio/wordpress-lib
src/Admin.php
Admin.add_field
function add_field($name, $title=null, \Closure $display_callback=null, Setting\Section $section=null, $default=null) { if(is_array($name)){ $field = $name + [ $display_callback=null, $section = null, $default = null, $type = 'text' ]; } else { //legacy full param format $field = compact('name','title','display_callback','section'); } if(empty($field['section'])){ $field['section'] = $this->get_default_section(); } $this->fields[$field['name']] = $field; }
php
function add_field($name, $title=null, \Closure $display_callback=null, Setting\Section $section=null, $default=null) { if(is_array($name)){ $field = $name + [ $display_callback=null, $section = null, $default = null, $type = 'text' ]; } else { //legacy full param format $field = compact('name','title','display_callback','section'); } if(empty($field['section'])){ $field['section'] = $this->get_default_section(); } $this->fields[$field['name']] = $field; }
[ "function", "add_field", "(", "$", "name", ",", "$", "title", "=", "null", ",", "\\", "Closure", "$", "display_callback", "=", "null", ",", "Setting", "\\", "Section", "$", "section", "=", "null", ",", "$", "default", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", "$", "field", "=", "$", "name", "+", "[", "$", "display_callback", "=", "null", ",", "$", "section", "=", "null", ",", "$", "default", "=", "null", ",", "$", "type", "=", "'text'", "]", ";", "}", "else", "{", "//legacy full param format", "$", "field", "=", "compact", "(", "'name'", ",", "'title'", ",", "'display_callback'", ",", "'section'", ")", ";", "}", "if", "(", "empty", "(", "$", "field", "[", "'section'", "]", ")", ")", "{", "$", "field", "[", "'section'", "]", "=", "$", "this", "->", "get_default_section", "(", ")", ";", "}", "$", "this", "->", "fields", "[", "$", "field", "[", "'name'", "]", "]", "=", "$", "field", ";", "}" ]
Just pass name which is an assoc array - what you see here are legacy params
[ "Just", "pass", "name", "which", "is", "an", "assoc", "array", "-", "what", "you", "see", "here", "are", "legacy", "params" ]
10ff55bc02a1e48c3e53a8a80bd5a0f3d14736af
https://github.com/Mohiohio/wordpress-lib/blob/10ff55bc02a1e48c3e53a8a80bd5a0f3d14736af/src/Admin.php#L26-L47
train
attogram/shared-media-orm
src/Attogram/SharedMedia/Orm/PageQuery.php
PageQuery.format
public function format(array $response) { $car = '<br />'; $format = ''; foreach ($response as $page) { $format .= '<div class="page"><span class="title">' . ApiTools::safeString($page->getTitle()) . '</span>' .$car . 'pageid: <span class="pageid">' . $page->getPageid() . '</span>' .$car . 'displaytitle: ' . ApiTools::safeString($page->getDisplaytitle()) .$car . 'page_image_free: ' . $page->getPageImageFree() .$car . 'wikibase_item: ' . $page->getWikibaseItem() .$car . 'disambiguation: ' . $page->getDisambiguation() .$car . 'defaultsort: ' . $page->getDefaultsort() .'</div>'; } return $format; }
php
public function format(array $response) { $car = '<br />'; $format = ''; foreach ($response as $page) { $format .= '<div class="page"><span class="title">' . ApiTools::safeString($page->getTitle()) . '</span>' .$car . 'pageid: <span class="pageid">' . $page->getPageid() . '</span>' .$car . 'displaytitle: ' . ApiTools::safeString($page->getDisplaytitle()) .$car . 'page_image_free: ' . $page->getPageImageFree() .$car . 'wikibase_item: ' . $page->getWikibaseItem() .$car . 'disambiguation: ' . $page->getDisambiguation() .$car . 'defaultsort: ' . $page->getDefaultsort() .'</div>'; } return $format; }
[ "public", "function", "format", "(", "array", "$", "response", ")", "{", "$", "car", "=", "'<br />'", ";", "$", "format", "=", "''", ";", "foreach", "(", "$", "response", "as", "$", "page", ")", "{", "$", "format", ".=", "'<div class=\"page\"><span class=\"title\">'", ".", "ApiTools", "::", "safeString", "(", "$", "page", "->", "getTitle", "(", ")", ")", ".", "'</span>'", ".", "$", "car", ".", "'pageid: <span class=\"pageid\">'", ".", "$", "page", "->", "getPageid", "(", ")", ".", "'</span>'", ".", "$", "car", ".", "'displaytitle: '", ".", "ApiTools", "::", "safeString", "(", "$", "page", "->", "getDisplaytitle", "(", ")", ")", ".", "$", "car", ".", "'page_image_free: '", ".", "$", "page", "->", "getPageImageFree", "(", ")", ".", "$", "car", ".", "'wikibase_item: '", ".", "$", "page", "->", "getWikibaseItem", "(", ")", ".", "$", "car", ".", "'disambiguation: '", ".", "$", "page", "->", "getDisambiguation", "(", ")", ".", "$", "car", ".", "'defaultsort: '", ".", "$", "page", "->", "getDefaultsort", "(", ")", ".", "'</div>'", ";", "}", "return", "$", "format", ";", "}" ]
format a page response as an HTML string @param array $response @return string
[ "format", "a", "page", "response", "as", "an", "HTML", "string" ]
81b5ef7d749b1e50f51e95747ce24cf8ce6f21d8
https://github.com/attogram/shared-media-orm/blob/81b5ef7d749b1e50f51e95747ce24cf8ce6f21d8/src/Attogram/SharedMedia/Orm/PageQuery.php#L81-L97
train
nattreid/mailing
src/Mail.php
Mail.setCommand
public function setCommand(string $args): self { if ($this->mailer instanceof SendmailMailer) { $this->mailer->commandArgs = $args; } return $this; }
php
public function setCommand(string $args): self { if ($this->mailer instanceof SendmailMailer) { $this->mailer->commandArgs = $args; } return $this; }
[ "public", "function", "setCommand", "(", "string", "$", "args", ")", ":", "self", "{", "if", "(", "$", "this", "->", "mailer", "instanceof", "SendmailMailer", ")", "{", "$", "this", "->", "mailer", "->", "commandArgs", "=", "$", "args", ";", "}", "return", "$", "this", ";", "}" ]
Nastavi argumenty pro mailer @param string $args @return self
[ "Nastavi", "argumenty", "pro", "mailer" ]
d61750a47c38d7533294d74d6601ca99a25f1b7c
https://github.com/nattreid/mailing/blob/d61750a47c38d7533294d74d6601ca99a25f1b7c/src/Mail.php#L137-L143
train
hiqdev/minii-helpers
src/BaseStringHelper.php
BaseStringHelper.explode
public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false) { $result = explode($delimiter, $string); if ($trim) { if ($trim === true) { $trim = 'trim'; } elseif (!is_callable($trim)) { $trim = function ($v) use ($trim) { return trim($v, $trim); }; } $result = array_map($trim, $result); } if ($skipEmpty) { // Wrapped with array_values to make array keys sequential after empty values removing $result = array_values(array_filter($result)); } return $result; }
php
public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false) { $result = explode($delimiter, $string); if ($trim) { if ($trim === true) { $trim = 'trim'; } elseif (!is_callable($trim)) { $trim = function ($v) use ($trim) { return trim($v, $trim); }; } $result = array_map($trim, $result); } if ($skipEmpty) { // Wrapped with array_values to make array keys sequential after empty values removing $result = array_values(array_filter($result)); } return $result; }
[ "public", "static", "function", "explode", "(", "$", "string", ",", "$", "delimiter", "=", "','", ",", "$", "trim", "=", "true", ",", "$", "skipEmpty", "=", "false", ")", "{", "$", "result", "=", "explode", "(", "$", "delimiter", ",", "$", "string", ")", ";", "if", "(", "$", "trim", ")", "{", "if", "(", "$", "trim", "===", "true", ")", "{", "$", "trim", "=", "'trim'", ";", "}", "elseif", "(", "!", "is_callable", "(", "$", "trim", ")", ")", "{", "$", "trim", "=", "function", "(", "$", "v", ")", "use", "(", "$", "trim", ")", "{", "return", "trim", "(", "$", "v", ",", "$", "trim", ")", ";", "}", ";", "}", "$", "result", "=", "array_map", "(", "$", "trim", ",", "$", "result", ")", ";", "}", "if", "(", "$", "skipEmpty", ")", "{", "// Wrapped with array_values to make array keys sequential after empty values removing", "$", "result", "=", "array_values", "(", "array_filter", "(", "$", "result", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Explodes string into array, optionally trims values and skips empty ones @param string $string String to be exploded. @param string $delimiter Delimiter. Default is ','. @param mixed $trim Whether to trim each element. Can be: - boolean - to trim normally; - string - custom characters to trim. Will be passed as a second argument to `trim()` function. - callable - will be called for each value instead of trim. Takes the only argument - value. @param boolean $skipEmpty Whether to skip empty strings between delimiters. Default is false. @return array @since 2.0.4
[ "Explodes", "string", "into", "array", "optionally", "trims", "values", "and", "skips", "empty", "ones" ]
001b7a56a6ebdc432c4683fe47c00a913f8e57d7
https://github.com/hiqdev/minii-helpers/blob/001b7a56a6ebdc432c4683fe47c00a913f8e57d7/src/BaseStringHelper.php#L252-L270
train
freialib/hlin.archetype
src/Mock/Filesystem.php
FilesystemMock.&
function & mock_mount(array $fs, $mountpoint = '~/approot') { $mountpoint = str_replace('~', $this->mock_homedir, trim($mountpoint, '/')); $normalizedfs = $this->mock_normalize($fs); $path = & $this->mock_ensurepath($mountpoint); $this->mock_fsmerge($path, $normalizedfs); return $path; }
php
function & mock_mount(array $fs, $mountpoint = '~/approot') { $mountpoint = str_replace('~', $this->mock_homedir, trim($mountpoint, '/')); $normalizedfs = $this->mock_normalize($fs); $path = & $this->mock_ensurepath($mountpoint); $this->mock_fsmerge($path, $normalizedfs); return $path; }
[ "function", "&", "mock_mount", "(", "array", "$", "fs", ",", "$", "mountpoint", "=", "'~/approot'", ")", "{", "$", "mountpoint", "=", "str_replace", "(", "'~'", ",", "$", "this", "->", "mock_homedir", ",", "trim", "(", "$", "mountpoint", ",", "'/'", ")", ")", ";", "$", "normalizedfs", "=", "$", "this", "->", "mock_normalize", "(", "$", "fs", ")", ";", "$", "path", "=", "&", "$", "this", "->", "mock_ensurepath", "(", "$", "mountpoint", ")", ";", "$", "this", "->", "mock_fsmerge", "(", "$", "path", ",", "$", "normalizedfs", ")", ";", "return", "$", "path", ";", "}" ]
Mount virtual filesystem at specified location. @return array path reference
[ "Mount", "virtual", "filesystem", "at", "specified", "location", "." ]
d8750a9bf4b7efb8063899969e3f39c1915c423a
https://github.com/freialib/hlin.archetype/blob/d8750a9bf4b7efb8063899969e3f39c1915c423a/src/Mock/Filesystem.php#L50-L58
train
freialib/hlin.archetype
src/Mock/Filesystem.php
FilesystemMock.mock_fsmerge
function mock_fsmerge( & $fs, & $comp) { if (isset($comp['%type']) && $comp['%type'] == 'file') { throw new \Exception('[Mock] Tried to copy file as directory.'); } // map existing files $existing_files = []; foreach ($fs as $node => $file) { if (is_integer($node)) { $existing_files[] = $file['filename']; } } // merge foreach ($comp as $node => $file) { if (is_integer($node)) { if (in_array($file['filename'], $existing_files)) { throw new \Exception("[Mock] Tried to overwrite file: {$file['filename']}"); } $fs[] = $file; } else if ($node[0] == '%') { // attribute $fs[$node] = $file; } else { // dir isset($fs[$node]) or $fs[$node] = []; $this->mock_fsmerge($fs[$node], $file); } } }
php
function mock_fsmerge( & $fs, & $comp) { if (isset($comp['%type']) && $comp['%type'] == 'file') { throw new \Exception('[Mock] Tried to copy file as directory.'); } // map existing files $existing_files = []; foreach ($fs as $node => $file) { if (is_integer($node)) { $existing_files[] = $file['filename']; } } // merge foreach ($comp as $node => $file) { if (is_integer($node)) { if (in_array($file['filename'], $existing_files)) { throw new \Exception("[Mock] Tried to overwrite file: {$file['filename']}"); } $fs[] = $file; } else if ($node[0] == '%') { // attribute $fs[$node] = $file; } else { // dir isset($fs[$node]) or $fs[$node] = []; $this->mock_fsmerge($fs[$node], $file); } } }
[ "function", "mock_fsmerge", "(", "&", "$", "fs", ",", "&", "$", "comp", ")", "{", "if", "(", "isset", "(", "$", "comp", "[", "'%type'", "]", ")", "&&", "$", "comp", "[", "'%type'", "]", "==", "'file'", ")", "{", "throw", "new", "\\", "Exception", "(", "'[Mock] Tried to copy file as directory.'", ")", ";", "}", "// map existing files", "$", "existing_files", "=", "[", "]", ";", "foreach", "(", "$", "fs", "as", "$", "node", "=>", "$", "file", ")", "{", "if", "(", "is_integer", "(", "$", "node", ")", ")", "{", "$", "existing_files", "[", "]", "=", "$", "file", "[", "'filename'", "]", ";", "}", "}", "// merge", "foreach", "(", "$", "comp", "as", "$", "node", "=>", "$", "file", ")", "{", "if", "(", "is_integer", "(", "$", "node", ")", ")", "{", "if", "(", "in_array", "(", "$", "file", "[", "'filename'", "]", ",", "$", "existing_files", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"[Mock] Tried to overwrite file: {$file['filename']}\"", ")", ";", "}", "$", "fs", "[", "]", "=", "$", "file", ";", "}", "else", "if", "(", "$", "node", "[", "0", "]", "==", "'%'", ")", "{", "// attribute", "$", "fs", "[", "$", "node", "]", "=", "$", "file", ";", "}", "else", "{", "// dir", "isset", "(", "$", "fs", "[", "$", "node", "]", ")", "or", "$", "fs", "[", "$", "node", "]", "=", "[", "]", ";", "$", "this", "->", "mock_fsmerge", "(", "$", "fs", "[", "$", "node", "]", ",", "$", "file", ")", ";", "}", "}", "}" ]
Merges two file system definitions togheter.
[ "Merges", "two", "file", "system", "definitions", "togheter", "." ]
d8750a9bf4b7efb8063899969e3f39c1915c423a
https://github.com/freialib/hlin.archetype/blob/d8750a9bf4b7efb8063899969e3f39c1915c423a/src/Mock/Filesystem.php#L63-L92
train
projek-xyz/ci-installer
src/ComposerInstaller.php
ComposerInstaller.getModuleMigrations
protected function getModuleMigrations($downloadPath, $moduleMigrationPath = 'asset/data') { $moduleMigrationPath = trim($moduleMigrationPath, '/'); $moduleMigrations = glob($downloadPath . '/' . $moduleMigrationPath . '/*.php'); sort($moduleMigrations); return $moduleMigrations; }
php
protected function getModuleMigrations($downloadPath, $moduleMigrationPath = 'asset/data') { $moduleMigrationPath = trim($moduleMigrationPath, '/'); $moduleMigrations = glob($downloadPath . '/' . $moduleMigrationPath . '/*.php'); sort($moduleMigrations); return $moduleMigrations; }
[ "protected", "function", "getModuleMigrations", "(", "$", "downloadPath", ",", "$", "moduleMigrationPath", "=", "'asset/data'", ")", "{", "$", "moduleMigrationPath", "=", "trim", "(", "$", "moduleMigrationPath", ",", "'/'", ")", ";", "$", "moduleMigrations", "=", "glob", "(", "$", "downloadPath", ".", "'/'", ".", "$", "moduleMigrationPath", ".", "'/*.php'", ")", ";", "sort", "(", "$", "moduleMigrations", ")", ";", "return", "$", "moduleMigrations", ";", "}" ]
Check if module have migrations files @param string $downloadPath Module download path @param string $moduleMigrationPath Module migration path it's relative to $download path and any slash will be trimmed @return bool
[ "Check", "if", "module", "have", "migrations", "files" ]
2628fa58e5298460f3f6595e369bb94ab7bd8003
https://github.com/projek-xyz/ci-installer/blob/2628fa58e5298460f3f6595e369bb94ab7bd8003/src/ComposerInstaller.php#L173-L180
train
projek-xyz/ci-installer
src/ComposerInstaller.php
ComposerInstaller.copyModuleMigrations
protected function copyModuleMigrations(array $config, array $moduleMigrations) { $migrationPath = $this->checkMigrationsPath($config); if ($migrationPath === false) { return false; } $migrations = glob($migrationPath . '*.php'); $old_migration_names = array(); $copied = 0; sort($migrations); foreach ($migrations as $migration) { $old_migration_names[] = $this->getMigrationName($migration); } if (isset($config['migration_type']) && $config['migration_type'] === 'timestamp') { $number = (int) date('YmdHis'); } else { // Get the latest migration number and increment if (count($migrations) > 0) { $migration = array_pop($migrations); $number = ((int) basename($migration)) + 1; } else { $number = 1; } } // Copy each migration into the application migration directory foreach ($moduleMigrations as $migration) { if (array_search($this->getMigrationName($migration), $old_migration_names) === false) { // Re-number the migration $newMigration = $migrationPath . preg_replace('/^(\d+)/', sprintf('%03d', $number), basename($migration)); // Copy the migration file copy($migration, $newMigration); $number++; $copied++; } } return $copied; }
php
protected function copyModuleMigrations(array $config, array $moduleMigrations) { $migrationPath = $this->checkMigrationsPath($config); if ($migrationPath === false) { return false; } $migrations = glob($migrationPath . '*.php'); $old_migration_names = array(); $copied = 0; sort($migrations); foreach ($migrations as $migration) { $old_migration_names[] = $this->getMigrationName($migration); } if (isset($config['migration_type']) && $config['migration_type'] === 'timestamp') { $number = (int) date('YmdHis'); } else { // Get the latest migration number and increment if (count($migrations) > 0) { $migration = array_pop($migrations); $number = ((int) basename($migration)) + 1; } else { $number = 1; } } // Copy each migration into the application migration directory foreach ($moduleMigrations as $migration) { if (array_search($this->getMigrationName($migration), $old_migration_names) === false) { // Re-number the migration $newMigration = $migrationPath . preg_replace('/^(\d+)/', sprintf('%03d', $number), basename($migration)); // Copy the migration file copy($migration, $newMigration); $number++; $copied++; } } return $copied; }
[ "protected", "function", "copyModuleMigrations", "(", "array", "$", "config", ",", "array", "$", "moduleMigrations", ")", "{", "$", "migrationPath", "=", "$", "this", "->", "checkMigrationsPath", "(", "$", "config", ")", ";", "if", "(", "$", "migrationPath", "===", "false", ")", "{", "return", "false", ";", "}", "$", "migrations", "=", "glob", "(", "$", "migrationPath", ".", "'*.php'", ")", ";", "$", "old_migration_names", "=", "array", "(", ")", ";", "$", "copied", "=", "0", ";", "sort", "(", "$", "migrations", ")", ";", "foreach", "(", "$", "migrations", "as", "$", "migration", ")", "{", "$", "old_migration_names", "[", "]", "=", "$", "this", "->", "getMigrationName", "(", "$", "migration", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'migration_type'", "]", ")", "&&", "$", "config", "[", "'migration_type'", "]", "===", "'timestamp'", ")", "{", "$", "number", "=", "(", "int", ")", "date", "(", "'YmdHis'", ")", ";", "}", "else", "{", "// Get the latest migration number and increment", "if", "(", "count", "(", "$", "migrations", ")", ">", "0", ")", "{", "$", "migration", "=", "array_pop", "(", "$", "migrations", ")", ";", "$", "number", "=", "(", "(", "int", ")", "basename", "(", "$", "migration", ")", ")", "+", "1", ";", "}", "else", "{", "$", "number", "=", "1", ";", "}", "}", "// Copy each migration into the application migration directory", "foreach", "(", "$", "moduleMigrations", "as", "$", "migration", ")", "{", "if", "(", "array_search", "(", "$", "this", "->", "getMigrationName", "(", "$", "migration", ")", ",", "$", "old_migration_names", ")", "===", "false", ")", "{", "// Re-number the migration", "$", "newMigration", "=", "$", "migrationPath", ".", "preg_replace", "(", "'/^(\\d+)/'", ",", "sprintf", "(", "'%03d'", ",", "$", "number", ")", ",", "basename", "(", "$", "migration", ")", ")", ";", "// Copy the migration file", "copy", "(", "$", "migration", ",", "$", "newMigration", ")", ";", "$", "number", "++", ";", "$", "copied", "++", ";", "}", "}", "return", "$", "copied", ";", "}" ]
Copy all module migration files to application migration directory @param array $config Migration configs @param array $moduleMigrations Module migration file list @return void
[ "Copy", "all", "module", "migration", "files", "to", "application", "migration", "directory" ]
2628fa58e5298460f3f6595e369bb94ab7bd8003
https://github.com/projek-xyz/ci-installer/blob/2628fa58e5298460f3f6595e369bb94ab7bd8003/src/ComposerInstaller.php#L189-L233
train
projek-xyz/ci-installer
src/ComposerInstaller.php
ComposerInstaller.checkMigrationsPath
protected function checkMigrationsPath(array $config) { // Check if $config['migration_path'] is already defined $migrationPath = isset($config['migration_path']) ? $config['migration_path'] : false; $migrationPath = str_replace('FCPATH', '', $migrationPath); // Check if $config['migration_path'] directory is not available yet, create new one if ($migrationPath !== false && !is_dir($migrationPath)) { mkdir($migrationPath, 0755, true); } return $migrationPath; }
php
protected function checkMigrationsPath(array $config) { // Check if $config['migration_path'] is already defined $migrationPath = isset($config['migration_path']) ? $config['migration_path'] : false; $migrationPath = str_replace('FCPATH', '', $migrationPath); // Check if $config['migration_path'] directory is not available yet, create new one if ($migrationPath !== false && !is_dir($migrationPath)) { mkdir($migrationPath, 0755, true); } return $migrationPath; }
[ "protected", "function", "checkMigrationsPath", "(", "array", "$", "config", ")", "{", "// Check if $config['migration_path'] is already defined", "$", "migrationPath", "=", "isset", "(", "$", "config", "[", "'migration_path'", "]", ")", "?", "$", "config", "[", "'migration_path'", "]", ":", "false", ";", "$", "migrationPath", "=", "str_replace", "(", "'FCPATH'", ",", "''", ",", "$", "migrationPath", ")", ";", "// Check if $config['migration_path'] directory is not available yet, create new one", "if", "(", "$", "migrationPath", "!==", "false", "&&", "!", "is_dir", "(", "$", "migrationPath", ")", ")", "{", "mkdir", "(", "$", "migrationPath", ",", "0755", ",", "true", ")", ";", "}", "return", "$", "migrationPath", ";", "}" ]
Check Application Migrations path, if not available it will create new one @param array $config Migration configuration @return string
[ "Check", "Application", "Migrations", "path", "if", "not", "available", "it", "will", "create", "new", "one" ]
2628fa58e5298460f3f6595e369bb94ab7bd8003
https://github.com/projek-xyz/ci-installer/blob/2628fa58e5298460f3f6595e369bb94ab7bd8003/src/ComposerInstaller.php#L254-L266
train
projek-xyz/ci-installer
src/ComposerInstaller.php
ComposerInstaller.getMigrationConfig
protected function getMigrationConfig($downloadPath) { $extra = ($pkg = $this->composer->getPackage()) ? $pkg->getExtra() : array(); // Check CI APPPATH $appPath = defined('APPPATH') ? APPPATH : $extra['codeigniter-application-dir']; // $appPath = defined('APPPATH') ? APPPATH : dirname(dirname($downloadPath)); // Load CI Migration Config @include $appPath . '/config/migration.php'; return isset($config) ? $config : array(); }
php
protected function getMigrationConfig($downloadPath) { $extra = ($pkg = $this->composer->getPackage()) ? $pkg->getExtra() : array(); // Check CI APPPATH $appPath = defined('APPPATH') ? APPPATH : $extra['codeigniter-application-dir']; // $appPath = defined('APPPATH') ? APPPATH : dirname(dirname($downloadPath)); // Load CI Migration Config @include $appPath . '/config/migration.php'; return isset($config) ? $config : array(); }
[ "protected", "function", "getMigrationConfig", "(", "$", "downloadPath", ")", "{", "$", "extra", "=", "(", "$", "pkg", "=", "$", "this", "->", "composer", "->", "getPackage", "(", ")", ")", "?", "$", "pkg", "->", "getExtra", "(", ")", ":", "array", "(", ")", ";", "// Check CI APPPATH", "$", "appPath", "=", "defined", "(", "'APPPATH'", ")", "?", "APPPATH", ":", "$", "extra", "[", "'codeigniter-application-dir'", "]", ";", "// $appPath = defined('APPPATH') ? APPPATH : dirname(dirname($downloadPath));", "// Load CI Migration Config", "@", "include", "$", "appPath", ".", "'/config/migration.php'", ";", "return", "isset", "(", "$", "config", ")", "?", "$", "config", ":", "array", "(", ")", ";", "}" ]
Get migration configurations @return array
[ "Get", "migration", "configurations" ]
2628fa58e5298460f3f6595e369bb94ab7bd8003
https://github.com/projek-xyz/ci-installer/blob/2628fa58e5298460f3f6595e369bb94ab7bd8003/src/ComposerInstaller.php#L273-L283
train
e-commit/EcommitUtilBundle
Helper/UtilHelper.php
UtilHelper.tag
public function tag($name, Array $options = array(), $content = null, $open = false) { if (!$name) { return ''; } $htmlOptions = ''; foreach ($options as $key => $value) { $htmlOptions .= ' ' . $key . '="' . \htmlspecialchars($value, \ENT_COMPAT) . '"'; } if ($content !== null) { return '<' . $name . $htmlOptions . '>' . $content . '</' . $name . '>'; } else { return '<' . $name . $htmlOptions . (($open) ? '>' : ' />'); } }
php
public function tag($name, Array $options = array(), $content = null, $open = false) { if (!$name) { return ''; } $htmlOptions = ''; foreach ($options as $key => $value) { $htmlOptions .= ' ' . $key . '="' . \htmlspecialchars($value, \ENT_COMPAT) . '"'; } if ($content !== null) { return '<' . $name . $htmlOptions . '>' . $content . '</' . $name . '>'; } else { return '<' . $name . $htmlOptions . (($open) ? '>' : ' />'); } }
[ "public", "function", "tag", "(", "$", "name", ",", "Array", "$", "options", "=", "array", "(", ")", ",", "$", "content", "=", "null", ",", "$", "open", "=", "false", ")", "{", "if", "(", "!", "$", "name", ")", "{", "return", "''", ";", "}", "$", "htmlOptions", "=", "''", ";", "foreach", "(", "$", "options", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "htmlOptions", ".=", "' '", ".", "$", "key", ".", "'=\"'", ".", "\\", "htmlspecialchars", "(", "$", "value", ",", "\\", "ENT_COMPAT", ")", ".", "'\"'", ";", "}", "if", "(", "$", "content", "!==", "null", ")", "{", "return", "'<'", ".", "$", "name", ".", "$", "htmlOptions", ".", "'>'", ".", "$", "content", ".", "'</'", ".", "$", "name", ".", "'>'", ";", "}", "else", "{", "return", "'<'", ".", "$", "name", ".", "$", "htmlOptions", ".", "(", "(", "$", "open", ")", "?", "'>'", ":", "' />'", ")", ";", "}", "}" ]
Constructs an html tag @param string $name Tag name @param array $options Tag options @param string $content Content @param bool $open True to leave tag open @return string
[ "Constructs", "an", "html", "tag" ]
2ee5ddae7709e8ad4412739cbecda28e0590da8b
https://github.com/e-commit/EcommitUtilBundle/blob/2ee5ddae7709e8ad4412739cbecda28e0590da8b/Helper/UtilHelper.php#L63-L77
train
ekyna/Resource
Model/TranslatableTrait.php
TranslatableTrait.translate
public function translate($locale = null, $create = false) { $locale = $locale ?: $this->currentLocale; if (null === $locale) { throw new \RuntimeException('No locale has been set and current locale is undefined.'); } if ($this->currentTranslation && $locale === $this->currentTranslation->getLocale()) { return $this->currentTranslation; } if (!$translation = $this->translations->get($locale)) { if ($create) { $className = $this->getTranslationClass(); /** @var TranslationInterface $translation */ $translation = new $className(); $translation->setLocale($locale); $this->addTranslation($translation); } else { if (null === $this->fallbackLocale) { throw new \RuntimeException('No fallback locale has been set.'); } if (!$fallbackTranslation = $this->translations->get($this->getFallbackLocale())) { $className = $this->getTranslationClass(); /** @var TranslationInterface $translation */ $translation = new $className(); $translation->setLocale($locale); $this->addTranslation($translation); } else { $translation = clone $fallbackTranslation; } } } $this->currentTranslation = $translation; $this->currentLocale = $locale; return $translation; }
php
public function translate($locale = null, $create = false) { $locale = $locale ?: $this->currentLocale; if (null === $locale) { throw new \RuntimeException('No locale has been set and current locale is undefined.'); } if ($this->currentTranslation && $locale === $this->currentTranslation->getLocale()) { return $this->currentTranslation; } if (!$translation = $this->translations->get($locale)) { if ($create) { $className = $this->getTranslationClass(); /** @var TranslationInterface $translation */ $translation = new $className(); $translation->setLocale($locale); $this->addTranslation($translation); } else { if (null === $this->fallbackLocale) { throw new \RuntimeException('No fallback locale has been set.'); } if (!$fallbackTranslation = $this->translations->get($this->getFallbackLocale())) { $className = $this->getTranslationClass(); /** @var TranslationInterface $translation */ $translation = new $className(); $translation->setLocale($locale); $this->addTranslation($translation); } else { $translation = clone $fallbackTranslation; } } } $this->currentTranslation = $translation; $this->currentLocale = $locale; return $translation; }
[ "public", "function", "translate", "(", "$", "locale", "=", "null", ",", "$", "create", "=", "false", ")", "{", "$", "locale", "=", "$", "locale", "?", ":", "$", "this", "->", "currentLocale", ";", "if", "(", "null", "===", "$", "locale", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'No locale has been set and current locale is undefined.'", ")", ";", "}", "if", "(", "$", "this", "->", "currentTranslation", "&&", "$", "locale", "===", "$", "this", "->", "currentTranslation", "->", "getLocale", "(", ")", ")", "{", "return", "$", "this", "->", "currentTranslation", ";", "}", "if", "(", "!", "$", "translation", "=", "$", "this", "->", "translations", "->", "get", "(", "$", "locale", ")", ")", "{", "if", "(", "$", "create", ")", "{", "$", "className", "=", "$", "this", "->", "getTranslationClass", "(", ")", ";", "/** @var TranslationInterface $translation */", "$", "translation", "=", "new", "$", "className", "(", ")", ";", "$", "translation", "->", "setLocale", "(", "$", "locale", ")", ";", "$", "this", "->", "addTranslation", "(", "$", "translation", ")", ";", "}", "else", "{", "if", "(", "null", "===", "$", "this", "->", "fallbackLocale", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'No fallback locale has been set.'", ")", ";", "}", "if", "(", "!", "$", "fallbackTranslation", "=", "$", "this", "->", "translations", "->", "get", "(", "$", "this", "->", "getFallbackLocale", "(", ")", ")", ")", "{", "$", "className", "=", "$", "this", "->", "getTranslationClass", "(", ")", ";", "/** @var TranslationInterface $translation */", "$", "translation", "=", "new", "$", "className", "(", ")", ";", "$", "translation", "->", "setLocale", "(", "$", "locale", ")", ";", "$", "this", "->", "addTranslation", "(", "$", "translation", ")", ";", "}", "else", "{", "$", "translation", "=", "clone", "$", "fallbackTranslation", ";", "}", "}", "}", "$", "this", "->", "currentTranslation", "=", "$", "translation", ";", "$", "this", "->", "currentLocale", "=", "$", "locale", ";", "return", "$", "translation", ";", "}" ]
Returns the translation regarding to the current or fallback locale. @param string $locale @param bool $create @return TranslationInterface @throws \RuntimeException
[ "Returns", "the", "translation", "regarding", "to", "the", "current", "or", "fallback", "locale", "." ]
96ee3d28e02bd9513705408e3bb7f88a76e52f56
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Model/TranslatableTrait.php#L63-L106
train
ekyna/Resource
Model/TranslatableTrait.php
TranslatableTrait.addTranslation
public function addTranslation(TranslationInterface $translation) { if (!$this->translations->containsKey($translation->getLocale())) { $this->translations->set($translation->getLocale(), $translation); $translation->setTranslatable($this); } return $this; }
php
public function addTranslation(TranslationInterface $translation) { if (!$this->translations->containsKey($translation->getLocale())) { $this->translations->set($translation->getLocale(), $translation); $translation->setTranslatable($this); } return $this; }
[ "public", "function", "addTranslation", "(", "TranslationInterface", "$", "translation", ")", "{", "if", "(", "!", "$", "this", "->", "translations", "->", "containsKey", "(", "$", "translation", "->", "getLocale", "(", ")", ")", ")", "{", "$", "this", "->", "translations", "->", "set", "(", "$", "translation", "->", "getLocale", "(", ")", ",", "$", "translation", ")", ";", "$", "translation", "->", "setTranslatable", "(", "$", "this", ")", ";", "}", "return", "$", "this", ";", "}" ]
Adds the translation. @param TranslationInterface $translation @return TranslatableInterface|$this
[ "Adds", "the", "translation", "." ]
96ee3d28e02bd9513705408e3bb7f88a76e52f56
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Model/TranslatableTrait.php#L160-L168
train
g4code/clean-core
src/UseCase/UseCaseAbstract.php
UseCaseAbstract.reference
public function reference($useCaseName, $resourcePart = null, Request $request = null) { if(null === $request) { $request = $this->getRequest(); } return $this->getUseCaseFactoryInstance() ->setUseCaseName($useCaseName) ->setRequest($request) ->getResource($resourcePart); }
php
public function reference($useCaseName, $resourcePart = null, Request $request = null) { if(null === $request) { $request = $this->getRequest(); } return $this->getUseCaseFactoryInstance() ->setUseCaseName($useCaseName) ->setRequest($request) ->getResource($resourcePart); }
[ "public", "function", "reference", "(", "$", "useCaseName", ",", "$", "resourcePart", "=", "null", ",", "Request", "$", "request", "=", "null", ")", "{", "if", "(", "null", "===", "$", "request", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "}", "return", "$", "this", "->", "getUseCaseFactoryInstance", "(", ")", "->", "setUseCaseName", "(", "$", "useCaseName", ")", "->", "setRequest", "(", "$", "request", ")", "->", "getResource", "(", "$", "resourcePart", ")", ";", "}" ]
Factory method for use of a new UseCase class Returns whole resource or just one part @param string $useCaseName @param string $resourcePart @param Request $request @return mixed
[ "Factory", "method", "for", "use", "of", "a", "new", "UseCase", "class", "Returns", "whole", "resource", "or", "just", "one", "part" ]
7cbe9b4f93aa96c23b93c89e0262941d2b159f5c
https://github.com/g4code/clean-core/blob/7cbe9b4f93aa96c23b93c89e0262941d2b159f5c/src/UseCase/UseCaseAbstract.php#L82-L91
train
ARCANESOFT/Blog
src/ViewComposers/Admin/Dashboard/CategoriesRatiosComposer.php
CategoriesRatiosComposer.prepareRatios
private function prepareRatios(Collection $categories) { $ratios = $categories->filter(function (Category $category) { return $category->hasPosts(); }) ->transform(function (Category $category) { return [ 'label' => $category->name, 'posts' => $category->posts->count(), ]; }) ->sortByDesc('posts'); $chunk = $ratios->splice(5); $ratios = $this->colorizeRatios($ratios); return $chunk->isEmpty() ? $ratios : $ratios->push([ 'label' => 'Other Categories', 'posts' => $chunk->sum('posts'), 'color' => '#D2D6DE', ]); }
php
private function prepareRatios(Collection $categories) { $ratios = $categories->filter(function (Category $category) { return $category->hasPosts(); }) ->transform(function (Category $category) { return [ 'label' => $category->name, 'posts' => $category->posts->count(), ]; }) ->sortByDesc('posts'); $chunk = $ratios->splice(5); $ratios = $this->colorizeRatios($ratios); return $chunk->isEmpty() ? $ratios : $ratios->push([ 'label' => 'Other Categories', 'posts' => $chunk->sum('posts'), 'color' => '#D2D6DE', ]); }
[ "private", "function", "prepareRatios", "(", "Collection", "$", "categories", ")", "{", "$", "ratios", "=", "$", "categories", "->", "filter", "(", "function", "(", "Category", "$", "category", ")", "{", "return", "$", "category", "->", "hasPosts", "(", ")", ";", "}", ")", "->", "transform", "(", "function", "(", "Category", "$", "category", ")", "{", "return", "[", "'label'", "=>", "$", "category", "->", "name", ",", "'posts'", "=>", "$", "category", "->", "posts", "->", "count", "(", ")", ",", "]", ";", "}", ")", "->", "sortByDesc", "(", "'posts'", ")", ";", "$", "chunk", "=", "$", "ratios", "->", "splice", "(", "5", ")", ";", "$", "ratios", "=", "$", "this", "->", "colorizeRatios", "(", "$", "ratios", ")", ";", "return", "$", "chunk", "->", "isEmpty", "(", ")", "?", "$", "ratios", ":", "$", "ratios", "->", "push", "(", "[", "'label'", "=>", "'Other Categories'", ",", "'posts'", "=>", "$", "chunk", "->", "sum", "(", "'posts'", ")", ",", "'color'", "=>", "'#D2D6DE'", ",", "]", ")", ";", "}" ]
Prepare the categories ratios. @param \Illuminate\Database\Eloquent\Collection $categories @return \Illuminate\Database\Eloquent\Collection
[ "Prepare", "the", "categories", "ratios", "." ]
2078fdfdcbccda161c02899b9e1f344f011b2859
https://github.com/ARCANESOFT/Blog/blob/2078fdfdcbccda161c02899b9e1f344f011b2859/src/ViewComposers/Admin/Dashboard/CategoriesRatiosComposer.php#L47-L68
train
agentmedia/phine-builtin
src/BuiltIn/Logic/Hooks/DeleteContainer.php
DeleteContainer.BeforeDelete
public function BeforeDelete($item) { $contContainers = ContentContainer::Schema()->FetchByContainer(true, $item); $logger = new Logger(BackendModule::Guard()->GetUser()); foreach ($contContainers as $contContainer) { $content = $contContainer->GetContent(); $provider = ContentTreeUtil::GetTreeProvider($content); $tree = new TreeBuilder($provider); $logger->ReportContentAction($content, Action::Delete()); $tree->Remove($provider->ItemByContent($content)); } }
php
public function BeforeDelete($item) { $contContainers = ContentContainer::Schema()->FetchByContainer(true, $item); $logger = new Logger(BackendModule::Guard()->GetUser()); foreach ($contContainers as $contContainer) { $content = $contContainer->GetContent(); $provider = ContentTreeUtil::GetTreeProvider($content); $tree = new TreeBuilder($provider); $logger->ReportContentAction($content, Action::Delete()); $tree->Remove($provider->ItemByContent($content)); } }
[ "public", "function", "BeforeDelete", "(", "$", "item", ")", "{", "$", "contContainers", "=", "ContentContainer", "::", "Schema", "(", ")", "->", "FetchByContainer", "(", "true", ",", "$", "item", ")", ";", "$", "logger", "=", "new", "Logger", "(", "BackendModule", "::", "Guard", "(", ")", "->", "GetUser", "(", ")", ")", ";", "foreach", "(", "$", "contContainers", "as", "$", "contContainer", ")", "{", "$", "content", "=", "$", "contContainer", "->", "GetContent", "(", ")", ";", "$", "provider", "=", "ContentTreeUtil", "::", "GetTreeProvider", "(", "$", "content", ")", ";", "$", "tree", "=", "new", "TreeBuilder", "(", "$", "provider", ")", ";", "$", "logger", "->", "ReportContentAction", "(", "$", "content", ",", "Action", "::", "Delete", "(", ")", ")", ";", "$", "tree", "->", "Remove", "(", "$", "provider", "->", "ItemByContent", "(", "$", "content", ")", ")", ";", "}", "}" ]
Deletes the container contents related to the container @param Container $item The container to be deleted
[ "Deletes", "the", "container", "contents", "related", "to", "the", "container" ]
4dd05bc406a71e997bd4eaa16b12e23dbe62a456
https://github.com/agentmedia/phine-builtin/blob/4dd05bc406a71e997bd4eaa16b12e23dbe62a456/src/BuiltIn/Logic/Hooks/DeleteContainer.php#L23-L35
train
perryflynn/PerrysLambda
src/PerrysLambda/LambdaUtils.php
LambdaUtils.toSelectCallable
public static function toSelectCallable($mixed=null) { // callable if(self::isClosure($mixed) || self::isInstanceCallable($mixed)) { return $mixed; } // nothing, return full row elseif(is_null($mixed) || $mixed==="") { return function($v) { return $v; }; } // row field from string elseif(is_int($mixed) || is_float($mixed) || is_string($mixed)) { return function($v) use($mixed) { if(is_object($v)) { if(method_exists($v, $mixed)) { return $v->$mixed(); } else { return $v->$mixed; } } else if(is_array($v) || ($v instanceof \ArrayAccess)) { return $v[$mixed]; } }; } throw new InvalidException("Could not convert expression of type ".gettype($mixed)." into a lambda callable"); }
php
public static function toSelectCallable($mixed=null) { // callable if(self::isClosure($mixed) || self::isInstanceCallable($mixed)) { return $mixed; } // nothing, return full row elseif(is_null($mixed) || $mixed==="") { return function($v) { return $v; }; } // row field from string elseif(is_int($mixed) || is_float($mixed) || is_string($mixed)) { return function($v) use($mixed) { if(is_object($v)) { if(method_exists($v, $mixed)) { return $v->$mixed(); } else { return $v->$mixed; } } else if(is_array($v) || ($v instanceof \ArrayAccess)) { return $v[$mixed]; } }; } throw new InvalidException("Could not convert expression of type ".gettype($mixed)." into a lambda callable"); }
[ "public", "static", "function", "toSelectCallable", "(", "$", "mixed", "=", "null", ")", "{", "// callable", "if", "(", "self", "::", "isClosure", "(", "$", "mixed", ")", "||", "self", "::", "isInstanceCallable", "(", "$", "mixed", ")", ")", "{", "return", "$", "mixed", ";", "}", "// nothing, return full row", "elseif", "(", "is_null", "(", "$", "mixed", ")", "||", "$", "mixed", "===", "\"\"", ")", "{", "return", "function", "(", "$", "v", ")", "{", "return", "$", "v", ";", "}", ";", "}", "// row field from string", "elseif", "(", "is_int", "(", "$", "mixed", ")", "||", "is_float", "(", "$", "mixed", ")", "||", "is_string", "(", "$", "mixed", ")", ")", "{", "return", "function", "(", "$", "v", ")", "use", "(", "$", "mixed", ")", "{", "if", "(", "is_object", "(", "$", "v", ")", ")", "{", "if", "(", "method_exists", "(", "$", "v", ",", "$", "mixed", ")", ")", "{", "return", "$", "v", "->", "$", "mixed", "(", ")", ";", "}", "else", "{", "return", "$", "v", "->", "$", "mixed", ";", "}", "}", "else", "if", "(", "is_array", "(", "$", "v", ")", "||", "(", "$", "v", "instanceof", "\\", "ArrayAccess", ")", ")", "{", "return", "$", "v", "[", "$", "mixed", "]", ";", "}", "}", ";", "}", "throw", "new", "InvalidException", "(", "\"Could not convert expression of type \"", ".", "gettype", "(", "$", "mixed", ")", ".", "\" into a lambda callable\"", ")", ";", "}" ]
Converts strings, empty strings and NULL into a callable @param string|callable|null $mixed @return callable @throws \PerrysLambda\Exception\InvalidException
[ "Converts", "strings", "empty", "strings", "and", "NULL", "into", "a", "callable" ]
9f1734ae4689d73278b887f9354dfd31428e96de
https://github.com/perryflynn/PerrysLambda/blob/9f1734ae4689d73278b887f9354dfd31428e96de/src/PerrysLambda/LambdaUtils.php#L43-L79
train
perryflynn/PerrysLambda
src/PerrysLambda/LambdaUtils.php
LambdaUtils.toConditionCallable
public static function toConditionCallable($mixed=null) { // callable if(self::isClosure($mixed) || self::isInstanceCallable($mixed)) { return $mixed; } // is bool elseif(is_bool($mixed) || is_string($mixed) || is_numeric($mixed)) { return function($v) use($mixed) { return $v===$mixed; }; } // conditions from array elseif(is_array($mixed) && count($mixed)>0) { return function($v) use($mixed) { foreach($mixed as $field => $expression) { if(self::isClosure($expression) || self::isInstanceCallable($expression)) { if(call_user_func($expression, $v[$field])!==true) { return false; } } else { if((is_array($v) || $v instanceof \ArrayAccess) && $v[$field]!==$expression) { return false; } } } return true; }; } throw new InvalidException("Could not convert expression of type ".gettype($mixed)." into a lambda callable"); }
php
public static function toConditionCallable($mixed=null) { // callable if(self::isClosure($mixed) || self::isInstanceCallable($mixed)) { return $mixed; } // is bool elseif(is_bool($mixed) || is_string($mixed) || is_numeric($mixed)) { return function($v) use($mixed) { return $v===$mixed; }; } // conditions from array elseif(is_array($mixed) && count($mixed)>0) { return function($v) use($mixed) { foreach($mixed as $field => $expression) { if(self::isClosure($expression) || self::isInstanceCallable($expression)) { if(call_user_func($expression, $v[$field])!==true) { return false; } } else { if((is_array($v) || $v instanceof \ArrayAccess) && $v[$field]!==$expression) { return false; } } } return true; }; } throw new InvalidException("Could not convert expression of type ".gettype($mixed)." into a lambda callable"); }
[ "public", "static", "function", "toConditionCallable", "(", "$", "mixed", "=", "null", ")", "{", "// callable", "if", "(", "self", "::", "isClosure", "(", "$", "mixed", ")", "||", "self", "::", "isInstanceCallable", "(", "$", "mixed", ")", ")", "{", "return", "$", "mixed", ";", "}", "// is bool", "elseif", "(", "is_bool", "(", "$", "mixed", ")", "||", "is_string", "(", "$", "mixed", ")", "||", "is_numeric", "(", "$", "mixed", ")", ")", "{", "return", "function", "(", "$", "v", ")", "use", "(", "$", "mixed", ")", "{", "return", "$", "v", "===", "$", "mixed", ";", "}", ";", "}", "// conditions from array", "elseif", "(", "is_array", "(", "$", "mixed", ")", "&&", "count", "(", "$", "mixed", ")", ">", "0", ")", "{", "return", "function", "(", "$", "v", ")", "use", "(", "$", "mixed", ")", "{", "foreach", "(", "$", "mixed", "as", "$", "field", "=>", "$", "expression", ")", "{", "if", "(", "self", "::", "isClosure", "(", "$", "expression", ")", "||", "self", "::", "isInstanceCallable", "(", "$", "expression", ")", ")", "{", "if", "(", "call_user_func", "(", "$", "expression", ",", "$", "v", "[", "$", "field", "]", ")", "!==", "true", ")", "{", "return", "false", ";", "}", "}", "else", "{", "if", "(", "(", "is_array", "(", "$", "v", ")", "||", "$", "v", "instanceof", "\\", "ArrayAccess", ")", "&&", "$", "v", "[", "$", "field", "]", "!==", "$", "expression", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}", ";", "}", "throw", "new", "InvalidException", "(", "\"Could not convert expression of type \"", ".", "gettype", "(", "$", "mixed", ")", ".", "\" into a lambda callable\"", ")", ";", "}" ]
Convert strings, numbers, booleans and arrays into a callable @param type $mixed @return type @throws InvalidException
[ "Convert", "strings", "numbers", "booleans", "and", "arrays", "into", "a", "callable" ]
9f1734ae4689d73278b887f9354dfd31428e96de
https://github.com/perryflynn/PerrysLambda/blob/9f1734ae4689d73278b887f9354dfd31428e96de/src/PerrysLambda/LambdaUtils.php#L88-L128
train
rafflesargentina/l5-filterable-sortable
src/FilterableSortableTrait.php
FilterableSortableTrait.scopeFilter
public function scopeFilter($query) { if (!$this->filters) { $message = 'Please set the $filters property.'; throw new FilterableSortableException($message); } $this->filters = app()->make($this->filters); if (!$this->filters instanceof QueryFilters) { $message = '$filters property must be a class instance of QueryFilter.'; throw new FilterableSortableException($message); } return $this->filters->apply($query); }
php
public function scopeFilter($query) { if (!$this->filters) { $message = 'Please set the $filters property.'; throw new FilterableSortableException($message); } $this->filters = app()->make($this->filters); if (!$this->filters instanceof QueryFilters) { $message = '$filters property must be a class instance of QueryFilter.'; throw new FilterableSortableException($message); } return $this->filters->apply($query); }
[ "public", "function", "scopeFilter", "(", "$", "query", ")", "{", "if", "(", "!", "$", "this", "->", "filters", ")", "{", "$", "message", "=", "'Please set the $filters property.'", ";", "throw", "new", "FilterableSortableException", "(", "$", "message", ")", ";", "}", "$", "this", "->", "filters", "=", "app", "(", ")", "->", "make", "(", "$", "this", "->", "filters", ")", ";", "if", "(", "!", "$", "this", "->", "filters", "instanceof", "QueryFilters", ")", "{", "$", "message", "=", "'$filters property must be a class instance of QueryFilter.'", ";", "throw", "new", "FilterableSortableException", "(", "$", "message", ")", ";", "}", "return", "$", "this", "->", "filters", "->", "apply", "(", "$", "query", ")", ";", "}" ]
Filter a result set. @param Bulder $query The builder instance. @return Builder @throws FilterableSortableException
[ "Filter", "a", "result", "set", "." ]
eb3ecf399145ec7c5241ba2134ed0bea2057e6c3
https://github.com/rafflesargentina/l5-filterable-sortable/blob/eb3ecf399145ec7c5241ba2134ed0bea2057e6c3/src/FilterableSortableTrait.php#L18-L35
train
rafflesargentina/l5-filterable-sortable
src/FilterableSortableTrait.php
FilterableSortableTrait.scopeSort
public function scopeSort($query) { if (!$this->sorters) { $message = 'Please set the $sorters property.'; throw new FilterableSortableException($message); } $this->sorters = app()->make($this->sorters); if (!$this->sorters instanceof QuerySorters) { $message = '$sorters property must be a class instance of QuerySorter.'; throw new FilterableSortableException($message); } return $this->sorters->apply($query); }
php
public function scopeSort($query) { if (!$this->sorters) { $message = 'Please set the $sorters property.'; throw new FilterableSortableException($message); } $this->sorters = app()->make($this->sorters); if (!$this->sorters instanceof QuerySorters) { $message = '$sorters property must be a class instance of QuerySorter.'; throw new FilterableSortableException($message); } return $this->sorters->apply($query); }
[ "public", "function", "scopeSort", "(", "$", "query", ")", "{", "if", "(", "!", "$", "this", "->", "sorters", ")", "{", "$", "message", "=", "'Please set the $sorters property.'", ";", "throw", "new", "FilterableSortableException", "(", "$", "message", ")", ";", "}", "$", "this", "->", "sorters", "=", "app", "(", ")", "->", "make", "(", "$", "this", "->", "sorters", ")", ";", "if", "(", "!", "$", "this", "->", "sorters", "instanceof", "QuerySorters", ")", "{", "$", "message", "=", "'$sorters property must be a class instance of QuerySorter.'", ";", "throw", "new", "FilterableSortableException", "(", "$", "message", ")", ";", "}", "return", "$", "this", "->", "sorters", "->", "apply", "(", "$", "query", ")", ";", "}" ]
Sort a result set. @param Builder $query The builder instance. @return Builder @throws FilterableSortableException
[ "Sort", "a", "result", "set", "." ]
eb3ecf399145ec7c5241ba2134ed0bea2057e6c3
https://github.com/rafflesargentina/l5-filterable-sortable/blob/eb3ecf399145ec7c5241ba2134ed0bea2057e6c3/src/FilterableSortableTrait.php#L46-L63
train
MindyPHP/QueryBuilder
QueryBuilder.php
QueryBuilder.makeAliasKey
public function makeAliasKey($table, $increment = true) { // if ($increment) { // $this->_aliasesCount += 1; // } return strtr('{table}_{count}', [ '{table}' => TableNameResolver::getTableName($table), '{count}' => $this->_aliasesCount + 1, ]); }
php
public function makeAliasKey($table, $increment = true) { // if ($increment) { // $this->_aliasesCount += 1; // } return strtr('{table}_{count}', [ '{table}' => TableNameResolver::getTableName($table), '{count}' => $this->_aliasesCount + 1, ]); }
[ "public", "function", "makeAliasKey", "(", "$", "table", ",", "$", "increment", "=", "true", ")", "{", "// if ($increment) {", "// $this->_aliasesCount += 1;", "// }", "return", "strtr", "(", "'{table}_{count}'", ",", "[", "'{table}'", "=>", "TableNameResolver", "::", "getTableName", "(", "$", "table", ")", ",", "'{count}'", "=>", "$", "this", "->", "_aliasesCount", "+", "1", ",", "]", ")", ";", "}" ]
Makes alias for joined table. @param $table @param bool $increment @return string
[ "Makes", "alias", "for", "joined", "table", "." ]
fc486454786f3d38887dd7246802ea11e2954e54
https://github.com/MindyPHP/QueryBuilder/blob/fc486454786f3d38887dd7246802ea11e2954e54/QueryBuilder.php#L1010-L1019
train
t3v/t3v_datamapper
Classes/Service/DatabaseService.php
DatabaseService.setup
public static function setup(string $connection = 'Default') { // First, create a new `Capsule` manager instance. Capsule aims to make configuring the library for usage outside of // the Laravel framework as easy as possible. $capsule = new Capsule(); // Add connection to Capsule. $capsule->addConnection(self::getConnection($connection)); // Make this Capsule instance available globally via static methods. $capsule->setAsGlobal(); // Setup the Eloquent ORM. $capsule->bootEloquent(); }
php
public static function setup(string $connection = 'Default') { // First, create a new `Capsule` manager instance. Capsule aims to make configuring the library for usage outside of // the Laravel framework as easy as possible. $capsule = new Capsule(); // Add connection to Capsule. $capsule->addConnection(self::getConnection($connection)); // Make this Capsule instance available globally via static methods. $capsule->setAsGlobal(); // Setup the Eloquent ORM. $capsule->bootEloquent(); }
[ "public", "static", "function", "setup", "(", "string", "$", "connection", "=", "'Default'", ")", "{", "// First, create a new `Capsule` manager instance. Capsule aims to make configuring the library for usage outside of", "// the Laravel framework as easy as possible.", "$", "capsule", "=", "new", "Capsule", "(", ")", ";", "// Add connection to Capsule.", "$", "capsule", "->", "addConnection", "(", "self", "::", "getConnection", "(", "$", "connection", ")", ")", ";", "// Make this Capsule instance available globally via static methods.", "$", "capsule", "->", "setAsGlobal", "(", ")", ";", "// Setup the Eloquent ORM.", "$", "capsule", "->", "bootEloquent", "(", ")", ";", "}" ]
Setup the Eloquent ORM. @param string $connection The optional connection, defaults to `Default`
[ "Setup", "the", "Eloquent", "ORM", "." ]
bab2de90f467936fbe4270cd133cb4109d1108eb
https://github.com/t3v/t3v_datamapper/blob/bab2de90f467936fbe4270cd133cb4109d1108eb/Classes/Service/DatabaseService.php#L19-L32
train
t3v/t3v_datamapper
Classes/Service/DatabaseService.php
DatabaseService.getConnection
protected static function getConnection(string $connection = 'Default'): array { $configuration = []; if (is_array($GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection])) { $extensionConfiguration = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['t3v_datamapper']; if (is_string($extensionConfiguration)) { $extensionConfiguration = @unserialize($extensionConfiguration); } $configuration = [ 'driver' => $extensionConfiguration['driver'] ?: 'mysql', 'host' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['host'], 'username' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['user'], 'password' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['password'], 'database' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['dbname'], 'charset' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['charset'] ?: 'utf8', 'collation' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['collation'] ?: 'utf8_general_ci', 'prefix' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['prefix'] ?: '' ]; } return $configuration; }
php
protected static function getConnection(string $connection = 'Default'): array { $configuration = []; if (is_array($GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection])) { $extensionConfiguration = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['t3v_datamapper']; if (is_string($extensionConfiguration)) { $extensionConfiguration = @unserialize($extensionConfiguration); } $configuration = [ 'driver' => $extensionConfiguration['driver'] ?: 'mysql', 'host' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['host'], 'username' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['user'], 'password' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['password'], 'database' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['dbname'], 'charset' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['charset'] ?: 'utf8', 'collation' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['collation'] ?: 'utf8_general_ci', 'prefix' => $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections'][$connection]['prefix'] ?: '' ]; } return $configuration; }
[ "protected", "static", "function", "getConnection", "(", "string", "$", "connection", "=", "'Default'", ")", ":", "array", "{", "$", "configuration", "=", "[", "]", ";", "if", "(", "is_array", "(", "$", "GLOBALS", "[", "'TYPO3_CONF_VARS'", "]", "[", "'DB'", "]", "[", "'Connections'", "]", "[", "$", "connection", "]", ")", ")", "{", "$", "extensionConfiguration", "=", "$", "GLOBALS", "[", "'TYPO3_CONF_VARS'", "]", "[", "'EXT'", "]", "[", "'extConf'", "]", "[", "'t3v_datamapper'", "]", ";", "if", "(", "is_string", "(", "$", "extensionConfiguration", ")", ")", "{", "$", "extensionConfiguration", "=", "@", "unserialize", "(", "$", "extensionConfiguration", ")", ";", "}", "$", "configuration", "=", "[", "'driver'", "=>", "$", "extensionConfiguration", "[", "'driver'", "]", "?", ":", "'mysql'", ",", "'host'", "=>", "$", "GLOBALS", "[", "'TYPO3_CONF_VARS'", "]", "[", "'DB'", "]", "[", "'Connections'", "]", "[", "$", "connection", "]", "[", "'host'", "]", ",", "'username'", "=>", "$", "GLOBALS", "[", "'TYPO3_CONF_VARS'", "]", "[", "'DB'", "]", "[", "'Connections'", "]", "[", "$", "connection", "]", "[", "'user'", "]", ",", "'password'", "=>", "$", "GLOBALS", "[", "'TYPO3_CONF_VARS'", "]", "[", "'DB'", "]", "[", "'Connections'", "]", "[", "$", "connection", "]", "[", "'password'", "]", ",", "'database'", "=>", "$", "GLOBALS", "[", "'TYPO3_CONF_VARS'", "]", "[", "'DB'", "]", "[", "'Connections'", "]", "[", "$", "connection", "]", "[", "'dbname'", "]", ",", "'charset'", "=>", "$", "GLOBALS", "[", "'TYPO3_CONF_VARS'", "]", "[", "'DB'", "]", "[", "'Connections'", "]", "[", "$", "connection", "]", "[", "'charset'", "]", "?", ":", "'utf8'", ",", "'collation'", "=>", "$", "GLOBALS", "[", "'TYPO3_CONF_VARS'", "]", "[", "'DB'", "]", "[", "'Connections'", "]", "[", "$", "connection", "]", "[", "'collation'", "]", "?", ":", "'utf8_general_ci'", ",", "'prefix'", "=>", "$", "GLOBALS", "[", "'TYPO3_CONF_VARS'", "]", "[", "'DB'", "]", "[", "'Connections'", "]", "[", "$", "connection", "]", "[", "'prefix'", "]", "?", ":", "''", "]", ";", "}", "return", "$", "configuration", ";", "}" ]
Returns the connection configuration from the Global TYPO3 configuration options. @param string $connection The optional connection, defaults to `Default` @return array The connection configuration @link https://laravel.com/docs/master/database#configuration The Laravel Database Configuration @link https://docs.typo3.org/typo3cms/CoreApiReference/stable/ApiOverview/GlobalValues/GlobalVariables The TYPO3 Global variables
[ "Returns", "the", "connection", "configuration", "from", "the", "Global", "TYPO3", "configuration", "options", "." ]
bab2de90f467936fbe4270cd133cb4109d1108eb
https://github.com/t3v/t3v_datamapper/blob/bab2de90f467936fbe4270cd133cb4109d1108eb/Classes/Service/DatabaseService.php#L42-L65
train
Subscribo/klarna-invoice-sdk-wrapped
src/Encoding.php
KlarnaEncoding.get
public static function get($country) { switch (strtoupper($country)) { case "DE": return KlarnaEncoding::PNO_DE; case "DK": return KlarnaEncoding::PNO_DK; case "FI": return KlarnaEncoding::PNO_FI; case "NL": return KlarnaEncoding::PNO_NL; case "NO": return KlarnaEncoding::PNO_NO; case "SE": return KlarnaEncoding::PNO_SE; case "AT": return KlarnaEncoding::PNO_AT; default: return -1; } }
php
public static function get($country) { switch (strtoupper($country)) { case "DE": return KlarnaEncoding::PNO_DE; case "DK": return KlarnaEncoding::PNO_DK; case "FI": return KlarnaEncoding::PNO_FI; case "NL": return KlarnaEncoding::PNO_NL; case "NO": return KlarnaEncoding::PNO_NO; case "SE": return KlarnaEncoding::PNO_SE; case "AT": return KlarnaEncoding::PNO_AT; default: return -1; } }
[ "public", "static", "function", "get", "(", "$", "country", ")", "{", "switch", "(", "strtoupper", "(", "$", "country", ")", ")", "{", "case", "\"DE\"", ":", "return", "KlarnaEncoding", "::", "PNO_DE", ";", "case", "\"DK\"", ":", "return", "KlarnaEncoding", "::", "PNO_DK", ";", "case", "\"FI\"", ":", "return", "KlarnaEncoding", "::", "PNO_FI", ";", "case", "\"NL\"", ":", "return", "KlarnaEncoding", "::", "PNO_NL", ";", "case", "\"NO\"", ":", "return", "KlarnaEncoding", "::", "PNO_NO", ";", "case", "\"SE\"", ":", "return", "KlarnaEncoding", "::", "PNO_SE", ";", "case", "\"AT\"", ":", "return", "KlarnaEncoding", "::", "PNO_AT", ";", "default", ":", "return", "-", "1", ";", "}", "}" ]
Returns the constant for the wanted country. @param string $country country @return int
[ "Returns", "the", "constant", "for", "the", "wanted", "country", "." ]
4a45ddd9ec444f5a6d02628ad65e635a3e12611c
https://github.com/Subscribo/klarna-invoice-sdk-wrapped/blob/4a45ddd9ec444f5a6d02628ad65e635a3e12611c/src/Encoding.php#L114-L134
train
Subscribo/klarna-invoice-sdk-wrapped
src/Encoding.php
KlarnaEncoding.getRegexp
public static function getRegexp($enc) { switch($enc) { case self::PNO_SE: /* * All positions except C contain numbers 0-9. * * PNO: * YYYYMMDDCNNNN, C = -|+ length 13 * YYYYMMDDNNNN 12 * YYMMDDCNNNN 11 * YYMMDDNNNN 10 * * ORGNO: * XXXXXXNNNN * XXXXXX-NNNN * 16XXXXXXNNNN * 16XXXXXX-NNNN * */ return '/^[0-9]{6,6}(([0-9]{2,2}[-\+]{1,1}[0-9]{4,4})|([-\+]'. '{1,1}[0-9]{4,4})|([0-9]{4,6}))$/'; case self::PNO_NO: /* * All positions contain numbers 0-9. * * Pno * DDMMYYIIIKK ("fodelsenummer" or "D-nummer") length = 11 * DDMMYY-IIIKK ("fodelsenummer" or "D-nummer") length = 12 * DDMMYYYYIIIKK ("fodelsenummer" or "D-nummer") length = 13 * DDMMYYYY-IIIKK ("fodelsenummer" or "D-nummer") length = 14 * * Orgno * Starts with 8 or 9. * * NNNNNNNNK (orgno) length = 9 */ return '/^[0-9]{6,6}((-[0-9]{5,5})|([0-9]{2,2}((-[0-9]'. '{5,5})|([0-9]{1,1})|([0-9]{3,3})|([0-9]{5,5))))$/'; case self::PNO_FI: /* * Pno * DDMMYYCIIIT * DDMMYYIIIT * C = century, '+' = 1800, '-' = 1900 och 'A' = 2000. * I = 0-9 * T = 0-9, A-F, H, J, K-N, P, R-Y * * Orgno * NNNNNNN-T * NNNNNNNT * T = 0-9, A-F, H, J, K-N, P, R-Y */ return '/^[0-9]{6,6}(([A\+-]{1,1}[0-9]{3,3}[0-9A-FHJK-NPR-Y]'. '{1,1})|([0-9]{3,3}[0-9A-FHJK-NPR-Y]{1,1})|([0-9]{1,1}-{0,1}'. '[0-9A-FHJK-NPR-Y]{1,1}))$/i'; case self::PNO_DK: /* * Pno * DDMMYYNNNG length 10 * G = gender, odd/even for men/women. * * Orgno * XXXXXXXX length 8 */ return '/^[0-9]{8,8}([0-9]{2,2})?$/'; case self::PNO_NL: case self::PNO_DE: /** * Pno * DDMMYYYYG length 9 * DDMMYYYY 8 * * Orgno * XXXXXXX 7 company org nr */ return '/^[0-9]{7,9}$/'; case self::EMAIL: /** * Validates an email. */ return '/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]'. '+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z0-9-][a-zA-Z0-9-]+)+$/'; case self::CELLNO: /** * Validates a cellno. * @TODO Is this encoding only for Sweden? */ return '/^07[\ \-0-9]{8,13}$/'; default: throw new Klarna_UnknownEncodingException($enc); } }
php
public static function getRegexp($enc) { switch($enc) { case self::PNO_SE: /* * All positions except C contain numbers 0-9. * * PNO: * YYYYMMDDCNNNN, C = -|+ length 13 * YYYYMMDDNNNN 12 * YYMMDDCNNNN 11 * YYMMDDNNNN 10 * * ORGNO: * XXXXXXNNNN * XXXXXX-NNNN * 16XXXXXXNNNN * 16XXXXXX-NNNN * */ return '/^[0-9]{6,6}(([0-9]{2,2}[-\+]{1,1}[0-9]{4,4})|([-\+]'. '{1,1}[0-9]{4,4})|([0-9]{4,6}))$/'; case self::PNO_NO: /* * All positions contain numbers 0-9. * * Pno * DDMMYYIIIKK ("fodelsenummer" or "D-nummer") length = 11 * DDMMYY-IIIKK ("fodelsenummer" or "D-nummer") length = 12 * DDMMYYYYIIIKK ("fodelsenummer" or "D-nummer") length = 13 * DDMMYYYY-IIIKK ("fodelsenummer" or "D-nummer") length = 14 * * Orgno * Starts with 8 or 9. * * NNNNNNNNK (orgno) length = 9 */ return '/^[0-9]{6,6}((-[0-9]{5,5})|([0-9]{2,2}((-[0-9]'. '{5,5})|([0-9]{1,1})|([0-9]{3,3})|([0-9]{5,5))))$/'; case self::PNO_FI: /* * Pno * DDMMYYCIIIT * DDMMYYIIIT * C = century, '+' = 1800, '-' = 1900 och 'A' = 2000. * I = 0-9 * T = 0-9, A-F, H, J, K-N, P, R-Y * * Orgno * NNNNNNN-T * NNNNNNNT * T = 0-9, A-F, H, J, K-N, P, R-Y */ return '/^[0-9]{6,6}(([A\+-]{1,1}[0-9]{3,3}[0-9A-FHJK-NPR-Y]'. '{1,1})|([0-9]{3,3}[0-9A-FHJK-NPR-Y]{1,1})|([0-9]{1,1}-{0,1}'. '[0-9A-FHJK-NPR-Y]{1,1}))$/i'; case self::PNO_DK: /* * Pno * DDMMYYNNNG length 10 * G = gender, odd/even for men/women. * * Orgno * XXXXXXXX length 8 */ return '/^[0-9]{8,8}([0-9]{2,2})?$/'; case self::PNO_NL: case self::PNO_DE: /** * Pno * DDMMYYYYG length 9 * DDMMYYYY 8 * * Orgno * XXXXXXX 7 company org nr */ return '/^[0-9]{7,9}$/'; case self::EMAIL: /** * Validates an email. */ return '/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]'. '+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z0-9-][a-zA-Z0-9-]+)+$/'; case self::CELLNO: /** * Validates a cellno. * @TODO Is this encoding only for Sweden? */ return '/^07[\ \-0-9]{8,13}$/'; default: throw new Klarna_UnknownEncodingException($enc); } }
[ "public", "static", "function", "getRegexp", "(", "$", "enc", ")", "{", "switch", "(", "$", "enc", ")", "{", "case", "self", "::", "PNO_SE", ":", "/*\n * All positions except C contain numbers 0-9.\n *\n * PNO:\n * YYYYMMDDCNNNN, C = -|+ length 13\n * YYYYMMDDNNNN 12\n * YYMMDDCNNNN 11\n * YYMMDDNNNN 10\n *\n * ORGNO:\n * XXXXXXNNNN\n * XXXXXX-NNNN\n * 16XXXXXXNNNN\n * 16XXXXXX-NNNN\n *\n */", "return", "'/^[0-9]{6,6}(([0-9]{2,2}[-\\+]{1,1}[0-9]{4,4})|([-\\+]'", ".", "'{1,1}[0-9]{4,4})|([0-9]{4,6}))$/'", ";", "case", "self", "::", "PNO_NO", ":", "/*\n * All positions contain numbers 0-9.\n *\n * Pno\n * DDMMYYIIIKK (\"fodelsenummer\" or \"D-nummer\") length = 11\n * DDMMYY-IIIKK (\"fodelsenummer\" or \"D-nummer\") length = 12\n * DDMMYYYYIIIKK (\"fodelsenummer\" or \"D-nummer\") length = 13\n * DDMMYYYY-IIIKK (\"fodelsenummer\" or \"D-nummer\") length = 14\n *\n * Orgno\n * Starts with 8 or 9.\n *\n * NNNNNNNNK (orgno) length = 9\n */", "return", "'/^[0-9]{6,6}((-[0-9]{5,5})|([0-9]{2,2}((-[0-9]'", ".", "'{5,5})|([0-9]{1,1})|([0-9]{3,3})|([0-9]{5,5))))$/'", ";", "case", "self", "::", "PNO_FI", ":", "/*\n * Pno\n * DDMMYYCIIIT\n * DDMMYYIIIT\n * C = century, '+' = 1800, '-' = 1900 och 'A' = 2000.\n * I = 0-9\n * T = 0-9, A-F, H, J, K-N, P, R-Y\n *\n * Orgno\n * NNNNNNN-T\n * NNNNNNNT\n * T = 0-9, A-F, H, J, K-N, P, R-Y\n */", "return", "'/^[0-9]{6,6}(([A\\+-]{1,1}[0-9]{3,3}[0-9A-FHJK-NPR-Y]'", ".", "'{1,1})|([0-9]{3,3}[0-9A-FHJK-NPR-Y]{1,1})|([0-9]{1,1}-{0,1}'", ".", "'[0-9A-FHJK-NPR-Y]{1,1}))$/i'", ";", "case", "self", "::", "PNO_DK", ":", "/*\n * Pno\n * DDMMYYNNNG length 10\n * G = gender, odd/even for men/women.\n *\n * Orgno\n * XXXXXXXX length 8\n */", "return", "'/^[0-9]{8,8}([0-9]{2,2})?$/'", ";", "case", "self", "::", "PNO_NL", ":", "case", "self", "::", "PNO_DE", ":", "/**\n * Pno\n * DDMMYYYYG length 9\n * DDMMYYYY 8\n *\n * Orgno\n * XXXXXXX 7 company org nr\n */", "return", "'/^[0-9]{7,9}$/'", ";", "case", "self", "::", "EMAIL", ":", "/**\n * Validates an email.\n */", "return", "'/^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]'", ".", "'+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z0-9-][a-zA-Z0-9-]+)+$/'", ";", "case", "self", "::", "CELLNO", ":", "/**\n * Validates a cellno.\n * @TODO Is this encoding only for Sweden?\n */", "return", "'/^07[\\ \\-0-9]{8,13}$/'", ";", "default", ":", "throw", "new", "Klarna_UnknownEncodingException", "(", "$", "enc", ")", ";", "}", "}" ]
Returns a regexp string for the specified encoding constant. @param int $enc PNO/SSN encoding constant. @return string The regular expression. @throws Klarna_UnknownEncodingException
[ "Returns", "a", "regexp", "string", "for", "the", "specified", "encoding", "constant", "." ]
4a45ddd9ec444f5a6d02628ad65e635a3e12611c
https://github.com/Subscribo/klarna-invoice-sdk-wrapped/blob/4a45ddd9ec444f5a6d02628ad65e635a3e12611c/src/Encoding.php#L144-L236
train
theopera/framework
src/Component/WebApplication/ConfigurationBag.php
ConfigurationBag.getSection
public function getSection(string $key) : ConfigurationBagInterface { return new ConfigurationBag(isset($this->parameters[$key]) ? $this->parameters[$key] : []); }
php
public function getSection(string $key) : ConfigurationBagInterface { return new ConfigurationBag(isset($this->parameters[$key]) ? $this->parameters[$key] : []); }
[ "public", "function", "getSection", "(", "string", "$", "key", ")", ":", "ConfigurationBagInterface", "{", "return", "new", "ConfigurationBag", "(", "isset", "(", "$", "this", "->", "parameters", "[", "$", "key", "]", ")", "?", "$", "this", "->", "parameters", "[", "$", "key", "]", ":", "[", "]", ")", ";", "}" ]
Returns a new ConfigurationBag with parameters If the section does not exists an empty ConfigurationBag is returned @param string $key @return ConfigurationBagInterface
[ "Returns", "a", "new", "ConfigurationBag", "with", "parameters", "If", "the", "section", "does", "not", "exists", "an", "empty", "ConfigurationBag", "is", "returned" ]
fa6165d3891a310faa580c81dee49a63c150c711
https://github.com/theopera/framework/blob/fa6165d3891a310faa580c81dee49a63c150c711/src/Component/WebApplication/ConfigurationBag.php#L133-L136
train
Topolis/FunctionLibrary
src/String.php
String.getNest
public static function getNest($input, $open = "(", $close = ")"){ $pattern = '#\\'.$open.'((?>[^\\'.$open.'[\\'.$close.']+)|(?R))*\\'.$close.'#'; $count = preg_match_all($pattern, $input, $matches); if($count > 0) return $matches[0][0]; return false; }
php
public static function getNest($input, $open = "(", $close = ")"){ $pattern = '#\\'.$open.'((?>[^\\'.$open.'[\\'.$close.']+)|(?R))*\\'.$close.'#'; $count = preg_match_all($pattern, $input, $matches); if($count > 0) return $matches[0][0]; return false; }
[ "public", "static", "function", "getNest", "(", "$", "input", ",", "$", "open", "=", "\"(\"", ",", "$", "close", "=", "\")\"", ")", "{", "$", "pattern", "=", "'#\\\\'", ".", "$", "open", ".", "'((?>[^\\\\'", ".", "$", "open", ".", "'[\\\\'", ".", "$", "close", ".", "']+)|(?R))*\\\\'", ".", "$", "close", ".", "'#'", ";", "$", "count", "=", "preg_match_all", "(", "$", "pattern", ",", "$", "input", ",", "$", "matches", ")", ";", "if", "(", "$", "count", ">", "0", ")", "return", "$", "matches", "[", "0", "]", "[", "0", "]", ";", "return", "false", ";", "}" ]
return anything within specified balanced brackets, including any nested brackets @param string $input source string @param string $open opening bracket. Default: '(' @param string $close closing bracket. Default: ')'
[ "return", "anything", "within", "specified", "balanced", "brackets", "including", "any", "nested", "brackets" ]
bc57f465932fbf297927c2a32765255131b907eb
https://github.com/Topolis/FunctionLibrary/blob/bc57f465932fbf297927c2a32765255131b907eb/src/String.php#L84-L93
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/QueryBuilder.php
QueryBuilder.addFilterCriteria
private function addFilterCriteria() { $filters = $this->dm->getFilterCollection()->getFilterCriteria($this->class); foreach ($filters as $filter) { $this->addCriteria($filter); } }
php
private function addFilterCriteria() { $filters = $this->dm->getFilterCollection()->getFilterCriteria($this->class); foreach ($filters as $filter) { $this->addCriteria($filter); } }
[ "private", "function", "addFilterCriteria", "(", ")", "{", "$", "filters", "=", "$", "this", "->", "dm", "->", "getFilterCollection", "(", ")", "->", "getFilterCriteria", "(", "$", "this", "->", "class", ")", ";", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "$", "this", "->", "addCriteria", "(", "$", "filter", ")", ";", "}", "}" ]
Add any filters to the query criteria. @return void
[ "Add", "any", "filters", "to", "the", "query", "criteria", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/QueryBuilder.php#L162-L169
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/QueryBuilder.php
QueryBuilder.checkIndexIsEligible
private function checkIndexIsEligible() { $index = $this->getIndex(); if ($index->isSecondaryGlobal() && !$index->hasAttributes($this->expr->getAttributes())) { throw ODMException::queryIndexProjectionIncompatible(); } return (bool)$this->getKeyCondition(); }
php
private function checkIndexIsEligible() { $index = $this->getIndex(); if ($index->isSecondaryGlobal() && !$index->hasAttributes($this->expr->getAttributes())) { throw ODMException::queryIndexProjectionIncompatible(); } return (bool)$this->getKeyCondition(); }
[ "private", "function", "checkIndexIsEligible", "(", ")", "{", "$", "index", "=", "$", "this", "->", "getIndex", "(", ")", ";", "if", "(", "$", "index", "->", "isSecondaryGlobal", "(", ")", "&&", "!", "$", "index", "->", "hasAttributes", "(", "$", "this", "->", "expr", "->", "getAttributes", "(", ")", ")", ")", "{", "throw", "ODMException", "::", "queryIndexProjectionIncompatible", "(", ")", ";", "}", "return", "(", "bool", ")", "$", "this", "->", "getKeyCondition", "(", ")", ";", "}" ]
Indicates if the selected index is eligible for the assembled query. @return bool @throws ODMException
[ "Indicates", "if", "the", "selected", "index", "is", "eligible", "for", "the", "assembled", "query", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/QueryBuilder.php#L269-L278
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/QueryBuilder.php
QueryBuilder.delete
public function delete($hashValue = null, $rangeValue = null) { $this->setQueryClass(DeleteItem::class); if ($hashValue !== null) { $this->setPrimaryKey($hashValue, $rangeValue); } return $this; }
php
public function delete($hashValue = null, $rangeValue = null) { $this->setQueryClass(DeleteItem::class); if ($hashValue !== null) { $this->setPrimaryKey($hashValue, $rangeValue); } return $this; }
[ "public", "function", "delete", "(", "$", "hashValue", "=", "null", ",", "$", "rangeValue", "=", "null", ")", "{", "$", "this", "->", "setQueryClass", "(", "DeleteItem", "::", "class", ")", ";", "if", "(", "$", "hashValue", "!==", "null", ")", "{", "$", "this", "->", "setPrimaryKey", "(", "$", "hashValue", ",", "$", "rangeValue", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the query operation to 'delete' and optionally specifies the primary key. @param mixed|null $hashValue @param mixed|null $rangeValue @return $this
[ "Sets", "the", "query", "operation", "to", "delete", "and", "optionally", "specifies", "the", "primary", "key", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/QueryBuilder.php#L308-L317
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/QueryBuilder.php
QueryBuilder.get
public function get($hashValue = null, $rangeValue = null) { if ($this->expr->condition->count() > 0) { throw ODMException::queryGetOperationConditionsNotSupported(); } $this->setQueryClass(GetItem::class); if ($hashValue !== null) { $this->setPrimaryKey($hashValue, $rangeValue); } return $this; }
php
public function get($hashValue = null, $rangeValue = null) { if ($this->expr->condition->count() > 0) { throw ODMException::queryGetOperationConditionsNotSupported(); } $this->setQueryClass(GetItem::class); if ($hashValue !== null) { $this->setPrimaryKey($hashValue, $rangeValue); } return $this; }
[ "public", "function", "get", "(", "$", "hashValue", "=", "null", ",", "$", "rangeValue", "=", "null", ")", "{", "if", "(", "$", "this", "->", "expr", "->", "condition", "->", "count", "(", ")", ">", "0", ")", "{", "throw", "ODMException", "::", "queryGetOperationConditionsNotSupported", "(", ")", ";", "}", "$", "this", "->", "setQueryClass", "(", "GetItem", "::", "class", ")", ";", "if", "(", "$", "hashValue", "!==", "null", ")", "{", "$", "this", "->", "setPrimaryKey", "(", "$", "hashValue", ",", "$", "rangeValue", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the query operation to 'get' and optionally specifies the primary key. @param mixed|null $hashValue @param mixed|null $rangeValue @return $this @throws ODMException
[ "Sets", "the", "query", "operation", "to", "get", "and", "optionally", "specifies", "the", "primary", "key", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/QueryBuilder.php#L374-L387
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/QueryBuilder.php
QueryBuilder.getFilter
private function getFilter($keyCondition) { $filter = clone $this->expr->condition; $conditions = $keyCondition instanceof Composite ? $keyCondition->getParts() : [$keyCondition]; foreach ($conditions as $condition) { $filter->remove($condition); } return $filter; }
php
private function getFilter($keyCondition) { $filter = clone $this->expr->condition; $conditions = $keyCondition instanceof Composite ? $keyCondition->getParts() : [$keyCondition]; foreach ($conditions as $condition) { $filter->remove($condition); } return $filter; }
[ "private", "function", "getFilter", "(", "$", "keyCondition", ")", "{", "$", "filter", "=", "clone", "$", "this", "->", "expr", "->", "condition", ";", "$", "conditions", "=", "$", "keyCondition", "instanceof", "Composite", "?", "$", "keyCondition", "->", "getParts", "(", ")", ":", "[", "$", "keyCondition", "]", ";", "foreach", "(", "$", "conditions", "as", "$", "condition", ")", "{", "$", "filter", "->", "remove", "(", "$", "condition", ")", ";", "}", "return", "$", "filter", ";", "}" ]
Return a expression containing only the subexpression parts which are not part of specified key condition. @param Equality|AddAnd $keyCondition @return AddAnd
[ "Return", "a", "expression", "containing", "only", "the", "subexpression", "parts", "which", "are", "not", "part", "of", "specified", "key", "condition", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/QueryBuilder.php#L476-L487
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/QueryBuilder.php
QueryBuilder.getQuery
public function getQuery() { switch ($this->queryClass) { case DeleteItem::class: return $this->makeDelete(); case GetItem::class: return $this->makeGet(); case PutItem::class: return $this->makePut(); case Scan::class: return $this->makeScan(); case UpdateItem::class: return $this->makeUpdate(); case Query::class: return $this->makeQuery(); } throw new \LogicException; }
php
public function getQuery() { switch ($this->queryClass) { case DeleteItem::class: return $this->makeDelete(); case GetItem::class: return $this->makeGet(); case PutItem::class: return $this->makePut(); case Scan::class: return $this->makeScan(); case UpdateItem::class: return $this->makeUpdate(); case Query::class: return $this->makeQuery(); } throw new \LogicException; }
[ "public", "function", "getQuery", "(", ")", "{", "switch", "(", "$", "this", "->", "queryClass", ")", "{", "case", "DeleteItem", "::", "class", ":", "return", "$", "this", "->", "makeDelete", "(", ")", ";", "case", "GetItem", "::", "class", ":", "return", "$", "this", "->", "makeGet", "(", ")", ";", "case", "PutItem", "::", "class", ":", "return", "$", "this", "->", "makePut", "(", ")", ";", "case", "Scan", "::", "class", ":", "return", "$", "this", "->", "makeScan", "(", ")", ";", "case", "UpdateItem", "::", "class", ":", "return", "$", "this", "->", "makeUpdate", "(", ")", ";", "case", "Query", "::", "class", ":", "return", "$", "this", "->", "makeQuery", "(", ")", ";", "}", "throw", "new", "\\", "LogicException", ";", "}" ]
Build and return the query object. @return Scan|Query|GetItem|PutItem|UpdateItem|DeleteItem
[ "Build", "and", "return", "the", "query", "object", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/QueryBuilder.php#L549-L567
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/QueryBuilder.php
QueryBuilder.requireIndexes
public function requireIndexes($bool = true) { if (!$this->isQueryOrScan()) { //TODO: exception } if ($bool) { $this->queryClass = Query::class; } else { $this->queryClass = Scan::class; } return $this; }
php
public function requireIndexes($bool = true) { if (!$this->isQueryOrScan()) { //TODO: exception } if ($bool) { $this->queryClass = Query::class; } else { $this->queryClass = Scan::class; } return $this; }
[ "public", "function", "requireIndexes", "(", "$", "bool", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "isQueryOrScan", "(", ")", ")", "{", "//TODO: exception", "}", "if", "(", "$", "bool", ")", "{", "$", "this", "->", "queryClass", "=", "Query", "::", "class", ";", "}", "else", "{", "$", "this", "->", "queryClass", "=", "Scan", "::", "class", ";", "}", "return", "$", "this", ";", "}" ]
Set whether or not to require indexes. @param bool $bool @return $this
[ "Set", "whether", "or", "not", "to", "require", "indexes", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/QueryBuilder.php#L843-L856
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/QueryBuilder.php
QueryBuilder.update
public function update($hashValue = null, $rangeValue = null) { $this->setQueryClass(UpdateItem::class); if ($hashValue !== null) { $this->setPrimaryKey($hashValue, $rangeValue); } return $this; }
php
public function update($hashValue = null, $rangeValue = null) { $this->setQueryClass(UpdateItem::class); if ($hashValue !== null) { $this->setPrimaryKey($hashValue, $rangeValue); } return $this; }
[ "public", "function", "update", "(", "$", "hashValue", "=", "null", ",", "$", "rangeValue", "=", "null", ")", "{", "$", "this", "->", "setQueryClass", "(", "UpdateItem", "::", "class", ")", ";", "if", "(", "$", "hashValue", "!==", "null", ")", "{", "$", "this", "->", "setPrimaryKey", "(", "$", "hashValue", ",", "$", "rangeValue", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the query operation to 'update' and optionally specifies the primary key. @param mixed|null $hashValue @param mixed|null $rangeValue @return $this
[ "Sets", "the", "query", "operation", "to", "update", "and", "optionally", "specifies", "the", "primary", "key", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/QueryBuilder.php#L926-L935
train
ciims/ciims-modules-api
controllers/CommentController.php
CommentController.beforeAction
public function beforeAction($action) { if (Cii::getConfig('useDisqusComments')) throw new CHttpException(403, Yii::t('Api.comment', 'The comment API is not available while Disqus comments are enabled.')); if (Cii::getConfig('useDiscourceComments')) throw new CHttpException(403, Yii::t('Api.comment', 'The comment API is not available while Discourse comments are enabled.')); return parent::beforeAction($action); }
php
public function beforeAction($action) { if (Cii::getConfig('useDisqusComments')) throw new CHttpException(403, Yii::t('Api.comment', 'The comment API is not available while Disqus comments are enabled.')); if (Cii::getConfig('useDiscourceComments')) throw new CHttpException(403, Yii::t('Api.comment', 'The comment API is not available while Discourse comments are enabled.')); return parent::beforeAction($action); }
[ "public", "function", "beforeAction", "(", "$", "action", ")", "{", "if", "(", "Cii", "::", "getConfig", "(", "'useDisqusComments'", ")", ")", "throw", "new", "CHttpException", "(", "403", ",", "Yii", "::", "t", "(", "'Api.comment'", ",", "'The comment API is not available while Disqus comments are enabled.'", ")", ")", ";", "if", "(", "Cii", "::", "getConfig", "(", "'useDiscourceComments'", ")", ")", "throw", "new", "CHttpException", "(", "403", ",", "Yii", "::", "t", "(", "'Api.comment'", ",", "'The comment API is not available while Discourse comments are enabled.'", ")", ")", ";", "return", "parent", "::", "beforeAction", "(", "$", "action", ")", ";", "}" ]
If Disqus comments are enabled, disable the entire API @param CAction $action The action we are using @return null|boolean
[ "If", "Disqus", "comments", "are", "enabled", "disable", "the", "entire", "API" ]
4351855328da0b112ac27bde7e7e07e212be8689
https://github.com/ciims/ciims-modules-api/blob/4351855328da0b112ac27bde7e7e07e212be8689/controllers/CommentController.php#L36-L45
train
ciims/ciims-modules-api
controllers/CommentController.php
CommentController.getCommentModel
private function getCommentModel($id=NULL) { if ($id === NULL) throw new CHttpException(400, Yii::t('Api.comment', 'Missing id')); $model = Comments::model()->findByPk($id); if ($model === NULL) throw new CHttpException(404, Yii::t('Api.comment', 'Comment #{{id}} was not found.', array('{{id}}' => $id))); return $model; }
php
private function getCommentModel($id=NULL) { if ($id === NULL) throw new CHttpException(400, Yii::t('Api.comment', 'Missing id')); $model = Comments::model()->findByPk($id); if ($model === NULL) throw new CHttpException(404, Yii::t('Api.comment', 'Comment #{{id}} was not found.', array('{{id}}' => $id))); return $model; }
[ "private", "function", "getCommentModel", "(", "$", "id", "=", "NULL", ")", "{", "if", "(", "$", "id", "===", "NULL", ")", "throw", "new", "CHttpException", "(", "400", ",", "Yii", "::", "t", "(", "'Api.comment'", ",", "'Missing id'", ")", ")", ";", "$", "model", "=", "Comments", "::", "model", "(", ")", "->", "findByPk", "(", "$", "id", ")", ";", "if", "(", "$", "model", "===", "NULL", ")", "throw", "new", "CHttpException", "(", "404", ",", "Yii", "::", "t", "(", "'Api.comment'", ",", "'Comment #{{id}} was not found.'", ",", "array", "(", "'{{id}}'", "=>", "$", "id", ")", ")", ")", ";", "return", "$", "model", ";", "}" ]
Retrieves the Comment model @param int $id The comment model @return Comment
[ "Retrieves", "the", "Comment", "model" ]
4351855328da0b112ac27bde7e7e07e212be8689
https://github.com/ciims/ciims-modules-api/blob/4351855328da0b112ac27bde7e7e07e212be8689/controllers/CommentController.php#L241-L251
train
nicmart/Arrayze
src/ArrayAdapterTrait.php
ArrayAdapterTrait.toArray
public function toArray() { $ary = []; foreach ($this as $key => $value) { $ary[$key] = $value; } return $ary; }
php
public function toArray() { $ary = []; foreach ($this as $key => $value) { $ary[$key] = $value; } return $ary; }
[ "public", "function", "toArray", "(", ")", "{", "$", "ary", "=", "[", "]", ";", "foreach", "(", "$", "this", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "ary", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "$", "ary", ";", "}" ]
Converts the object to an array @return array
[ "Converts", "the", "object", "to", "an", "array" ]
7a86c8a661456b5f7055857aeda3e6ee3af05b13
https://github.com/nicmart/Arrayze/blob/7a86c8a661456b5f7055857aeda3e6ee3af05b13/src/ArrayAdapterTrait.php#L78-L87
train
sokil/CommandBusBundle
src/CommandBus.php
CommandBus.addHandlerDefinition
public function addHandlerDefinition($commandClassName, $handlerServiceId) { // Check if handler already associated with command if (isset($this->handlerDefinitions[$commandClassName])) { throw new \InvalidArgumentException(sprintf( "Handler with service id '%s' already configured for command %s'", $this->handlerDefinitions[$commandClassName]['handler'], $commandClassName )); } // Add handler definition $this->handlerDefinitions[$commandClassName] = [ 'handler' => $handlerServiceId, ]; return $this; }
php
public function addHandlerDefinition($commandClassName, $handlerServiceId) { // Check if handler already associated with command if (isset($this->handlerDefinitions[$commandClassName])) { throw new \InvalidArgumentException(sprintf( "Handler with service id '%s' already configured for command %s'", $this->handlerDefinitions[$commandClassName]['handler'], $commandClassName )); } // Add handler definition $this->handlerDefinitions[$commandClassName] = [ 'handler' => $handlerServiceId, ]; return $this; }
[ "public", "function", "addHandlerDefinition", "(", "$", "commandClassName", ",", "$", "handlerServiceId", ")", "{", "// Check if handler already associated with command", "if", "(", "isset", "(", "$", "this", "->", "handlerDefinitions", "[", "$", "commandClassName", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "\"Handler with service id '%s' already configured for command %s'\"", ",", "$", "this", "->", "handlerDefinitions", "[", "$", "commandClassName", "]", "[", "'handler'", "]", ",", "$", "commandClassName", ")", ")", ";", "}", "// Add handler definition", "$", "this", "->", "handlerDefinitions", "[", "$", "commandClassName", "]", "=", "[", "'handler'", "=>", "$", "handlerServiceId", ",", "]", ";", "return", "$", "this", ";", "}" ]
Add handler definition @param string $commandClassName @param string $handlerServiceId @return CommandBus
[ "Add", "handler", "definition" ]
7cfdd5f1e8a77f0620b94dd5214091a2159a143d
https://github.com/sokil/CommandBusBundle/blob/7cfdd5f1e8a77f0620b94dd5214091a2159a143d/src/CommandBus.php#L37-L54
train
alphalemon/BootstrapBundle
Core/Listener/ExecutePostActionsListener.php
ExecutePostActionsListener.onKernelRequest
public function onKernelRequest() { if ($this->executed) return; $installerScript = $this->scriptFactory->createScript('PostBootInstaller'); $installerScript->setContainer($this->container) ->executeActionsFromFile($this->basePath . '/.PostInstall'); $installerScript = $this->scriptFactory->createScript('PostBootUninstaller'); $installerScript->setContainer($this->container) ->executeActionsFromFile($this->basePath . '/.PostUninstall'); $this->executed = true; }
php
public function onKernelRequest() { if ($this->executed) return; $installerScript = $this->scriptFactory->createScript('PostBootInstaller'); $installerScript->setContainer($this->container) ->executeActionsFromFile($this->basePath . '/.PostInstall'); $installerScript = $this->scriptFactory->createScript('PostBootUninstaller'); $installerScript->setContainer($this->container) ->executeActionsFromFile($this->basePath . '/.PostUninstall'); $this->executed = true; }
[ "public", "function", "onKernelRequest", "(", ")", "{", "if", "(", "$", "this", "->", "executed", ")", "return", ";", "$", "installerScript", "=", "$", "this", "->", "scriptFactory", "->", "createScript", "(", "'PostBootInstaller'", ")", ";", "$", "installerScript", "->", "setContainer", "(", "$", "this", "->", "container", ")", "->", "executeActionsFromFile", "(", "$", "this", "->", "basePath", ".", "'/.PostInstall'", ")", ";", "$", "installerScript", "=", "$", "this", "->", "scriptFactory", "->", "createScript", "(", "'PostBootUninstaller'", ")", ";", "$", "installerScript", "->", "setContainer", "(", "$", "this", "->", "container", ")", "->", "executeActionsFromFile", "(", "$", "this", "->", "basePath", ".", "'/.PostUninstall'", ")", ";", "$", "this", "->", "executed", "=", "true", ";", "}" ]
Executes the action when the onKernelRequest event is dispatched
[ "Executes", "the", "action", "when", "the", "onKernelRequest", "event", "is", "dispatched" ]
27ff5cbc58d58149ec72a974f2a9d765a6fd37a6
https://github.com/alphalemon/BootstrapBundle/blob/27ff5cbc58d58149ec72a974f2a9d765a6fd37a6/Core/Listener/ExecutePostActionsListener.php#L35-L48
train
indigoram89/laravel-translatable
src/Translatable.php
Translatable.getTranslation
public function getTranslation(string $key, string $locale = null) { $this->throwExceptionIfAttributeIsNotTranslatable($key); $translations = $this->getTranslations($key); if (count($translations)) { $locale = $locale ?: config('app.locale'); if (isset($translations[$locale])) { $translation = $translations[$locale]; } else { $translation = $translations[$this->getDefaultLocale()] ?? head($translations); } } else { $translation = null; } if ($this->hasGetMutator($key)) { return $this->mutateAttribute($key, $translation); } return $translation; }
php
public function getTranslation(string $key, string $locale = null) { $this->throwExceptionIfAttributeIsNotTranslatable($key); $translations = $this->getTranslations($key); if (count($translations)) { $locale = $locale ?: config('app.locale'); if (isset($translations[$locale])) { $translation = $translations[$locale]; } else { $translation = $translations[$this->getDefaultLocale()] ?? head($translations); } } else { $translation = null; } if ($this->hasGetMutator($key)) { return $this->mutateAttribute($key, $translation); } return $translation; }
[ "public", "function", "getTranslation", "(", "string", "$", "key", ",", "string", "$", "locale", "=", "null", ")", "{", "$", "this", "->", "throwExceptionIfAttributeIsNotTranslatable", "(", "$", "key", ")", ";", "$", "translations", "=", "$", "this", "->", "getTranslations", "(", "$", "key", ")", ";", "if", "(", "count", "(", "$", "translations", ")", ")", "{", "$", "locale", "=", "$", "locale", "?", ":", "config", "(", "'app.locale'", ")", ";", "if", "(", "isset", "(", "$", "translations", "[", "$", "locale", "]", ")", ")", "{", "$", "translation", "=", "$", "translations", "[", "$", "locale", "]", ";", "}", "else", "{", "$", "translation", "=", "$", "translations", "[", "$", "this", "->", "getDefaultLocale", "(", ")", "]", "??", "head", "(", "$", "translations", ")", ";", "}", "}", "else", "{", "$", "translation", "=", "null", ";", "}", "if", "(", "$", "this", "->", "hasGetMutator", "(", "$", "key", ")", ")", "{", "return", "$", "this", "->", "mutateAttribute", "(", "$", "key", ",", "$", "translation", ")", ";", "}", "return", "$", "translation", ";", "}" ]
Get attribute translation. @param string $key @param string|null $locale @return mixed
[ "Get", "attribute", "translation", "." ]
b981d719ac7dc21d7b507917fa04cc1d49c09f36
https://github.com/indigoram89/laravel-translatable/blob/b981d719ac7dc21d7b507917fa04cc1d49c09f36/src/Translatable.php#L39-L63
train
indigoram89/laravel-translatable
src/Translatable.php
Translatable.setTranslation
public function setTranslation(string $key, string $value = null, string $locale = null) { $this->throwExceptionIfAttributeIsNotTranslatable($key); $locale = $locale ?: config('app.locale'); $translations = $this->getTranslations($key); if ($this->hasSetMutator($key)) { $value = $this->{'set'.Str::studly($key).'Attribute'}($value); } $translations[$locale] = $value; $this->attributes[$key] = json_encode($translations); return $this; }
php
public function setTranslation(string $key, string $value = null, string $locale = null) { $this->throwExceptionIfAttributeIsNotTranslatable($key); $locale = $locale ?: config('app.locale'); $translations = $this->getTranslations($key); if ($this->hasSetMutator($key)) { $value = $this->{'set'.Str::studly($key).'Attribute'}($value); } $translations[$locale] = $value; $this->attributes[$key] = json_encode($translations); return $this; }
[ "public", "function", "setTranslation", "(", "string", "$", "key", ",", "string", "$", "value", "=", "null", ",", "string", "$", "locale", "=", "null", ")", "{", "$", "this", "->", "throwExceptionIfAttributeIsNotTranslatable", "(", "$", "key", ")", ";", "$", "locale", "=", "$", "locale", "?", ":", "config", "(", "'app.locale'", ")", ";", "$", "translations", "=", "$", "this", "->", "getTranslations", "(", "$", "key", ")", ";", "if", "(", "$", "this", "->", "hasSetMutator", "(", "$", "key", ")", ")", "{", "$", "value", "=", "$", "this", "->", "{", "'set'", ".", "Str", "::", "studly", "(", "$", "key", ")", ".", "'Attribute'", "}", "(", "$", "value", ")", ";", "}", "$", "translations", "[", "$", "locale", "]", "=", "$", "value", ";", "$", "this", "->", "attributes", "[", "$", "key", "]", "=", "json_encode", "(", "$", "translations", ")", ";", "return", "$", "this", ";", "}" ]
Set attribute translation. @param string $key @param string $value @param string|null $locale @return mixed
[ "Set", "attribute", "translation", "." ]
b981d719ac7dc21d7b507917fa04cc1d49c09f36
https://github.com/indigoram89/laravel-translatable/blob/b981d719ac7dc21d7b507917fa04cc1d49c09f36/src/Translatable.php#L105-L122
train
ciims/ciims-modules-install
commands/InstallerCommand.php
InstallerCommand.runMigrationTool
private function runMigrationTool(array $dsn) { $runner=new CConsoleCommandRunner(); $runner->commands=array( 'migrate' => array( 'class' => 'application.commands.CiiMigrateCommand', 'dsn' => $dsn, 'interactive' => 0, ), 'db'=>array( 'class'=>'CDbConnection', 'connectionString' => "mysql:host={$dsn['host']};dbname={$dsn['dbname']}", 'emulatePrepare' => true, 'username' => $dsn['username'], 'password' => $dsn['password'], 'charset' => 'utf8', ), ); ob_start(); $runner->run(array( 'yiic', 'migrate' )); return htmlentities(ob_get_clean(), null, Yii::app()->charset); }
php
private function runMigrationTool(array $dsn) { $runner=new CConsoleCommandRunner(); $runner->commands=array( 'migrate' => array( 'class' => 'application.commands.CiiMigrateCommand', 'dsn' => $dsn, 'interactive' => 0, ), 'db'=>array( 'class'=>'CDbConnection', 'connectionString' => "mysql:host={$dsn['host']};dbname={$dsn['dbname']}", 'emulatePrepare' => true, 'username' => $dsn['username'], 'password' => $dsn['password'], 'charset' => 'utf8', ), ); ob_start(); $runner->run(array( 'yiic', 'migrate' )); return htmlentities(ob_get_clean(), null, Yii::app()->charset); }
[ "private", "function", "runMigrationTool", "(", "array", "$", "dsn", ")", "{", "$", "runner", "=", "new", "CConsoleCommandRunner", "(", ")", ";", "$", "runner", "->", "commands", "=", "array", "(", "'migrate'", "=>", "array", "(", "'class'", "=>", "'application.commands.CiiMigrateCommand'", ",", "'dsn'", "=>", "$", "dsn", ",", "'interactive'", "=>", "0", ",", ")", ",", "'db'", "=>", "array", "(", "'class'", "=>", "'CDbConnection'", ",", "'connectionString'", "=>", "\"mysql:host={$dsn['host']};dbname={$dsn['dbname']}\"", ",", "'emulatePrepare'", "=>", "true", ",", "'username'", "=>", "$", "dsn", "[", "'username'", "]", ",", "'password'", "=>", "$", "dsn", "[", "'password'", "]", ",", "'charset'", "=>", "'utf8'", ",", ")", ",", ")", ";", "ob_start", "(", ")", ";", "$", "runner", "->", "run", "(", "array", "(", "'yiic'", ",", "'migrate'", ")", ")", ";", "return", "htmlentities", "(", "ob_get_clean", "(", ")", ",", "null", ",", "Yii", "::", "app", "(", ")", "->", "charset", ")", ";", "}" ]
Runs the migration tool, effectivly installing the database an all appliciable default settings
[ "Runs", "the", "migration", "tool", "effectivly", "installing", "the", "database", "an", "all", "appliciable", "default", "settings" ]
54d6a93e5c42c2d98e19de38a90e27f77358e88b
https://github.com/ciims/ciims-modules-install/blob/54d6a93e5c42c2d98e19de38a90e27f77358e88b/commands/InstallerCommand.php#L79-L105
train
shgysk8zer0/core_api
traits/ports.php
Ports.getDefaultPort
final public function getDefaultPort($name) { $this->_getPortKey($name); if ($this->isNamedPort($name)) { return constant($this->_port_class . $name); } else { throw new \InvalidArgumentException("Unknown name or scheme: {$name}"); } }
php
final public function getDefaultPort($name) { $this->_getPortKey($name); if ($this->isNamedPort($name)) { return constant($this->_port_class . $name); } else { throw new \InvalidArgumentException("Unknown name or scheme: {$name}"); } }
[ "final", "public", "function", "getDefaultPort", "(", "$", "name", ")", "{", "$", "this", "->", "_getPortKey", "(", "$", "name", ")", ";", "if", "(", "$", "this", "->", "isNamedPort", "(", "$", "name", ")", ")", "{", "return", "constant", "(", "$", "this", "->", "_port_class", ".", "$", "name", ")", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Unknown name or scheme: {$name}\"", ")", ";", "}", "}" ]
Get the port number from its name or scheme @param string $name The name or scheme @return int The default port number for it
[ "Get", "the", "port", "number", "from", "its", "name", "or", "scheme" ]
9e9b8baf761af874b95256ad2462e55fbb2b2e58
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/ports.php#L45-L53
train
shgysk8zer0/core_api
traits/ports.php
Ports.isDefaultPort
final public function isDefaultPort($scheme, $port) { $this->_getPortKey($scheme); try { return $this->isNamedPort($scheme) and ($this->getDefaultPort($scheme) === (int)$port); } catch (\Exception $e) { echo $e. PHP_EOL; } }
php
final public function isDefaultPort($scheme, $port) { $this->_getPortKey($scheme); try { return $this->isNamedPort($scheme) and ($this->getDefaultPort($scheme) === (int)$port); } catch (\Exception $e) { echo $e. PHP_EOL; } }
[ "final", "public", "function", "isDefaultPort", "(", "$", "scheme", ",", "$", "port", ")", "{", "$", "this", "->", "_getPortKey", "(", "$", "scheme", ")", ";", "try", "{", "return", "$", "this", "->", "isNamedPort", "(", "$", "scheme", ")", "and", "(", "$", "this", "->", "getDefaultPort", "(", "$", "scheme", ")", "===", "(", "int", ")", "$", "port", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "echo", "$", "e", ".", "PHP_EOL", ";", "}", "}" ]
Checks that the given scheme and port match, according to defaults @param string $scheme The scheme name (E.G. http) @param int $port The number to check default port against @return bool Whether or not given port is the default for the scheme
[ "Checks", "that", "the", "given", "scheme", "and", "port", "match", "according", "to", "defaults" ]
9e9b8baf761af874b95256ad2462e55fbb2b2e58
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/ports.php#L63-L71
train
bkstg/schedule-bundle
EventListener/FullCompanyListener.php
FullCompanyListener.onFlush
public function onFlush(OnFlushEventArgs $args): void { // Get the entity manager and unit of work. $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); // Check insertions for new events. foreach ($uow->getScheduledEntityInsertions() as $entity) { foreach ($this->getInvitations($entity) as $invitation) { $em->persist($invitation); $uow->computeChangeset($em->getClassMetadata(Invitation::class), $invitation); } } // Check updates for updated events. foreach ($uow->getScheduledEntityUpdates() as $entity) { foreach ($this->getInvitations($entity) as $invitation) { $em->persist($invitation); $uow->computeChangeset($em->getClassMetadata(Invitation::class), $invitation); } } }
php
public function onFlush(OnFlushEventArgs $args): void { // Get the entity manager and unit of work. $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); // Check insertions for new events. foreach ($uow->getScheduledEntityInsertions() as $entity) { foreach ($this->getInvitations($entity) as $invitation) { $em->persist($invitation); $uow->computeChangeset($em->getClassMetadata(Invitation::class), $invitation); } } // Check updates for updated events. foreach ($uow->getScheduledEntityUpdates() as $entity) { foreach ($this->getInvitations($entity) as $invitation) { $em->persist($invitation); $uow->computeChangeset($em->getClassMetadata(Invitation::class), $invitation); } } }
[ "public", "function", "onFlush", "(", "OnFlushEventArgs", "$", "args", ")", ":", "void", "{", "// Get the entity manager and unit of work.", "$", "em", "=", "$", "args", "->", "getEntityManager", "(", ")", ";", "$", "uow", "=", "$", "em", "->", "getUnitOfWork", "(", ")", ";", "// Check insertions for new events.", "foreach", "(", "$", "uow", "->", "getScheduledEntityInsertions", "(", ")", "as", "$", "entity", ")", "{", "foreach", "(", "$", "this", "->", "getInvitations", "(", "$", "entity", ")", "as", "$", "invitation", ")", "{", "$", "em", "->", "persist", "(", "$", "invitation", ")", ";", "$", "uow", "->", "computeChangeset", "(", "$", "em", "->", "getClassMetadata", "(", "Invitation", "::", "class", ")", ",", "$", "invitation", ")", ";", "}", "}", "// Check updates for updated events.", "foreach", "(", "$", "uow", "->", "getScheduledEntityUpdates", "(", ")", "as", "$", "entity", ")", "{", "foreach", "(", "$", "this", "->", "getInvitations", "(", "$", "entity", ")", "as", "$", "invitation", ")", "{", "$", "em", "->", "persist", "(", "$", "invitation", ")", ";", "$", "uow", "->", "computeChangeset", "(", "$", "em", "->", "getClassMetadata", "(", "Invitation", "::", "class", ")", ",", "$", "invitation", ")", ";", "}", "}", "}" ]
Listens for the onFlush event. @param OnFlushEventArgs $args The arguments for this event. @return void
[ "Listens", "for", "the", "onFlush", "event", "." ]
e64ac897aa7b28bc48319470d65de13cd4788afe
https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/EventListener/FullCompanyListener.php#L41-L62
train
bkstg/schedule-bundle
EventListener/FullCompanyListener.php
FullCompanyListener.getInvitations
private function getInvitations($object) { // This must be an event with a full company call. if (!$object instanceof Event || !$object->getFullCompany()) { return []; } // Index existing invites so that we don't duplicate any. $existing = []; foreach ($object->getInvitations() as $existing_invitation) { $existing[] = $existing_invitation->getInvitee(); } // Create and persist invitations for all active members of groups. $invitations = []; foreach ($object->getGroups() as $group) { foreach ($this->membership_provider->loadActiveMembershipsByProduction($group) as $membership) { // We can only act on our users. if (!$membership->getMember() instanceof UserInterface) { continue; } // If this membership is active, has not expired and is not // already invited create new invitation. if ($membership->isActive() && !$membership->isExpired() && !in_array($membership->getMember()->getUsername(), $existing) ) { // Create new invitation to this event for this member. $invite = new Invitation(); $invite->setEvent($object); $invite->setInvitee($membership->getMember()->getUsername()); $invite->setOptional(false); $invitations[] = $invite; } } } // Return the new invitations for this event. return $invitations; }
php
private function getInvitations($object) { // This must be an event with a full company call. if (!$object instanceof Event || !$object->getFullCompany()) { return []; } // Index existing invites so that we don't duplicate any. $existing = []; foreach ($object->getInvitations() as $existing_invitation) { $existing[] = $existing_invitation->getInvitee(); } // Create and persist invitations for all active members of groups. $invitations = []; foreach ($object->getGroups() as $group) { foreach ($this->membership_provider->loadActiveMembershipsByProduction($group) as $membership) { // We can only act on our users. if (!$membership->getMember() instanceof UserInterface) { continue; } // If this membership is active, has not expired and is not // already invited create new invitation. if ($membership->isActive() && !$membership->isExpired() && !in_array($membership->getMember()->getUsername(), $existing) ) { // Create new invitation to this event for this member. $invite = new Invitation(); $invite->setEvent($object); $invite->setInvitee($membership->getMember()->getUsername()); $invite->setOptional(false); $invitations[] = $invite; } } } // Return the new invitations for this event. return $invitations; }
[ "private", "function", "getInvitations", "(", "$", "object", ")", "{", "// This must be an event with a full company call.", "if", "(", "!", "$", "object", "instanceof", "Event", "||", "!", "$", "object", "->", "getFullCompany", "(", ")", ")", "{", "return", "[", "]", ";", "}", "// Index existing invites so that we don't duplicate any.", "$", "existing", "=", "[", "]", ";", "foreach", "(", "$", "object", "->", "getInvitations", "(", ")", "as", "$", "existing_invitation", ")", "{", "$", "existing", "[", "]", "=", "$", "existing_invitation", "->", "getInvitee", "(", ")", ";", "}", "// Create and persist invitations for all active members of groups.", "$", "invitations", "=", "[", "]", ";", "foreach", "(", "$", "object", "->", "getGroups", "(", ")", "as", "$", "group", ")", "{", "foreach", "(", "$", "this", "->", "membership_provider", "->", "loadActiveMembershipsByProduction", "(", "$", "group", ")", "as", "$", "membership", ")", "{", "// We can only act on our users.", "if", "(", "!", "$", "membership", "->", "getMember", "(", ")", "instanceof", "UserInterface", ")", "{", "continue", ";", "}", "// If this membership is active, has not expired and is not", "// already invited create new invitation.", "if", "(", "$", "membership", "->", "isActive", "(", ")", "&&", "!", "$", "membership", "->", "isExpired", "(", ")", "&&", "!", "in_array", "(", "$", "membership", "->", "getMember", "(", ")", "->", "getUsername", "(", ")", ",", "$", "existing", ")", ")", "{", "// Create new invitation to this event for this member.", "$", "invite", "=", "new", "Invitation", "(", ")", ";", "$", "invite", "->", "setEvent", "(", "$", "object", ")", ";", "$", "invite", "->", "setInvitee", "(", "$", "membership", "->", "getMember", "(", ")", "->", "getUsername", "(", ")", ")", ";", "$", "invite", "->", "setOptional", "(", "false", ")", ";", "$", "invitations", "[", "]", "=", "$", "invite", ";", "}", "}", "}", "// Return the new invitations for this event.", "return", "$", "invitations", ";", "}" ]
Helper function that generates new invitations as needed. @param mixed $object The entity being acted on. @return Invitation[] The new invitations needed for this event.
[ "Helper", "function", "that", "generates", "new", "invitations", "as", "needed", "." ]
e64ac897aa7b28bc48319470d65de13cd4788afe
https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/EventListener/FullCompanyListener.php#L71-L112
train
wearenolte/wp-acf
src/Acf/RestApi.php
RestApi.register
public static function register() { foreach ( [ 'post', 'user' ] as $type ) { \register_rest_field( 'post' === $type ? get_post_types() : $type , self::FIELD_NAME, [ 'get_callback' => [ __CLASS__, 'get_' . $type . '_fields' ] ] ); } }
php
public static function register() { foreach ( [ 'post', 'user' ] as $type ) { \register_rest_field( 'post' === $type ? get_post_types() : $type , self::FIELD_NAME, [ 'get_callback' => [ __CLASS__, 'get_' . $type . '_fields' ] ] ); } }
[ "public", "static", "function", "register", "(", ")", "{", "foreach", "(", "[", "'post'", ",", "'user'", "]", "as", "$", "type", ")", "{", "\\", "register_rest_field", "(", "'post'", "===", "$", "type", "?", "get_post_types", "(", ")", ":", "$", "type", ",", "self", "::", "FIELD_NAME", ",", "[", "'get_callback'", "=>", "[", "__CLASS__", ",", "'get_'", ".", "$", "type", ".", "'_fields'", "]", "]", ")", ";", "}", "}" ]
Register the field for all post types and users.
[ "Register", "the", "field", "for", "all", "post", "types", "and", "users", "." ]
2f5093438d637fa0eca42ad6d10f6b433ec078b2
https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf/RestApi.php#L22-L30
train
jabernardo/lollipop-php
Library/Page.php
Page.render
static function render($view, array $data = []) { if (file_exists($view)) { if (is_array($data)) { foreach ($data as $_data => $_value) { if (Config::get('security.anti_xss') && is_string($_value)) { $_value = Text::entities($_value); } $$_data = $_value; } } else { throw new \Lollipop\Exception\Runtime('Cannot define variable'); } $file = new \SplFileInfo($view); $file_ext = strtolower($file->getExtension()); ob_start(); if ($file_ext == 'php' || $file_ext == 'phtml') { include($view); } else { readfile($view); } $output = ob_get_clean(); return $output; } return false; }
php
static function render($view, array $data = []) { if (file_exists($view)) { if (is_array($data)) { foreach ($data as $_data => $_value) { if (Config::get('security.anti_xss') && is_string($_value)) { $_value = Text::entities($_value); } $$_data = $_value; } } else { throw new \Lollipop\Exception\Runtime('Cannot define variable'); } $file = new \SplFileInfo($view); $file_ext = strtolower($file->getExtension()); ob_start(); if ($file_ext == 'php' || $file_ext == 'phtml') { include($view); } else { readfile($view); } $output = ob_get_clean(); return $output; } return false; }
[ "static", "function", "render", "(", "$", "view", ",", "array", "$", "data", "=", "[", "]", ")", "{", "if", "(", "file_exists", "(", "$", "view", ")", ")", "{", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "foreach", "(", "$", "data", "as", "$", "_data", "=>", "$", "_value", ")", "{", "if", "(", "Config", "::", "get", "(", "'security.anti_xss'", ")", "&&", "is_string", "(", "$", "_value", ")", ")", "{", "$", "_value", "=", "Text", "::", "entities", "(", "$", "_value", ")", ";", "}", "$", "$", "_data", "=", "$", "_value", ";", "}", "}", "else", "{", "throw", "new", "\\", "Lollipop", "\\", "Exception", "\\", "Runtime", "(", "'Cannot define variable'", ")", ";", "}", "$", "file", "=", "new", "\\", "SplFileInfo", "(", "$", "view", ")", ";", "$", "file_ext", "=", "strtolower", "(", "$", "file", "->", "getExtension", "(", ")", ")", ";", "ob_start", "(", ")", ";", "if", "(", "$", "file_ext", "==", "'php'", "||", "$", "file_ext", "==", "'phtml'", ")", "{", "include", "(", "$", "view", ")", ";", "}", "else", "{", "readfile", "(", "$", "view", ")", ";", "}", "$", "output", "=", "ob_get_clean", "(", ")", ";", "return", "$", "output", ";", "}", "return", "false", ";", "}" ]
Alias read file @param string $view File address @param array $data Data @throws \Lollipop\Exception\Runtime @return string
[ "Alias", "read", "file" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/Page.php#L30-L62
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PhpDumper.addServiceInstance
private function addServiceInstance($id, Definition $definition, $isSimpleInstance) { $class = $this->dumpValue($definition->getClass()); if (0 === strpos($class, "'") && false === strpos($class, '$') && !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) { throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id)); } $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition); $instantiation = ''; if (!$isProxyCandidate && $definition->isShared()) { $instantiation = "\$this->services['$id'] = ".($isSimpleInstance ? '' : '$instance'); } elseif (!$isSimpleInstance) { $instantiation = '$instance'; } $return = ''; if ($isSimpleInstance) { $return = 'return '; } else { $instantiation .= ' = '; } $code = $this->addNewInstance($definition, $return, $instantiation, $id); if (!$isSimpleInstance) { $code .= "\n"; } return $code; }
php
private function addServiceInstance($id, Definition $definition, $isSimpleInstance) { $class = $this->dumpValue($definition->getClass()); if (0 === strpos($class, "'") && false === strpos($class, '$') && !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) { throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id)); } $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition); $instantiation = ''; if (!$isProxyCandidate && $definition->isShared()) { $instantiation = "\$this->services['$id'] = ".($isSimpleInstance ? '' : '$instance'); } elseif (!$isSimpleInstance) { $instantiation = '$instance'; } $return = ''; if ($isSimpleInstance) { $return = 'return '; } else { $instantiation .= ' = '; } $code = $this->addNewInstance($definition, $return, $instantiation, $id); if (!$isSimpleInstance) { $code .= "\n"; } return $code; }
[ "private", "function", "addServiceInstance", "(", "$", "id", ",", "Definition", "$", "definition", ",", "$", "isSimpleInstance", ")", "{", "$", "class", "=", "$", "this", "->", "dumpValue", "(", "$", "definition", "->", "getClass", "(", ")", ")", ";", "if", "(", "0", "===", "strpos", "(", "$", "class", ",", "\"'\"", ")", "&&", "false", "===", "strpos", "(", "$", "class", ",", "'$'", ")", "&&", "!", "preg_match", "(", "'/^\\'(?:\\\\\\{2})?[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*(?:\\\\\\{2}[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)*\\'$/'", ",", "$", "class", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'\"%s\" is not a valid class name for the \"%s\" service.'", ",", "$", "class", ",", "$", "id", ")", ")", ";", "}", "$", "isProxyCandidate", "=", "$", "this", "->", "getProxyDumper", "(", ")", "->", "isProxyCandidate", "(", "$", "definition", ")", ";", "$", "instantiation", "=", "''", ";", "if", "(", "!", "$", "isProxyCandidate", "&&", "$", "definition", "->", "isShared", "(", ")", ")", "{", "$", "instantiation", "=", "\"\\$this->services['$id'] = \"", ".", "(", "$", "isSimpleInstance", "?", "''", ":", "'$instance'", ")", ";", "}", "elseif", "(", "!", "$", "isSimpleInstance", ")", "{", "$", "instantiation", "=", "'$instance'", ";", "}", "$", "return", "=", "''", ";", "if", "(", "$", "isSimpleInstance", ")", "{", "$", "return", "=", "'return '", ";", "}", "else", "{", "$", "instantiation", ".=", "' = '", ";", "}", "$", "code", "=", "$", "this", "->", "addNewInstance", "(", "$", "definition", ",", "$", "return", ",", "$", "instantiation", ",", "$", "id", ")", ";", "if", "(", "!", "$", "isSimpleInstance", ")", "{", "$", "code", ".=", "\"\\n\"", ";", "}", "return", "$", "code", ";", "}" ]
Generates the service instance. @param string $id @param Definition $definition @param bool $isSimpleInstance @return string @throws InvalidArgumentException @throws RuntimeException
[ "Generates", "the", "service", "instance", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L531-L562
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PhpDumper.isTrivialInstance
private function isTrivialInstance(Definition $definition) { if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) { return false; } if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < count($definition->getArguments())) { return false; } foreach ($definition->getArguments() as $arg) { if (!$arg || $arg instanceof Parameter) { continue; } if (is_array($arg) && 3 >= count($arg)) { foreach ($arg as $k => $v) { if ($this->dumpValue($k) !== $this->dumpValue($k, false)) { return false; } if (!$v || $v instanceof Parameter) { continue; } if ($v instanceof Reference && $this->container->has($id = (string) $v) && $this->container->findDefinition($id)->isSynthetic()) { continue; } if (!is_scalar($v) || $this->dumpValue($v) !== $this->dumpValue($v, false)) { return false; } } } elseif ($arg instanceof Reference && $this->container->has($id = (string) $arg) && $this->container->findDefinition($id)->isSynthetic()) { continue; } elseif (!is_scalar($arg) || $this->dumpValue($arg) !== $this->dumpValue($arg, false)) { return false; } } if (false !== strpos($this->dumpLiteralClass($this->dumpValue($definition->getClass())), '$')) { return false; } return true; }
php
private function isTrivialInstance(Definition $definition) { if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) { return false; } if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < count($definition->getArguments())) { return false; } foreach ($definition->getArguments() as $arg) { if (!$arg || $arg instanceof Parameter) { continue; } if (is_array($arg) && 3 >= count($arg)) { foreach ($arg as $k => $v) { if ($this->dumpValue($k) !== $this->dumpValue($k, false)) { return false; } if (!$v || $v instanceof Parameter) { continue; } if ($v instanceof Reference && $this->container->has($id = (string) $v) && $this->container->findDefinition($id)->isSynthetic()) { continue; } if (!is_scalar($v) || $this->dumpValue($v) !== $this->dumpValue($v, false)) { return false; } } } elseif ($arg instanceof Reference && $this->container->has($id = (string) $arg) && $this->container->findDefinition($id)->isSynthetic()) { continue; } elseif (!is_scalar($arg) || $this->dumpValue($arg) !== $this->dumpValue($arg, false)) { return false; } } if (false !== strpos($this->dumpLiteralClass($this->dumpValue($definition->getClass())), '$')) { return false; } return true; }
[ "private", "function", "isTrivialInstance", "(", "Definition", "$", "definition", ")", "{", "if", "(", "$", "definition", "->", "isSynthetic", "(", ")", "||", "$", "definition", "->", "getFile", "(", ")", "||", "$", "definition", "->", "getMethodCalls", "(", ")", "||", "$", "definition", "->", "getProperties", "(", ")", "||", "$", "definition", "->", "getConfigurator", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "definition", "->", "isDeprecated", "(", ")", "||", "$", "definition", "->", "isLazy", "(", ")", "||", "$", "definition", "->", "getFactory", "(", ")", "||", "3", "<", "count", "(", "$", "definition", "->", "getArguments", "(", ")", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "definition", "->", "getArguments", "(", ")", "as", "$", "arg", ")", "{", "if", "(", "!", "$", "arg", "||", "$", "arg", "instanceof", "Parameter", ")", "{", "continue", ";", "}", "if", "(", "is_array", "(", "$", "arg", ")", "&&", "3", ">=", "count", "(", "$", "arg", ")", ")", "{", "foreach", "(", "$", "arg", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "this", "->", "dumpValue", "(", "$", "k", ")", "!==", "$", "this", "->", "dumpValue", "(", "$", "k", ",", "false", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "$", "v", "||", "$", "v", "instanceof", "Parameter", ")", "{", "continue", ";", "}", "if", "(", "$", "v", "instanceof", "Reference", "&&", "$", "this", "->", "container", "->", "has", "(", "$", "id", "=", "(", "string", ")", "$", "v", ")", "&&", "$", "this", "->", "container", "->", "findDefinition", "(", "$", "id", ")", "->", "isSynthetic", "(", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "is_scalar", "(", "$", "v", ")", "||", "$", "this", "->", "dumpValue", "(", "$", "v", ")", "!==", "$", "this", "->", "dumpValue", "(", "$", "v", ",", "false", ")", ")", "{", "return", "false", ";", "}", "}", "}", "elseif", "(", "$", "arg", "instanceof", "Reference", "&&", "$", "this", "->", "container", "->", "has", "(", "$", "id", "=", "(", "string", ")", "$", "arg", ")", "&&", "$", "this", "->", "container", "->", "findDefinition", "(", "$", "id", ")", "->", "isSynthetic", "(", ")", ")", "{", "continue", ";", "}", "elseif", "(", "!", "is_scalar", "(", "$", "arg", ")", "||", "$", "this", "->", "dumpValue", "(", "$", "arg", ")", "!==", "$", "this", "->", "dumpValue", "(", "$", "arg", ",", "false", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "false", "!==", "strpos", "(", "$", "this", "->", "dumpLiteralClass", "(", "$", "this", "->", "dumpValue", "(", "$", "definition", "->", "getClass", "(", ")", ")", ")", ",", "'$'", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks if the definition is a trivial instance. @param Definition $definition @return bool
[ "Checks", "if", "the", "definition", "is", "a", "trivial", "instance", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L571-L611
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PhpDumper.addServiceMethodCalls
private function addServiceMethodCalls(Definition $definition, $variableName = 'instance') { $calls = ''; foreach ($definition->getMethodCalls() as $call) { $arguments = array(); foreach ($call[1] as $value) { $arguments[] = $this->dumpValue($value); } $calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$%s->%s(%s);\n", $variableName, $call[0], implode(', ', $arguments))); } return $calls; }
php
private function addServiceMethodCalls(Definition $definition, $variableName = 'instance') { $calls = ''; foreach ($definition->getMethodCalls() as $call) { $arguments = array(); foreach ($call[1] as $value) { $arguments[] = $this->dumpValue($value); } $calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$%s->%s(%s);\n", $variableName, $call[0], implode(', ', $arguments))); } return $calls; }
[ "private", "function", "addServiceMethodCalls", "(", "Definition", "$", "definition", ",", "$", "variableName", "=", "'instance'", ")", "{", "$", "calls", "=", "''", ";", "foreach", "(", "$", "definition", "->", "getMethodCalls", "(", ")", "as", "$", "call", ")", "{", "$", "arguments", "=", "array", "(", ")", ";", "foreach", "(", "$", "call", "[", "1", "]", "as", "$", "value", ")", "{", "$", "arguments", "[", "]", "=", "$", "this", "->", "dumpValue", "(", "$", "value", ")", ";", "}", "$", "calls", ".=", "$", "this", "->", "wrapServiceConditionals", "(", "$", "call", "[", "1", "]", ",", "sprintf", "(", "\" \\$%s->%s(%s);\\n\"", ",", "$", "variableName", ",", "$", "call", "[", "0", "]", ",", "implode", "(", "', '", ",", "$", "arguments", ")", ")", ")", ";", "}", "return", "$", "calls", ";", "}" ]
Adds method calls to a service definition. @param Definition $definition @param string $variableName @return string
[ "Adds", "method", "calls", "to", "a", "service", "definition", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L621-L634
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PhpDumper.addServiceConfigurator
private function addServiceConfigurator(Definition $definition, $variableName = 'instance') { if (!$callable = $definition->getConfigurator()) { return ''; } if (is_array($callable)) { if ($callable[0] instanceof Reference || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) { return sprintf(" %s->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } $class = $this->dumpValue($callable[0]); // If the class is a string we can optimize call_user_func away if (0 === strpos($class, "'") && false === strpos($class, '$')) { return sprintf(" %s::%s(\$%s);\n", $this->dumpLiteralClass($class), $callable[1], $variableName); } if (0 === strpos($class, 'new ')) { return sprintf(" (%s)->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } return sprintf(" \\call_user_func(array(%s, '%s'), \$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } return sprintf(" %s(\$%s);\n", $callable, $variableName); }
php
private function addServiceConfigurator(Definition $definition, $variableName = 'instance') { if (!$callable = $definition->getConfigurator()) { return ''; } if (is_array($callable)) { if ($callable[0] instanceof Reference || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) { return sprintf(" %s->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } $class = $this->dumpValue($callable[0]); // If the class is a string we can optimize call_user_func away if (0 === strpos($class, "'") && false === strpos($class, '$')) { return sprintf(" %s::%s(\$%s);\n", $this->dumpLiteralClass($class), $callable[1], $variableName); } if (0 === strpos($class, 'new ')) { return sprintf(" (%s)->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } return sprintf(" \\call_user_func(array(%s, '%s'), \$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } return sprintf(" %s(\$%s);\n", $callable, $variableName); }
[ "private", "function", "addServiceConfigurator", "(", "Definition", "$", "definition", ",", "$", "variableName", "=", "'instance'", ")", "{", "if", "(", "!", "$", "callable", "=", "$", "definition", "->", "getConfigurator", "(", ")", ")", "{", "return", "''", ";", "}", "if", "(", "is_array", "(", "$", "callable", ")", ")", "{", "if", "(", "$", "callable", "[", "0", "]", "instanceof", "Reference", "||", "(", "$", "callable", "[", "0", "]", "instanceof", "Definition", "&&", "$", "this", "->", "definitionVariables", "->", "contains", "(", "$", "callable", "[", "0", "]", ")", ")", ")", "{", "return", "sprintf", "(", "\" %s->%s(\\$%s);\\n\"", ",", "$", "this", "->", "dumpValue", "(", "$", "callable", "[", "0", "]", ")", ",", "$", "callable", "[", "1", "]", ",", "$", "variableName", ")", ";", "}", "$", "class", "=", "$", "this", "->", "dumpValue", "(", "$", "callable", "[", "0", "]", ")", ";", "// If the class is a string we can optimize call_user_func away", "if", "(", "0", "===", "strpos", "(", "$", "class", ",", "\"'\"", ")", "&&", "false", "===", "strpos", "(", "$", "class", ",", "'$'", ")", ")", "{", "return", "sprintf", "(", "\" %s::%s(\\$%s);\\n\"", ",", "$", "this", "->", "dumpLiteralClass", "(", "$", "class", ")", ",", "$", "callable", "[", "1", "]", ",", "$", "variableName", ")", ";", "}", "if", "(", "0", "===", "strpos", "(", "$", "class", ",", "'new '", ")", ")", "{", "return", "sprintf", "(", "\" (%s)->%s(\\$%s);\\n\"", ",", "$", "this", "->", "dumpValue", "(", "$", "callable", "[", "0", "]", ")", ",", "$", "callable", "[", "1", "]", ",", "$", "variableName", ")", ";", "}", "return", "sprintf", "(", "\" \\\\call_user_func(array(%s, '%s'), \\$%s);\\n\"", ",", "$", "this", "->", "dumpValue", "(", "$", "callable", "[", "0", "]", ")", ",", "$", "callable", "[", "1", "]", ",", "$", "variableName", ")", ";", "}", "return", "sprintf", "(", "\" %s(\\$%s);\\n\"", ",", "$", "callable", ",", "$", "variableName", ")", ";", "}" ]
Adds configurator definition. @param Definition $definition @param string $variableName @return string
[ "Adds", "configurator", "definition", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L690-L716
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PhpDumper.addNormalizedIds
private function addNormalizedIds() { $code = ''; $normalizedIds = $this->container->getNormalizedIds(); ksort($normalizedIds); foreach ($normalizedIds as $id => $normalizedId) { if ($this->container->has($normalizedId)) { $code .= ' '.$this->doExport($id).' => '.$this->doExport($normalizedId).",\n"; } } return $code ? " \$this->normalizedIds = array(\n".$code." );\n" : ''; }
php
private function addNormalizedIds() { $code = ''; $normalizedIds = $this->container->getNormalizedIds(); ksort($normalizedIds); foreach ($normalizedIds as $id => $normalizedId) { if ($this->container->has($normalizedId)) { $code .= ' '.$this->doExport($id).' => '.$this->doExport($normalizedId).",\n"; } } return $code ? " \$this->normalizedIds = array(\n".$code." );\n" : ''; }
[ "private", "function", "addNormalizedIds", "(", ")", "{", "$", "code", "=", "''", ";", "$", "normalizedIds", "=", "$", "this", "->", "container", "->", "getNormalizedIds", "(", ")", ";", "ksort", "(", "$", "normalizedIds", ")", ";", "foreach", "(", "$", "normalizedIds", "as", "$", "id", "=>", "$", "normalizedId", ")", "{", "if", "(", "$", "this", "->", "container", "->", "has", "(", "$", "normalizedId", ")", ")", "{", "$", "code", ".=", "' '", ".", "$", "this", "->", "doExport", "(", "$", "id", ")", ".", "' => '", ".", "$", "this", "->", "doExport", "(", "$", "normalizedId", ")", ".", "\",\\n\"", ";", "}", "}", "return", "$", "code", "?", "\" \\$this->normalizedIds = array(\\n\"", ".", "$", "code", ".", "\" );\\n\"", ":", "''", ";", "}" ]
Adds the normalizedIds property definition. @return string
[ "Adds", "the", "normalizedIds", "property", "definition", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L1086-L1098
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PhpDumper.addRemovedIds
private function addRemovedIds() { if (!$ids = $this->container->getRemovedIds()) { return ''; } if ($this->asFiles) { $code = "require \$this->containerDir.\\DIRECTORY_SEPARATOR.'removed-ids.php'"; } else { $code = ''; $ids = array_keys($ids); sort($ids); foreach ($ids as $id) { $code .= ' '.$this->doExport($id)." => true,\n"; } $code = "array(\n{$code} )"; } return <<<EOF public function getRemovedIds() { return {$code}; } EOF; }
php
private function addRemovedIds() { if (!$ids = $this->container->getRemovedIds()) { return ''; } if ($this->asFiles) { $code = "require \$this->containerDir.\\DIRECTORY_SEPARATOR.'removed-ids.php'"; } else { $code = ''; $ids = array_keys($ids); sort($ids); foreach ($ids as $id) { $code .= ' '.$this->doExport($id)." => true,\n"; } $code = "array(\n{$code} )"; } return <<<EOF public function getRemovedIds() { return {$code}; } EOF; }
[ "private", "function", "addRemovedIds", "(", ")", "{", "if", "(", "!", "$", "ids", "=", "$", "this", "->", "container", "->", "getRemovedIds", "(", ")", ")", "{", "return", "''", ";", "}", "if", "(", "$", "this", "->", "asFiles", ")", "{", "$", "code", "=", "\"require \\$this->containerDir.\\\\DIRECTORY_SEPARATOR.'removed-ids.php'\"", ";", "}", "else", "{", "$", "code", "=", "''", ";", "$", "ids", "=", "array_keys", "(", "$", "ids", ")", ";", "sort", "(", "$", "ids", ")", ";", "foreach", "(", "$", "ids", "as", "$", "id", ")", "{", "$", "code", ".=", "' '", ".", "$", "this", "->", "doExport", "(", "$", "id", ")", ".", "\" => true,\\n\"", ";", "}", "$", "code", "=", "\"array(\\n{$code} )\"", ";", "}", "return", " <<<EOF\n\n public function getRemovedIds()\n {\n return {$code};\n }\n\nEOF", ";", "}" ]
Adds the removedIds definition. @return string
[ "Adds", "the", "removedIds", "definition", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L1124-L1150
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PhpDumper.addFileMap
private function addFileMap() { $code = ''; $definitions = $this->container->getDefinitions(); ksort($definitions); foreach ($definitions as $id => $definition) { if (!$definition->isSynthetic() && $definition->isShared() && !$this->isHotPath($definition)) { $code .= sprintf(" %s => '%s.php',\n", $this->doExport($id), $this->generateMethodName($id)); } } return $code ? " \$this->fileMap = array(\n{$code} );\n" : ''; }
php
private function addFileMap() { $code = ''; $definitions = $this->container->getDefinitions(); ksort($definitions); foreach ($definitions as $id => $definition) { if (!$definition->isSynthetic() && $definition->isShared() && !$this->isHotPath($definition)) { $code .= sprintf(" %s => '%s.php',\n", $this->doExport($id), $this->generateMethodName($id)); } } return $code ? " \$this->fileMap = array(\n{$code} );\n" : ''; }
[ "private", "function", "addFileMap", "(", ")", "{", "$", "code", "=", "''", ";", "$", "definitions", "=", "$", "this", "->", "container", "->", "getDefinitions", "(", ")", ";", "ksort", "(", "$", "definitions", ")", ";", "foreach", "(", "$", "definitions", "as", "$", "id", "=>", "$", "definition", ")", "{", "if", "(", "!", "$", "definition", "->", "isSynthetic", "(", ")", "&&", "$", "definition", "->", "isShared", "(", ")", "&&", "!", "$", "this", "->", "isHotPath", "(", "$", "definition", ")", ")", "{", "$", "code", ".=", "sprintf", "(", "\" %s => '%s.php',\\n\"", ",", "$", "this", "->", "doExport", "(", "$", "id", ")", ",", "$", "this", "->", "generateMethodName", "(", "$", "id", ")", ")", ";", "}", "}", "return", "$", "code", "?", "\" \\$this->fileMap = array(\\n{$code} );\\n\"", ":", "''", ";", "}" ]
Adds the fileMap property definition. @return string
[ "Adds", "the", "fileMap", "property", "definition", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L1176-L1188
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PhpDumper.getServiceConditionals
private function getServiceConditionals($value) { $conditions = array(); foreach (ContainerBuilder::getInitializedConditionals($value) as $service) { if (!$this->container->hasDefinition($service)) { return 'false'; } $conditions[] = sprintf("isset(\$this->services['%s'])", $service); } foreach (ContainerBuilder::getServiceConditionals($value) as $service) { if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) { continue; } $conditions[] = sprintf("\$this->has('%s')", $service); } if (!$conditions) { return ''; } return implode(' && ', $conditions); }
php
private function getServiceConditionals($value) { $conditions = array(); foreach (ContainerBuilder::getInitializedConditionals($value) as $service) { if (!$this->container->hasDefinition($service)) { return 'false'; } $conditions[] = sprintf("isset(\$this->services['%s'])", $service); } foreach (ContainerBuilder::getServiceConditionals($value) as $service) { if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) { continue; } $conditions[] = sprintf("\$this->has('%s')", $service); } if (!$conditions) { return ''; } return implode(' && ', $conditions); }
[ "private", "function", "getServiceConditionals", "(", "$", "value", ")", "{", "$", "conditions", "=", "array", "(", ")", ";", "foreach", "(", "ContainerBuilder", "::", "getInitializedConditionals", "(", "$", "value", ")", "as", "$", "service", ")", "{", "if", "(", "!", "$", "this", "->", "container", "->", "hasDefinition", "(", "$", "service", ")", ")", "{", "return", "'false'", ";", "}", "$", "conditions", "[", "]", "=", "sprintf", "(", "\"isset(\\$this->services['%s'])\"", ",", "$", "service", ")", ";", "}", "foreach", "(", "ContainerBuilder", "::", "getServiceConditionals", "(", "$", "value", ")", "as", "$", "service", ")", "{", "if", "(", "$", "this", "->", "container", "->", "hasDefinition", "(", "$", "service", ")", "&&", "!", "$", "this", "->", "container", "->", "getDefinition", "(", "$", "service", ")", "->", "isPublic", "(", ")", ")", "{", "continue", ";", "}", "$", "conditions", "[", "]", "=", "sprintf", "(", "\"\\$this->has('%s')\"", ",", "$", "service", ")", ";", "}", "if", "(", "!", "$", "conditions", ")", "{", "return", "''", ";", "}", "return", "implode", "(", "' && '", ",", "$", "conditions", ")", ";", "}" ]
Get the conditions to execute for conditional services. @param string $value @return null|string
[ "Get", "the", "conditions", "to", "execute", "for", "conditional", "services", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L1530-L1552
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PhpDumper.getNextVariableName
private function getNextVariableName() { $firstChars = self::FIRST_CHARS; $firstCharsLength = strlen($firstChars); $nonFirstChars = self::NON_FIRST_CHARS; $nonFirstCharsLength = strlen($nonFirstChars); while (true) { $name = ''; $i = $this->variableCount; if ('' === $name) { $name .= $firstChars[$i % $firstCharsLength]; $i = (int) ($i / $firstCharsLength); } while ($i > 0) { --$i; $name .= $nonFirstChars[$i % $nonFirstCharsLength]; $i = (int) ($i / $nonFirstCharsLength); } ++$this->variableCount; // check that the name is not reserved if (in_array($name, $this->reservedVariables, true)) { continue; } return $name; } }
php
private function getNextVariableName() { $firstChars = self::FIRST_CHARS; $firstCharsLength = strlen($firstChars); $nonFirstChars = self::NON_FIRST_CHARS; $nonFirstCharsLength = strlen($nonFirstChars); while (true) { $name = ''; $i = $this->variableCount; if ('' === $name) { $name .= $firstChars[$i % $firstCharsLength]; $i = (int) ($i / $firstCharsLength); } while ($i > 0) { --$i; $name .= $nonFirstChars[$i % $nonFirstCharsLength]; $i = (int) ($i / $nonFirstCharsLength); } ++$this->variableCount; // check that the name is not reserved if (in_array($name, $this->reservedVariables, true)) { continue; } return $name; } }
[ "private", "function", "getNextVariableName", "(", ")", "{", "$", "firstChars", "=", "self", "::", "FIRST_CHARS", ";", "$", "firstCharsLength", "=", "strlen", "(", "$", "firstChars", ")", ";", "$", "nonFirstChars", "=", "self", "::", "NON_FIRST_CHARS", ";", "$", "nonFirstCharsLength", "=", "strlen", "(", "$", "nonFirstChars", ")", ";", "while", "(", "true", ")", "{", "$", "name", "=", "''", ";", "$", "i", "=", "$", "this", "->", "variableCount", ";", "if", "(", "''", "===", "$", "name", ")", "{", "$", "name", ".=", "$", "firstChars", "[", "$", "i", "%", "$", "firstCharsLength", "]", ";", "$", "i", "=", "(", "int", ")", "(", "$", "i", "/", "$", "firstCharsLength", ")", ";", "}", "while", "(", "$", "i", ">", "0", ")", "{", "--", "$", "i", ";", "$", "name", ".=", "$", "nonFirstChars", "[", "$", "i", "%", "$", "nonFirstCharsLength", "]", ";", "$", "i", "=", "(", "int", ")", "(", "$", "i", "/", "$", "nonFirstCharsLength", ")", ";", "}", "++", "$", "this", "->", "variableCount", ";", "// check that the name is not reserved", "if", "(", "in_array", "(", "$", "name", ",", "$", "this", "->", "reservedVariables", ",", "true", ")", ")", "{", "continue", ";", "}", "return", "$", "name", ";", "}", "}" ]
Returns the next name to use. @return string
[ "Returns", "the", "next", "name", "to", "use", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L1979-L2010
train
freialib/ran.tools
src/Field.php
Field.fieldfillers
protected function fieldfillers() { $fieldrender = $this->fieldrender(); if ($this->hintrenderer !== null) { $callable = &$this->hintrenderer; $hintsrender = $callable($this->hints()); } else { # no hint renderer $hintsrender = null; } if ($this->showerrors && $this->errorrenderer) { $callable = &$this->errorrenderer; $errorrrender = $callable($this->errors()); } else { # no error renderer $errorrrender = null; } return array ( ':id' => $this->get('id', null), ':field' => $fieldrender, ':label' => $this->fieldlabel(), ':hints' => $hintsrender, ':errors' => $errorrrender, ); }
php
protected function fieldfillers() { $fieldrender = $this->fieldrender(); if ($this->hintrenderer !== null) { $callable = &$this->hintrenderer; $hintsrender = $callable($this->hints()); } else { # no hint renderer $hintsrender = null; } if ($this->showerrors && $this->errorrenderer) { $callable = &$this->errorrenderer; $errorrrender = $callable($this->errors()); } else { # no error renderer $errorrrender = null; } return array ( ':id' => $this->get('id', null), ':field' => $fieldrender, ':label' => $this->fieldlabel(), ':hints' => $hintsrender, ':errors' => $errorrrender, ); }
[ "protected", "function", "fieldfillers", "(", ")", "{", "$", "fieldrender", "=", "$", "this", "->", "fieldrender", "(", ")", ";", "if", "(", "$", "this", "->", "hintrenderer", "!==", "null", ")", "{", "$", "callable", "=", "&", "$", "this", "->", "hintrenderer", ";", "$", "hintsrender", "=", "$", "callable", "(", "$", "this", "->", "hints", "(", ")", ")", ";", "}", "else", "{", "# no hint renderer", "$", "hintsrender", "=", "null", ";", "}", "if", "(", "$", "this", "->", "showerrors", "&&", "$", "this", "->", "errorrenderer", ")", "{", "$", "callable", "=", "&", "$", "this", "->", "errorrenderer", ";", "$", "errorrrender", "=", "$", "callable", "(", "$", "this", "->", "errors", "(", ")", ")", ";", "}", "else", "{", "# no error renderer", "$", "errorrrender", "=", "null", ";", "}", "return", "array", "(", "':id'", "=>", "$", "this", "->", "get", "(", "'id'", ",", "null", ")", ",", "':field'", "=>", "$", "fieldrender", ",", "':label'", "=>", "$", "this", "->", "fieldlabel", "(", ")", ",", "':hints'", "=>", "$", "hintsrender", ",", "':errors'", "=>", "$", "errorrrender", ",", ")", ";", "}" ]
Hook for adding additional fillers for hotwiring funcitonality. eg. say you need special classes on labels, you would overwrite this method to enable your templates to understand new inputs @return array
[ "Hook", "for", "adding", "additional", "fillers", "for", "hotwiring", "funcitonality", "." ]
f4cbb926ef54da357b102cbfa4b6ce273be6ce63
https://github.com/freialib/ran.tools/blob/f4cbb926ef54da357b102cbfa4b6ce273be6ce63/src/Field.php#L46-L74
train
stubbles/stubbles-date
src/main/php/Date.php
Date.castFrom
public static function castFrom($value, string $name = 'Date'): self { if (is_int($value) || is_string($value) || $value instanceof \DateTime) { return new self($value); } if (!($value instanceof Date)) { throw new \InvalidArgumentException( $name . ' must be a timestamp, a string containing time info' . ' or an instance of \DateTime or ' . __CLASS__ . ', but was ' . gettype($value) ); } return $value; }
php
public static function castFrom($value, string $name = 'Date'): self { if (is_int($value) || is_string($value) || $value instanceof \DateTime) { return new self($value); } if (!($value instanceof Date)) { throw new \InvalidArgumentException( $name . ' must be a timestamp, a string containing time info' . ' or an instance of \DateTime or ' . __CLASS__ . ', but was ' . gettype($value) ); } return $value; }
[ "public", "static", "function", "castFrom", "(", "$", "value", ",", "string", "$", "name", "=", "'Date'", ")", ":", "self", "{", "if", "(", "is_int", "(", "$", "value", ")", "||", "is_string", "(", "$", "value", ")", "||", "$", "value", "instanceof", "\\", "DateTime", ")", "{", "return", "new", "self", "(", "$", "value", ")", ";", "}", "if", "(", "!", "(", "$", "value", "instanceof", "Date", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "$", "name", ".", "' must be a timestamp, a string containing time info'", ".", "' or an instance of \\DateTime or '", ".", "__CLASS__", ".", "', but was '", ".", "gettype", "(", "$", "value", ")", ")", ";", "}", "return", "$", "value", ";", "}" ]
casts given value to an instance of Date @param int|string|\DateTime|Date $value @param string $name @return \stubbles\date\Date @throws \InvalidArgumentException @since 3.4.4
[ "casts", "given", "value", "to", "an", "instance", "of", "Date" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/Date.php#L112-L127
train
silverorange/Concentrate
Concentrate/Path.php
Concentrate_Path.writeDirectory
public function writeDirectory() { $toDirectory = dirname($this->path); if (!file_exists($toDirectory)) { mkdir($toDirectory, 0770, true); } if (!is_dir($toDirectory)) { throw new Concentrate_FileException( "Could not write to directory {$toDirectory} because it " . "exists and is not a directory.", 0, $toDirectory ); } return $this; }
php
public function writeDirectory() { $toDirectory = dirname($this->path); if (!file_exists($toDirectory)) { mkdir($toDirectory, 0770, true); } if (!is_dir($toDirectory)) { throw new Concentrate_FileException( "Could not write to directory {$toDirectory} because it " . "exists and is not a directory.", 0, $toDirectory ); } return $this; }
[ "public", "function", "writeDirectory", "(", ")", "{", "$", "toDirectory", "=", "dirname", "(", "$", "this", "->", "path", ")", ";", "if", "(", "!", "file_exists", "(", "$", "toDirectory", ")", ")", "{", "mkdir", "(", "$", "toDirectory", ",", "0770", ",", "true", ")", ";", "}", "if", "(", "!", "is_dir", "(", "$", "toDirectory", ")", ")", "{", "throw", "new", "Concentrate_FileException", "(", "\"Could not write to directory {$toDirectory} because it \"", ".", "\"exists and is not a directory.\"", ",", "0", ",", "$", "toDirectory", ")", ";", "}", "return", "$", "this", ";", "}" ]
Creates a directory for this path if such a directory does not already exist The last item in this path is considered the file and is stripped off the path before the directory is created. For example, this creates the directory '/foo/bar': <code> <?php $path = new Concentrate_Path('/foo/bar/baz'); $path->writeDirectory(); ?> </code> @return Concentrate_Path the current object for fluent interface. @throws Concentrate_FileException if the directory could not be created.
[ "Creates", "a", "directory", "for", "this", "path", "if", "such", "a", "directory", "does", "not", "already", "exist" ]
e0b679bedc105dc4280bb68a233c31246d20e6c5
https://github.com/silverorange/Concentrate/blob/e0b679bedc105dc4280bb68a233c31246d20e6c5/Concentrate/Path.php#L55-L73
train
silverorange/Concentrate
Concentrate/Path.php
Concentrate_Path.evaluate
public function evaluate() { $postPath = array(); $prePath = array(); $path = rtrim($this->path, '/'); $pathSegments = explode('/', $path); foreach ($pathSegments as $segment) { if ($segment == '..') { if (count($postPath) > 0) { array_pop($postPath); } else { // we've gone past the start of the relative path array_push($prePath, '..'); } } else if ($segment == '.') { // no-op } else { array_push($postPath, $segment); } } return new Concentrate_Path( implode( '/', array_merge( $prePath, $postPath ) ) ); }
php
public function evaluate() { $postPath = array(); $prePath = array(); $path = rtrim($this->path, '/'); $pathSegments = explode('/', $path); foreach ($pathSegments as $segment) { if ($segment == '..') { if (count($postPath) > 0) { array_pop($postPath); } else { // we've gone past the start of the relative path array_push($prePath, '..'); } } else if ($segment == '.') { // no-op } else { array_push($postPath, $segment); } } return new Concentrate_Path( implode( '/', array_merge( $prePath, $postPath ) ) ); }
[ "public", "function", "evaluate", "(", ")", "{", "$", "postPath", "=", "array", "(", ")", ";", "$", "prePath", "=", "array", "(", ")", ";", "$", "path", "=", "rtrim", "(", "$", "this", "->", "path", ",", "'/'", ")", ";", "$", "pathSegments", "=", "explode", "(", "'/'", ",", "$", "path", ")", ";", "foreach", "(", "$", "pathSegments", "as", "$", "segment", ")", "{", "if", "(", "$", "segment", "==", "'..'", ")", "{", "if", "(", "count", "(", "$", "postPath", ")", ">", "0", ")", "{", "array_pop", "(", "$", "postPath", ")", ";", "}", "else", "{", "// we've gone past the start of the relative path", "array_push", "(", "$", "prePath", ",", "'..'", ")", ";", "}", "}", "else", "if", "(", "$", "segment", "==", "'.'", ")", "{", "// no-op", "}", "else", "{", "array_push", "(", "$", "postPath", ",", "$", "segment", ")", ";", "}", "}", "return", "new", "Concentrate_Path", "(", "implode", "(", "'/'", ",", "array_merge", "(", "$", "prePath", ",", "$", "postPath", ")", ")", ")", ";", "}" ]
Evaluates a path that contains relative references and removes superfluous current directory references @return Concentrate_Path a new path object.
[ "Evaluates", "a", "path", "that", "contains", "relative", "references", "and", "removes", "superfluous", "current", "directory", "references" ]
e0b679bedc105dc4280bb68a233c31246d20e6c5
https://github.com/silverorange/Concentrate/blob/e0b679bedc105dc4280bb68a233c31246d20e6c5/Concentrate/Path.php#L81-L112
train
miBadger/miBadger.Observer
src/SubjectTrait.php
SubjectTrait.attach
public function attach(ObserverInterface $observer) { if ($this->isAttached($observer)) { return false; } $this->observers[] = $observer; return true; }
php
public function attach(ObserverInterface $observer) { if ($this->isAttached($observer)) { return false; } $this->observers[] = $observer; return true; }
[ "public", "function", "attach", "(", "ObserverInterface", "$", "observer", ")", "{", "if", "(", "$", "this", "->", "isAttached", "(", "$", "observer", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "observers", "[", "]", "=", "$", "observer", ";", "return", "true", ";", "}" ]
Returns true if the observer is attached successfully. @param ObserverInterface $observer @return bool true if the observer is attached successfully.
[ "Returns", "true", "if", "the", "observer", "is", "attached", "successfully", "." ]
bbb87638acd7b524793042660ffd4d42c8d6b8e5
https://github.com/miBadger/miBadger.Observer/blob/bbb87638acd7b524793042660ffd4d42c8d6b8e5/src/SubjectTrait.php#L41-L50
train
miBadger/miBadger.Observer
src/SubjectTrait.php
SubjectTrait.detach
public function detach(ObserverInterface $observer) { foreach ($this->observers as $key => $value) { if ($value === $observer) { unset($this->observers[$key]); return true; } } return false; }
php
public function detach(ObserverInterface $observer) { foreach ($this->observers as $key => $value) { if ($value === $observer) { unset($this->observers[$key]); return true; } } return false; }
[ "public", "function", "detach", "(", "ObserverInterface", "$", "observer", ")", "{", "foreach", "(", "$", "this", "->", "observers", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "===", "$", "observer", ")", "{", "unset", "(", "$", "this", "->", "observers", "[", "$", "key", "]", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if the observer is detached successfully. @param ObserverInterface $observer @return bool true if the observer is detached successfully.
[ "Returns", "true", "if", "the", "observer", "is", "detached", "successfully", "." ]
bbb87638acd7b524793042660ffd4d42c8d6b8e5
https://github.com/miBadger/miBadger.Observer/blob/bbb87638acd7b524793042660ffd4d42c8d6b8e5/src/SubjectTrait.php#L58-L69
train
miBadger/miBadger.Observer
src/SubjectTrait.php
SubjectTrait.notify
public function notify($arguments = null) { foreach ($this->observers as $observer) { $observer->update($this, $arguments); } }
php
public function notify($arguments = null) { foreach ($this->observers as $observer) { $observer->update($this, $arguments); } }
[ "public", "function", "notify", "(", "$", "arguments", "=", "null", ")", "{", "foreach", "(", "$", "this", "->", "observers", "as", "$", "observer", ")", "{", "$", "observer", "->", "update", "(", "$", "this", ",", "$", "arguments", ")", ";", "}", "}" ]
Notify all the attached observers. @param mixed $arguments @return null
[ "Notify", "all", "the", "attached", "observers", "." ]
bbb87638acd7b524793042660ffd4d42c8d6b8e5
https://github.com/miBadger/miBadger.Observer/blob/bbb87638acd7b524793042660ffd4d42c8d6b8e5/src/SubjectTrait.php#L77-L82
train
JBZoo/Path
src/Path.php
Path.clean
public function clean($path) { $tokens = []; $path = $this->cleanPath($path); $prefix = $this->prefix($path); $path = substr($path, strlen($prefix)); $parts = array_filter(explode('/', $path), 'strlen'); foreach ($parts as $part) { if ('..' === $part) { array_pop($tokens); } elseif ('.' !== $part) { $tokens[] = $part; } } return $prefix . implode('/', $tokens); }
php
public function clean($path) { $tokens = []; $path = $this->cleanPath($path); $prefix = $this->prefix($path); $path = substr($path, strlen($prefix)); $parts = array_filter(explode('/', $path), 'strlen'); foreach ($parts as $part) { if ('..' === $part) { array_pop($tokens); } elseif ('.' !== $part) { $tokens[] = $part; } } return $prefix . implode('/', $tokens); }
[ "public", "function", "clean", "(", "$", "path", ")", "{", "$", "tokens", "=", "[", "]", ";", "$", "path", "=", "$", "this", "->", "cleanPath", "(", "$", "path", ")", ";", "$", "prefix", "=", "$", "this", "->", "prefix", "(", "$", "path", ")", ";", "$", "path", "=", "substr", "(", "$", "path", ",", "strlen", "(", "$", "prefix", ")", ")", ";", "$", "parts", "=", "array_filter", "(", "explode", "(", "'/'", ",", "$", "path", ")", ",", "'strlen'", ")", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "{", "if", "(", "'..'", "===", "$", "part", ")", "{", "array_pop", "(", "$", "tokens", ")", ";", "}", "elseif", "(", "'.'", "!==", "$", "part", ")", "{", "$", "tokens", "[", "]", "=", "$", "part", ";", "}", "}", "return", "$", "prefix", ".", "implode", "(", "'/'", ",", "$", "tokens", ")", ";", "}" ]
Normalize and clean path. @param string $path ("C:\server\test.dev\file.txt") @return string
[ "Normalize", "and", "clean", "path", "." ]
98f8427340ba3f55a999e1ea99f41a526fe2ee90
https://github.com/JBZoo/Path/blob/98f8427340ba3f55a999e1ea99f41a526fe2ee90/src/Path.php#L195-L212
train
JBZoo/Path
src/Path.php
Path.getPaths
public function getPaths($source) { $source = $this->cleanSource($source); list(, $paths) = $this->parse($source); return $paths; }
php
public function getPaths($source) { $source = $this->cleanSource($source); list(, $paths) = $this->parse($source); return $paths; }
[ "public", "function", "getPaths", "(", "$", "source", ")", "{", "$", "source", "=", "$", "this", "->", "cleanSource", "(", "$", "source", ")", ";", "list", "(", ",", "$", "paths", ")", "=", "$", "this", "->", "parse", "(", "$", "source", ")", ";", "return", "$", "paths", ";", "}" ]
Get all absolute path to a file or a directory. @param $source (example: "default:file.txt") @return mixed
[ "Get", "all", "absolute", "path", "to", "a", "file", "or", "a", "directory", "." ]
98f8427340ba3f55a999e1ea99f41a526fe2ee90
https://github.com/JBZoo/Path/blob/98f8427340ba3f55a999e1ea99f41a526fe2ee90/src/Path.php#L244-L250
train
JBZoo/Path
src/Path.php
Path.isVirtual
public function isVirtual($path): bool { $parts = explode(':', $path, 2); list($alias) = $parts; $alias = $this->cleanAlias($alias); if (!array_key_exists($alias, $this->paths) && $this->prefix($path) !== null) { return false; } return count($parts) === 2; }
php
public function isVirtual($path): bool { $parts = explode(':', $path, 2); list($alias) = $parts; $alias = $this->cleanAlias($alias); if (!array_key_exists($alias, $this->paths) && $this->prefix($path) !== null) { return false; } return count($parts) === 2; }
[ "public", "function", "isVirtual", "(", "$", "path", ")", ":", "bool", "{", "$", "parts", "=", "explode", "(", "':'", ",", "$", "path", ",", "2", ")", ";", "list", "(", "$", "alias", ")", "=", "$", "parts", ";", "$", "alias", "=", "$", "this", "->", "cleanAlias", "(", "$", "alias", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "alias", ",", "$", "this", "->", "paths", ")", "&&", "$", "this", "->", "prefix", "(", "$", "path", ")", "!==", "null", ")", "{", "return", "false", ";", "}", "return", "count", "(", "$", "parts", ")", "===", "2", ";", "}" ]
Check virtual or real path. @param string $path (example: "default:file.txt" or "C:\server\test.dev\file.txt") @return bool
[ "Check", "virtual", "or", "real", "path", "." ]
98f8427340ba3f55a999e1ea99f41a526fe2ee90
https://github.com/JBZoo/Path/blob/98f8427340ba3f55a999e1ea99f41a526fe2ee90/src/Path.php#L281-L292
train