repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
alphacomm/alpharpc
src/AlphaRPC/Manager/WorkerHandler/Action.php
Action.removeWorker
public function removeWorker($id) { if ($id instanceof Worker) { $id = $id->getId(); } if (isset($this->waitingList[$id])) { unset($this->waitingList[$id]); } if (isset($this->workerList[$id])) { unset($this->workerList[$id]); } return $this; }
php
public function removeWorker($id) { if ($id instanceof Worker) { $id = $id->getId(); } if (isset($this->waitingList[$id])) { unset($this->waitingList[$id]); } if (isset($this->workerList[$id])) { unset($this->workerList[$id]); } return $this; }
[ "public", "function", "removeWorker", "(", "$", "id", ")", "{", "if", "(", "$", "id", "instanceof", "Worker", ")", "{", "$", "id", "=", "$", "id", "->", "getId", "(", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "waitingList", "[", "$", "id", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "waitingList", "[", "$", "id", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "workerList", "[", "$", "id", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "workerList", "[", "$", "id", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
Removes the worker from the action. @param Worker $id @return Action
[ "Removes", "the", "worker", "from", "the", "action", "." ]
cf162854500554c4ba8d39f2675de35a49c30ed0
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Action.php#L93-L107
train
alphacomm/alpharpc
src/AlphaRPC/Manager/WorkerHandler/Action.php
Action.addWaitingWorker
public function addWaitingWorker($id) { if ($id instanceof Worker) { $id = $id->getId(); } if (!isset($this->workerList[$id])) { throw new \Exception('Trying to add non existent worker to the queue.'); } $worker = $this->workerList[$id]; $this->ready = true; /* * Only add the worker to the end of the wait list if it is not * already there. */ if (!isset($this->waitingList[$id])) { $this->waitingList[$id] = $worker; } return $this; }
php
public function addWaitingWorker($id) { if ($id instanceof Worker) { $id = $id->getId(); } if (!isset($this->workerList[$id])) { throw new \Exception('Trying to add non existent worker to the queue.'); } $worker = $this->workerList[$id]; $this->ready = true; /* * Only add the worker to the end of the wait list if it is not * already there. */ if (!isset($this->waitingList[$id])) { $this->waitingList[$id] = $worker; } return $this; }
[ "public", "function", "addWaitingWorker", "(", "$", "id", ")", "{", "if", "(", "$", "id", "instanceof", "Worker", ")", "{", "$", "id", "=", "$", "id", "->", "getId", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "workerList", "[", "$", "id", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Trying to add non existent worker to the queue.'", ")", ";", "}", "$", "worker", "=", "$", "this", "->", "workerList", "[", "$", "id", "]", ";", "$", "this", "->", "ready", "=", "true", ";", "/*\n * Only add the worker to the end of the wait list if it is not\n * already there.\n */", "if", "(", "!", "isset", "(", "$", "this", "->", "waitingList", "[", "$", "id", "]", ")", ")", "{", "$", "this", "->", "waitingList", "[", "$", "id", "]", "=", "$", "worker", ";", "}", "return", "$", "this", ";", "}" ]
Adds the worker to the waiting list if it is not already in there. @param string|Worker $id @return Action @throws \Exception
[ "Adds", "the", "worker", "to", "the", "waiting", "list", "if", "it", "is", "not", "already", "in", "there", "." ]
cf162854500554c4ba8d39f2675de35a49c30ed0
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Action.php#L117-L139
train
alphacomm/alpharpc
src/AlphaRPC/Manager/WorkerHandler/Action.php
Action.fetchWaitingWorker
public function fetchWaitingWorker() { $count = count($this->waitingList); for ($i = 0; $i < $count; $i++) { $worker = array_shift($this->waitingList); if ($worker->isValid() && $worker->isReady()) { return $worker; } } $this->ready = false; return null; }
php
public function fetchWaitingWorker() { $count = count($this->waitingList); for ($i = 0; $i < $count; $i++) { $worker = array_shift($this->waitingList); if ($worker->isValid() && $worker->isReady()) { return $worker; } } $this->ready = false; return null; }
[ "public", "function", "fetchWaitingWorker", "(", ")", "{", "$", "count", "=", "count", "(", "$", "this", "->", "waitingList", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "$", "worker", "=", "array_shift", "(", "$", "this", "->", "waitingList", ")", ";", "if", "(", "$", "worker", "->", "isValid", "(", ")", "&&", "$", "worker", "->", "isReady", "(", ")", ")", "{", "return", "$", "worker", ";", "}", "}", "$", "this", "->", "ready", "=", "false", ";", "return", "null", ";", "}" ]
Gets the first available worker in the waiting list. @return Worker|null
[ "Gets", "the", "first", "available", "worker", "in", "the", "waiting", "list", "." ]
cf162854500554c4ba8d39f2675de35a49c30ed0
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Action.php#L146-L159
train
alphacomm/alpharpc
src/AlphaRPC/Manager/WorkerHandler/Action.php
Action.cleanup
public function cleanup() { foreach ($this->workerList as $worker) { if (!$worker->isValid()) { $this->removeWorker($worker); } } return $this; }
php
public function cleanup() { foreach ($this->workerList as $worker) { if (!$worker->isValid()) { $this->removeWorker($worker); } } return $this; }
[ "public", "function", "cleanup", "(", ")", "{", "foreach", "(", "$", "this", "->", "workerList", "as", "$", "worker", ")", "{", "if", "(", "!", "$", "worker", "->", "isValid", "(", ")", ")", "{", "$", "this", "->", "removeWorker", "(", "$", "worker", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Removes all invalid workers. @return Action
[ "Removes", "all", "invalid", "workers", "." ]
cf162854500554c4ba8d39f2675de35a49c30ed0
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Action.php#L187-L196
train
acacha/forge-publish
src/Console/Commands/PublishInit.php
PublishInit.confirmAnUserIsCreatedInAcachaLaravelForge
protected function confirmAnUserIsCreatedInAcachaLaravelForge() { $this->info(''); $this->info('Please visit and login on http://forge.acacha.org'); $this->info(''); $this->error('Please use Github Social Login for login!!!'); while (! $this->confirm('Do you have an user created at http:://forge.acacha.com?')) { } }
php
protected function confirmAnUserIsCreatedInAcachaLaravelForge() { $this->info(''); $this->info('Please visit and login on http://forge.acacha.org'); $this->info(''); $this->error('Please use Github Social Login for login!!!'); while (! $this->confirm('Do you have an user created at http:://forge.acacha.com?')) { } }
[ "protected", "function", "confirmAnUserIsCreatedInAcachaLaravelForge", "(", ")", "{", "$", "this", "->", "info", "(", "''", ")", ";", "$", "this", "->", "info", "(", "'Please visit and login on http://forge.acacha.org'", ")", ";", "$", "this", "->", "info", "(", "''", ")", ";", "$", "this", "->", "error", "(", "'Please use Github Social Login for login!!!'", ")", ";", "while", "(", "!", "$", "this", "->", "confirm", "(", "'Do you have an user created at http:://forge.acacha.com?'", ")", ")", "{", "}", "}" ]
Confirm an user is created in Acacha Laravel Forge.
[ "Confirm", "an", "user", "is", "created", "in", "Acacha", "Laravel", "Forge", "." ]
010779e3d2297c763b82dc3fbde992edffb3a6c6
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishInit.php#L69-L78
train
YiMAproject/yimaWidgetator
src/yimaWidgetator/Widget/AbstractWidgetMvc.php
AbstractWidgetMvc.getLayout
function getLayout() { $layoutName = ($this->layout) ? $this->layout : $this->getDefaultLayoutName(); if (strstr($layoutName, '/') === false) { // we have just layout name // the directory prefix assigned to it $DS = (defined('DS')) ? constant('DS') : DIRECTORY_SEPARATOR; // derive default layout pathname $pathname = self::$PATH_PREFIX # widgets .$DS .$this->deriveLayoutPathPrefix() # namespace_widget\widget_name\ .$DS .$layoutName; $this->layout = $pathname; } return $this->layout; }
php
function getLayout() { $layoutName = ($this->layout) ? $this->layout : $this->getDefaultLayoutName(); if (strstr($layoutName, '/') === false) { // we have just layout name // the directory prefix assigned to it $DS = (defined('DS')) ? constant('DS') : DIRECTORY_SEPARATOR; // derive default layout pathname $pathname = self::$PATH_PREFIX # widgets .$DS .$this->deriveLayoutPathPrefix() # namespace_widget\widget_name\ .$DS .$layoutName; $this->layout = $pathname; } return $this->layout; }
[ "function", "getLayout", "(", ")", "{", "$", "layoutName", "=", "(", "$", "this", "->", "layout", ")", "?", "$", "this", "->", "layout", ":", "$", "this", "->", "getDefaultLayoutName", "(", ")", ";", "if", "(", "strstr", "(", "$", "layoutName", ",", "'/'", ")", "===", "false", ")", "{", "// we have just layout name", "// the directory prefix assigned to it", "$", "DS", "=", "(", "defined", "(", "'DS'", ")", ")", "?", "constant", "(", "'DS'", ")", ":", "DIRECTORY_SEPARATOR", ";", "// derive default layout pathname", "$", "pathname", "=", "self", "::", "$", "PATH_PREFIX", "# widgets", ".", "$", "DS", ".", "$", "this", "->", "deriveLayoutPathPrefix", "(", ")", "# namespace_widget\\widget_name\\", ".", "$", "DS", ".", "$", "layoutName", ";", "$", "this", "->", "layout", "=", "$", "pathname", ";", "}", "return", "$", "this", "->", "layout", ";", "}" ]
Get view script layout @return string|ModelInterface
[ "Get", "view", "script", "layout" ]
332bc9318e6ceaec918147b30317da2f5b3d2636
https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Widget/AbstractWidgetMvc.php#L69-L90
train
YiMAproject/yimaWidgetator
src/yimaWidgetator/Widget/AbstractWidgetMvc.php
AbstractWidgetMvc.deriveLayoutPathPrefix
final function deriveLayoutPathPrefix() { $moduleNamespace = $this->deriveModuleNamespace(); $path = ($moduleNamespace) ? $moduleNamespace .'/' : ''; $path .= $this->deriveWidgetName(); // in some cases widget name contains \ from class namespace $path = str_replace('\\', '/', $this->inflectName($path)); return $path; }
php
final function deriveLayoutPathPrefix() { $moduleNamespace = $this->deriveModuleNamespace(); $path = ($moduleNamespace) ? $moduleNamespace .'/' : ''; $path .= $this->deriveWidgetName(); // in some cases widget name contains \ from class namespace $path = str_replace('\\', '/', $this->inflectName($path)); return $path; }
[ "final", "function", "deriveLayoutPathPrefix", "(", ")", "{", "$", "moduleNamespace", "=", "$", "this", "->", "deriveModuleNamespace", "(", ")", ";", "$", "path", "=", "(", "$", "moduleNamespace", ")", "?", "$", "moduleNamespace", ".", "'/'", ":", "''", ";", "$", "path", ".=", "$", "this", "->", "deriveWidgetName", "(", ")", ";", "// in some cases widget name contains \\ from class namespace", "$", "path", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "this", "->", "inflectName", "(", "$", "path", ")", ")", ";", "return", "$", "path", ";", "}" ]
Get layout path prefixed to module layout name note: WidgetNamespace\WidgetName inflected: widget_namespace\widget_name @return string
[ "Get", "layout", "path", "prefixed", "to", "module", "layout", "name" ]
332bc9318e6ceaec918147b30317da2f5b3d2636
https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Widget/AbstractWidgetMvc.php#L138-L148
train
air-php/database
src/Connection.php
Connection.getConnection
private function getConnection() { if (!isset($this->connection)) { $config = new Configuration(); $this->connection = DriverManager::getConnection($this->connectionParams, $config); } return $this->connection; }
php
private function getConnection() { if (!isset($this->connection)) { $config = new Configuration(); $this->connection = DriverManager::getConnection($this->connectionParams, $config); } return $this->connection; }
[ "private", "function", "getConnection", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "connection", ")", ")", "{", "$", "config", "=", "new", "Configuration", "(", ")", ";", "$", "this", "->", "connection", "=", "DriverManager", "::", "getConnection", "(", "$", "this", "->", "connectionParams", ",", "$", "config", ")", ";", "}", "return", "$", "this", "->", "connection", ";", "}" ]
Returns the connection object. @return Connection
[ "Returns", "the", "connection", "object", "." ]
74bdd485b36f3f353b51ab146d2130dd9fc714bd
https://github.com/air-php/database/blob/74bdd485b36f3f353b51ab146d2130dd9fc714bd/src/Connection.php#L70-L79
train
air-php/database
src/Connection.php
Connection.setTimezone
public function setTimezone($timezone) { $smt = $this->getConnection()->prepare('SET time_zone = ?'); $smt->bindValue(1, $timezone); $smt->execute(); }
php
public function setTimezone($timezone) { $smt = $this->getConnection()->prepare('SET time_zone = ?'); $smt->bindValue(1, $timezone); $smt->execute(); }
[ "public", "function", "setTimezone", "(", "$", "timezone", ")", "{", "$", "smt", "=", "$", "this", "->", "getConnection", "(", ")", "->", "prepare", "(", "'SET time_zone = ?'", ")", ";", "$", "smt", "->", "bindValue", "(", "1", ",", "$", "timezone", ")", ";", "$", "smt", "->", "execute", "(", ")", ";", "}" ]
Sets a timezone. @param string $timezone The timezone you wish to set.
[ "Sets", "a", "timezone", "." ]
74bdd485b36f3f353b51ab146d2130dd9fc714bd
https://github.com/air-php/database/blob/74bdd485b36f3f353b51ab146d2130dd9fc714bd/src/Connection.php#L87-L92
train
hal-platform/hal-core
src/Crypto/Encryption.php
Encryption.encrypt
public function encrypt($data) { if (!$data || !is_scalar($data)) { return null; } $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $cipher = sodium_crypto_secretbox($data, $nonce, $this->key); return base64_encode($nonce . $cipher); }
php
public function encrypt($data) { if (!$data || !is_scalar($data)) { return null; } $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $cipher = sodium_crypto_secretbox($data, $nonce, $this->key); return base64_encode($nonce . $cipher); }
[ "public", "function", "encrypt", "(", "$", "data", ")", "{", "if", "(", "!", "$", "data", "||", "!", "is_scalar", "(", "$", "data", ")", ")", "{", "return", "null", ";", "}", "$", "nonce", "=", "random_bytes", "(", "SODIUM_CRYPTO_SECRETBOX_NONCEBYTES", ")", ";", "$", "cipher", "=", "sodium_crypto_secretbox", "(", "$", "data", ",", "$", "nonce", ",", "$", "this", "->", "key", ")", ";", "return", "base64_encode", "(", "$", "nonce", ".", "$", "cipher", ")", ";", "}" ]
Encrypt a string. @param string $data @return string|null
[ "Encrypt", "a", "string", "." ]
30d456f8392fc873301ad4217d2ae90436c67090
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Crypto/Encryption.php#L52-L62
train
acacha/forge-publish
src/Console/Commands/Traits/ChecksSite.php
ChecksSite.checkSite
protected function checkSite() { $sites = $this->fetchSites(fp_env('ACACHA_FORGE_SERVER')); return in_array(fp_env('ACACHA_FORGE_SITE'), collect($sites)->pluck('id')->toArray()); }
php
protected function checkSite() { $sites = $this->fetchSites(fp_env('ACACHA_FORGE_SERVER')); return in_array(fp_env('ACACHA_FORGE_SITE'), collect($sites)->pluck('id')->toArray()); }
[ "protected", "function", "checkSite", "(", ")", "{", "$", "sites", "=", "$", "this", "->", "fetchSites", "(", "fp_env", "(", "'ACACHA_FORGE_SERVER'", ")", ")", ";", "return", "in_array", "(", "fp_env", "(", "'ACACHA_FORGE_SITE'", ")", ",", "collect", "(", "$", "sites", ")", "->", "pluck", "(", "'id'", ")", "->", "toArray", "(", ")", ")", ";", "}" ]
Check site. @return bool
[ "Check", "site", "." ]
010779e3d2297c763b82dc3fbde992edffb3a6c6
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/Traits/ChecksSite.php#L19-L23
train
acacha/forge-publish
src/Console/Commands/Traits/ChecksSite.php
ChecksSite.checkSiteAndAbort
protected function checkSiteAndAbort($site = null) { $site = $site ? $site : fp_env('ACACHA_FORGE_SITE'); if (! $this->checkSite($site)) { $this->error('Site ' . $site . ' not valid'); die(); } }
php
protected function checkSiteAndAbort($site = null) { $site = $site ? $site : fp_env('ACACHA_FORGE_SITE'); if (! $this->checkSite($site)) { $this->error('Site ' . $site . ' not valid'); die(); } }
[ "protected", "function", "checkSiteAndAbort", "(", "$", "site", "=", "null", ")", "{", "$", "site", "=", "$", "site", "?", "$", "site", ":", "fp_env", "(", "'ACACHA_FORGE_SITE'", ")", ";", "if", "(", "!", "$", "this", "->", "checkSite", "(", "$", "site", ")", ")", "{", "$", "this", "->", "error", "(", "'Site '", ".", "$", "site", ".", "' not valid'", ")", ";", "die", "(", ")", ";", "}", "}" ]
Check site and abort. @param null $site
[ "Check", "site", "and", "abort", "." ]
010779e3d2297c763b82dc3fbde992edffb3a6c6
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/Traits/ChecksSite.php#L30-L37
train
gluephp/glue
src/Router/Router.php
Router.resolveErrorHandler
public function resolveErrorHandler($errorCode) { return array_key_exists($errorCode, $this->errorHandlers) ? call_user_func_array($this->errorHandlers[$errorCode], []) : ''; }
php
public function resolveErrorHandler($errorCode) { return array_key_exists($errorCode, $this->errorHandlers) ? call_user_func_array($this->errorHandlers[$errorCode], []) : ''; }
[ "public", "function", "resolveErrorHandler", "(", "$", "errorCode", ")", "{", "return", "array_key_exists", "(", "$", "errorCode", ",", "$", "this", "->", "errorHandlers", ")", "?", "call_user_func_array", "(", "$", "this", "->", "errorHandlers", "[", "$", "errorCode", "]", ",", "[", "]", ")", ":", "''", ";", "}" ]
Resolve an error handler @return [type] [description]
[ "Resolve", "an", "error", "handler" ]
d54e0905dfe74d1c114c04f33fa89a60e2651562
https://github.com/gluephp/glue/blob/d54e0905dfe74d1c114c04f33fa89a60e2651562/src/Router/Router.php#L42-L47
train
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Framework/Theme/Zone/Repository/Doctrine/DoctrineRepository.php
DoctrineRepository.onCreateZone
public function onCreateZone(ZoneEvent $event) { $zone = $event->getZone(); if ($zone->getComponents()->isEmpty()) { return; } $this->save($zone); }
php
public function onCreateZone(ZoneEvent $event) { $zone = $event->getZone(); if ($zone->getComponents()->isEmpty()) { return; } $this->save($zone); }
[ "public", "function", "onCreateZone", "(", "ZoneEvent", "$", "event", ")", "{", "$", "zone", "=", "$", "event", "->", "getZone", "(", ")", ";", "if", "(", "$", "zone", "->", "getComponents", "(", ")", "->", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "$", "this", "->", "save", "(", "$", "zone", ")", ";", "}" ]
Zone creation event handler. Triggers persistence call only if component was defined into it. @param ZoneEvent $event
[ "Zone", "creation", "event", "handler", ".", "Triggers", "persistence", "call", "only", "if", "component", "was", "defined", "into", "it", "." ]
d8122a4150a83d5607289724425cf35c56a5e880
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Theme/Zone/Repository/Doctrine/DoctrineRepository.php#L38-L46
train
phpui/hom-php
src/HOM/Container.php
Container.setItem
public function setItem($item, $index = null): ContainerInterface { if (is_null($index)) { $this->items[] = $item; } else { $this->items[$index] = $item; } return $this; }
php
public function setItem($item, $index = null): ContainerInterface { if (is_null($index)) { $this->items[] = $item; } else { $this->items[$index] = $item; } return $this; }
[ "public", "function", "setItem", "(", "$", "item", ",", "$", "index", "=", "null", ")", ":", "ContainerInterface", "{", "if", "(", "is_null", "(", "$", "index", ")", ")", "{", "$", "this", "->", "items", "[", "]", "=", "$", "item", ";", "}", "else", "{", "$", "this", "->", "items", "[", "$", "index", "]", "=", "$", "item", ";", "}", "return", "$", "this", ";", "}" ]
Set an item into children list. @param mixed $item @param mixed $index Optional. @return \HOM\ContainerInterface
[ "Set", "an", "item", "into", "children", "list", "." ]
c4eccd3e64cf8c7b5ff663f9fea3f31579e17006
https://github.com/phpui/hom-php/blob/c4eccd3e64cf8c7b5ff663f9fea3f31579e17006/src/HOM/Container.php#L54-L62
train
phpui/hom-php
src/HOM/Container.php
Container.removeItemByIndex
public function removeItemByIndex($index): ContainerInterface { if ($this->hasItem($index)) { $this->items[$index] = null; //prevente unset item. unset($this->items[$index]); //unset only index, not the item. } return $this; }
php
public function removeItemByIndex($index): ContainerInterface { if ($this->hasItem($index)) { $this->items[$index] = null; //prevente unset item. unset($this->items[$index]); //unset only index, not the item. } return $this; }
[ "public", "function", "removeItemByIndex", "(", "$", "index", ")", ":", "ContainerInterface", "{", "if", "(", "$", "this", "->", "hasItem", "(", "$", "index", ")", ")", "{", "$", "this", "->", "items", "[", "$", "index", "]", "=", "null", ";", "//prevente unset item.", "unset", "(", "$", "this", "->", "items", "[", "$", "index", "]", ")", ";", "//unset only index, not the item.", "}", "return", "$", "this", ";", "}" ]
Removes the child from the children list for the given index. @param mixed $index @return \HOM\ContainerInterface
[ "Removes", "the", "child", "from", "the", "children", "list", "for", "the", "given", "index", "." ]
c4eccd3e64cf8c7b5ff663f9fea3f31579e17006
https://github.com/phpui/hom-php/blob/c4eccd3e64cf8c7b5ff663f9fea3f31579e17006/src/HOM/Container.php#L127-L135
train
phpui/hom-php
src/HOM/Container.php
Container.getItemsCode
protected function getItemsCode(): string { $code = ''; if ($this->countItems() > 0) { foreach ($this->getAllItems() as $item) { if (is_string($item)) { $code .= $item; } else { $code .= (string) $item; } } } return $code; }
php
protected function getItemsCode(): string { $code = ''; if ($this->countItems() > 0) { foreach ($this->getAllItems() as $item) { if (is_string($item)) { $code .= $item; } else { $code .= (string) $item; } } } return $code; }
[ "protected", "function", "getItemsCode", "(", ")", ":", "string", "{", "$", "code", "=", "''", ";", "if", "(", "$", "this", "->", "countItems", "(", ")", ">", "0", ")", "{", "foreach", "(", "$", "this", "->", "getAllItems", "(", ")", "as", "$", "item", ")", "{", "if", "(", "is_string", "(", "$", "item", ")", ")", "{", "$", "code", ".=", "$", "item", ";", "}", "else", "{", "$", "code", ".=", "(", "string", ")", "$", "item", ";", "}", "}", "}", "return", "$", "code", ";", "}" ]
Get html code for children. @return string
[ "Get", "html", "code", "for", "children", "." ]
c4eccd3e64cf8c7b5ff663f9fea3f31579e17006
https://github.com/phpui/hom-php/blob/c4eccd3e64cf8c7b5ff663f9fea3f31579e17006/src/HOM/Container.php#L142-L155
train
Etenil/assegai
src/assegai/Controller.php
Controller.helper
function helper($helper_name) { if(array_key_exists($helper_name, $this->helpers)) { return $this->helpers[$helper_name]; } else { $classname = 'Helper_' . ucwords($helper_name); return new $classname($this->modules, $this->server, $this->request, $this->security); } }
php
function helper($helper_name) { if(array_key_exists($helper_name, $this->helpers)) { return $this->helpers[$helper_name]; } else { $classname = 'Helper_' . ucwords($helper_name); return new $classname($this->modules, $this->server, $this->request, $this->security); } }
[ "function", "helper", "(", "$", "helper_name", ")", "{", "if", "(", "array_key_exists", "(", "$", "helper_name", ",", "$", "this", "->", "helpers", ")", ")", "{", "return", "$", "this", "->", "helpers", "[", "$", "helper_name", "]", ";", "}", "else", "{", "$", "classname", "=", "'Helper_'", ".", "ucwords", "(", "$", "helper_name", ")", ";", "return", "new", "$", "classname", "(", "$", "this", "->", "modules", ",", "$", "this", "->", "server", ",", "$", "this", "->", "request", ",", "$", "this", "->", "security", ")", ";", "}", "}" ]
Instanciates a helper.
[ "Instanciates", "a", "helper", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L147-L155
train
Etenil/assegai
src/assegai/Controller.php
Controller.view
function view($view_name, array $var_list = NULL, array $block_list = NULL) { if($var_list === NULL) { $var_list = array(); // Avoids notices. } $vars = (object)$var_list; $blocks = (object)$block_list; if($hook_data = $this->modules->preView($this->request, $view_name, $vars)) { return $hook_data; } $serv = $this->server; $me = $this; $parent_tpl = false; $current_block = false; $helpers = new \stdClass(); // Little hack to access urls easier. $url = function($url) use($serv) { return $serv->siteUrl($url); }; $load_helper = function($helper_name) use(&$helpers, &$me) { $helpers->{$helper_name} = $me->helper($helper_name); }; $startblock = function($name) use(&$current_block) { $current_block = $name; ob_start(); }; $endblock = function() use(&$block_list, &$current_block) { $block_list[$current_block] = ob_get_clean(); $current_block = false; }; $inherit = function($template) use(&$parent_tpl) { $parent_tpl = $template; }; $clean = function($val, $placeholder='-') { return \assegai\Utils::cleanFilename($val, $placeholder); }; $template_path = false; // Shorthands $h = &$helpers; ob_start(); $template_path = $this->server->getRelAppPath('views/' . $view_name . '.phtml'); if(!file_exists($template_path)) { $template_path = $this->server->main->get('templates_path') . '/' . $view_name . '.phtml'; } // Traditional PHP template. require($template_path); $data = ob_get_clean(); if($hook_data = $this->modules->postView($this->request, $view_name, $vars, $data)) { return $hook_data; } if($parent_tpl) { return $this->view($parent_tpl, $var_list, $block_list); } return $data; }
php
function view($view_name, array $var_list = NULL, array $block_list = NULL) { if($var_list === NULL) { $var_list = array(); // Avoids notices. } $vars = (object)$var_list; $blocks = (object)$block_list; if($hook_data = $this->modules->preView($this->request, $view_name, $vars)) { return $hook_data; } $serv = $this->server; $me = $this; $parent_tpl = false; $current_block = false; $helpers = new \stdClass(); // Little hack to access urls easier. $url = function($url) use($serv) { return $serv->siteUrl($url); }; $load_helper = function($helper_name) use(&$helpers, &$me) { $helpers->{$helper_name} = $me->helper($helper_name); }; $startblock = function($name) use(&$current_block) { $current_block = $name; ob_start(); }; $endblock = function() use(&$block_list, &$current_block) { $block_list[$current_block] = ob_get_clean(); $current_block = false; }; $inherit = function($template) use(&$parent_tpl) { $parent_tpl = $template; }; $clean = function($val, $placeholder='-') { return \assegai\Utils::cleanFilename($val, $placeholder); }; $template_path = false; // Shorthands $h = &$helpers; ob_start(); $template_path = $this->server->getRelAppPath('views/' . $view_name . '.phtml'); if(!file_exists($template_path)) { $template_path = $this->server->main->get('templates_path') . '/' . $view_name . '.phtml'; } // Traditional PHP template. require($template_path); $data = ob_get_clean(); if($hook_data = $this->modules->postView($this->request, $view_name, $vars, $data)) { return $hook_data; } if($parent_tpl) { return $this->view($parent_tpl, $var_list, $block_list); } return $data; }
[ "function", "view", "(", "$", "view_name", ",", "array", "$", "var_list", "=", "NULL", ",", "array", "$", "block_list", "=", "NULL", ")", "{", "if", "(", "$", "var_list", "===", "NULL", ")", "{", "$", "var_list", "=", "array", "(", ")", ";", "// Avoids notices.", "}", "$", "vars", "=", "(", "object", ")", "$", "var_list", ";", "$", "blocks", "=", "(", "object", ")", "$", "block_list", ";", "if", "(", "$", "hook_data", "=", "$", "this", "->", "modules", "->", "preView", "(", "$", "this", "->", "request", ",", "$", "view_name", ",", "$", "vars", ")", ")", "{", "return", "$", "hook_data", ";", "}", "$", "serv", "=", "$", "this", "->", "server", ";", "$", "me", "=", "$", "this", ";", "$", "parent_tpl", "=", "false", ";", "$", "current_block", "=", "false", ";", "$", "helpers", "=", "new", "\\", "stdClass", "(", ")", ";", "// Little hack to access urls easier.", "$", "url", "=", "function", "(", "$", "url", ")", "use", "(", "$", "serv", ")", "{", "return", "$", "serv", "->", "siteUrl", "(", "$", "url", ")", ";", "}", ";", "$", "load_helper", "=", "function", "(", "$", "helper_name", ")", "use", "(", "&", "$", "helpers", ",", "&", "$", "me", ")", "{", "$", "helpers", "->", "{", "$", "helper_name", "}", "=", "$", "me", "->", "helper", "(", "$", "helper_name", ")", ";", "}", ";", "$", "startblock", "=", "function", "(", "$", "name", ")", "use", "(", "&", "$", "current_block", ")", "{", "$", "current_block", "=", "$", "name", ";", "ob_start", "(", ")", ";", "}", ";", "$", "endblock", "=", "function", "(", ")", "use", "(", "&", "$", "block_list", ",", "&", "$", "current_block", ")", "{", "$", "block_list", "[", "$", "current_block", "]", "=", "ob_get_clean", "(", ")", ";", "$", "current_block", "=", "false", ";", "}", ";", "$", "inherit", "=", "function", "(", "$", "template", ")", "use", "(", "&", "$", "parent_tpl", ")", "{", "$", "parent_tpl", "=", "$", "template", ";", "}", ";", "$", "clean", "=", "function", "(", "$", "val", ",", "$", "placeholder", "=", "'-'", ")", "{", "return", "\\", "assegai", "\\", "Utils", "::", "cleanFilename", "(", "$", "val", ",", "$", "placeholder", ")", ";", "}", ";", "$", "template_path", "=", "false", ";", "// Shorthands", "$", "h", "=", "&", "$", "helpers", ";", "ob_start", "(", ")", ";", "$", "template_path", "=", "$", "this", "->", "server", "->", "getRelAppPath", "(", "'views/'", ".", "$", "view_name", ".", "'.phtml'", ")", ";", "if", "(", "!", "file_exists", "(", "$", "template_path", ")", ")", "{", "$", "template_path", "=", "$", "this", "->", "server", "->", "main", "->", "get", "(", "'templates_path'", ")", ".", "'/'", ".", "$", "view_name", ".", "'.phtml'", ";", "}", "// Traditional PHP template.", "require", "(", "$", "template_path", ")", ";", "$", "data", "=", "ob_get_clean", "(", ")", ";", "if", "(", "$", "hook_data", "=", "$", "this", "->", "modules", "->", "postView", "(", "$", "this", "->", "request", ",", "$", "view_name", ",", "$", "vars", ",", "$", "data", ")", ")", "{", "return", "$", "hook_data", ";", "}", "if", "(", "$", "parent_tpl", ")", "{", "return", "$", "this", "->", "view", "(", "$", "parent_tpl", ",", "$", "var_list", ",", "$", "block_list", ")", ";", "}", "return", "$", "data", ";", "}" ]
Loads a view.
[ "Loads", "a", "view", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L160-L231
train
Etenil/assegai
src/assegai/Controller.php
Controller.model
protected function model($model_name) { if(stripos($model_name, 'model') === false) { $model_name = sprintf('%s\models\%s', $this->server->getAppName(), $model_name); } if($hook_data = $this->modules->preModel($model_name)) { return $hook_data; } if(!class_exists($model_name)) { throw new exceptions\HttpInternalServerError("Class $model_name not found"); } $model = new $model_name($this->modules); if($hook_data = $this->modules->postModel($model_name) === true) { return $hook_data; } return $model; }
php
protected function model($model_name) { if(stripos($model_name, 'model') === false) { $model_name = sprintf('%s\models\%s', $this->server->getAppName(), $model_name); } if($hook_data = $this->modules->preModel($model_name)) { return $hook_data; } if(!class_exists($model_name)) { throw new exceptions\HttpInternalServerError("Class $model_name not found"); } $model = new $model_name($this->modules); if($hook_data = $this->modules->postModel($model_name) === true) { return $hook_data; } return $model; }
[ "protected", "function", "model", "(", "$", "model_name", ")", "{", "if", "(", "stripos", "(", "$", "model_name", ",", "'model'", ")", "===", "false", ")", "{", "$", "model_name", "=", "sprintf", "(", "'%s\\models\\%s'", ",", "$", "this", "->", "server", "->", "getAppName", "(", ")", ",", "$", "model_name", ")", ";", "}", "if", "(", "$", "hook_data", "=", "$", "this", "->", "modules", "->", "preModel", "(", "$", "model_name", ")", ")", "{", "return", "$", "hook_data", ";", "}", "if", "(", "!", "class_exists", "(", "$", "model_name", ")", ")", "{", "throw", "new", "exceptions", "\\", "HttpInternalServerError", "(", "\"Class $model_name not found\"", ")", ";", "}", "$", "model", "=", "new", "$", "model_name", "(", "$", "this", "->", "modules", ")", ";", "if", "(", "$", "hook_data", "=", "$", "this", "->", "modules", "->", "postModel", "(", "$", "model_name", ")", "===", "true", ")", "{", "return", "$", "hook_data", ";", "}", "return", "$", "model", ";", "}" ]
Loads a model.
[ "Loads", "a", "model", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L236-L257
train
Etenil/assegai
src/assegai/Controller.php
Controller.dump
protected function dump($var, $no_html = false) { $dump = var_export($var, true); if($no_html) { return $dump; } else { return '<pre>' . htmlentities($dump) . '</pre>' . PHP_EOL;; } }
php
protected function dump($var, $no_html = false) { $dump = var_export($var, true); if($no_html) { return $dump; } else { return '<pre>' . htmlentities($dump) . '</pre>' . PHP_EOL;; } }
[ "protected", "function", "dump", "(", "$", "var", ",", "$", "no_html", "=", "false", ")", "{", "$", "dump", "=", "var_export", "(", "$", "var", ",", "true", ")", ";", "if", "(", "$", "no_html", ")", "{", "return", "$", "dump", ";", "}", "else", "{", "return", "'<pre>'", ".", "htmlentities", "(", "$", "dump", ")", ".", "'</pre>'", ".", "PHP_EOL", ";", ";", "}", "}" ]
Tiny wrapper arround var_dump to ease debugging. @param mixed $var is the variable to be dumped @param boolean $no_html defines whether the variable contains messy HTML characters or not. The given $var will be escaped if set to false. Default is false. @return The HTML code of a human representation of the $var.
[ "Tiny", "wrapper", "arround", "var_dump", "to", "ease", "debugging", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L277-L285
train
Etenil/assegai
src/assegai/Controller.php
Controller.checkCsrf
protected final function checkCsrf() { $valid = false; $r = $this->request; if($r->getSession('assegai_csrf_token') && $r->post('csrf') && $r->getSession('assegai_csrf_token') == $r->post('csrf')) { $valid = true; } $this->request->killSession('assegai_csrf_token'); return $valid; }
php
protected final function checkCsrf() { $valid = false; $r = $this->request; if($r->getSession('assegai_csrf_token') && $r->post('csrf') && $r->getSession('assegai_csrf_token') == $r->post('csrf')) { $valid = true; } $this->request->killSession('assegai_csrf_token'); return $valid; }
[ "protected", "final", "function", "checkCsrf", "(", ")", "{", "$", "valid", "=", "false", ";", "$", "r", "=", "$", "this", "->", "request", ";", "if", "(", "$", "r", "->", "getSession", "(", "'assegai_csrf_token'", ")", "&&", "$", "r", "->", "post", "(", "'csrf'", ")", "&&", "$", "r", "->", "getSession", "(", "'assegai_csrf_token'", ")", "==", "$", "r", "->", "post", "(", "'csrf'", ")", ")", "{", "$", "valid", "=", "true", ";", "}", "$", "this", "->", "request", "->", "killSession", "(", "'assegai_csrf_token'", ")", ";", "return", "$", "valid", ";", "}" ]
Checks the validity of the CSRF token.
[ "Checks", "the", "validity", "of", "the", "CSRF", "token", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L319-L333
train
objective-php/events-handler
src/EventsHandlerAwareTrait.php
EventsHandlerAwareTrait.trigger
public function trigger($eventName, $origin = null, $context = [], EventInterface $event = null) { if ($eventsHandler = $this->getEventsHandler()) { $eventsHandler->trigger($eventName, $origin, $context, $event); } }
php
public function trigger($eventName, $origin = null, $context = [], EventInterface $event = null) { if ($eventsHandler = $this->getEventsHandler()) { $eventsHandler->trigger($eventName, $origin, $context, $event); } }
[ "public", "function", "trigger", "(", "$", "eventName", ",", "$", "origin", "=", "null", ",", "$", "context", "=", "[", "]", ",", "EventInterface", "$", "event", "=", "null", ")", "{", "if", "(", "$", "eventsHandler", "=", "$", "this", "->", "getEventsHandler", "(", ")", ")", "{", "$", "eventsHandler", "->", "trigger", "(", "$", "eventName", ",", "$", "origin", ",", "$", "context", ",", "$", "event", ")", ";", "}", "}" ]
Proxy trigger method @param string $eventName @param mixed $origin @param array $context @param EventInterface|null $event
[ "Proxy", "trigger", "method" ]
2e8fb6c5649bb1cc22ae4541ea0467031b4505ed
https://github.com/objective-php/events-handler/blob/2e8fb6c5649bb1cc22ae4541ea0467031b4505ed/src/EventsHandlerAwareTrait.php#L49-L54
train
objective-php/events-handler
src/EventsHandlerAwareTrait.php
EventsHandlerAwareTrait.bind
public function bind($eventName, $callback, $mode = EventsHandlerInterface::BINDING_MODE_LAST) { if ($eventsHandler = $this->getEventsHandler()) { $eventsHandler->bind($eventName, $callback, $mode); } }
php
public function bind($eventName, $callback, $mode = EventsHandlerInterface::BINDING_MODE_LAST) { if ($eventsHandler = $this->getEventsHandler()) { $eventsHandler->bind($eventName, $callback, $mode); } }
[ "public", "function", "bind", "(", "$", "eventName", ",", "$", "callback", ",", "$", "mode", "=", "EventsHandlerInterface", "::", "BINDING_MODE_LAST", ")", "{", "if", "(", "$", "eventsHandler", "=", "$", "this", "->", "getEventsHandler", "(", ")", ")", "{", "$", "eventsHandler", "->", "bind", "(", "$", "eventName", ",", "$", "callback", ",", "$", "mode", ")", ";", "}", "}" ]
Proxy bind method @param string $eventName @param string $callback @param string $mode
[ "Proxy", "bind", "method" ]
2e8fb6c5649bb1cc22ae4541ea0467031b4505ed
https://github.com/objective-php/events-handler/blob/2e8fb6c5649bb1cc22ae4541ea0467031b4505ed/src/EventsHandlerAwareTrait.php#L63-L68
train
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.processExchangePlatformOrder
public function processExchangePlatformOrder(Varien_Event_Observer $observer) { $order = $observer->getEvent()->getOrder(); $quote = $order->getQuote(); Mage::dispatchEvent('ebayenterprise_giftcard_redeem', array('quote' => $quote, 'order' => $order)); return $this; }
php
public function processExchangePlatformOrder(Varien_Event_Observer $observer) { $order = $observer->getEvent()->getOrder(); $quote = $order->getQuote(); Mage::dispatchEvent('ebayenterprise_giftcard_redeem', array('quote' => $quote, 'order' => $order)); return $this; }
[ "public", "function", "processExchangePlatformOrder", "(", "Varien_Event_Observer", "$", "observer", ")", "{", "$", "order", "=", "$", "observer", "->", "getEvent", "(", ")", "->", "getOrder", "(", ")", ";", "$", "quote", "=", "$", "order", "->", "getQuote", "(", ")", ";", "Mage", "::", "dispatchEvent", "(", "'ebayenterprise_giftcard_redeem'", ",", "array", "(", "'quote'", "=>", "$", "quote", ",", "'order'", "=>", "$", "order", ")", ")", ";", "return", "$", "this", ";", "}" ]
Perform all processing necessary for the order to be placed with the Exchange Platform - allocate inventory, redeem SVC. If any of the observers need to indicate that an order should not be created, the observer method should throw an exception. Observers the 'sales_order_place_before' event. @see Mage_Sales_Model_Order::place @param Varien_Event_Observer $observer contains the order being placed which will have a reference to the quote the order was created for @throws EbayEnterprise_Eb2cInventory_Model_Allocation_Exception @throws Exception @return self
[ "Perform", "all", "processing", "necessary", "for", "the", "order", "to", "be", "placed", "with", "the", "Exchange", "Platform", "-", "allocate", "inventory", "redeem", "SVC", ".", "If", "any", "of", "the", "observers", "need", "to", "indicate", "that", "an", "order", "should", "not", "be", "created", "the", "observer", "method", "should", "throw", "an", "exception", ".", "Observers", "the", "sales_order_place_before", "event", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L91-L97
train
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.rollbackExchangePlatformOrder
public function rollbackExchangePlatformOrder(Varien_Event_Observer $observer) { Mage::helper('ebayenterprise_magelog')->debug(__METHOD__); Mage::dispatchEvent('eb2c_order_creation_failure', array( 'quote' => $observer->getEvent()->getQuote(), 'order' => $observer->getEvent()->getOrder() )); return $this; }
php
public function rollbackExchangePlatformOrder(Varien_Event_Observer $observer) { Mage::helper('ebayenterprise_magelog')->debug(__METHOD__); Mage::dispatchEvent('eb2c_order_creation_failure', array( 'quote' => $observer->getEvent()->getQuote(), 'order' => $observer->getEvent()->getOrder() )); return $this; }
[ "public", "function", "rollbackExchangePlatformOrder", "(", "Varien_Event_Observer", "$", "observer", ")", "{", "Mage", "::", "helper", "(", "'ebayenterprise_magelog'", ")", "->", "debug", "(", "__METHOD__", ")", ";", "Mage", "::", "dispatchEvent", "(", "'eb2c_order_creation_failure'", ",", "array", "(", "'quote'", "=>", "$", "observer", "->", "getEvent", "(", ")", "->", "getQuote", "(", ")", ",", "'order'", "=>", "$", "observer", "->", "getEvent", "(", ")", "->", "getOrder", "(", ")", ")", ")", ";", "return", "$", "this", ";", "}" ]
Roll back any Exchange Platform actions made for the order - rollback allocation, void SVC redemptions, void payment auths. Observes the 'sales_model_service_quote_submit_failure' event. @see Mage_Sales_Model_Service_Quote::submitOrder @param Varien_Event_Observer $observer Contains the failed order as well as the quote the order was created for @return self
[ "Roll", "back", "any", "Exchange", "Platform", "actions", "made", "for", "the", "order", "-", "rollback", "allocation", "void", "SVC", "redemptions", "void", "payment", "auths", ".", "Observes", "the", "sales_model_service_quote_submit_failure", "event", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L106-L114
train
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.handleShipGroupChargeType
public function handleShipGroupChargeType(Varien_Event_Observer $observer) { $event = $observer->getEvent(); $shipGroup = $event->getShipGroupPayload(); Mage::helper('radial_core/shipping_chargetype')->setShippingChargeType($shipGroup); return $this; }
php
public function handleShipGroupChargeType(Varien_Event_Observer $observer) { $event = $observer->getEvent(); $shipGroup = $event->getShipGroupPayload(); Mage::helper('radial_core/shipping_chargetype')->setShippingChargeType($shipGroup); return $this; }
[ "public", "function", "handleShipGroupChargeType", "(", "Varien_Event_Observer", "$", "observer", ")", "{", "$", "event", "=", "$", "observer", "->", "getEvent", "(", ")", ";", "$", "shipGroup", "=", "$", "event", "->", "getShipGroupPayload", "(", ")", ";", "Mage", "::", "helper", "(", "'radial_core/shipping_chargetype'", ")", "->", "setShippingChargeType", "(", "$", "shipGroup", ")", ";", "return", "$", "this", ";", "}" ]
respond to the order create's request for a valid ship group charge type @param Varien_Event_Observer $observer @return self
[ "respond", "to", "the", "order", "create", "s", "request", "for", "a", "valid", "ship", "group", "charge", "type" ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L135-L141
train
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.handleSalesQuoteCollectTotalsAfter
public function handleSalesQuoteCollectTotalsAfter(Varien_Event_Observer $observer) { $event = $observer->getEvent(); /** @var Mage_Sales_Model_Quote $quote */ $quote = $event->getQuote(); /** @var Mage_Sales_Model_Resource_Quote_Address_Collection */ $addresses = $quote->getAddressesCollection(); foreach ($addresses as $address) { $appliedRuleIds = $address->getAppliedRuleIds(); if (is_array($appliedRuleIds)) { $appliedRuleIds = implode(',', $appliedRuleIds); } $data = (array) $address->getEbayEnterpriseOrderDiscountData(); $data[$appliedRuleIds] = [ 'id' => $appliedRuleIds, 'amount' => $address->getBaseShippingDiscountAmount(), 'description' => $this->helper->__('Shipping Discount'), ]; $address->setEbayEnterpriseOrderDiscountData($data); } }
php
public function handleSalesQuoteCollectTotalsAfter(Varien_Event_Observer $observer) { $event = $observer->getEvent(); /** @var Mage_Sales_Model_Quote $quote */ $quote = $event->getQuote(); /** @var Mage_Sales_Model_Resource_Quote_Address_Collection */ $addresses = $quote->getAddressesCollection(); foreach ($addresses as $address) { $appliedRuleIds = $address->getAppliedRuleIds(); if (is_array($appliedRuleIds)) { $appliedRuleIds = implode(',', $appliedRuleIds); } $data = (array) $address->getEbayEnterpriseOrderDiscountData(); $data[$appliedRuleIds] = [ 'id' => $appliedRuleIds, 'amount' => $address->getBaseShippingDiscountAmount(), 'description' => $this->helper->__('Shipping Discount'), ]; $address->setEbayEnterpriseOrderDiscountData($data); } }
[ "public", "function", "handleSalesQuoteCollectTotalsAfter", "(", "Varien_Event_Observer", "$", "observer", ")", "{", "$", "event", "=", "$", "observer", "->", "getEvent", "(", ")", ";", "/** @var Mage_Sales_Model_Quote $quote */", "$", "quote", "=", "$", "event", "->", "getQuote", "(", ")", ";", "/** @var Mage_Sales_Model_Resource_Quote_Address_Collection */", "$", "addresses", "=", "$", "quote", "->", "getAddressesCollection", "(", ")", ";", "foreach", "(", "$", "addresses", "as", "$", "address", ")", "{", "$", "appliedRuleIds", "=", "$", "address", "->", "getAppliedRuleIds", "(", ")", ";", "if", "(", "is_array", "(", "$", "appliedRuleIds", ")", ")", "{", "$", "appliedRuleIds", "=", "implode", "(", "','", ",", "$", "appliedRuleIds", ")", ";", "}", "$", "data", "=", "(", "array", ")", "$", "address", "->", "getEbayEnterpriseOrderDiscountData", "(", ")", ";", "$", "data", "[", "$", "appliedRuleIds", "]", "=", "[", "'id'", "=>", "$", "appliedRuleIds", ",", "'amount'", "=>", "$", "address", "->", "getBaseShippingDiscountAmount", "(", ")", ",", "'description'", "=>", "$", "this", "->", "helper", "->", "__", "(", "'Shipping Discount'", ")", ",", "]", ";", "$", "address", "->", "setEbayEnterpriseOrderDiscountData", "(", "$", "data", ")", ";", "}", "}" ]
Account for shipping discounts not attached to an item. Combine all shipping discounts into one. @see self::handleSalesConvertQuoteAddressToOrderAddress @see Mage_SalesRule_Model_Validator::processShippingAmount @param Varien_Event_Observer @return void
[ "Account", "for", "shipping", "discounts", "not", "attached", "to", "an", "item", ".", "Combine", "all", "shipping", "discounts", "into", "one", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L152-L172
train
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.handleSalesRuleValidatorProcess
public function handleSalesRuleValidatorProcess(Varien_Event_Observer $observer) { /** @var Varien_Event $event */ $event = $observer->getEvent(); /** @var Mage_SalesRule_Model_Rule $rule */ $rule = $event->getRule(); /** @var Mage_Sales_Model_Quote $quote */ $quote = $event->getQuote(); /** @var Mage_Core_Model_Store $store */ $store = $quote->getStore(); /** @var Mage_Sales_Model_Quote_Item $item */ $item = $event->getItem(); /** @var Varien_Object */ $result = $event->getResult(); $data = (array) $item->getEbayEnterpriseOrderDiscountData(); $ruleId = $rule->getId(); // Use the rule id to prevent duplicates. $data[$ruleId] = [ 'amount' => $this->calculateDiscountAmount($item, $result, $data), 'applied_count' => $event->getQty(), 'code' => $this->helper->getQuoteCouponCode($quote, $rule), 'description' => $rule->getStoreLabel($store) ?: $rule->getName(), 'effect_type' => $rule->getSimpleAction(), 'id' => $ruleId, ]; if( $item instanceof Mage_Sales_Model_Quote_Address_Item ) { $item->setEbayEnterpriseOrderDiscountData($data); foreach( $quote->getAllItems() as $quoteItem ) { if( $quoteItem->getId() === $item->getQuoteItemId()) { $quoteItem->setData('ebayenterprise_order_discount_data', serialize($data)); $quoteItem->save(); break; } } } else { $item->setEbayEnterpriseOrderDiscountData($data); $item->setData('ebayenterprise_order_discount_data', serialize($data)); $item->save(); } }
php
public function handleSalesRuleValidatorProcess(Varien_Event_Observer $observer) { /** @var Varien_Event $event */ $event = $observer->getEvent(); /** @var Mage_SalesRule_Model_Rule $rule */ $rule = $event->getRule(); /** @var Mage_Sales_Model_Quote $quote */ $quote = $event->getQuote(); /** @var Mage_Core_Model_Store $store */ $store = $quote->getStore(); /** @var Mage_Sales_Model_Quote_Item $item */ $item = $event->getItem(); /** @var Varien_Object */ $result = $event->getResult(); $data = (array) $item->getEbayEnterpriseOrderDiscountData(); $ruleId = $rule->getId(); // Use the rule id to prevent duplicates. $data[$ruleId] = [ 'amount' => $this->calculateDiscountAmount($item, $result, $data), 'applied_count' => $event->getQty(), 'code' => $this->helper->getQuoteCouponCode($quote, $rule), 'description' => $rule->getStoreLabel($store) ?: $rule->getName(), 'effect_type' => $rule->getSimpleAction(), 'id' => $ruleId, ]; if( $item instanceof Mage_Sales_Model_Quote_Address_Item ) { $item->setEbayEnterpriseOrderDiscountData($data); foreach( $quote->getAllItems() as $quoteItem ) { if( $quoteItem->getId() === $item->getQuoteItemId()) { $quoteItem->setData('ebayenterprise_order_discount_data', serialize($data)); $quoteItem->save(); break; } } } else { $item->setEbayEnterpriseOrderDiscountData($data); $item->setData('ebayenterprise_order_discount_data', serialize($data)); $item->save(); } }
[ "public", "function", "handleSalesRuleValidatorProcess", "(", "Varien_Event_Observer", "$", "observer", ")", "{", "/** @var Varien_Event $event */", "$", "event", "=", "$", "observer", "->", "getEvent", "(", ")", ";", "/** @var Mage_SalesRule_Model_Rule $rule */", "$", "rule", "=", "$", "event", "->", "getRule", "(", ")", ";", "/** @var Mage_Sales_Model_Quote $quote */", "$", "quote", "=", "$", "event", "->", "getQuote", "(", ")", ";", "/** @var Mage_Core_Model_Store $store */", "$", "store", "=", "$", "quote", "->", "getStore", "(", ")", ";", "/** @var Mage_Sales_Model_Quote_Item $item */", "$", "item", "=", "$", "event", "->", "getItem", "(", ")", ";", "/** @var Varien_Object */", "$", "result", "=", "$", "event", "->", "getResult", "(", ")", ";", "$", "data", "=", "(", "array", ")", "$", "item", "->", "getEbayEnterpriseOrderDiscountData", "(", ")", ";", "$", "ruleId", "=", "$", "rule", "->", "getId", "(", ")", ";", "// Use the rule id to prevent duplicates.", "$", "data", "[", "$", "ruleId", "]", "=", "[", "'amount'", "=>", "$", "this", "->", "calculateDiscountAmount", "(", "$", "item", ",", "$", "result", ",", "$", "data", ")", ",", "'applied_count'", "=>", "$", "event", "->", "getQty", "(", ")", ",", "'code'", "=>", "$", "this", "->", "helper", "->", "getQuoteCouponCode", "(", "$", "quote", ",", "$", "rule", ")", ",", "'description'", "=>", "$", "rule", "->", "getStoreLabel", "(", "$", "store", ")", "?", ":", "$", "rule", "->", "getName", "(", ")", ",", "'effect_type'", "=>", "$", "rule", "->", "getSimpleAction", "(", ")", ",", "'id'", "=>", "$", "ruleId", ",", "]", ";", "if", "(", "$", "item", "instanceof", "Mage_Sales_Model_Quote_Address_Item", ")", "{", "$", "item", "->", "setEbayEnterpriseOrderDiscountData", "(", "$", "data", ")", ";", "foreach", "(", "$", "quote", "->", "getAllItems", "(", ")", "as", "$", "quoteItem", ")", "{", "if", "(", "$", "quoteItem", "->", "getId", "(", ")", "===", "$", "item", "->", "getQuoteItemId", "(", ")", ")", "{", "$", "quoteItem", "->", "setData", "(", "'ebayenterprise_order_discount_data'", ",", "serialize", "(", "$", "data", ")", ")", ";", "$", "quoteItem", "->", "save", "(", ")", ";", "break", ";", "}", "}", "}", "else", "{", "$", "item", "->", "setEbayEnterpriseOrderDiscountData", "(", "$", "data", ")", ";", "$", "item", "->", "setData", "(", "'ebayenterprise_order_discount_data'", ",", "serialize", "(", "$", "data", ")", ")", ";", "$", "item", "->", "save", "(", ")", ";", "}", "}" ]
Account for discounts in order create request. @see self::handleSalesConvertQuoteItemToOrderItem @see Mage_SalesRule_Model_Validator::process @see Order-Datatypes-Common-1.0.xsd:PromoDiscountSet @param Varien_Event_Observer @return void
[ "Account", "for", "discounts", "in", "order", "create", "request", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L183-L226
train
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.calculateDiscountAmount
protected function calculateDiscountAmount(Mage_Sales_Model_Quote_Item_Abstract $item, Varien_Object $result, array $data) { /** @var float */ $itemRowTotal = $item->getBaseRowTotal(); /** @var float */ $currentDiscountAmount = $result->getBaseDiscountAmount(); /** @var float */ $previousAppliedDiscountAmount = 0.00; foreach ($data as $discount) { $previousAppliedDiscountAmount += $discount['amount']; } /** @var float */ $itemRowTotalWithAppliedPreviousDiscount = $itemRowTotal - $previousAppliedDiscountAmount; if ($itemRowTotalWithAppliedPreviousDiscount < 0) { $itemRowTotalWithAppliedPreviousDiscount = 0; } return $itemRowTotalWithAppliedPreviousDiscount < $currentDiscountAmount ? $itemRowTotalWithAppliedPreviousDiscount : $currentDiscountAmount; }
php
protected function calculateDiscountAmount(Mage_Sales_Model_Quote_Item_Abstract $item, Varien_Object $result, array $data) { /** @var float */ $itemRowTotal = $item->getBaseRowTotal(); /** @var float */ $currentDiscountAmount = $result->getBaseDiscountAmount(); /** @var float */ $previousAppliedDiscountAmount = 0.00; foreach ($data as $discount) { $previousAppliedDiscountAmount += $discount['amount']; } /** @var float */ $itemRowTotalWithAppliedPreviousDiscount = $itemRowTotal - $previousAppliedDiscountAmount; if ($itemRowTotalWithAppliedPreviousDiscount < 0) { $itemRowTotalWithAppliedPreviousDiscount = 0; } return $itemRowTotalWithAppliedPreviousDiscount < $currentDiscountAmount ? $itemRowTotalWithAppliedPreviousDiscount : $currentDiscountAmount; }
[ "protected", "function", "calculateDiscountAmount", "(", "Mage_Sales_Model_Quote_Item_Abstract", "$", "item", ",", "Varien_Object", "$", "result", ",", "array", "$", "data", ")", "{", "/** @var float */", "$", "itemRowTotal", "=", "$", "item", "->", "getBaseRowTotal", "(", ")", ";", "/** @var float */", "$", "currentDiscountAmount", "=", "$", "result", "->", "getBaseDiscountAmount", "(", ")", ";", "/** @var float */", "$", "previousAppliedDiscountAmount", "=", "0.00", ";", "foreach", "(", "$", "data", "as", "$", "discount", ")", "{", "$", "previousAppliedDiscountAmount", "+=", "$", "discount", "[", "'amount'", "]", ";", "}", "/** @var float */", "$", "itemRowTotalWithAppliedPreviousDiscount", "=", "$", "itemRowTotal", "-", "$", "previousAppliedDiscountAmount", ";", "if", "(", "$", "itemRowTotalWithAppliedPreviousDiscount", "<", "0", ")", "{", "$", "itemRowTotalWithAppliedPreviousDiscount", "=", "0", ";", "}", "return", "$", "itemRowTotalWithAppliedPreviousDiscount", "<", "$", "currentDiscountAmount", "?", "$", "itemRowTotalWithAppliedPreviousDiscount", ":", "$", "currentDiscountAmount", ";", "}" ]
When the previously applied discount amount on the item row total is less than the current applied discount recalculate the current discount to account for previously applied discount. Otherwise, don't recalculate the current discount. @param Mage_Sales_Model_Quote_Item @param Varien_Object @param array @return float
[ "When", "the", "previously", "applied", "discount", "amount", "on", "the", "item", "row", "total", "is", "less", "than", "the", "current", "applied", "discount", "recalculate", "the", "current", "discount", "to", "account", "for", "previously", "applied", "discount", ".", "Otherwise", "don", "t", "recalculate", "the", "current", "discount", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L239-L258
train
ellipsephp/handlers-adr
src/ContainerResponder.php
ContainerResponder.response
public function response(ServerRequestInterface $request, PayloadInterface $payload): ResponseInterface { $responder = $this->container->get($this->id); if ($responder instanceof ResponderInterface) { return $responder->response($request, $payload); } throw new ContainedResponderTypeException($this->id, $responder); }
php
public function response(ServerRequestInterface $request, PayloadInterface $payload): ResponseInterface { $responder = $this->container->get($this->id); if ($responder instanceof ResponderInterface) { return $responder->response($request, $payload); } throw new ContainedResponderTypeException($this->id, $responder); }
[ "public", "function", "response", "(", "ServerRequestInterface", "$", "request", ",", "PayloadInterface", "$", "payload", ")", ":", "ResponseInterface", "{", "$", "responder", "=", "$", "this", "->", "container", "->", "get", "(", "$", "this", "->", "id", ")", ";", "if", "(", "$", "responder", "instanceof", "ResponderInterface", ")", "{", "return", "$", "responder", "->", "response", "(", "$", "request", ",", "$", "payload", ")", ";", "}", "throw", "new", "ContainedResponderTypeException", "(", "$", "this", "->", "id", ",", "$", "responder", ")", ";", "}" ]
Get the responder from the container then proxy its response method. @param \Psr\Http\Message\ServerRequestInterface $request @param \Ellipse\ADR\PayloadInterface $payload @return \Psr\Http\Message\ResponseInterface @throws \Ellipse\Handlers\Exceptions\ContainedResponderTypeException
[ "Get", "the", "responder", "from", "the", "container", "then", "proxy", "its", "response", "method", "." ]
1c0879494a8b7718f7e157d0cd41b4c5ec19b5c5
https://github.com/ellipsephp/handlers-adr/blob/1c0879494a8b7718f7e157d0cd41b4c5ec19b5c5/src/ContainerResponder.php#L50-L61
train
as3io/modlr
src/Metadata/Cache/CacheWarmer.php
CacheWarmer.clear
public function clear($type = null) { if (false === $this->mf->hasCache()) { return []; } return $this->doClear($this->getTypes($type)); }
php
public function clear($type = null) { if (false === $this->mf->hasCache()) { return []; } return $this->doClear($this->getTypes($type)); }
[ "public", "function", "clear", "(", "$", "type", "=", "null", ")", "{", "if", "(", "false", "===", "$", "this", "->", "mf", "->", "hasCache", "(", ")", ")", "{", "return", "[", "]", ";", "}", "return", "$", "this", "->", "doClear", "(", "$", "this", "->", "getTypes", "(", "$", "type", ")", ")", ";", "}" ]
Clears metadata objects from the cache. @param string|array|null $type @return array
[ "Clears", "metadata", "objects", "from", "the", "cache", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/Cache/CacheWarmer.php#L38-L44
train
as3io/modlr
src/Metadata/Cache/CacheWarmer.php
CacheWarmer.warm
public function warm($type = null) { if (false === $this->mf->hasCache()) { return []; } return $this->doWarm($this->getTypes($type)); }
php
public function warm($type = null) { if (false === $this->mf->hasCache()) { return []; } return $this->doWarm($this->getTypes($type)); }
[ "public", "function", "warm", "(", "$", "type", "=", "null", ")", "{", "if", "(", "false", "===", "$", "this", "->", "mf", "->", "hasCache", "(", ")", ")", "{", "return", "[", "]", ";", "}", "return", "$", "this", "->", "doWarm", "(", "$", "this", "->", "getTypes", "(", "$", "type", ")", ")", ";", "}" ]
Warms up metadata objects into the cache. @param string|array|null $type @return array
[ "Warms", "up", "metadata", "objects", "into", "the", "cache", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/Cache/CacheWarmer.php#L52-L58
train
as3io/modlr
src/Metadata/Cache/CacheWarmer.php
CacheWarmer.doClear
private function doClear(array $types) { $cleared = []; $this->mf->enableCache(false); foreach ($types as $type) { $metadata = $this->mf->getMetadataForType($type); $this->mf->getCache()->evictMetadataFromCache($metadata); $cleared[] = $type; } $this->mf->enableCache(true); $this->mf->clearMemory(); return $cleared; }
php
private function doClear(array $types) { $cleared = []; $this->mf->enableCache(false); foreach ($types as $type) { $metadata = $this->mf->getMetadataForType($type); $this->mf->getCache()->evictMetadataFromCache($metadata); $cleared[] = $type; } $this->mf->enableCache(true); $this->mf->clearMemory(); return $cleared; }
[ "private", "function", "doClear", "(", "array", "$", "types", ")", "{", "$", "cleared", "=", "[", "]", ";", "$", "this", "->", "mf", "->", "enableCache", "(", "false", ")", ";", "foreach", "(", "$", "types", "as", "$", "type", ")", "{", "$", "metadata", "=", "$", "this", "->", "mf", "->", "getMetadataForType", "(", "$", "type", ")", ";", "$", "this", "->", "mf", "->", "getCache", "(", ")", "->", "evictMetadataFromCache", "(", "$", "metadata", ")", ";", "$", "cleared", "[", "]", "=", "$", "type", ";", "}", "$", "this", "->", "mf", "->", "enableCache", "(", "true", ")", ";", "$", "this", "->", "mf", "->", "clearMemory", "(", ")", ";", "return", "$", "cleared", ";", "}" ]
Clears metadata objects for the provided model types. @param array $types @return array
[ "Clears", "metadata", "objects", "for", "the", "provided", "model", "types", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/Cache/CacheWarmer.php#L66-L80
train
as3io/modlr
src/Metadata/Cache/CacheWarmer.php
CacheWarmer.doWarm
private function doWarm(array $types) { $warmed = []; $this->doClear($types); foreach ($types as $type) { $this->mf->getMetadataForType($type); $warmed[] = $type; } return $warmed; }
php
private function doWarm(array $types) { $warmed = []; $this->doClear($types); foreach ($types as $type) { $this->mf->getMetadataForType($type); $warmed[] = $type; } return $warmed; }
[ "private", "function", "doWarm", "(", "array", "$", "types", ")", "{", "$", "warmed", "=", "[", "]", ";", "$", "this", "->", "doClear", "(", "$", "types", ")", ";", "foreach", "(", "$", "types", "as", "$", "type", ")", "{", "$", "this", "->", "mf", "->", "getMetadataForType", "(", "$", "type", ")", ";", "$", "warmed", "[", "]", "=", "$", "type", ";", "}", "return", "$", "warmed", ";", "}" ]
Warms up the metadata objects for the provided model types. @param array $types @return array
[ "Warms", "up", "the", "metadata", "objects", "for", "the", "provided", "model", "types", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/Cache/CacheWarmer.php#L88-L97
train
IftekherSunny/Planet-Framework
src/Sun/Mail/Mailer.php
Mailer.send
public function send($email, $name = null, $subject, $body, $attachment = null, $bcc = null) { $this->phpMailer->isSMTP(); $this->phpMailer->Host = $this->app->config->getMail('host'); $this->phpMailer->SMTPAuth = true; $this->phpMailer->Username = $this->app->config->getMail('username'); $this->phpMailer->Password = $this->app->config->getMail('password'); $this->phpMailer->SMTPSecure = $this->app->config->getMail('encryption'); $this->phpMailer->Port = $this->app->config->getMail('port'); $this->phpMailer->From = $this->app->config->getMail('from.email'); $this->phpMailer->FromName = $this->app->config->getMail('from.name'); $this->phpMailer->addAddress($email, $name); $this->phpMailer->addReplyTo( $this->app->config->getMail('reply.email'), $this->app->config->getMail('mail.reply.name') ); $this->phpMailer->addBCC($bcc); $this->phpMailer->addAttachment($attachment); $this->phpMailer->isHTML(true); $this->phpMailer->Subject = $subject; $this->phpMailer->Body = $body; /** * If log set to true * then log email */ if ($this->app->config->getMail('log') == true) return $this->logEmail($body); /** * If log set to false * then send email */ if ( $this->app->config->getMail('log') !== true) { try { set_time_limit(0); if( ! $this->phpMailer->send()) throw new MailerException($this->phpMailer->ErrorInfo); else return true; } catch(phpmailerException $e) { throw new MailerException($e->errorMessage()); } } }
php
public function send($email, $name = null, $subject, $body, $attachment = null, $bcc = null) { $this->phpMailer->isSMTP(); $this->phpMailer->Host = $this->app->config->getMail('host'); $this->phpMailer->SMTPAuth = true; $this->phpMailer->Username = $this->app->config->getMail('username'); $this->phpMailer->Password = $this->app->config->getMail('password'); $this->phpMailer->SMTPSecure = $this->app->config->getMail('encryption'); $this->phpMailer->Port = $this->app->config->getMail('port'); $this->phpMailer->From = $this->app->config->getMail('from.email'); $this->phpMailer->FromName = $this->app->config->getMail('from.name'); $this->phpMailer->addAddress($email, $name); $this->phpMailer->addReplyTo( $this->app->config->getMail('reply.email'), $this->app->config->getMail('mail.reply.name') ); $this->phpMailer->addBCC($bcc); $this->phpMailer->addAttachment($attachment); $this->phpMailer->isHTML(true); $this->phpMailer->Subject = $subject; $this->phpMailer->Body = $body; /** * If log set to true * then log email */ if ($this->app->config->getMail('log') == true) return $this->logEmail($body); /** * If log set to false * then send email */ if ( $this->app->config->getMail('log') !== true) { try { set_time_limit(0); if( ! $this->phpMailer->send()) throw new MailerException($this->phpMailer->ErrorInfo); else return true; } catch(phpmailerException $e) { throw new MailerException($e->errorMessage()); } } }
[ "public", "function", "send", "(", "$", "email", ",", "$", "name", "=", "null", ",", "$", "subject", ",", "$", "body", ",", "$", "attachment", "=", "null", ",", "$", "bcc", "=", "null", ")", "{", "$", "this", "->", "phpMailer", "->", "isSMTP", "(", ")", ";", "$", "this", "->", "phpMailer", "->", "Host", "=", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'host'", ")", ";", "$", "this", "->", "phpMailer", "->", "SMTPAuth", "=", "true", ";", "$", "this", "->", "phpMailer", "->", "Username", "=", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'username'", ")", ";", "$", "this", "->", "phpMailer", "->", "Password", "=", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'password'", ")", ";", "$", "this", "->", "phpMailer", "->", "SMTPSecure", "=", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'encryption'", ")", ";", "$", "this", "->", "phpMailer", "->", "Port", "=", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'port'", ")", ";", "$", "this", "->", "phpMailer", "->", "From", "=", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'from.email'", ")", ";", "$", "this", "->", "phpMailer", "->", "FromName", "=", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'from.name'", ")", ";", "$", "this", "->", "phpMailer", "->", "addAddress", "(", "$", "email", ",", "$", "name", ")", ";", "$", "this", "->", "phpMailer", "->", "addReplyTo", "(", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'reply.email'", ")", ",", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'mail.reply.name'", ")", ")", ";", "$", "this", "->", "phpMailer", "->", "addBCC", "(", "$", "bcc", ")", ";", "$", "this", "->", "phpMailer", "->", "addAttachment", "(", "$", "attachment", ")", ";", "$", "this", "->", "phpMailer", "->", "isHTML", "(", "true", ")", ";", "$", "this", "->", "phpMailer", "->", "Subject", "=", "$", "subject", ";", "$", "this", "->", "phpMailer", "->", "Body", "=", "$", "body", ";", "/**\r\n * If log set to true\r\n * then log email\r\n */", "if", "(", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'log'", ")", "==", "true", ")", "return", "$", "this", "->", "logEmail", "(", "$", "body", ")", ";", "/**\r\n * If log set to false\r\n * then send email\r\n */", "if", "(", "$", "this", "->", "app", "->", "config", "->", "getMail", "(", "'log'", ")", "!==", "true", ")", "{", "try", "{", "set_time_limit", "(", "0", ")", ";", "if", "(", "!", "$", "this", "->", "phpMailer", "->", "send", "(", ")", ")", "throw", "new", "MailerException", "(", "$", "this", "->", "phpMailer", "->", "ErrorInfo", ")", ";", "else", "return", "true", ";", "}", "catch", "(", "phpmailerException", "$", "e", ")", "{", "throw", "new", "MailerException", "(", "$", "e", "->", "errorMessage", "(", ")", ")", ";", "}", "}", "}" ]
To send an email @param string $email @param string $name @param string $subject @param string $body @param string $attachment @param array $bcc @return bool @throws MailerException
[ "To", "send", "an", "email" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Mail/Mailer.php#L63-L117
train
IftekherSunny/Planet-Framework
src/Sun/Mail/Mailer.php
Mailer.logEmail
protected function logEmail($body) { if(!$this->filesystem->exists($this->getLogDirectory())) { $this->filesystem->createDirectory($this->getLogDirectory()); } return $this->filesystem->create($this->logFileName, $body); }
php
protected function logEmail($body) { if(!$this->filesystem->exists($this->getLogDirectory())) { $this->filesystem->createDirectory($this->getLogDirectory()); } return $this->filesystem->create($this->logFileName, $body); }
[ "protected", "function", "logEmail", "(", "$", "body", ")", "{", "if", "(", "!", "$", "this", "->", "filesystem", "->", "exists", "(", "$", "this", "->", "getLogDirectory", "(", ")", ")", ")", "{", "$", "this", "->", "filesystem", "->", "createDirectory", "(", "$", "this", "->", "getLogDirectory", "(", ")", ")", ";", "}", "return", "$", "this", "->", "filesystem", "->", "create", "(", "$", "this", "->", "logFileName", ",", "$", "body", ")", ";", "}" ]
Generate Email Log File @param $body @return bool
[ "Generate", "Email", "Log", "File" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Mail/Mailer.php#L126-L133
train
PhoxPHP/Glider
src/Console/TemplateBuilder.php
TemplateBuilder.createClassTemplate
public function createClassTemplate(String $templateName, String $filename, $savePath=null, Array $templateTags) { $template = file_get_contents(__DIR__ . '/templates/' . $templateName); foreach($templateTags as $key => $tag) { if (!preg_match_all('/' . $key . '/', $template)) { throw new RuntimeException(sprintf('[%s] tag does not exist in template.', $key)); } } if (!is_dir($savePath) || !is_readable($savePath)) { throw new RuntimeException(sprintf('[%s] directory is not readable', $savePath)); } $template = str_replace( array_keys($templateTags), array_values($templateTags), $template ); $file = $savePath . '/' . $filename . '.php'; $handle = fopen($file, 'w+'); fwrite($handle, $template); fclose($handle); $this->env->sendOutput( sprintf( '[%s] class has been generated and placed in [%s]', $templateTags['phx:class'], $file ), 'green', 'black' ); }
php
public function createClassTemplate(String $templateName, String $filename, $savePath=null, Array $templateTags) { $template = file_get_contents(__DIR__ . '/templates/' . $templateName); foreach($templateTags as $key => $tag) { if (!preg_match_all('/' . $key . '/', $template)) { throw new RuntimeException(sprintf('[%s] tag does not exist in template.', $key)); } } if (!is_dir($savePath) || !is_readable($savePath)) { throw new RuntimeException(sprintf('[%s] directory is not readable', $savePath)); } $template = str_replace( array_keys($templateTags), array_values($templateTags), $template ); $file = $savePath . '/' . $filename . '.php'; $handle = fopen($file, 'w+'); fwrite($handle, $template); fclose($handle); $this->env->sendOutput( sprintf( '[%s] class has been generated and placed in [%s]', $templateTags['phx:class'], $file ), 'green', 'black' ); }
[ "public", "function", "createClassTemplate", "(", "String", "$", "templateName", ",", "String", "$", "filename", ",", "$", "savePath", "=", "null", ",", "Array", "$", "templateTags", ")", "{", "$", "template", "=", "file_get_contents", "(", "__DIR__", ".", "'/templates/'", ".", "$", "templateName", ")", ";", "foreach", "(", "$", "templateTags", "as", "$", "key", "=>", "$", "tag", ")", "{", "if", "(", "!", "preg_match_all", "(", "'/'", ".", "$", "key", ".", "'/'", ",", "$", "template", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'[%s] tag does not exist in template.'", ",", "$", "key", ")", ")", ";", "}", "}", "if", "(", "!", "is_dir", "(", "$", "savePath", ")", "||", "!", "is_readable", "(", "$", "savePath", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'[%s] directory is not readable'", ",", "$", "savePath", ")", ")", ";", "}", "$", "template", "=", "str_replace", "(", "array_keys", "(", "$", "templateTags", ")", ",", "array_values", "(", "$", "templateTags", ")", ",", "$", "template", ")", ";", "$", "file", "=", "$", "savePath", ".", "'/'", ".", "$", "filename", ".", "'.php'", ";", "$", "handle", "=", "fopen", "(", "$", "file", ",", "'w+'", ")", ";", "fwrite", "(", "$", "handle", ",", "$", "template", ")", ";", "fclose", "(", "$", "handle", ")", ";", "$", "this", "->", "env", "->", "sendOutput", "(", "sprintf", "(", "'[%s] class has been generated and placed in [%s]'", ",", "$", "templateTags", "[", "'phx:class'", "]", ",", "$", "file", ")", ",", "'green'", ",", "'black'", ")", ";", "}" ]
Builds a class template. @param $templateName <String> @param $filename <String> @param $savePath <String> @param $templateTags <Array> @access public @return <void>
[ "Builds", "a", "class", "template", "." ]
17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Console/TemplateBuilder.php#L68-L101
train
stonedz/pff2
src/modules/logger/Utils/LoggerFile.php
LoggerFile.getLogFile
public function getLogFile() { if ($this->_fp === null) { $this->LOG_DIR = ROOT .DS. 'app' . DS . 'logs'; $filename = $this->LOG_DIR . DS . date("Y-m-d"); $this->_fp = fopen($filename, 'a'); if ($this->_fp === false) { throw new LoggerException('Cannot open log file: ' . $filename); } chmod($filename, 0774); } return $this->_fp; }
php
public function getLogFile() { if ($this->_fp === null) { $this->LOG_DIR = ROOT .DS. 'app' . DS . 'logs'; $filename = $this->LOG_DIR . DS . date("Y-m-d"); $this->_fp = fopen($filename, 'a'); if ($this->_fp === false) { throw new LoggerException('Cannot open log file: ' . $filename); } chmod($filename, 0774); } return $this->_fp; }
[ "public", "function", "getLogFile", "(", ")", "{", "if", "(", "$", "this", "->", "_fp", "===", "null", ")", "{", "$", "this", "->", "LOG_DIR", "=", "ROOT", ".", "DS", ".", "'app'", ".", "DS", ".", "'logs'", ";", "$", "filename", "=", "$", "this", "->", "LOG_DIR", ".", "DS", ".", "date", "(", "\"Y-m-d\"", ")", ";", "$", "this", "->", "_fp", "=", "fopen", "(", "$", "filename", ",", "'a'", ")", ";", "if", "(", "$", "this", "->", "_fp", "===", "false", ")", "{", "throw", "new", "LoggerException", "(", "'Cannot open log file: '", ".", "$", "filename", ")", ";", "}", "chmod", "(", "$", "filename", ",", "0774", ")", ";", "}", "return", "$", "this", "->", "_fp", ";", "}" ]
Opens log file only if it's not already open @throws LoggerException @return null|resource
[ "Opens", "log", "file", "only", "if", "it", "s", "not", "already", "open" ]
ec3b087d4d4732816f61ac487f0cb25511e0da88
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/logger/Utils/LoggerFile.php#L55-L69
train
crisu83/yii-consoletools
commands/FlushCommand.php
FlushCommand.flush
protected function flush() { echo "\nFlushing directories... "; foreach ($this->flushPaths as $dir) { $path = $this->basePath . '/' . $dir; if (file_exists($path)) { $this->flushDirectory($path); } $this->ensureDirectory($path); } echo "done\n"; }
php
protected function flush() { echo "\nFlushing directories... "; foreach ($this->flushPaths as $dir) { $path = $this->basePath . '/' . $dir; if (file_exists($path)) { $this->flushDirectory($path); } $this->ensureDirectory($path); } echo "done\n"; }
[ "protected", "function", "flush", "(", ")", "{", "echo", "\"\\nFlushing directories... \"", ";", "foreach", "(", "$", "this", "->", "flushPaths", "as", "$", "dir", ")", "{", "$", "path", "=", "$", "this", "->", "basePath", ".", "'/'", ".", "$", "dir", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "$", "this", "->", "flushDirectory", "(", "$", "path", ")", ";", "}", "$", "this", "->", "ensureDirectory", "(", "$", "path", ")", ";", "}", "echo", "\"done\\n\"", ";", "}" ]
Flushes directories.
[ "Flushes", "directories", "." ]
53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/FlushCommand.php#L47-L58
train
crisu83/yii-consoletools
commands/FlushCommand.php
FlushCommand.flushDirectory
protected function flushDirectory($path, $delete = false) { if (is_dir($path)) { $entries = scandir($path); foreach ($entries as $entry) { $exclude = array_merge(array('.', '..'), $this->exclude); if (in_array($entry, $exclude)) { continue; } $entryPath = $path . '/' . $entry; if (!is_link($entryPath) && is_dir($entryPath)) { $this->flushDirectory($entryPath, true); } else { unlink($entryPath); } } if ($delete) { rmdir($path); } } }
php
protected function flushDirectory($path, $delete = false) { if (is_dir($path)) { $entries = scandir($path); foreach ($entries as $entry) { $exclude = array_merge(array('.', '..'), $this->exclude); if (in_array($entry, $exclude)) { continue; } $entryPath = $path . '/' . $entry; if (!is_link($entryPath) && is_dir($entryPath)) { $this->flushDirectory($entryPath, true); } else { unlink($entryPath); } } if ($delete) { rmdir($path); } } }
[ "protected", "function", "flushDirectory", "(", "$", "path", ",", "$", "delete", "=", "false", ")", "{", "if", "(", "is_dir", "(", "$", "path", ")", ")", "{", "$", "entries", "=", "scandir", "(", "$", "path", ")", ";", "foreach", "(", "$", "entries", "as", "$", "entry", ")", "{", "$", "exclude", "=", "array_merge", "(", "array", "(", "'.'", ",", "'..'", ")", ",", "$", "this", "->", "exclude", ")", ";", "if", "(", "in_array", "(", "$", "entry", ",", "$", "exclude", ")", ")", "{", "continue", ";", "}", "$", "entryPath", "=", "$", "path", ".", "'/'", ".", "$", "entry", ";", "if", "(", "!", "is_link", "(", "$", "entryPath", ")", "&&", "is_dir", "(", "$", "entryPath", ")", ")", "{", "$", "this", "->", "flushDirectory", "(", "$", "entryPath", ",", "true", ")", ";", "}", "else", "{", "unlink", "(", "$", "entryPath", ")", ";", "}", "}", "if", "(", "$", "delete", ")", "{", "rmdir", "(", "$", "path", ")", ";", "}", "}", "}" ]
Flushes a directory recursively. @param string $path the directory path. @param boolean $delete whether to delete the directory.
[ "Flushes", "a", "directory", "recursively", "." ]
53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/FlushCommand.php#L65-L85
train
jasny/meta
src/Source/CombinedSource.php
CombinedSource.mergeMeta
protected function mergeMeta(array $meta, array $sourceMeta): array { $properties = $meta['properties'] ?? []; $sourceProperties = $sourceMeta['properties'] ?? []; foreach ($sourceProperties as $name => $data) { $properties[$name] = array_merge($properties[$name] ?? [], $data); } $meta = array_merge($meta, $sourceMeta); $meta['properties'] = $properties; return $meta; }
php
protected function mergeMeta(array $meta, array $sourceMeta): array { $properties = $meta['properties'] ?? []; $sourceProperties = $sourceMeta['properties'] ?? []; foreach ($sourceProperties as $name => $data) { $properties[$name] = array_merge($properties[$name] ?? [], $data); } $meta = array_merge($meta, $sourceMeta); $meta['properties'] = $properties; return $meta; }
[ "protected", "function", "mergeMeta", "(", "array", "$", "meta", ",", "array", "$", "sourceMeta", ")", ":", "array", "{", "$", "properties", "=", "$", "meta", "[", "'properties'", "]", "??", "[", "]", ";", "$", "sourceProperties", "=", "$", "sourceMeta", "[", "'properties'", "]", "??", "[", "]", ";", "foreach", "(", "$", "sourceProperties", "as", "$", "name", "=>", "$", "data", ")", "{", "$", "properties", "[", "$", "name", "]", "=", "array_merge", "(", "$", "properties", "[", "$", "name", "]", "??", "[", "]", ",", "$", "data", ")", ";", "}", "$", "meta", "=", "array_merge", "(", "$", "meta", ",", "$", "sourceMeta", ")", ";", "$", "meta", "[", "'properties'", "]", "=", "$", "properties", ";", "return", "$", "meta", ";", "}" ]
Merge meta data @param array $meta @param array $sourceMeta @return array
[ "Merge", "meta", "data" ]
26cf119542433776fecc6c31341787091fc2dbb6
https://github.com/jasny/meta/blob/26cf119542433776fecc6c31341787091fc2dbb6/src/Source/CombinedSource.php#L60-L73
train
Phpillip/phpillip
src/Controller/ContentController.php
ContentController.page
public function page(Request $request, Application $app, Paginator $paginator) { return array_merge( ['pages' => count($paginator)], $this->extractViewParameters($request, ['app', 'paginator']) ); }
php
public function page(Request $request, Application $app, Paginator $paginator) { return array_merge( ['pages' => count($paginator)], $this->extractViewParameters($request, ['app', 'paginator']) ); }
[ "public", "function", "page", "(", "Request", "$", "request", ",", "Application", "$", "app", ",", "Paginator", "$", "paginator", ")", "{", "return", "array_merge", "(", "[", "'pages'", "=>", "count", "(", "$", "paginator", ")", "]", ",", "$", "this", "->", "extractViewParameters", "(", "$", "request", ",", "[", "'app'", ",", "'paginator'", "]", ")", ")", ";", "}" ]
Paginated list of contents @param Request $request @param Application $app @param Paginator $paginator @return array
[ "Paginated", "list", "of", "contents" ]
c37afaafb536361e7e0b564659f1cd5b80b98be9
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Controller/ContentController.php#L36-L42
train
Phpillip/phpillip
src/Controller/ContentController.php
ContentController.extractViewParameters
protected function extractViewParameters(Request $request, array $exclude = []) { $parameters = []; foreach ($request->attributes as $key => $value) { if (strpos($key, '_') !== 0 && !in_array($key, $exclude)) { $parameters[$key] = $value; } } return $parameters; }
php
protected function extractViewParameters(Request $request, array $exclude = []) { $parameters = []; foreach ($request->attributes as $key => $value) { if (strpos($key, '_') !== 0 && !in_array($key, $exclude)) { $parameters[$key] = $value; } } return $parameters; }
[ "protected", "function", "extractViewParameters", "(", "Request", "$", "request", ",", "array", "$", "exclude", "=", "[", "]", ")", "{", "$", "parameters", "=", "[", "]", ";", "foreach", "(", "$", "request", "->", "attributes", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "strpos", "(", "$", "key", ",", "'_'", ")", "!==", "0", "&&", "!", "in_array", "(", "$", "key", ",", "$", "exclude", ")", ")", "{", "$", "parameters", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "parameters", ";", "}" ]
Extract view parameters from Request attributes @param Request $request @param array $exclude Keys to exclude from view @return array
[ "Extract", "view", "parameters", "from", "Request", "attributes" ]
c37afaafb536361e7e0b564659f1cd5b80b98be9
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Controller/ContentController.php#L65-L76
train
IftekherSunny/Planet-Framework
src/Sun/Bus/CommandTranslator.php
CommandTranslator.translate
public function translate($object) { $commandBaseNamespace = app()->getNamespace() . "Commands"; $handlerBaseNamespace = app()->getNamespace(). "Handlers"; $reflectionObject = new ReflectionClass($object); $commandNamespace = $this->getCommandNamespace($commandBaseNamespace, $reflectionObject); $command = $this->getCommandName($reflectionObject); $handler = str_replace('Command', 'CommandHandler', $command); if($commandNamespace !== $commandBaseNamespace) { $handlerNamespace = $handlerBaseNamespace . $commandNamespace . "\\" . $handler; $commandNamespace = $commandBaseNamespace . $commandNamespace . "\\" . $command; } if(! class_exists($commandNamespace)) { throw new CommandNotFoundException("Command [ $command ] does not exist."); } if(! class_exists($handlerNamespace)) { throw new HandlerNotFoundException("Handler [ $handler ] does nto exist."); } return $handlerNamespace; }
php
public function translate($object) { $commandBaseNamespace = app()->getNamespace() . "Commands"; $handlerBaseNamespace = app()->getNamespace(). "Handlers"; $reflectionObject = new ReflectionClass($object); $commandNamespace = $this->getCommandNamespace($commandBaseNamespace, $reflectionObject); $command = $this->getCommandName($reflectionObject); $handler = str_replace('Command', 'CommandHandler', $command); if($commandNamespace !== $commandBaseNamespace) { $handlerNamespace = $handlerBaseNamespace . $commandNamespace . "\\" . $handler; $commandNamespace = $commandBaseNamespace . $commandNamespace . "\\" . $command; } if(! class_exists($commandNamespace)) { throw new CommandNotFoundException("Command [ $command ] does not exist."); } if(! class_exists($handlerNamespace)) { throw new HandlerNotFoundException("Handler [ $handler ] does nto exist."); } return $handlerNamespace; }
[ "public", "function", "translate", "(", "$", "object", ")", "{", "$", "commandBaseNamespace", "=", "app", "(", ")", "->", "getNamespace", "(", ")", ".", "\"Commands\"", ";", "$", "handlerBaseNamespace", "=", "app", "(", ")", "->", "getNamespace", "(", ")", ".", "\"Handlers\"", ";", "$", "reflectionObject", "=", "new", "ReflectionClass", "(", "$", "object", ")", ";", "$", "commandNamespace", "=", "$", "this", "->", "getCommandNamespace", "(", "$", "commandBaseNamespace", ",", "$", "reflectionObject", ")", ";", "$", "command", "=", "$", "this", "->", "getCommandName", "(", "$", "reflectionObject", ")", ";", "$", "handler", "=", "str_replace", "(", "'Command'", ",", "'CommandHandler'", ",", "$", "command", ")", ";", "if", "(", "$", "commandNamespace", "!==", "$", "commandBaseNamespace", ")", "{", "$", "handlerNamespace", "=", "$", "handlerBaseNamespace", ".", "$", "commandNamespace", ".", "\"\\\\\"", ".", "$", "handler", ";", "$", "commandNamespace", "=", "$", "commandBaseNamespace", ".", "$", "commandNamespace", ".", "\"\\\\\"", ".", "$", "command", ";", "}", "if", "(", "!", "class_exists", "(", "$", "commandNamespace", ")", ")", "{", "throw", "new", "CommandNotFoundException", "(", "\"Command [ $command ] does not exist.\"", ")", ";", "}", "if", "(", "!", "class_exists", "(", "$", "handlerNamespace", ")", ")", "{", "throw", "new", "HandlerNotFoundException", "(", "\"Handler [ $handler ] does nto exist.\"", ")", ";", "}", "return", "$", "handlerNamespace", ";", "}" ]
To translate command to command handler @param $object @return string @throws CommandNotFoundException @throws HandlerNotFoundException
[ "To", "translate", "command", "to", "command", "handler" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Bus/CommandTranslator.php#L19-L48
train
IftekherSunny/Planet-Framework
src/Sun/Support/Config.php
Config.find
public function find($item = null, $array = null) { if(is_null($item)) return null; if(strpos($item, '.')) { $arr = explode('.', $item); if(count($arr) > 2 ) { $itemToSearch = join('.', array_slice($arr, 1)); } else { $itemToSearch = $arr[1]; } return $this->findItemIn($itemToSearch, $arr[0]); } else { $array = !is_null($array) ? $array : $this->settings; foreach ($array as $key => $value) { if($key === $item) { $this->currentItem = $value; $this->found = true; break; } else { if(is_array($value)) { $this->find($item, $value); } } } } if(!$this->found) { return false; } return $this->currentItem; }
php
public function find($item = null, $array = null) { if(is_null($item)) return null; if(strpos($item, '.')) { $arr = explode('.', $item); if(count($arr) > 2 ) { $itemToSearch = join('.', array_slice($arr, 1)); } else { $itemToSearch = $arr[1]; } return $this->findItemIn($itemToSearch, $arr[0]); } else { $array = !is_null($array) ? $array : $this->settings; foreach ($array as $key => $value) { if($key === $item) { $this->currentItem = $value; $this->found = true; break; } else { if(is_array($value)) { $this->find($item, $value); } } } } if(!$this->found) { return false; } return $this->currentItem; }
[ "public", "function", "find", "(", "$", "item", "=", "null", ",", "$", "array", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "item", ")", ")", "return", "null", ";", "if", "(", "strpos", "(", "$", "item", ",", "'.'", ")", ")", "{", "$", "arr", "=", "explode", "(", "'.'", ",", "$", "item", ")", ";", "if", "(", "count", "(", "$", "arr", ")", ">", "2", ")", "{", "$", "itemToSearch", "=", "join", "(", "'.'", ",", "array_slice", "(", "$", "arr", ",", "1", ")", ")", ";", "}", "else", "{", "$", "itemToSearch", "=", "$", "arr", "[", "1", "]", ";", "}", "return", "$", "this", "->", "findItemIn", "(", "$", "itemToSearch", ",", "$", "arr", "[", "0", "]", ")", ";", "}", "else", "{", "$", "array", "=", "!", "is_null", "(", "$", "array", ")", "?", "$", "array", ":", "$", "this", "->", "settings", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "key", "===", "$", "item", ")", "{", "$", "this", "->", "currentItem", "=", "$", "value", ";", "$", "this", "->", "found", "=", "true", ";", "break", ";", "}", "else", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "this", "->", "find", "(", "$", "item", ",", "$", "value", ")", ";", "}", "}", "}", "}", "if", "(", "!", "$", "this", "->", "found", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "currentItem", ";", "}" ]
Recursively finds an item from the settings array @param string $item @param array $array @return object/$this
[ "Recursively", "finds", "an", "item", "from", "the", "settings", "array" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Support/Config.php#L191-L225
train
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.getLabelFor
private function getLabelFor($property) { switch ($property) { case 'nid': return t("Node ID."); case 'vid': return t("Revision ID."); case 'type': return t("Type"); case 'language': return t("Language"); case 'label': return t("Label"); case 'title': return t("Title"); case 'uid': return t("User ID."); case 'status': return t("Status"); case 'changed': return t("Latest update at"); case 'created': return t("Created at"); case 'promote': return t("Promoted"); case 'sticky': return t("Sticked"); case 'name': return t("Name"); case 'pass': return t("Password"); case 'mail': return t("E-mail"); case 'theme': return t("Theme"); case 'signature': return t("Signature"); case 'signature_format': return t("Signature format"); case 'access': return t("Lastest access at"); case 'login': return t("Lastest login at"); case 'timezone': return t("Timezone"); case 'description': return t("Description"); case 'format': return t("Format"); } return $property; }
php
private function getLabelFor($property) { switch ($property) { case 'nid': return t("Node ID."); case 'vid': return t("Revision ID."); case 'type': return t("Type"); case 'language': return t("Language"); case 'label': return t("Label"); case 'title': return t("Title"); case 'uid': return t("User ID."); case 'status': return t("Status"); case 'changed': return t("Latest update at"); case 'created': return t("Created at"); case 'promote': return t("Promoted"); case 'sticky': return t("Sticked"); case 'name': return t("Name"); case 'pass': return t("Password"); case 'mail': return t("E-mail"); case 'theme': return t("Theme"); case 'signature': return t("Signature"); case 'signature_format': return t("Signature format"); case 'access': return t("Lastest access at"); case 'login': return t("Lastest login at"); case 'timezone': return t("Timezone"); case 'description': return t("Description"); case 'format': return t("Format"); } return $property; }
[ "private", "function", "getLabelFor", "(", "$", "property", ")", "{", "switch", "(", "$", "property", ")", "{", "case", "'nid'", ":", "return", "t", "(", "\"Node ID.\"", ")", ";", "case", "'vid'", ":", "return", "t", "(", "\"Revision ID.\"", ")", ";", "case", "'type'", ":", "return", "t", "(", "\"Type\"", ")", ";", "case", "'language'", ":", "return", "t", "(", "\"Language\"", ")", ";", "case", "'label'", ":", "return", "t", "(", "\"Label\"", ")", ";", "case", "'title'", ":", "return", "t", "(", "\"Title\"", ")", ";", "case", "'uid'", ":", "return", "t", "(", "\"User ID.\"", ")", ";", "case", "'status'", ":", "return", "t", "(", "\"Status\"", ")", ";", "case", "'changed'", ":", "return", "t", "(", "\"Latest update at\"", ")", ";", "case", "'created'", ":", "return", "t", "(", "\"Created at\"", ")", ";", "case", "'promote'", ":", "return", "t", "(", "\"Promoted\"", ")", ";", "case", "'sticky'", ":", "return", "t", "(", "\"Sticked\"", ")", ";", "case", "'name'", ":", "return", "t", "(", "\"Name\"", ")", ";", "case", "'pass'", ":", "return", "t", "(", "\"Password\"", ")", ";", "case", "'mail'", ":", "return", "t", "(", "\"E-mail\"", ")", ";", "case", "'theme'", ":", "return", "t", "(", "\"Theme\"", ")", ";", "case", "'signature'", ":", "return", "t", "(", "\"Signature\"", ")", ";", "case", "'signature_format'", ":", "return", "t", "(", "\"Signature format\"", ")", ";", "case", "'access'", ":", "return", "t", "(", "\"Lastest access at\"", ")", ";", "case", "'login'", ":", "return", "t", "(", "\"Lastest login at\"", ")", ";", "case", "'timezone'", ":", "return", "t", "(", "\"Timezone\"", ")", ";", "case", "'description'", ":", "return", "t", "(", "\"Description\"", ")", ";", "case", "'format'", ":", "return", "t", "(", "\"Format\"", ")", ";", "}", "return", "$", "property", ";", "}" ]
Attempt to guess the property description, knowing that Drupalisms are strong and a lot of people will always use the same colum names @param string $property @param string
[ "Attempt", "to", "guess", "the", "property", "description", "knowing", "that", "Drupalisms", "are", "strong", "and", "a", "lot", "of", "people", "will", "always", "use", "the", "same", "colum", "names" ]
cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L43-L118
train
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.schemaApiTypeToPropertyInfoType
private function schemaApiTypeToPropertyInfoType($type) { switch ($type) { case 'serial': case 'int': return new Type(Type::BUILTIN_TYPE_INT, true); case 'float': case 'numeric': return new Type(Type::BUILTIN_TYPE_FLOAT, true); case 'varchar': case 'text': case 'blob': return new Type(Type::BUILTIN_TYPE_STRING, true); } }
php
private function schemaApiTypeToPropertyInfoType($type) { switch ($type) { case 'serial': case 'int': return new Type(Type::BUILTIN_TYPE_INT, true); case 'float': case 'numeric': return new Type(Type::BUILTIN_TYPE_FLOAT, true); case 'varchar': case 'text': case 'blob': return new Type(Type::BUILTIN_TYPE_STRING, true); } }
[ "private", "function", "schemaApiTypeToPropertyInfoType", "(", "$", "type", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "'serial'", ":", "case", "'int'", ":", "return", "new", "Type", "(", "Type", "::", "BUILTIN_TYPE_INT", ",", "true", ")", ";", "case", "'float'", ":", "case", "'numeric'", ":", "return", "new", "Type", "(", "Type", "::", "BUILTIN_TYPE_FLOAT", ",", "true", ")", ";", "case", "'varchar'", ":", "case", "'text'", ":", "case", "'blob'", ":", "return", "new", "Type", "(", "Type", "::", "BUILTIN_TYPE_STRING", ",", "true", ")", ";", "}", "}" ]
Convert schema API type to property info type @param string $type @return null|Type
[ "Convert", "schema", "API", "type", "to", "property", "info", "type" ]
cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L127-L144
train
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.getEntityTypeInfo
private function getEntityTypeInfo($class) { $entityType = $this->getEntityType($class); if (!$entityType) { return [null, null]; } $info = entity_get_info($entityType); if (!$info) { return [null, null]; } return [$entityType, $info]; }
php
private function getEntityTypeInfo($class) { $entityType = $this->getEntityType($class); if (!$entityType) { return [null, null]; } $info = entity_get_info($entityType); if (!$info) { return [null, null]; } return [$entityType, $info]; }
[ "private", "function", "getEntityTypeInfo", "(", "$", "class", ")", "{", "$", "entityType", "=", "$", "this", "->", "getEntityType", "(", "$", "class", ")", ";", "if", "(", "!", "$", "entityType", ")", "{", "return", "[", "null", ",", "null", "]", ";", "}", "$", "info", "=", "entity_get_info", "(", "$", "entityType", ")", ";", "if", "(", "!", "$", "info", ")", "{", "return", "[", "null", ",", "null", "]", ";", "}", "return", "[", "$", "entityType", ",", "$", "info", "]", ";", "}" ]
Get entity type info for the given class @param string $class @return array If entity type is found, first key is the entity type, second value is the entity info array
[ "Get", "entity", "type", "info", "for", "the", "given", "class" ]
cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L155-L170
train
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.findFieldInstances
private function findFieldInstances($entityType, $entityInfo) { $ret = []; // Add field properties, since Drupal does not differenciate entity // bundles using different class for different object, we are just // gonna give the whole field list foreach (field_info_instances($entityType) as $fields) { foreach ($fields as $name => $instance) { if (isset($ret[$name])) { continue; } $ret[$name] = $instance; } } return $ret; }
php
private function findFieldInstances($entityType, $entityInfo) { $ret = []; // Add field properties, since Drupal does not differenciate entity // bundles using different class for different object, we are just // gonna give the whole field list foreach (field_info_instances($entityType) as $fields) { foreach ($fields as $name => $instance) { if (isset($ret[$name])) { continue; } $ret[$name] = $instance; } } return $ret; }
[ "private", "function", "findFieldInstances", "(", "$", "entityType", ",", "$", "entityInfo", ")", "{", "$", "ret", "=", "[", "]", ";", "// Add field properties, since Drupal does not differenciate entity", "// bundles using different class for different object, we are just", "// gonna give the whole field list", "foreach", "(", "field_info_instances", "(", "$", "entityType", ")", "as", "$", "fields", ")", "{", "foreach", "(", "$", "fields", "as", "$", "name", "=>", "$", "instance", ")", "{", "if", "(", "isset", "(", "$", "ret", "[", "$", "name", "]", ")", ")", "{", "continue", ";", "}", "$", "ret", "[", "$", "name", "]", "=", "$", "instance", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Guess the while field instances for the given entity type @param string $entityType @param array $entityInfo @param string $property @return null|array
[ "Guess", "the", "while", "field", "instances", "for", "the", "given", "entity", "type" ]
cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L181-L200
train
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.findFieldInstanceFor
private function findFieldInstanceFor($entityType, $entityInfo, $property) { $instances = $this->findFieldInstances($entityType, $entityInfo); if (isset($instances[$property])) { return $instances[$property]; } }
php
private function findFieldInstanceFor($entityType, $entityInfo, $property) { $instances = $this->findFieldInstances($entityType, $entityInfo); if (isset($instances[$property])) { return $instances[$property]; } }
[ "private", "function", "findFieldInstanceFor", "(", "$", "entityType", ",", "$", "entityInfo", ",", "$", "property", ")", "{", "$", "instances", "=", "$", "this", "->", "findFieldInstances", "(", "$", "entityType", ",", "$", "entityInfo", ")", ";", "if", "(", "isset", "(", "$", "instances", "[", "$", "property", "]", ")", ")", "{", "return", "$", "instances", "[", "$", "property", "]", ";", "}", "}" ]
Guess the field instance for a single property of the given entity type @param string $entityType @param array $entityInfo @param string $property @return null|array
[ "Guess", "the", "field", "instance", "for", "a", "single", "property", "of", "the", "given", "entity", "type" ]
cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L211-L218
train
salernolabs/camelize
src/Camel.php
Camel.camelize
public function camelize($input) { $input = trim($input); if (empty($input)) { throw new \Exception("Can not camelize an empty string."); } $output = ''; $capitalizeNext = $this->shouldCapitalizeFirstLetter; for ($i = 0; $i < mb_strlen($input); ++$i) { $character = mb_substr($input, $i, 1); if ($character == '_' || $character == ' ') { $capitalizeNext = true; } else { if ($capitalizeNext) { $capitalizeNext = false; $output .= mb_strtoupper($character); } else { $output .= mb_strtolower($character); } } } return $output; }
php
public function camelize($input) { $input = trim($input); if (empty($input)) { throw new \Exception("Can not camelize an empty string."); } $output = ''; $capitalizeNext = $this->shouldCapitalizeFirstLetter; for ($i = 0; $i < mb_strlen($input); ++$i) { $character = mb_substr($input, $i, 1); if ($character == '_' || $character == ' ') { $capitalizeNext = true; } else { if ($capitalizeNext) { $capitalizeNext = false; $output .= mb_strtoupper($character); } else { $output .= mb_strtolower($character); } } } return $output; }
[ "public", "function", "camelize", "(", "$", "input", ")", "{", "$", "input", "=", "trim", "(", "$", "input", ")", ";", "if", "(", "empty", "(", "$", "input", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Can not camelize an empty string.\"", ")", ";", "}", "$", "output", "=", "''", ";", "$", "capitalizeNext", "=", "$", "this", "->", "shouldCapitalizeFirstLetter", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "mb_strlen", "(", "$", "input", ")", ";", "++", "$", "i", ")", "{", "$", "character", "=", "mb_substr", "(", "$", "input", ",", "$", "i", ",", "1", ")", ";", "if", "(", "$", "character", "==", "'_'", "||", "$", "character", "==", "' '", ")", "{", "$", "capitalizeNext", "=", "true", ";", "}", "else", "{", "if", "(", "$", "capitalizeNext", ")", "{", "$", "capitalizeNext", "=", "false", ";", "$", "output", ".=", "mb_strtoupper", "(", "$", "character", ")", ";", "}", "else", "{", "$", "output", ".=", "mb_strtolower", "(", "$", "character", ")", ";", "}", "}", "}", "return", "$", "output", ";", "}" ]
Camel Case a String @param $input @return string
[ "Camel", "Case", "a", "String" ]
6098e9827fd21509592fc7062b653582d0dd00d1
https://github.com/salernolabs/camelize/blob/6098e9827fd21509592fc7062b653582d0dd00d1/src/Camel.php#L37-L72
train
philipbrown/money
src/Money.php
Money.equals
public function equals(Money $money) { return $this->isSameCurrency($money) && $this->cents == $money->cents; }
php
public function equals(Money $money) { return $this->isSameCurrency($money) && $this->cents == $money->cents; }
[ "public", "function", "equals", "(", "Money", "$", "money", ")", "{", "return", "$", "this", "->", "isSameCurrency", "(", "$", "money", ")", "&&", "$", "this", "->", "cents", "==", "$", "money", "->", "cents", ";", "}" ]
Check the equality of two Money objects. First check the currency and then check the value. @param PhilipBrown\Money\Money @return bool
[ "Check", "the", "equality", "of", "two", "Money", "objects", ".", "First", "check", "the", "currency", "and", "then", "check", "the", "value", "." ]
2ba3a1e4b52869f8696384a5033459708f25c109
https://github.com/philipbrown/money/blob/2ba3a1e4b52869f8696384a5033459708f25c109/src/Money.php#L86-L89
train
philipbrown/money
src/Money.php
Money.add
public function add(Money $money) { if($this->isSameCurrency($money)) { return Money::init($this->cents + $money->cents, $this->currency->getIsoCode()); } throw new InvalidCurrencyException("You can't add two Money objects with different currencies"); }
php
public function add(Money $money) { if($this->isSameCurrency($money)) { return Money::init($this->cents + $money->cents, $this->currency->getIsoCode()); } throw new InvalidCurrencyException("You can't add two Money objects with different currencies"); }
[ "public", "function", "add", "(", "Money", "$", "money", ")", "{", "if", "(", "$", "this", "->", "isSameCurrency", "(", "$", "money", ")", ")", "{", "return", "Money", "::", "init", "(", "$", "this", "->", "cents", "+", "$", "money", "->", "cents", ",", "$", "this", "->", "currency", "->", "getIsoCode", "(", ")", ")", ";", "}", "throw", "new", "InvalidCurrencyException", "(", "\"You can't add two Money objects with different currencies\"", ")", ";", "}" ]
Add two the value of two Money objects and return a new Money object. @param PhilipBrown\Money\Money $money @return PhilipBrown\Money\Money
[ "Add", "two", "the", "value", "of", "two", "Money", "objects", "and", "return", "a", "new", "Money", "object", "." ]
2ba3a1e4b52869f8696384a5033459708f25c109
https://github.com/philipbrown/money/blob/2ba3a1e4b52869f8696384a5033459708f25c109/src/Money.php#L97-L105
train
philipbrown/money
src/Money.php
Money.multiply
public function multiply($number) { return Money::init((int) round($this->cents * $number, 0, PHP_ROUND_HALF_EVEN), $this->currency->getIsoCode()); }
php
public function multiply($number) { return Money::init((int) round($this->cents * $number, 0, PHP_ROUND_HALF_EVEN), $this->currency->getIsoCode()); }
[ "public", "function", "multiply", "(", "$", "number", ")", "{", "return", "Money", "::", "init", "(", "(", "int", ")", "round", "(", "$", "this", "->", "cents", "*", "$", "number", ",", "0", ",", "PHP_ROUND_HALF_EVEN", ")", ",", "$", "this", "->", "currency", "->", "getIsoCode", "(", ")", ")", ";", "}" ]
Multiply two Money objects together and return a new Money object @param int $number @return PhilipBrown\Money\Money
[ "Multiply", "two", "Money", "objects", "together", "and", "return", "a", "new", "Money", "object" ]
2ba3a1e4b52869f8696384a5033459708f25c109
https://github.com/philipbrown/money/blob/2ba3a1e4b52869f8696384a5033459708f25c109/src/Money.php#L129-L132
train
ZhukV/LanguageDetector
src/Ideea/LanguageDetector/LanguageDetector.php
LanguageDetector.addVisitor
public function addVisitor(VisitorInterface $visitor, $priority = 0) { $this->sortedVisitors = null; $this->visitors[spl_object_hash($visitor)] = array( 'priority' => $priority, 'visitor' => $visitor ); return $this; }
php
public function addVisitor(VisitorInterface $visitor, $priority = 0) { $this->sortedVisitors = null; $this->visitors[spl_object_hash($visitor)] = array( 'priority' => $priority, 'visitor' => $visitor ); return $this; }
[ "public", "function", "addVisitor", "(", "VisitorInterface", "$", "visitor", ",", "$", "priority", "=", "0", ")", "{", "$", "this", "->", "sortedVisitors", "=", "null", ";", "$", "this", "->", "visitors", "[", "spl_object_hash", "(", "$", "visitor", ")", "]", "=", "array", "(", "'priority'", "=>", "$", "priority", ",", "'visitor'", "=>", "$", "visitor", ")", ";", "return", "$", "this", ";", "}" ]
Add detection visitor @param VisitorInterface $visitor @param int $priority @return LanguageDetector
[ "Add", "detection", "visitor" ]
e5138f4c789e899801e098ce1e719337b015af7c
https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/LanguageDetector.php#L46-L56
train
ZhukV/LanguageDetector
src/Ideea/LanguageDetector/LanguageDetector.php
LanguageDetector.createDefault
public static function createDefault(DictionaryInterface $dictionary = null) { /** @var LanguageDetector $detector */ $detector = new static(); $dataDirectory = realpath(__DIR__ . '/../../../data'); $alphabetLoader = new AlphabetLoader(); $sectionLoader = new SectionLoader(); $sections = $sectionLoader->load($dataDirectory . '/sections.yml'); $alphabets = $alphabetLoader->load($dataDirectory . '/alphabets.yml'); $detector ->addVisitor(new SectionVisitor($sections), -1024) ->addVisitor(new AlphabetVisitor($alphabets), -512); if ($dictionary) { $detector->addVisitor(new DictionaryVisitor($dictionary), -256); } return $detector; }
php
public static function createDefault(DictionaryInterface $dictionary = null) { /** @var LanguageDetector $detector */ $detector = new static(); $dataDirectory = realpath(__DIR__ . '/../../../data'); $alphabetLoader = new AlphabetLoader(); $sectionLoader = new SectionLoader(); $sections = $sectionLoader->load($dataDirectory . '/sections.yml'); $alphabets = $alphabetLoader->load($dataDirectory . '/alphabets.yml'); $detector ->addVisitor(new SectionVisitor($sections), -1024) ->addVisitor(new AlphabetVisitor($alphabets), -512); if ($dictionary) { $detector->addVisitor(new DictionaryVisitor($dictionary), -256); } return $detector; }
[ "public", "static", "function", "createDefault", "(", "DictionaryInterface", "$", "dictionary", "=", "null", ")", "{", "/** @var LanguageDetector $detector */", "$", "detector", "=", "new", "static", "(", ")", ";", "$", "dataDirectory", "=", "realpath", "(", "__DIR__", ".", "'/../../../data'", ")", ";", "$", "alphabetLoader", "=", "new", "AlphabetLoader", "(", ")", ";", "$", "sectionLoader", "=", "new", "SectionLoader", "(", ")", ";", "$", "sections", "=", "$", "sectionLoader", "->", "load", "(", "$", "dataDirectory", ".", "'/sections.yml'", ")", ";", "$", "alphabets", "=", "$", "alphabetLoader", "->", "load", "(", "$", "dataDirectory", ".", "'/alphabets.yml'", ")", ";", "$", "detector", "->", "addVisitor", "(", "new", "SectionVisitor", "(", "$", "sections", ")", ",", "-", "1024", ")", "->", "addVisitor", "(", "new", "AlphabetVisitor", "(", "$", "alphabets", ")", ",", "-", "512", ")", ";", "if", "(", "$", "dictionary", ")", "{", "$", "detector", "->", "addVisitor", "(", "new", "DictionaryVisitor", "(", "$", "dictionary", ")", ",", "-", "256", ")", ";", "}", "return", "$", "detector", ";", "}" ]
Create default detector @param DictionaryInterface $dictionary @return LanguageDetector
[ "Create", "default", "detector" ]
e5138f4c789e899801e098ce1e719337b015af7c
https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/LanguageDetector.php#L123-L145
train
wigedev/farm
src/FormBuilder/FormElement/Checkboxgroup.php
Checkboxgroup.setDefaultValue
public function setDefaultValue($value) : FormElement { if (is_array($value)) { $value = implode(',', $value); } parent::setDefaultValue($value); return $this; }
php
public function setDefaultValue($value) : FormElement { if (is_array($value)) { $value = implode(',', $value); } parent::setDefaultValue($value); return $this; }
[ "public", "function", "setDefaultValue", "(", "$", "value", ")", ":", "FormElement", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "implode", "(", "','", ",", "$", "value", ")", ";", "}", "parent", "::", "setDefaultValue", "(", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Sets the default or database value for the element. Overridden to convert arrays to strings. @param mixed $value The value of the form field. @return FormElement
[ "Sets", "the", "default", "or", "database", "value", "for", "the", "element", ".", "Overridden", "to", "convert", "arrays", "to", "strings", "." ]
7a1729ec78628b7e5435e4a42e42d547a07af851
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement/Checkboxgroup.php#L31-L38
train
wigedev/farm
src/FormBuilder/FormElement/Checkboxgroup.php
Checkboxgroup.setUserValue
public function setUserValue(string $value) : FormElement { if (is_array($value)) { $value = implode(',', $value); } parent::setUserValue($value); return $this; }
php
public function setUserValue(string $value) : FormElement { if (is_array($value)) { $value = implode(',', $value); } parent::setUserValue($value); return $this; }
[ "public", "function", "setUserValue", "(", "string", "$", "value", ")", ":", "FormElement", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "implode", "(", "','", ",", "$", "value", ")", ";", "}", "parent", "::", "setUserValue", "(", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Sets a user value to be validated. Overridden to convert arrays to strings. @param string $value @return FormElement
[ "Sets", "a", "user", "value", "to", "be", "validated", ".", "Overridden", "to", "convert", "arrays", "to", "strings", "." ]
7a1729ec78628b7e5435e4a42e42d547a07af851
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement/Checkboxgroup.php#L46-L53
train
wigedev/farm
src/FormBuilder/FormElement/Checkboxgroup.php
Checkboxgroup.validate
public function validate() : void { if (null === $this->is_valid) { if (null === $this->user_value && null !== $this->default_value) { // There is a preset value, and its not being changed $this->is_valid = true; } elseif (null != $this->validator && false != $this->validator) { $validator = $this->validator; $valids = array(); $all_valid = true; $pieces = explode(',', $this->user_value); foreach ($pieces as $piece) { $result = $validator::quickValidate($piece, $this->constraints); if (null !== $result) { $valids[] = $result; } else { $all_valid = false; } } $this->user_value = implode(',', $valids); $this->is_valid = $all_valid; if (!$all_valid) { $this->error = 'The provided value is not valid. Please enter a valid value.'; } } else { // This field does not get validated $this->is_valid = true; } } // Check if the input is different from the default value if ($this->is_valid && null !== $this->user_value) { $this->is_changed = ($this->default_value != $this->user_value); } }
php
public function validate() : void { if (null === $this->is_valid) { if (null === $this->user_value && null !== $this->default_value) { // There is a preset value, and its not being changed $this->is_valid = true; } elseif (null != $this->validator && false != $this->validator) { $validator = $this->validator; $valids = array(); $all_valid = true; $pieces = explode(',', $this->user_value); foreach ($pieces as $piece) { $result = $validator::quickValidate($piece, $this->constraints); if (null !== $result) { $valids[] = $result; } else { $all_valid = false; } } $this->user_value = implode(',', $valids); $this->is_valid = $all_valid; if (!$all_valid) { $this->error = 'The provided value is not valid. Please enter a valid value.'; } } else { // This field does not get validated $this->is_valid = true; } } // Check if the input is different from the default value if ($this->is_valid && null !== $this->user_value) { $this->is_changed = ($this->default_value != $this->user_value); } }
[ "public", "function", "validate", "(", ")", ":", "void", "{", "if", "(", "null", "===", "$", "this", "->", "is_valid", ")", "{", "if", "(", "null", "===", "$", "this", "->", "user_value", "&&", "null", "!==", "$", "this", "->", "default_value", ")", "{", "// There is a preset value, and its not being changed", "$", "this", "->", "is_valid", "=", "true", ";", "}", "elseif", "(", "null", "!=", "$", "this", "->", "validator", "&&", "false", "!=", "$", "this", "->", "validator", ")", "{", "$", "validator", "=", "$", "this", "->", "validator", ";", "$", "valids", "=", "array", "(", ")", ";", "$", "all_valid", "=", "true", ";", "$", "pieces", "=", "explode", "(", "','", ",", "$", "this", "->", "user_value", ")", ";", "foreach", "(", "$", "pieces", "as", "$", "piece", ")", "{", "$", "result", "=", "$", "validator", "::", "quickValidate", "(", "$", "piece", ",", "$", "this", "->", "constraints", ")", ";", "if", "(", "null", "!==", "$", "result", ")", "{", "$", "valids", "[", "]", "=", "$", "result", ";", "}", "else", "{", "$", "all_valid", "=", "false", ";", "}", "}", "$", "this", "->", "user_value", "=", "implode", "(", "','", ",", "$", "valids", ")", ";", "$", "this", "->", "is_valid", "=", "$", "all_valid", ";", "if", "(", "!", "$", "all_valid", ")", "{", "$", "this", "->", "error", "=", "'The provided value is not valid. Please enter a valid value.'", ";", "}", "}", "else", "{", "// This field does not get validated", "$", "this", "->", "is_valid", "=", "true", ";", "}", "}", "// Check if the input is different from the default value", "if", "(", "$", "this", "->", "is_valid", "&&", "null", "!==", "$", "this", "->", "user_value", ")", "{", "$", "this", "->", "is_changed", "=", "(", "$", "this", "->", "default_value", "!=", "$", "this", "->", "user_value", ")", ";", "}", "}" ]
Validates the user value according to the validator defined for this element.
[ "Validates", "the", "user", "value", "according", "to", "the", "validator", "defined", "for", "this", "element", "." ]
7a1729ec78628b7e5435e4a42e42d547a07af851
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement/Checkboxgroup.php#L68-L102
train
Falc/TwigTextExtension
src/TextExtension.php
TextExtension.p2br
public function p2br($data) { // Remove opening <p> tags $data = preg_replace('#<p[^>]*?>#', '', $data); // Remove trailing </p> to prevent it to be replaced with unneeded <br /> $data = preg_replace('#</p>$#', '', $data); // Replace each end of paragraph with two <br /> $data = str_replace('</p>', '<br /><br />', $data); return $data; }
php
public function p2br($data) { // Remove opening <p> tags $data = preg_replace('#<p[^>]*?>#', '', $data); // Remove trailing </p> to prevent it to be replaced with unneeded <br /> $data = preg_replace('#</p>$#', '', $data); // Replace each end of paragraph with two <br /> $data = str_replace('</p>', '<br /><br />', $data); return $data; }
[ "public", "function", "p2br", "(", "$", "data", ")", "{", "// Remove opening <p> tags", "$", "data", "=", "preg_replace", "(", "'#<p[^>]*?>#'", ",", "''", ",", "$", "data", ")", ";", "// Remove trailing </p> to prevent it to be replaced with unneeded <br />", "$", "data", "=", "preg_replace", "(", "'#</p>$#'", ",", "''", ",", "$", "data", ")", ";", "// Replace each end of paragraph with two <br />", "$", "data", "=", "str_replace", "(", "'</p>'", ",", "'<br /><br />'", ",", "$", "data", ")", ";", "return", "$", "data", ";", "}" ]
Replaces paragraph formatting with double linebreaks. Example: '<p>This is a text.</p><p>This should be another paragraph.</p>' Output: 'This is a text.<br /><br>This should be another paragraph.' @param string $data Text to format. @return string Formatted text.
[ "Replaces", "paragraph", "formatting", "with", "double", "linebreaks", "." ]
5036da5fddf5c055bd98d42209ae1d8cd88b1889
https://github.com/Falc/TwigTextExtension/blob/5036da5fddf5c055bd98d42209ae1d8cd88b1889/src/TextExtension.php#L73-L85
train
Falc/TwigTextExtension
src/TextExtension.php
TextExtension.paragraphs_slice
public function paragraphs_slice($text, $offset = 0, $length = null) { $result = array(); preg_match_all('#<p[^>]*>(.*?)</p>#', $text, $result); // Null length = all the paragraphs if ($length === null) { $length = count($result[0]) - $offset; } return array_slice($result[0], $offset, $length); }
php
public function paragraphs_slice($text, $offset = 0, $length = null) { $result = array(); preg_match_all('#<p[^>]*>(.*?)</p>#', $text, $result); // Null length = all the paragraphs if ($length === null) { $length = count($result[0]) - $offset; } return array_slice($result[0], $offset, $length); }
[ "public", "function", "paragraphs_slice", "(", "$", "text", ",", "$", "offset", "=", "0", ",", "$", "length", "=", "null", ")", "{", "$", "result", "=", "array", "(", ")", ";", "preg_match_all", "(", "'#<p[^>]*>(.*?)</p>#'", ",", "$", "text", ",", "$", "result", ")", ";", "// Null length = all the paragraphs", "if", "(", "$", "length", "===", "null", ")", "{", "$", "length", "=", "count", "(", "$", "result", "[", "0", "]", ")", "-", "$", "offset", ";", "}", "return", "array_slice", "(", "$", "result", "[", "0", "]", ",", "$", "offset", ",", "$", "length", ")", ";", "}" ]
Extracts paragraphs from a string. This function uses array_slice(). The function signatures are similar. @see http://www.php.net/manual/en/function.array-slice.php @param string $text String containing paragraphs. @param integer $offset Number of paragraphs to offset. Default: 0. @param integer $length Number of paragraphs to extract. Default: null. @return string[]
[ "Extracts", "paragraphs", "from", "a", "string", "." ]
5036da5fddf5c055bd98d42209ae1d8cd88b1889
https://github.com/Falc/TwigTextExtension/blob/5036da5fddf5c055bd98d42209ae1d8cd88b1889/src/TextExtension.php#L99-L110
train
Falc/TwigTextExtension
src/TextExtension.php
TextExtension.regex_replace
public function regex_replace($subject, $pattern, $replacement, $limit = -1) { return preg_replace($pattern, $replacement, $subject, $limit); }
php
public function regex_replace($subject, $pattern, $replacement, $limit = -1) { return preg_replace($pattern, $replacement, $subject, $limit); }
[ "public", "function", "regex_replace", "(", "$", "subject", ",", "$", "pattern", ",", "$", "replacement", ",", "$", "limit", "=", "-", "1", ")", "{", "return", "preg_replace", "(", "$", "pattern", ",", "$", "replacement", ",", "$", "subject", ",", "$", "limit", ")", ";", "}" ]
Performs a regular expression search and replace. @see http://php.net/manual/en/function.preg-replace.php @param string $subject String or array of strings to search and replace. @param mixed $pattern Pattern to search for. It can be either a string or an array with strings. @param mixed $replacement String or array with strings to replace. @param integer $limit Maximum possible replacements for each pattern in each subject string. Default is no limit. @return string
[ "Performs", "a", "regular", "expression", "search", "and", "replace", "." ]
5036da5fddf5c055bd98d42209ae1d8cd88b1889
https://github.com/Falc/TwigTextExtension/blob/5036da5fddf5c055bd98d42209ae1d8cd88b1889/src/TextExtension.php#L123-L126
train
antaresproject/translations
src/Http/Datatables/Languages.php
Languages.getActionsColumn
protected function getActionsColumn($canAddLanguage) { return function ($row) use($canAddLanguage) { $btns = []; $html = app('html'); if ($canAddLanguage && !$row->is_default) { $btns[] = $html->create('li', $html->link(handles("antares::translations/languages/delete/" . $row->id), trans('Delete'), ['class' => "triggerable confirm", 'data-icon' => 'delete', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Deleting language') . ' ' . $row->code])); $btns[] = $html->create('li', $html->link(handles("antares::translations/languages/default/" . $row->id), trans('Set as default'), ['data-icon' => 'spellcheck'])); } if (empty($btns)) { return ''; } $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu'])->get(); return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get(); }; }
php
protected function getActionsColumn($canAddLanguage) { return function ($row) use($canAddLanguage) { $btns = []; $html = app('html'); if ($canAddLanguage && !$row->is_default) { $btns[] = $html->create('li', $html->link(handles("antares::translations/languages/delete/" . $row->id), trans('Delete'), ['class' => "triggerable confirm", 'data-icon' => 'delete', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Deleting language') . ' ' . $row->code])); $btns[] = $html->create('li', $html->link(handles("antares::translations/languages/default/" . $row->id), trans('Set as default'), ['data-icon' => 'spellcheck'])); } if (empty($btns)) { return ''; } $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu'])->get(); return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get(); }; }
[ "protected", "function", "getActionsColumn", "(", "$", "canAddLanguage", ")", "{", "return", "function", "(", "$", "row", ")", "use", "(", "$", "canAddLanguage", ")", "{", "$", "btns", "=", "[", "]", ";", "$", "html", "=", "app", "(", "'html'", ")", ";", "if", "(", "$", "canAddLanguage", "&&", "!", "$", "row", "->", "is_default", ")", "{", "$", "btns", "[", "]", "=", "$", "html", "->", "create", "(", "'li'", ",", "$", "html", "->", "link", "(", "handles", "(", "\"antares::translations/languages/delete/\"", ".", "$", "row", "->", "id", ")", ",", "trans", "(", "'Delete'", ")", ",", "[", "'class'", "=>", "\"triggerable confirm\"", ",", "'data-icon'", "=>", "'delete'", ",", "'data-title'", "=>", "trans", "(", "\"Are you sure?\"", ")", ",", "'data-description'", "=>", "trans", "(", "'Deleting language'", ")", ".", "' '", ".", "$", "row", "->", "code", "]", ")", ")", ";", "$", "btns", "[", "]", "=", "$", "html", "->", "create", "(", "'li'", ",", "$", "html", "->", "link", "(", "handles", "(", "\"antares::translations/languages/default/\"", ".", "$", "row", "->", "id", ")", ",", "trans", "(", "'Set as default'", ")", ",", "[", "'data-icon'", "=>", "'spellcheck'", "]", ")", ")", ";", "}", "if", "(", "empty", "(", "$", "btns", ")", ")", "{", "return", "''", ";", "}", "$", "section", "=", "$", "html", "->", "create", "(", "'div'", ",", "$", "html", "->", "create", "(", "'section'", ",", "$", "html", "->", "create", "(", "'ul'", ",", "$", "html", "->", "raw", "(", "implode", "(", "''", ",", "$", "btns", ")", ")", ")", ")", ",", "[", "'class'", "=>", "'mass-actions-menu'", "]", ")", "->", "get", "(", ")", ";", "return", "'<i class=\"zmdi zmdi-more\"></i>'", ".", "$", "html", "->", "raw", "(", "$", "section", ")", "->", "get", "(", ")", ";", "}", ";", "}" ]
Actions column for datatable @param boolean $canAddLanguage @return String
[ "Actions", "column", "for", "datatable" ]
63097aeb97f18c5aeeef7dcf15f0c67959951685
https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Datatables/Languages.php#L90-L106
train
ekyna/AdminBundle
Operator/ResourceOperator.php
ResourceOperator.persistResource
protected function persistResource(ResourceEvent $event) { $resource = $event->getResource(); // TODO Validation ? try { $this->manager->persist($resource); $this->manager->flush(); } catch(DBALException $e) { if ($this->debug) { throw $e; } $event->addMessage(new ResourceMessage( 'ekyna_admin.resource.message.persist.failure', ResourceMessage::TYPE_ERROR )); return $event; } return $event->addMessage(new ResourceMessage( 'ekyna_admin.resource.message.persist.success', ResourceMessage::TYPE_SUCCESS )); }
php
protected function persistResource(ResourceEvent $event) { $resource = $event->getResource(); // TODO Validation ? try { $this->manager->persist($resource); $this->manager->flush(); } catch(DBALException $e) { if ($this->debug) { throw $e; } $event->addMessage(new ResourceMessage( 'ekyna_admin.resource.message.persist.failure', ResourceMessage::TYPE_ERROR )); return $event; } return $event->addMessage(new ResourceMessage( 'ekyna_admin.resource.message.persist.success', ResourceMessage::TYPE_SUCCESS )); }
[ "protected", "function", "persistResource", "(", "ResourceEvent", "$", "event", ")", "{", "$", "resource", "=", "$", "event", "->", "getResource", "(", ")", ";", "// TODO Validation ?", "try", "{", "$", "this", "->", "manager", "->", "persist", "(", "$", "resource", ")", ";", "$", "this", "->", "manager", "->", "flush", "(", ")", ";", "}", "catch", "(", "DBALException", "$", "e", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "{", "throw", "$", "e", ";", "}", "$", "event", "->", "addMessage", "(", "new", "ResourceMessage", "(", "'ekyna_admin.resource.message.persist.failure'", ",", "ResourceMessage", "::", "TYPE_ERROR", ")", ")", ";", "return", "$", "event", ";", "}", "return", "$", "event", "->", "addMessage", "(", "new", "ResourceMessage", "(", "'ekyna_admin.resource.message.persist.success'", ",", "ResourceMessage", "::", "TYPE_SUCCESS", ")", ")", ";", "}" ]
Persists a resource. @param ResourceEvent $event @return ResourceEvent @throws DBALException @throws \Exception
[ "Persists", "a", "resource", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Operator/ResourceOperator.php#L173-L197
train
crodas/ConcurrentFileWriter
src/ConcurrentFileWriter/Util.php
Util.delete
public static function delete($path) { if (!is_readable($path)) { return false; } if (!is_dir($path)) { unlink($path); return true; } foreach (scandir($path) as $file) { if ($file === '.' || $file === '..') { continue; } $file = $path . '/' . $file; if (is_dir($file)) { self::delete($file); } else { unlink($file); } } rmdir($path); return true; }
php
public static function delete($path) { if (!is_readable($path)) { return false; } if (!is_dir($path)) { unlink($path); return true; } foreach (scandir($path) as $file) { if ($file === '.' || $file === '..') { continue; } $file = $path . '/' . $file; if (is_dir($file)) { self::delete($file); } else { unlink($file); } } rmdir($path); return true; }
[ "public", "static", "function", "delete", "(", "$", "path", ")", "{", "if", "(", "!", "is_readable", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "unlink", "(", "$", "path", ")", ";", "return", "true", ";", "}", "foreach", "(", "scandir", "(", "$", "path", ")", "as", "$", "file", ")", "{", "if", "(", "$", "file", "===", "'.'", "||", "$", "file", "===", "'..'", ")", "{", "continue", ";", "}", "$", "file", "=", "$", "path", ".", "'/'", ".", "$", "file", ";", "if", "(", "is_dir", "(", "$", "file", ")", ")", "{", "self", "::", "delete", "(", "$", "file", ")", ";", "}", "else", "{", "unlink", "(", "$", "file", ")", ";", "}", "}", "rmdir", "(", "$", "path", ")", ";", "return", "true", ";", "}" ]
Deletes a file or directory recursively.
[ "Deletes", "a", "file", "or", "directory", "recursively", "." ]
13f88d8c2daf5fe9c70f8be6aeb3d862cd2a5e5a
https://github.com/crodas/ConcurrentFileWriter/blob/13f88d8c2daf5fe9c70f8be6aeb3d862cd2a5e5a/src/ConcurrentFileWriter/Util.php#L21-L47
train
PhoxPHP/Glider
src/Query/Parameters.php
Parameters.setParameter
public function setParameter(String $key, $value, Bool $override=false) { if ($this->getParameter($key)) { $defValue = $this->getParameter($key); $this->parameters[$key] = [$defValue]; $this->parameters[$key][] = $value; return; } $this->parameters[$key] = $value; }
php
public function setParameter(String $key, $value, Bool $override=false) { if ($this->getParameter($key)) { $defValue = $this->getParameter($key); $this->parameters[$key] = [$defValue]; $this->parameters[$key][] = $value; return; } $this->parameters[$key] = $value; }
[ "public", "function", "setParameter", "(", "String", "$", "key", ",", "$", "value", ",", "Bool", "$", "override", "=", "false", ")", "{", "if", "(", "$", "this", "->", "getParameter", "(", "$", "key", ")", ")", "{", "$", "defValue", "=", "$", "this", "->", "getParameter", "(", "$", "key", ")", ";", "$", "this", "->", "parameters", "[", "$", "key", "]", "=", "[", "$", "defValue", "]", ";", "$", "this", "->", "parameters", "[", "$", "key", "]", "[", "]", "=", "$", "value", ";", "return", ";", "}", "$", "this", "->", "parameters", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
Sets a parameter key and value. @param $key <String> @param $value <Mixed> @param $override <Boolean> If this option is set to true, the parameter value will be overriden if a value has already been set. @access public @return <void>
[ "Sets", "a", "parameter", "key", "and", "value", "." ]
17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Query/Parameters.php#L44-L54
train
PhoxPHP/Glider
src/Query/Parameters.php
Parameters.getType
public function getType($parameter='') { $parameterType = null; switch (gettype($parameter)) { case 'string': $parameterType = 's'; break; case 'numeric': case 'integer': $parameterType = 'i'; break; case 'double': $parameterType = 'd'; break; default: $parameterType = null; break; } return $parameterType; }
php
public function getType($parameter='') { $parameterType = null; switch (gettype($parameter)) { case 'string': $parameterType = 's'; break; case 'numeric': case 'integer': $parameterType = 'i'; break; case 'double': $parameterType = 'd'; break; default: $parameterType = null; break; } return $parameterType; }
[ "public", "function", "getType", "(", "$", "parameter", "=", "''", ")", "{", "$", "parameterType", "=", "null", ";", "switch", "(", "gettype", "(", "$", "parameter", ")", ")", "{", "case", "'string'", ":", "$", "parameterType", "=", "'s'", ";", "break", ";", "case", "'numeric'", ":", "case", "'integer'", ":", "$", "parameterType", "=", "'i'", ";", "break", ";", "case", "'double'", ":", "$", "parameterType", "=", "'d'", ";", "break", ";", "default", ":", "$", "parameterType", "=", "null", ";", "break", ";", "}", "return", "$", "parameterType", ";", "}" ]
Return a parameter type. @param $paramter <Mixed> @access public @return <Mixed>
[ "Return", "a", "parameter", "type", "." ]
17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Query/Parameters.php#L97-L117
train
stratedge/wye
src/Wye.php
Wye.makeBinding
public static function makeBinding( $parameter, $value, $data_type = PDO::PARAM_STR ) { $binding = new Binding(new static, $parameter, $value, $data_type); return $binding; }
php
public static function makeBinding( $parameter, $value, $data_type = PDO::PARAM_STR ) { $binding = new Binding(new static, $parameter, $value, $data_type); return $binding; }
[ "public", "static", "function", "makeBinding", "(", "$", "parameter", ",", "$", "value", ",", "$", "data_type", "=", "PDO", "::", "PARAM_STR", ")", "{", "$", "binding", "=", "new", "Binding", "(", "new", "static", ",", "$", "parameter", ",", "$", "value", ",", "$", "data_type", ")", ";", "return", "$", "binding", ";", "}" ]
Creates a new instance of Stratedge\Wye\Binding. @param int|string $parameter @param mixed $value @param int $data_type @return BindingInterface
[ "Creates", "a", "new", "instance", "of", "Stratedge", "\\", "Wye", "\\", "Binding", "." ]
9d3d32b4ea56c711d67b8498ab1a05d0aded40ea
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L154-L161
train
stratedge/wye
src/Wye.php
Wye.executeStatement
public static function executeStatement( PDOStatement $statement, array $params = null ) { //Add the statement to the list of those run static::addStatement($statement); //Add bindings to the statement if (is_array($params)) { $statement->getBindings() ->hydrateFromArray($params); } $result = static::getOrCreateResultAt(static::numQueries()); //Add the result to the statement $statement->setResult($result); //If a transaction is open, add the statement to it if (static::inTransaction()) { static::currentTransaction()->addStatement($statement); } //Increment number of queries run static::incrementNumQueries(); if (static::shouldLogBacktrace()) { $statement->setBacktrace( static::makeBacktraceCollection( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, static::resolveBacktraceLimit() ) ) ); } }
php
public static function executeStatement( PDOStatement $statement, array $params = null ) { //Add the statement to the list of those run static::addStatement($statement); //Add bindings to the statement if (is_array($params)) { $statement->getBindings() ->hydrateFromArray($params); } $result = static::getOrCreateResultAt(static::numQueries()); //Add the result to the statement $statement->setResult($result); //If a transaction is open, add the statement to it if (static::inTransaction()) { static::currentTransaction()->addStatement($statement); } //Increment number of queries run static::incrementNumQueries(); if (static::shouldLogBacktrace()) { $statement->setBacktrace( static::makeBacktraceCollection( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, static::resolveBacktraceLimit() ) ) ); } }
[ "public", "static", "function", "executeStatement", "(", "PDOStatement", "$", "statement", ",", "array", "$", "params", "=", "null", ")", "{", "//Add the statement to the list of those run", "static", "::", "addStatement", "(", "$", "statement", ")", ";", "//Add bindings to the statement", "if", "(", "is_array", "(", "$", "params", ")", ")", "{", "$", "statement", "->", "getBindings", "(", ")", "->", "hydrateFromArray", "(", "$", "params", ")", ";", "}", "$", "result", "=", "static", "::", "getOrCreateResultAt", "(", "static", "::", "numQueries", "(", ")", ")", ";", "//Add the result to the statement", "$", "statement", "->", "setResult", "(", "$", "result", ")", ";", "//If a transaction is open, add the statement to it", "if", "(", "static", "::", "inTransaction", "(", ")", ")", "{", "static", "::", "currentTransaction", "(", ")", "->", "addStatement", "(", "$", "statement", ")", ";", "}", "//Increment number of queries run", "static", "::", "incrementNumQueries", "(", ")", ";", "if", "(", "static", "::", "shouldLogBacktrace", "(", ")", ")", "{", "$", "statement", "->", "setBacktrace", "(", "static", "::", "makeBacktraceCollection", "(", "debug_backtrace", "(", "DEBUG_BACKTRACE_PROVIDE_OBJECT", "|", "DEBUG_BACKTRACE_IGNORE_ARGS", ",", "static", "::", "resolveBacktraceLimit", "(", ")", ")", ")", ")", ";", "}", "}" ]
Records a simulation of a query execution. @todo Raise an error if there are parameters already bound and params are provided. @param PDOStatement $statement @param array $params @return void
[ "Records", "a", "simulation", "of", "a", "query", "execution", "." ]
9d3d32b4ea56c711d67b8498ab1a05d0aded40ea
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L219-L255
train
stratedge/wye
src/Wye.php
Wye.beginTransaction
public static function beginTransaction() { if (static::inTransaction()) { throw new PDOException(); } static::inTransaction(true); $transaction = static::makeTransaction(static::countTransactions()); static::addTransaction($transaction); }
php
public static function beginTransaction() { if (static::inTransaction()) { throw new PDOException(); } static::inTransaction(true); $transaction = static::makeTransaction(static::countTransactions()); static::addTransaction($transaction); }
[ "public", "static", "function", "beginTransaction", "(", ")", "{", "if", "(", "static", "::", "inTransaction", "(", ")", ")", "{", "throw", "new", "PDOException", "(", ")", ";", "}", "static", "::", "inTransaction", "(", "true", ")", ";", "$", "transaction", "=", "static", "::", "makeTransaction", "(", "static", "::", "countTransactions", "(", ")", ")", ";", "static", "::", "addTransaction", "(", "$", "transaction", ")", ";", "}" ]
Places Wye into transaction mode and increments number of transactions. If a transaction is already open, throws a PDOException @todo Flesh out the details for the PDOException properly @throws PDOException @return void
[ "Places", "Wye", "into", "transaction", "mode", "and", "increments", "number", "of", "transactions", ".", "If", "a", "transaction", "is", "already", "open", "throws", "a", "PDOException" ]
9d3d32b4ea56c711d67b8498ab1a05d0aded40ea
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L288-L299
train
stratedge/wye
src/Wye.php
Wye.getOrCreateResultAt
public static function getOrCreateResultAt($index = 0) { $results = static::getResultAt($index); if (is_null($results)) { $results = static::makeResult()->attachAtIndex($index); } return $results; }
php
public static function getOrCreateResultAt($index = 0) { $results = static::getResultAt($index); if (is_null($results)) { $results = static::makeResult()->attachAtIndex($index); } return $results; }
[ "public", "static", "function", "getOrCreateResultAt", "(", "$", "index", "=", "0", ")", "{", "$", "results", "=", "static", "::", "getResultAt", "(", "$", "index", ")", ";", "if", "(", "is_null", "(", "$", "results", ")", ")", "{", "$", "results", "=", "static", "::", "makeResult", "(", ")", "->", "attachAtIndex", "(", "$", "index", ")", ";", "}", "return", "$", "results", ";", "}" ]
Retrieve a result at a specific index. If no result is found, a new, blank result will be generated, stored at the index, and returned. @param integer $index @return Result
[ "Retrieve", "a", "result", "at", "a", "specific", "index", ".", "If", "no", "result", "is", "found", "a", "new", "blank", "result", "will", "be", "generated", "stored", "at", "the", "index", "and", "returned", "." ]
9d3d32b4ea56c711d67b8498ab1a05d0aded40ea
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L604-L613
train
stratedge/wye
src/Wye.php
Wye.addResultAtIndex
public static function addResultAtIndex(Result $result, $index) { // Add result $results = static::getResults(); $results[$index] = $result; // Store results static::setResults($results); }
php
public static function addResultAtIndex(Result $result, $index) { // Add result $results = static::getResults(); $results[$index] = $result; // Store results static::setResults($results); }
[ "public", "static", "function", "addResultAtIndex", "(", "Result", "$", "result", ",", "$", "index", ")", "{", "// Add result", "$", "results", "=", "static", "::", "getResults", "(", ")", ";", "$", "results", "[", "$", "index", "]", "=", "$", "result", ";", "// Store results", "static", "::", "setResults", "(", "$", "results", ")", ";", "}" ]
Attach a result at a specific index. If a result already exists the current one will be replaced with the new one. @param Result $result @param integer $index
[ "Attach", "a", "result", "at", "a", "specific", "index", ".", "If", "a", "result", "already", "exists", "the", "current", "one", "will", "be", "replaced", "with", "the", "new", "one", "." ]
9d3d32b4ea56c711d67b8498ab1a05d0aded40ea
https://github.com/stratedge/wye/blob/9d3d32b4ea56c711d67b8498ab1a05d0aded40ea/src/Wye.php#L642-L650
train
phavour/phavour
Phavour/Helper/FileSystem/Directory.php
Directory.createPath
public function createPath($base, $path) { if (!is_dir($base) || !is_writable($base)) { return false; } if (empty($path)) { return false; } $pieces = explode(self::DS, $path); $dir = $base; foreach ($pieces as $directory) { if (empty($directory)) { // @codeCoverageIgnoreStart continue; // Handle the / from the exploded path // @codeCoverageIgnoreEnd } $singlePath = $dir . self::DS . $directory; if (!file_exists($singlePath) || !is_dir($singlePath)) { $create = @mkdir($singlePath); if ($create === false) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } } $dir = $singlePath; } return true; }
php
public function createPath($base, $path) { if (!is_dir($base) || !is_writable($base)) { return false; } if (empty($path)) { return false; } $pieces = explode(self::DS, $path); $dir = $base; foreach ($pieces as $directory) { if (empty($directory)) { // @codeCoverageIgnoreStart continue; // Handle the / from the exploded path // @codeCoverageIgnoreEnd } $singlePath = $dir . self::DS . $directory; if (!file_exists($singlePath) || !is_dir($singlePath)) { $create = @mkdir($singlePath); if ($create === false) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } } $dir = $singlePath; } return true; }
[ "public", "function", "createPath", "(", "$", "base", ",", "$", "path", ")", "{", "if", "(", "!", "is_dir", "(", "$", "base", ")", "||", "!", "is_writable", "(", "$", "base", ")", ")", "{", "return", "false", ";", "}", "if", "(", "empty", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "$", "pieces", "=", "explode", "(", "self", "::", "DS", ",", "$", "path", ")", ";", "$", "dir", "=", "$", "base", ";", "foreach", "(", "$", "pieces", "as", "$", "directory", ")", "{", "if", "(", "empty", "(", "$", "directory", ")", ")", "{", "// @codeCoverageIgnoreStart", "continue", ";", "// Handle the / from the exploded path", "// @codeCoverageIgnoreEnd", "}", "$", "singlePath", "=", "$", "dir", ".", "self", "::", "DS", ".", "$", "directory", ";", "if", "(", "!", "file_exists", "(", "$", "singlePath", ")", "||", "!", "is_dir", "(", "$", "singlePath", ")", ")", "{", "$", "create", "=", "@", "mkdir", "(", "$", "singlePath", ")", ";", "if", "(", "$", "create", "===", "false", ")", "{", "// @codeCoverageIgnoreStart", "return", "false", ";", "// @codeCoverageIgnoreEnd", "}", "}", "$", "dir", "=", "$", "singlePath", ";", "}", "return", "true", ";", "}" ]
Create a new path on top of a base directory @param string $base @param string $path @return boolean
[ "Create", "a", "new", "path", "on", "top", "of", "a", "base", "directory" ]
2246f78203312eb2e23fdb0f776f790e81b4d20f
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Helper/FileSystem/Directory.php#L51-L83
train
phavour/phavour
Phavour/Helper/FileSystem/Directory.php
Directory.recursivelyDeleteFromDirectory
public function recursivelyDeleteFromDirectory($baseDirectory) { if (!is_dir($baseDirectory)) { return; } $iterator = new \RecursiveDirectoryIterator($baseDirectory); $files = new \RecursiveIteratorIterator( $iterator, \RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $file) { $fname = $file->getFilename(); if ($fname == '.' || $fname == '..') { continue; } if ($file->isDir()) { $this->recursivelyDeleteFromDirectory($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($baseDirectory); return; }
php
public function recursivelyDeleteFromDirectory($baseDirectory) { if (!is_dir($baseDirectory)) { return; } $iterator = new \RecursiveDirectoryIterator($baseDirectory); $files = new \RecursiveIteratorIterator( $iterator, \RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $file) { $fname = $file->getFilename(); if ($fname == '.' || $fname == '..') { continue; } if ($file->isDir()) { $this->recursivelyDeleteFromDirectory($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($baseDirectory); return; }
[ "public", "function", "recursivelyDeleteFromDirectory", "(", "$", "baseDirectory", ")", "{", "if", "(", "!", "is_dir", "(", "$", "baseDirectory", ")", ")", "{", "return", ";", "}", "$", "iterator", "=", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "baseDirectory", ")", ";", "$", "files", "=", "new", "\\", "RecursiveIteratorIterator", "(", "$", "iterator", ",", "\\", "RecursiveIteratorIterator", "::", "CHILD_FIRST", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "fname", "=", "$", "file", "->", "getFilename", "(", ")", ";", "if", "(", "$", "fname", "==", "'.'", "||", "$", "fname", "==", "'..'", ")", "{", "continue", ";", "}", "if", "(", "$", "file", "->", "isDir", "(", ")", ")", "{", "$", "this", "->", "recursivelyDeleteFromDirectory", "(", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "}", "else", "{", "unlink", "(", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "}", "}", "rmdir", "(", "$", "baseDirectory", ")", ";", "return", ";", "}" ]
Recursively delete files and folders, when given a base path @param string $baseDirectory @return void
[ "Recursively", "delete", "files", "and", "folders", "when", "given", "a", "base", "path" ]
2246f78203312eb2e23fdb0f776f790e81b4d20f
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Helper/FileSystem/Directory.php#L90-L118
train
villermen/runescape-lookup-commons
src/ActivityFeed/ActivityFeedItem.php
ActivityFeedItem.equals
public function equals(ActivityFeedItem $otherItem): bool { return $this->getTime()->format("Ymd") == $otherItem->getTime()->format("Ymd") && $this->getTitle() == $otherItem->getTitle() && $this->getDescription() == $otherItem->getDescription(); }
php
public function equals(ActivityFeedItem $otherItem): bool { return $this->getTime()->format("Ymd") == $otherItem->getTime()->format("Ymd") && $this->getTitle() == $otherItem->getTitle() && $this->getDescription() == $otherItem->getDescription(); }
[ "public", "function", "equals", "(", "ActivityFeedItem", "$", "otherItem", ")", ":", "bool", "{", "return", "$", "this", "->", "getTime", "(", ")", "->", "format", "(", "\"Ymd\"", ")", "==", "$", "otherItem", "->", "getTime", "(", ")", "->", "format", "(", "\"Ymd\"", ")", "&&", "$", "this", "->", "getTitle", "(", ")", "==", "$", "otherItem", "->", "getTitle", "(", ")", "&&", "$", "this", "->", "getDescription", "(", ")", "==", "$", "otherItem", "->", "getDescription", "(", ")", ";", "}" ]
Compares this feed item to another. Only the date part of the time is compared, because adventurer's log feeds only contain accurate date parts. @param ActivityFeedItem $otherItem @return bool
[ "Compares", "this", "feed", "item", "to", "another", ".", "Only", "the", "date", "part", "of", "the", "time", "is", "compared", "because", "adventurer", "s", "log", "feeds", "only", "contain", "accurate", "date", "parts", "." ]
3e24dadbdc5e20b755280e5110f4ca0a1758b04c
https://github.com/villermen/runescape-lookup-commons/blob/3e24dadbdc5e20b755280e5110f4ca0a1758b04c/src/ActivityFeed/ActivityFeedItem.php#L61-L66
train
valu-digital/valuso
src/ValuSo/Feature/IdentityTrait.php
IdentityTrait.getIdentity
public function getIdentity($spec = null, $default = null) { if ($spec !== null) { return isset($this->identity[$spec]) ? $this->identity[$spec] : $default; } else { return $this->identity; } }
php
public function getIdentity($spec = null, $default = null) { if ($spec !== null) { return isset($this->identity[$spec]) ? $this->identity[$spec] : $default; } else { return $this->identity; } }
[ "public", "function", "getIdentity", "(", "$", "spec", "=", "null", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "spec", "!==", "null", ")", "{", "return", "isset", "(", "$", "this", "->", "identity", "[", "$", "spec", "]", ")", "?", "$", "this", "->", "identity", "[", "$", "spec", "]", ":", "$", "default", ";", "}", "else", "{", "return", "$", "this", "->", "identity", ";", "}", "}" ]
Retrieve identity or identity spec @param string|null $spec @param mixed $default @return \ArrayAccess|null
[ "Retrieve", "identity", "or", "identity", "spec" ]
c96bed0f6bd21551822334fe6cfe913a7436dd17
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Feature/IdentityTrait.php#L22-L29
train
headzoo/web-tools
src/Headzoo/Web/Tools/Utils.php
Utils.normalizeHeaderName
public static function normalizeHeaderName($headerName, $stripX = false) { if (is_array($headerName)) { array_walk($headerName, function(&$name) use($stripX) { $name = self::normalizeHeaderName($name, $stripX); }); } else { $headerName = trim((string)$headerName, " \t:"); if (count(explode(":", $headerName)) > 1 || preg_match("/[^\\w\\s-]/", $headerName)) { throw new Exceptions\InvalidArgumentException( "String '{$headerName}' cannot be normalized because of bad formatting." ); } $headerName = str_replace(["-", "_"], " ", $headerName); $headerName = ucwords(strtolower($headerName)); $headerName = str_replace(" ", "-", $headerName); if ($stripX && substr($headerName, 0, 2) === "X-") { $headerName = substr($headerName, 2); } $index = Arrays::findString(self::$headerSpecialCases, $headerName); if (false !== $index) { $headerName = self::$headerSpecialCases[$index]; } } return $headerName; }
php
public static function normalizeHeaderName($headerName, $stripX = false) { if (is_array($headerName)) { array_walk($headerName, function(&$name) use($stripX) { $name = self::normalizeHeaderName($name, $stripX); }); } else { $headerName = trim((string)$headerName, " \t:"); if (count(explode(":", $headerName)) > 1 || preg_match("/[^\\w\\s-]/", $headerName)) { throw new Exceptions\InvalidArgumentException( "String '{$headerName}' cannot be normalized because of bad formatting." ); } $headerName = str_replace(["-", "_"], " ", $headerName); $headerName = ucwords(strtolower($headerName)); $headerName = str_replace(" ", "-", $headerName); if ($stripX && substr($headerName, 0, 2) === "X-") { $headerName = substr($headerName, 2); } $index = Arrays::findString(self::$headerSpecialCases, $headerName); if (false !== $index) { $headerName = self::$headerSpecialCases[$index]; } } return $headerName; }
[ "public", "static", "function", "normalizeHeaderName", "(", "$", "headerName", ",", "$", "stripX", "=", "false", ")", "{", "if", "(", "is_array", "(", "$", "headerName", ")", ")", "{", "array_walk", "(", "$", "headerName", ",", "function", "(", "&", "$", "name", ")", "use", "(", "$", "stripX", ")", "{", "$", "name", "=", "self", "::", "normalizeHeaderName", "(", "$", "name", ",", "$", "stripX", ")", ";", "}", ")", ";", "}", "else", "{", "$", "headerName", "=", "trim", "(", "(", "string", ")", "$", "headerName", ",", "\" \\t:\"", ")", ";", "if", "(", "count", "(", "explode", "(", "\":\"", ",", "$", "headerName", ")", ")", ">", "1", "||", "preg_match", "(", "\"/[^\\\\w\\\\s-]/\"", ",", "$", "headerName", ")", ")", "{", "throw", "new", "Exceptions", "\\", "InvalidArgumentException", "(", "\"String '{$headerName}' cannot be normalized because of bad formatting.\"", ")", ";", "}", "$", "headerName", "=", "str_replace", "(", "[", "\"-\"", ",", "\"_\"", "]", ",", "\" \"", ",", "$", "headerName", ")", ";", "$", "headerName", "=", "ucwords", "(", "strtolower", "(", "$", "headerName", ")", ")", ";", "$", "headerName", "=", "str_replace", "(", "\" \"", ",", "\"-\"", ",", "$", "headerName", ")", ";", "if", "(", "$", "stripX", "&&", "substr", "(", "$", "headerName", ",", "0", ",", "2", ")", "===", "\"X-\"", ")", "{", "$", "headerName", "=", "substr", "(", "$", "headerName", ",", "2", ")", ";", "}", "$", "index", "=", "Arrays", "::", "findString", "(", "self", "::", "$", "headerSpecialCases", ",", "$", "headerName", ")", ";", "if", "(", "false", "!==", "$", "index", ")", "{", "$", "headerName", "=", "self", "::", "$", "headerSpecialCases", "[", "$", "index", "]", ";", "}", "}", "return", "$", "headerName", ";", "}" ]
Normalizes a header name Changes the value of $headerName to the format "Camel-Case-String" from any other format. For example the string "CONTENT_TYPE" becomes "Content-Type". Special cases are handled for header fields which typically use non-standard formatting. For example the headers "XSS-Protection" and "ETag". The value "xss-protection" is normalized to "XSS-Protection" rather than "Xss-Protection". The experimental header prefix "X-" is removed when $stripX is true. Prefixes are never added to the field names. When $headerName is an array, each value in the array will be normalized. Examples: ```php // The output from these method calls will be exactly "Content-Type". echo Utils::normalizeHeaderName("content-type"); echo Utils::normalizeHeaderName("content_type"); echo Utils::normalizeHeaderName("CONTENT-TYPE"); echo Utils::normalizeHeaderName("CONTENT_TYPE"); echo Utils::normalizeHeaderName("content type"); echo Utils::normalizeHeaderName(" content-type "); echo Utils::normalizeHeaderName("Content-Type: "); // The output from these method calls will be exactly "XSS-Protection". echo Utils::normalizeHeaderName("xss-protection"); echo Utils::normalizeHeaderName("XSS_PROTECTION"); echo Utils::normalizeHeaderName("X-XSS-Protection", true); // This method call throws an exception because it's a full header, and not just a name. echo Utils::normalizeHeaderName("content-type: text/html"); // This method call throws an exception because it contains special characters. echo Utils::normalizeHeaderName("content*type"); // Using an array of header names. $names = ["CONTENT_TYPE", "XSS_PROTECTION"]; $normal = Utils::normalizeHeaderName($names); // Produces: ["Content-Type", "XSS-Protection"] ``` @param string|array $headerName The header name or array of header names @param bool $stripX Should the experimental "X-" prefix be removed? @return string @throws Exceptions\InvalidArgumentException When the header name cannot be normalized
[ "Normalizes", "a", "header", "name" ]
305ce78029b86fa1fadaf8341d8fc737c84eab87
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/Utils.php#L76-L104
train
headzoo/web-tools
src/Headzoo/Web/Tools/Utils.php
Utils.appendUrlQuery
public static function appendUrlQuery($url, $query) { if (is_array($query)) { $query = http_build_query($query); } $query = ltrim($query, "?&"); $joiner = strpos($url, "?") === false ? "?" : "&"; return "{$url}{$joiner}{$query}"; }
php
public static function appendUrlQuery($url, $query) { if (is_array($query)) { $query = http_build_query($query); } $query = ltrim($query, "?&"); $joiner = strpos($url, "?") === false ? "?" : "&"; return "{$url}{$joiner}{$query}"; }
[ "public", "static", "function", "appendUrlQuery", "(", "$", "url", ",", "$", "query", ")", "{", "if", "(", "is_array", "(", "$", "query", ")", ")", "{", "$", "query", "=", "http_build_query", "(", "$", "query", ")", ";", "}", "$", "query", "=", "ltrim", "(", "$", "query", ",", "\"?&\"", ")", ";", "$", "joiner", "=", "strpos", "(", "$", "url", ",", "\"?\"", ")", "===", "false", "?", "\"?\"", ":", "\"&\"", ";", "return", "\"{$url}{$joiner}{$query}\"", ";", "}" ]
Appends the query string to the url Used when you need to append a query string to a url which may already have a query string. The $query argument be either a string, or an array. Note: This method does not merge values from the query string which are already in the url. @param string $url The base rul @param string|array $query The query string to append @return string
[ "Appends", "the", "query", "string", "to", "the", "url" ]
305ce78029b86fa1fadaf8341d8fc737c84eab87
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/Utils.php#L119-L128
train
diasbruno/stc
lib/stc/MarkdownRender.php
MarkdownRender.render
public function render($template, $options = array()) { $pre_render = view($template, $options); $md = new \Parsedown(); return $md->text($pre_render); }
php
public function render($template, $options = array()) { $pre_render = view($template, $options); $md = new \Parsedown(); return $md->text($pre_render); }
[ "public", "function", "render", "(", "$", "template", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "pre_render", "=", "view", "(", "$", "template", ",", "$", "options", ")", ";", "$", "md", "=", "new", "\\", "Parsedown", "(", ")", ";", "return", "$", "md", "->", "text", "(", "$", "pre_render", ")", ";", "}" ]
Render the template with options. @param $template string | The template name. @param $options array | A hash with options to render. @return string
[ "Render", "the", "template", "with", "options", "." ]
43f62c3b28167bff76274f954e235413a9e9c707
https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/MarkdownRender.php#L25-L31
train
CandleLight-Project/Framework
src/Migration.php
Migration.execUp
public function execUp(string $name): void{ DB::connection('default')->table('migrations')->insert(['name' => $name]); $this->up(); }
php
public function execUp(string $name): void{ DB::connection('default')->table('migrations')->insert(['name' => $name]); $this->up(); }
[ "public", "function", "execUp", "(", "string", "$", "name", ")", ":", "void", "{", "DB", "::", "connection", "(", "'default'", ")", "->", "table", "(", "'migrations'", ")", "->", "insert", "(", "[", "'name'", "=>", "$", "name", "]", ")", ";", "$", "this", "->", "up", "(", ")", ";", "}" ]
Kicks of the Migration-Up Process
[ "Kicks", "of", "the", "Migration", "-", "Up", "Process" ]
13c5cc34bd1118601406b0129f7b61c7b78d08f4
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L54-L57
train
CandleLight-Project/Framework
src/Migration.php
Migration.execDown
public function execDown(string $name): void{ $this->down(); DB::connection('default')->table('migrations')->where('name', $name)->delete(); }
php
public function execDown(string $name): void{ $this->down(); DB::connection('default')->table('migrations')->where('name', $name)->delete(); }
[ "public", "function", "execDown", "(", "string", "$", "name", ")", ":", "void", "{", "$", "this", "->", "down", "(", ")", ";", "DB", "::", "connection", "(", "'default'", ")", "->", "table", "(", "'migrations'", ")", "->", "where", "(", "'name'", ",", "$", "name", ")", "->", "delete", "(", ")", ";", "}" ]
Kicks of the Migration-Down Process
[ "Kicks", "of", "the", "Migration", "-", "Down", "Process" ]
13c5cc34bd1118601406b0129f7b61c7b78d08f4
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L62-L65
train
CandleLight-Project/Framework
src/Migration.php
Migration.hasMigrated
public static function hasMigrated(string $name){ $res = DB::connection('default')->table('migrations')->where('name', $name)->first(); return !is_null($res); }
php
public static function hasMigrated(string $name){ $res = DB::connection('default')->table('migrations')->where('name', $name)->first(); return !is_null($res); }
[ "public", "static", "function", "hasMigrated", "(", "string", "$", "name", ")", "{", "$", "res", "=", "DB", "::", "connection", "(", "'default'", ")", "->", "table", "(", "'migrations'", ")", "->", "where", "(", "'name'", ",", "$", "name", ")", "->", "first", "(", ")", ";", "return", "!", "is_null", "(", "$", "res", ")", ";", "}" ]
Checks if the given migration has been done already @param string $name @return bool
[ "Checks", "if", "the", "given", "migration", "has", "been", "done", "already" ]
13c5cc34bd1118601406b0129f7b61c7b78d08f4
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L82-L85
train
CandleLight-Project/Framework
src/Migration.php
Migration.getLastMigration
public static function getLastMigration(App $app){ $res = DB::connection('default')->table('migrations')->orderBy('id', 'desc')->first(); if (is_null($res) || !$app->hasMigration($res->name)){ return false; } return $res->name; }
php
public static function getLastMigration(App $app){ $res = DB::connection('default')->table('migrations')->orderBy('id', 'desc')->first(); if (is_null($res) || !$app->hasMigration($res->name)){ return false; } return $res->name; }
[ "public", "static", "function", "getLastMigration", "(", "App", "$", "app", ")", "{", "$", "res", "=", "DB", "::", "connection", "(", "'default'", ")", "->", "table", "(", "'migrations'", ")", "->", "orderBy", "(", "'id'", ",", "'desc'", ")", "->", "first", "(", ")", ";", "if", "(", "is_null", "(", "$", "res", ")", "||", "!", "$", "app", "->", "hasMigration", "(", "$", "res", "->", "name", ")", ")", "{", "return", "false", ";", "}", "return", "$", "res", "->", "name", ";", "}" ]
Returns the last migration-name, which has been done @param App $app CDL Application instance @return string|bool migration name or false if no migrations have been found
[ "Returns", "the", "last", "migration", "-", "name", "which", "has", "been", "done" ]
13c5cc34bd1118601406b0129f7b61c7b78d08f4
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L92-L98
train
CandleLight-Project/Framework
src/Migration.php
Migration.prepareMigrationTable
public static function prepareMigrationTable(App $app): void{ $migration = new class($app) extends Migration{ /** * Create the migration table if it does not exist yet */ public function up(): void{ $schema = $this->getSchema('default'); if (!$schema->hasTable('migrations')) { $schema->create('migrations', function (Blueprint $table){ $table->increments('id'); $table->string('name', 255); }); } } /** * Is not needed, but add it nevertheless */ public function down(): void{ $this->getSchema('default')->drop('migrations'); } }; $migration->up(); }
php
public static function prepareMigrationTable(App $app): void{ $migration = new class($app) extends Migration{ /** * Create the migration table if it does not exist yet */ public function up(): void{ $schema = $this->getSchema('default'); if (!$schema->hasTable('migrations')) { $schema->create('migrations', function (Blueprint $table){ $table->increments('id'); $table->string('name', 255); }); } } /** * Is not needed, but add it nevertheless */ public function down(): void{ $this->getSchema('default')->drop('migrations'); } }; $migration->up(); }
[ "public", "static", "function", "prepareMigrationTable", "(", "App", "$", "app", ")", ":", "void", "{", "$", "migration", "=", "new", "class", "(", "$", "app", ")", "extends", "Migration", "{", "/**\n * Create the migration table if it does not exist yet\n */", "public", "function", "up", "(", ")", ":", "void", "{", "$", "schema", "=", "$", "this", "->", "getSchema", "(", "'default'", ")", ";", "if", "(", "!", "$", "schema", "->", "hasTable", "(", "'migrations'", ")", ")", "{", "$", "schema", "->", "create", "(", "'migrations'", ",", "function", "(", "Blueprint", "$", "table", ")", "{", "$", "table", "->", "increments", "(", "'id'", ")", ";", "$", "table", "->", "string", "(", "'name'", ",", "255", ")", ";", "}", ")", ";", "}", "}", "/**\n * Is not needed, but add it nevertheless\n */", "public", "function", "down", "(", ")", ":", "void", "{", "$", "this", "->", "getSchema", "(", "'default'", ")", "->", "drop", "(", "'migrations'", ")", ";", "}", "}", ";", "$", "migration", "->", "up", "(", ")", ";", "}" ]
Prepares the migration table @param App $app
[ "Prepares", "the", "migration", "table" ]
13c5cc34bd1118601406b0129f7b61c7b78d08f4
https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Migration.php#L104-L128
train
UnionOfRAD/li3_quality
qa/rules/syntax/HasExplicitPropertyAndMethodVisibility.php
HasExplicitPropertyAndMethodVisibility.apply
public function apply($testable, array $config = array()) { $message = '{:name} has no declared visibility.'; $tokens = $testable->tokens(); $classes = $testable->findAll(array(T_CLASS)); $filtered = $testable->findAll($this->inspectableTokens); foreach ($classes as $classId) { $children = $tokens[$classId]['children']; foreach ($children as $member) { if (!in_array($member, $filtered)) { continue; } $modifiers = Parser::modifiers($member, $tokens); $visibility = $testable->findNext($this->findTokens, $modifiers); if ($visibility === false) { $token = $tokens[$member]; $this->addViolation(array( 'modifiers' => $modifiers, 'message' => String::insert($message, $token), 'line' => $token['line'], )); } } } }
php
public function apply($testable, array $config = array()) { $message = '{:name} has no declared visibility.'; $tokens = $testable->tokens(); $classes = $testable->findAll(array(T_CLASS)); $filtered = $testable->findAll($this->inspectableTokens); foreach ($classes as $classId) { $children = $tokens[$classId]['children']; foreach ($children as $member) { if (!in_array($member, $filtered)) { continue; } $modifiers = Parser::modifiers($member, $tokens); $visibility = $testable->findNext($this->findTokens, $modifiers); if ($visibility === false) { $token = $tokens[$member]; $this->addViolation(array( 'modifiers' => $modifiers, 'message' => String::insert($message, $token), 'line' => $token['line'], )); } } } }
[ "public", "function", "apply", "(", "$", "testable", ",", "array", "$", "config", "=", "array", "(", ")", ")", "{", "$", "message", "=", "'{:name} has no declared visibility.'", ";", "$", "tokens", "=", "$", "testable", "->", "tokens", "(", ")", ";", "$", "classes", "=", "$", "testable", "->", "findAll", "(", "array", "(", "T_CLASS", ")", ")", ";", "$", "filtered", "=", "$", "testable", "->", "findAll", "(", "$", "this", "->", "inspectableTokens", ")", ";", "foreach", "(", "$", "classes", "as", "$", "classId", ")", "{", "$", "children", "=", "$", "tokens", "[", "$", "classId", "]", "[", "'children'", "]", ";", "foreach", "(", "$", "children", "as", "$", "member", ")", "{", "if", "(", "!", "in_array", "(", "$", "member", ",", "$", "filtered", ")", ")", "{", "continue", ";", "}", "$", "modifiers", "=", "Parser", "::", "modifiers", "(", "$", "member", ",", "$", "tokens", ")", ";", "$", "visibility", "=", "$", "testable", "->", "findNext", "(", "$", "this", "->", "findTokens", ",", "$", "modifiers", ")", ";", "if", "(", "$", "visibility", "===", "false", ")", "{", "$", "token", "=", "$", "tokens", "[", "$", "member", "]", ";", "$", "this", "->", "addViolation", "(", "array", "(", "'modifiers'", "=>", "$", "modifiers", ",", "'message'", "=>", "String", "::", "insert", "(", "$", "message", ",", "$", "token", ")", ",", "'line'", "=>", "$", "token", "[", "'line'", "]", ",", ")", ")", ";", "}", "}", "}", "}" ]
Will iterate all the tokens looking for tokens in inspectableTokens The token needs an access modifier if it is a T_FUNCTION or T_VARIABLE and is in the first level of T_CLASS. This prevents functions and variables inside methods and outside classes to register violations. @param Testable $testable The testable object @return void
[ "Will", "iterate", "all", "the", "tokens", "looking", "for", "tokens", "in", "inspectableTokens", "The", "token", "needs", "an", "access", "modifier", "if", "it", "is", "a", "T_FUNCTION", "or", "T_VARIABLE", "and", "is", "in", "the", "first", "level", "of", "T_CLASS", ".", "This", "prevents", "functions", "and", "variables", "inside", "methods", "and", "outside", "classes", "to", "register", "violations", "." ]
acb72a43ae835e6d200bc0eba1a61aee610e36bf
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasExplicitPropertyAndMethodVisibility.php#L46-L70
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.email
public function email($message = null) { $this->setRule(__FUNCTION__, function($email) { if (strlen($email) == 0) return true; $isValid = true; $atIndex = strrpos($email, '@'); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } // check DNS if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { // hmm, the domain has no MX records if (checkdnsrr('gmail.com',"MX")) { // but Gmail does. the other domain must be dodgy $isValid = false; } // otherwise: probably running off-line or maybe DNS service is not working } } return $isValid; }, $message); return $this; }
php
public function email($message = null) { $this->setRule(__FUNCTION__, function($email) { if (strlen($email) == 0) return true; $isValid = true; $atIndex = strrpos($email, '@'); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } // check DNS if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { // hmm, the domain has no MX records if (checkdnsrr('gmail.com',"MX")) { // but Gmail does. the other domain must be dodgy $isValid = false; } // otherwise: probably running off-line or maybe DNS service is not working } } return $isValid; }, $message); return $this; }
[ "public", "function", "email", "(", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "email", ")", "{", "if", "(", "strlen", "(", "$", "email", ")", "==", "0", ")", "return", "true", ";", "$", "isValid", "=", "true", ";", "$", "atIndex", "=", "strrpos", "(", "$", "email", ",", "'@'", ")", ";", "if", "(", "is_bool", "(", "$", "atIndex", ")", "&&", "!", "$", "atIndex", ")", "{", "$", "isValid", "=", "false", ";", "}", "else", "{", "$", "domain", "=", "substr", "(", "$", "email", ",", "$", "atIndex", "+", "1", ")", ";", "$", "local", "=", "substr", "(", "$", "email", ",", "0", ",", "$", "atIndex", ")", ";", "$", "localLen", "=", "strlen", "(", "$", "local", ")", ";", "$", "domainLen", "=", "strlen", "(", "$", "domain", ")", ";", "if", "(", "$", "localLen", "<", "1", "||", "$", "localLen", ">", "64", ")", "{", "$", "isValid", "=", "false", ";", "}", "else", "if", "(", "$", "domainLen", "<", "1", "||", "$", "domainLen", ">", "255", ")", "{", "// domain part length exceeded", "$", "isValid", "=", "false", ";", "}", "else", "if", "(", "$", "local", "[", "0", "]", "==", "'.'", "||", "$", "local", "[", "$", "localLen", "-", "1", "]", "==", "'.'", ")", "{", "// local part starts or ends with '.'", "$", "isValid", "=", "false", ";", "}", "else", "if", "(", "preg_match", "(", "'/\\\\.\\\\./'", ",", "$", "local", ")", ")", "{", "// local part has two consecutive dots", "$", "isValid", "=", "false", ";", "}", "else", "if", "(", "!", "preg_match", "(", "'/^[A-Za-z0-9\\\\-\\\\.]+$/'", ",", "$", "domain", ")", ")", "{", "// character not valid in domain part", "$", "isValid", "=", "false", ";", "}", "else", "if", "(", "preg_match", "(", "'/\\\\.\\\\./'", ",", "$", "domain", ")", ")", "{", "// domain part has two consecutive dots", "$", "isValid", "=", "false", ";", "}", "else", "if", "(", "!", "preg_match", "(", "'/^(\\\\\\\\.|[A-Za-z0-9!#%&`_=\\\\/$\\'*+?^{}|~.-])+$/'", ",", "str_replace", "(", "\"\\\\\\\\\"", ",", "\"\"", ",", "$", "local", ")", ")", ")", "{", "// character not valid in local part unless", "// local part is quoted", "if", "(", "!", "preg_match", "(", "'/^\"(\\\\\\\\\"|[^\"])+\"$/'", ",", "str_replace", "(", "\"\\\\\\\\\"", ",", "\"\"", ",", "$", "local", ")", ")", ")", "{", "$", "isValid", "=", "false", ";", "}", "}", "// check DNS", "if", "(", "$", "isValid", "&&", "!", "(", "checkdnsrr", "(", "$", "domain", ",", "\"MX\"", ")", "||", "checkdnsrr", "(", "$", "domain", ",", "\"A\"", ")", ")", ")", "{", "// hmm, the domain has no MX records", "if", "(", "checkdnsrr", "(", "'gmail.com'", ",", "\"MX\"", ")", ")", "{", "// but Gmail does. the other domain must be dodgy", "$", "isValid", "=", "false", ";", "}", "// otherwise: probably running off-line or maybe DNS service is not working", "}", "}", "return", "$", "isValid", ";", "}", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field, if completed, has to be a valid email address. @param string $message @return FormValidator
[ "Field", "if", "completed", "has", "to", "be", "a", "valid", "email", "address", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L65-L122
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.required
public function required($message = null) { $this->setRule(__FUNCTION__, function($val) { if (is_scalar($val)) { $val = trim($val); } return !empty($val); }, $message); return $this; }
php
public function required($message = null) { $this->setRule(__FUNCTION__, function($val) { if (is_scalar($val)) { $val = trim($val); } return !empty($val); }, $message); return $this; }
[ "public", "function", "required", "(", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ")", "{", "if", "(", "is_scalar", "(", "$", "val", ")", ")", "{", "$", "val", "=", "trim", "(", "$", "val", ")", ";", "}", "return", "!", "empty", "(", "$", "val", ")", ";", "}", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field must be filled in. @param string $message @return FormValidator
[ "Field", "must", "be", "filled", "in", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L130-L140
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.exists
public function exists( $message = null) { $this->setRule(__FUNCTION__, function ($val) { return null !== $val; }, $message); return $this; }
php
public function exists( $message = null) { $this->setRule(__FUNCTION__, function ($val) { return null !== $val; }, $message); return $this; }
[ "public", "function", "exists", "(", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ")", "{", "return", "null", "!==", "$", "val", ";", "}", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field must exist, even if empty @param null $message @return $this
[ "Field", "must", "exist", "even", "if", "empty" ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L148-L154
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.float
public function float($message = null) { $this->setRule(__FUNCTION__, function($val) { return !(filter_var($val, FILTER_VALIDATE_FLOAT) === FALSE); }, $message); return $this; }
php
public function float($message = null) { $this->setRule(__FUNCTION__, function($val) { return !(filter_var($val, FILTER_VALIDATE_FLOAT) === FALSE); }, $message); return $this; }
[ "public", "function", "float", "(", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ")", "{", "return", "!", "(", "filter_var", "(", "$", "val", ",", "FILTER_VALIDATE_FLOAT", ")", "===", "FALSE", ")", ";", "}", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field must contain a valid float value. @param string $message @return FormValidator
[ "Field", "must", "contain", "a", "valid", "float", "value", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L162-L169
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.integer
public function integer($message = null) { $this->setRule(__FUNCTION__, function($val) { return !(filter_var($val, FILTER_VALIDATE_INT) === FALSE); }, $message); return $this; }
php
public function integer($message = null) { $this->setRule(__FUNCTION__, function($val) { return !(filter_var($val, FILTER_VALIDATE_INT) === FALSE); }, $message); return $this; }
[ "public", "function", "integer", "(", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ")", "{", "return", "!", "(", "filter_var", "(", "$", "val", ",", "FILTER_VALIDATE_INT", ")", "===", "FALSE", ")", ";", "}", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field must contain a valid integer value. @param string $message @return FormValidator
[ "Field", "must", "contain", "a", "valid", "integer", "value", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L177-L184
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.between
public function between($min, $max, $include = TRUE, $message = null) { $message = $this->_getDefaultMessage(__FUNCTION__, array($min, $max, $include)); $this->min($min, $include, $message)->max($max, $include, $message); return $this; }
php
public function between($min, $max, $include = TRUE, $message = null) { $message = $this->_getDefaultMessage(__FUNCTION__, array($min, $max, $include)); $this->min($min, $include, $message)->max($max, $include, $message); return $this; }
[ "public", "function", "between", "(", "$", "min", ",", "$", "max", ",", "$", "include", "=", "TRUE", ",", "$", "message", "=", "null", ")", "{", "$", "message", "=", "$", "this", "->", "_getDefaultMessage", "(", "__FUNCTION__", ",", "array", "(", "$", "min", ",", "$", "max", ",", "$", "include", ")", ")", ";", "$", "this", "->", "min", "(", "$", "min", ",", "$", "include", ",", "$", "message", ")", "->", "max", "(", "$", "max", ",", "$", "include", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field must be a number between X and Y. @param numeric $min @param numeric $max @param bool $include Whether to include limit value. @param string $message @return FormValidator
[ "Field", "must", "be", "a", "number", "between", "X", "and", "Y", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L261-L267
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.minlength
public function minlength($len, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { return !(strlen(trim($val)) < $args[0]); }, $message, array($len)); return $this; }
php
public function minlength($len, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { return !(strlen(trim($val)) < $args[0]); }, $message, array($len)); return $this; }
[ "public", "function", "minlength", "(", "$", "len", ",", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ",", "$", "args", ")", "{", "return", "!", "(", "strlen", "(", "trim", "(", "$", "val", ")", ")", "<", "$", "args", "[", "0", "]", ")", ";", "}", ",", "$", "message", ",", "array", "(", "$", "len", ")", ")", ";", "return", "$", "this", ";", "}" ]
Field has to be greater than or equal to X characters long. @param int $len @param string $message @return FormValidator
[ "Field", "has", "to", "be", "greater", "than", "or", "equal", "to", "X", "characters", "long", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L276-L283
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.betweenlength
public function betweenlength($minlength, $maxlength, $message = null) { $message = empty($message) ? self::getDefaultMessage(__FUNCTION__, array($minlength, $maxlength)) : NULL; $this->minlength($minlength, $message)->max($maxlength, $message); return $this; }
php
public function betweenlength($minlength, $maxlength, $message = null) { $message = empty($message) ? self::getDefaultMessage(__FUNCTION__, array($minlength, $maxlength)) : NULL; $this->minlength($minlength, $message)->max($maxlength, $message); return $this; }
[ "public", "function", "betweenlength", "(", "$", "minlength", ",", "$", "maxlength", ",", "$", "message", "=", "null", ")", "{", "$", "message", "=", "empty", "(", "$", "message", ")", "?", "self", "::", "getDefaultMessage", "(", "__FUNCTION__", ",", "array", "(", "$", "minlength", ",", "$", "maxlength", ")", ")", ":", "NULL", ";", "$", "this", "->", "minlength", "(", "$", "minlength", ",", "$", "message", ")", "->", "max", "(", "$", "maxlength", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field has to be between minlength and maxlength characters long. @param int $minlength @param int $maxlength @
[ "Field", "has", "to", "be", "between", "minlength", "and", "maxlength", "characters", "long", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L308-L314
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.endsWith
public function endsWith($sub, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { $sub = $args[0]; return (strlen($val) === 0 || substr($val, -strlen($sub)) === $sub); }, $message, array($sub)); return $this; }
php
public function endsWith($sub, $message = null) { $this->setRule(__FUNCTION__, function($val, $args) { $sub = $args[0]; return (strlen($val) === 0 || substr($val, -strlen($sub)) === $sub); }, $message, array($sub)); return $this; }
[ "public", "function", "endsWith", "(", "$", "sub", ",", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ",", "$", "args", ")", "{", "$", "sub", "=", "$", "args", "[", "0", "]", ";", "return", "(", "strlen", "(", "$", "val", ")", "===", "0", "||", "substr", "(", "$", "val", ",", "-", "strlen", "(", "$", "sub", ")", ")", "===", "$", "sub", ")", ";", "}", ",", "$", "message", ",", "array", "(", "$", "sub", ")", ")", ";", "return", "$", "this", ";", "}" ]
Field must end with a specific substring. @param string $sub @param string $message @return FormValidator
[ "Field", "must", "end", "with", "a", "specific", "substring", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L407-L415
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.ip
public function ip($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen(trim($val)) === 0 || filter_var($val, FILTER_VALIDATE_IP) !== FALSE); }, $message); return $this; }
php
public function ip($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen(trim($val)) === 0 || filter_var($val, FILTER_VALIDATE_IP) !== FALSE); }, $message); return $this; }
[ "public", "function", "ip", "(", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ")", "{", "return", "(", "strlen", "(", "trim", "(", "$", "val", ")", ")", "===", "0", "||", "filter_var", "(", "$", "val", ",", "FILTER_VALIDATE_IP", ")", "!==", "FALSE", ")", ";", "}", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field has to be valid IP address. @param string $message @return FormValidator
[ "Field", "has", "to", "be", "valid", "IP", "address", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L440-L447
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.url
public function url($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen(trim($val)) === 0 || filter_var($val, FILTER_VALIDATE_URL) !== FALSE); }, $message); return $this; }
php
public function url($message = null) { $this->setRule(__FUNCTION__, function($val) { return (strlen(trim($val)) === 0 || filter_var($val, FILTER_VALIDATE_URL) !== FALSE); }, $message); return $this; }
[ "public", "function", "url", "(", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ")", "{", "return", "(", "strlen", "(", "trim", "(", "$", "val", ")", ")", "===", "0", "||", "filter_var", "(", "$", "val", ",", "FILTER_VALIDATE_URL", ")", "!==", "FALSE", ")", ";", "}", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field has to be valid internet address. @param string $message @return FormValidator
[ "Field", "has", "to", "be", "valid", "internet", "address", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L455-L462
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.date
public function date($message = null, $format = null, $separator = '') { $this->setRule(__FUNCTION__, function($val, $args) { if (strlen(trim($val)) === 0) { return TRUE; } try { $dt = new \DateTime($val, new \DateTimeZone("UTC")); return true; } catch(\Exception $e) { return false; } }, $message, array($format, $separator)); return $this; }
php
public function date($message = null, $format = null, $separator = '') { $this->setRule(__FUNCTION__, function($val, $args) { if (strlen(trim($val)) === 0) { return TRUE; } try { $dt = new \DateTime($val, new \DateTimeZone("UTC")); return true; } catch(\Exception $e) { return false; } }, $message, array($format, $separator)); return $this; }
[ "public", "function", "date", "(", "$", "message", "=", "null", ",", "$", "format", "=", "null", ",", "$", "separator", "=", "''", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ",", "$", "args", ")", "{", "if", "(", "strlen", "(", "trim", "(", "$", "val", ")", ")", "===", "0", ")", "{", "return", "TRUE", ";", "}", "try", "{", "$", "dt", "=", "new", "\\", "DateTime", "(", "$", "val", ",", "new", "\\", "DateTimeZone", "(", "\"UTC\"", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "}", ",", "$", "message", ",", "array", "(", "$", "format", ",", "$", "separator", ")", ")", ";", "return", "$", "this", ";", "}" ]
Field has to be a valid date. @param string $message @return FormValidator
[ "Field", "has", "to", "be", "a", "valid", "date", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L479-L497
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.minDate
public function minDate($date = 0, $format = null, $message = null) { if (empty($format)) { $format = $this->_getDefaultDateFormat(); } if (is_numeric($date)) { $date = new \DateTime($date . ' days'); // Days difference from today } else { $fieldValue = $this->_getVal($date); $date = ($fieldValue == FALSE) ? $date : $fieldValue; $date = \DateTime::createFromFormat($format, $date); } $this->setRule(__FUNCTION__, function($val, $args) { $format = $args[1]; $limitDate = $args[0]; return ($limitDate > \DateTime::createFromFormat($format, $val)) ? FALSE : TRUE; }, $message, array($date, $format)); return $this; }
php
public function minDate($date = 0, $format = null, $message = null) { if (empty($format)) { $format = $this->_getDefaultDateFormat(); } if (is_numeric($date)) { $date = new \DateTime($date . ' days'); // Days difference from today } else { $fieldValue = $this->_getVal($date); $date = ($fieldValue == FALSE) ? $date : $fieldValue; $date = \DateTime::createFromFormat($format, $date); } $this->setRule(__FUNCTION__, function($val, $args) { $format = $args[1]; $limitDate = $args[0]; return ($limitDate > \DateTime::createFromFormat($format, $val)) ? FALSE : TRUE; }, $message, array($date, $format)); return $this; }
[ "public", "function", "minDate", "(", "$", "date", "=", "0", ",", "$", "format", "=", "null", ",", "$", "message", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "format", ")", ")", "{", "$", "format", "=", "$", "this", "->", "_getDefaultDateFormat", "(", ")", ";", "}", "if", "(", "is_numeric", "(", "$", "date", ")", ")", "{", "$", "date", "=", "new", "\\", "DateTime", "(", "$", "date", ".", "' days'", ")", ";", "// Days difference from today", "}", "else", "{", "$", "fieldValue", "=", "$", "this", "->", "_getVal", "(", "$", "date", ")", ";", "$", "date", "=", "(", "$", "fieldValue", "==", "FALSE", ")", "?", "$", "date", ":", "$", "fieldValue", ";", "$", "date", "=", "\\", "DateTime", "::", "createFromFormat", "(", "$", "format", ",", "$", "date", ")", ";", "}", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "val", ",", "$", "args", ")", "{", "$", "format", "=", "$", "args", "[", "1", "]", ";", "$", "limitDate", "=", "$", "args", "[", "0", "]", ";", "return", "(", "$", "limitDate", ">", "\\", "DateTime", "::", "createFromFormat", "(", "$", "format", ",", "$", "val", ")", ")", "?", "FALSE", ":", "TRUE", ";", "}", ",", "$", "message", ",", "array", "(", "$", "date", ",", "$", "format", ")", ")", ";", "return", "$", "this", ";", "}" ]
Field has to be a date later than or equal to X. @param string|int $date Limit date @param string $format Date format @param string $message @return FormValidator
[ "Field", "has", "to", "be", "a", "date", "later", "than", "or", "equal", "to", "X", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L507-L529
train
Etenil/assegai
src/assegai/modules/validator/Validator.php
Validator.ccnum
public function ccnum($message = null) { $this->setRule(__FUNCTION__, function($value) { $value = str_replace(' ', '', $value); $length = strlen($value); if ($length < 13 || $length > 19) { return FALSE; } $sum = 0; $weight = 2; for ($i = $length - 2; $i >= 0; $i--) { $digit = $weight * $value[$i]; $sum += floor($digit / 10) + $digit % 10; $weight = $weight % 2 + 1; } $mod = (10 - $sum % 10) % 10; return ($mod == $value[$length - 1]); }, $message); return $this; }
php
public function ccnum($message = null) { $this->setRule(__FUNCTION__, function($value) { $value = str_replace(' ', '', $value); $length = strlen($value); if ($length < 13 || $length > 19) { return FALSE; } $sum = 0; $weight = 2; for ($i = $length - 2; $i >= 0; $i--) { $digit = $weight * $value[$i]; $sum += floor($digit / 10) + $digit % 10; $weight = $weight % 2 + 1; } $mod = (10 - $sum % 10) % 10; return ($mod == $value[$length - 1]); }, $message); return $this; }
[ "public", "function", "ccnum", "(", "$", "message", "=", "null", ")", "{", "$", "this", "->", "setRule", "(", "__FUNCTION__", ",", "function", "(", "$", "value", ")", "{", "$", "value", "=", "str_replace", "(", "' '", ",", "''", ",", "$", "value", ")", ";", "$", "length", "=", "strlen", "(", "$", "value", ")", ";", "if", "(", "$", "length", "<", "13", "||", "$", "length", ">", "19", ")", "{", "return", "FALSE", ";", "}", "$", "sum", "=", "0", ";", "$", "weight", "=", "2", ";", "for", "(", "$", "i", "=", "$", "length", "-", "2", ";", "$", "i", ">=", "0", ";", "$", "i", "--", ")", "{", "$", "digit", "=", "$", "weight", "*", "$", "value", "[", "$", "i", "]", ";", "$", "sum", "+=", "floor", "(", "$", "digit", "/", "10", ")", "+", "$", "digit", "%", "10", ";", "$", "weight", "=", "$", "weight", "%", "2", "+", "1", ";", "}", "$", "mod", "=", "(", "10", "-", "$", "sum", "%", "10", ")", "%", "10", ";", "return", "(", "$", "mod", "==", "$", "value", "[", "$", "length", "-", "1", "]", ")", ";", "}", ",", "$", "message", ")", ";", "return", "$", "this", ";", "}" ]
Field has to be a valid credit card number format. @see https://github.com/funkatron/inspekt/blob/master/Inspekt.php @param string $message @return FormValidator
[ "Field", "has", "to", "be", "a", "valid", "credit", "card", "number", "format", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/validator/Validator.php#L570-L595
train