id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
222,800
EcomDev/EcomDev_Varnish
src/shell/ecomdev-varnish.php
EcomDev_Varnish_Shell.run
public function run() { if ($this->_action === null) { die($this->usageHelp()); } $reflection = new ReflectionClass(__CLASS__); $methodName = 'run' . uc_words($this->_action, '', ':'); if ($reflection->hasMethod($methodName)) { try { Mage::app('admin'); $this->$methodName(); } catch (Exception $e) { fwrite(STDERR, "Error: \n{$e->getMessage()}\n"); exit(1); } } else { die($this->usageHelp()); } }
php
public function run() { if ($this->_action === null) { die($this->usageHelp()); } $reflection = new ReflectionClass(__CLASS__); $methodName = 'run' . uc_words($this->_action, '', ':'); if ($reflection->hasMethod($methodName)) { try { Mage::app('admin'); $this->$methodName(); } catch (Exception $e) { fwrite(STDERR, "Error: \n{$e->getMessage()}\n"); exit(1); } } else { die($this->usageHelp()); } }
[ "public", "function", "run", "(", ")", "{", "if", "(", "$", "this", "->", "_action", "===", "null", ")", "{", "die", "(", "$", "this", "->", "usageHelp", "(", ")", ")", ";", "}", "$", "reflection", "=", "new", "ReflectionClass", "(", "__CLASS__", ")", ";", "$", "methodName", "=", "'run'", ".", "uc_words", "(", "$", "this", "->", "_action", ",", "''", ",", "':'", ")", ";", "if", "(", "$", "reflection", "->", "hasMethod", "(", "$", "methodName", ")", ")", "{", "try", "{", "Mage", "::", "app", "(", "'admin'", ")", ";", "$", "this", "->", "$", "methodName", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "fwrite", "(", "STDERR", ",", "\"Error: \\n{$e->getMessage()}\\n\"", ")", ";", "exit", "(", "1", ")", ";", "}", "}", "else", "{", "die", "(", "$", "this", "->", "usageHelp", "(", ")", ")", ";", "}", "}" ]
Runs scripts itself
[ "Runs", "scripts", "itself" ]
228b7b1bdaae15c1895f2533667fffa515447915
https://github.com/EcomDev/EcomDev_Varnish/blob/228b7b1bdaae15c1895f2533667fffa515447915/src/shell/ecomdev-varnish.php#L125-L144
222,801
EcomDev/EcomDev_Varnish
src/shell/ecomdev-varnish.php
EcomDev_Varnish_Shell.getConfigBlock
protected function getConfigBlock() { $designPackage = Mage::getSingleton('core/design_package'); $designPackage->setArea('shell'); $block = Mage::app()->getLayout()->createBlock('ecomdev_varnish/vcl_config'); return $block; }
php
protected function getConfigBlock() { $designPackage = Mage::getSingleton('core/design_package'); $designPackage->setArea('shell'); $block = Mage::app()->getLayout()->createBlock('ecomdev_varnish/vcl_config'); return $block; }
[ "protected", "function", "getConfigBlock", "(", ")", "{", "$", "designPackage", "=", "Mage", "::", "getSingleton", "(", "'core/design_package'", ")", ";", "$", "designPackage", "->", "setArea", "(", "'shell'", ")", ";", "$", "block", "=", "Mage", "::", "app", "(", ")", "->", "getLayout", "(", ")", "->", "createBlock", "(", "'ecomdev_varnish/vcl_config'", ")", ";", "return", "$", "block", ";", "}" ]
Returns block instance @return EcomDev_Varnish_Block_Vcl_Config
[ "Returns", "block", "instance" ]
228b7b1bdaae15c1895f2533667fffa515447915
https://github.com/EcomDev/EcomDev_Varnish/blob/228b7b1bdaae15c1895f2533667fffa515447915/src/shell/ecomdev-varnish.php#L151-L157
222,802
EcomDev/EcomDev_Varnish
src/shell/ecomdev-varnish.php
EcomDev_Varnish_Shell.runVclGenerate
protected function runVclGenerate() { $config = Mage::getModel( 'ecomdev_varnish/vcl_config_json', array('file' => $this->getArg('config')) ); $block = $this->getConfigBlock(); if ($version = $this->getArg('version')) { $block->setVersion($version); } if ($template = $this->getArg('template')) { $block->setTemplate($template); } $block->setConfig($config); $file = $this->getArg('file'); if ($file) { $file = fopen($file, 'w'); } else { $file = STDOUT; } fwrite($file, $block->toHtml()); }
php
protected function runVclGenerate() { $config = Mage::getModel( 'ecomdev_varnish/vcl_config_json', array('file' => $this->getArg('config')) ); $block = $this->getConfigBlock(); if ($version = $this->getArg('version')) { $block->setVersion($version); } if ($template = $this->getArg('template')) { $block->setTemplate($template); } $block->setConfig($config); $file = $this->getArg('file'); if ($file) { $file = fopen($file, 'w'); } else { $file = STDOUT; } fwrite($file, $block->toHtml()); }
[ "protected", "function", "runVclGenerate", "(", ")", "{", "$", "config", "=", "Mage", "::", "getModel", "(", "'ecomdev_varnish/vcl_config_json'", ",", "array", "(", "'file'", "=>", "$", "this", "->", "getArg", "(", "'config'", ")", ")", ")", ";", "$", "block", "=", "$", "this", "->", "getConfigBlock", "(", ")", ";", "if", "(", "$", "version", "=", "$", "this", "->", "getArg", "(", "'version'", ")", ")", "{", "$", "block", "->", "setVersion", "(", "$", "version", ")", ";", "}", "if", "(", "$", "template", "=", "$", "this", "->", "getArg", "(", "'template'", ")", ")", "{", "$", "block", "->", "setTemplate", "(", "$", "template", ")", ";", "}", "$", "block", "->", "setConfig", "(", "$", "config", ")", ";", "$", "file", "=", "$", "this", "->", "getArg", "(", "'file'", ")", ";", "if", "(", "$", "file", ")", "{", "$", "file", "=", "fopen", "(", "$", "file", ",", "'w'", ")", ";", "}", "else", "{", "$", "file", "=", "STDOUT", ";", "}", "fwrite", "(", "$", "file", ",", "$", "block", "->", "toHtml", "(", ")", ")", ";", "}" ]
Generates VCL configuration
[ "Generates", "VCL", "configuration" ]
228b7b1bdaae15c1895f2533667fffa515447915
https://github.com/EcomDev/EcomDev_Varnish/blob/228b7b1bdaae15c1895f2533667fffa515447915/src/shell/ecomdev-varnish.php#L163-L191
222,803
EcomDev/EcomDev_Varnish
src/shell/ecomdev-varnish.php
EcomDev_Varnish_Shell.runCacheBan
protected function runCacheBan() { $connector = Mage::getSingleton('ecomdev_varnish/connector'); $header = $this->getArg('header'); if (empty($header)) { $header = 'req.url'; } $value = $this->getArg('value'); $expression = $header . ' ~ ' . $value; $connector->getVarnishPool()->ban($expression); fwrite(STDOUT, sprintf('Executed %s command on all servers %s', $expression, PHP_EOL)); }
php
protected function runCacheBan() { $connector = Mage::getSingleton('ecomdev_varnish/connector'); $header = $this->getArg('header'); if (empty($header)) { $header = 'req.url'; } $value = $this->getArg('value'); $expression = $header . ' ~ ' . $value; $connector->getVarnishPool()->ban($expression); fwrite(STDOUT, sprintf('Executed %s command on all servers %s', $expression, PHP_EOL)); }
[ "protected", "function", "runCacheBan", "(", ")", "{", "$", "connector", "=", "Mage", "::", "getSingleton", "(", "'ecomdev_varnish/connector'", ")", ";", "$", "header", "=", "$", "this", "->", "getArg", "(", "'header'", ")", ";", "if", "(", "empty", "(", "$", "header", ")", ")", "{", "$", "header", "=", "'req.url'", ";", "}", "$", "value", "=", "$", "this", "->", "getArg", "(", "'value'", ")", ";", "$", "expression", "=", "$", "header", ".", "' ~ '", ".", "$", "value", ";", "$", "connector", "->", "getVarnishPool", "(", ")", "->", "ban", "(", "$", "expression", ")", ";", "fwrite", "(", "STDOUT", ",", "sprintf", "(", "'Executed %s command on all servers %s'", ",", "$", "expression", ",", "PHP_EOL", ")", ")", ";", "}" ]
Ban cache item
[ "Ban", "cache", "item" ]
228b7b1bdaae15c1895f2533667fffa515447915
https://github.com/EcomDev/EcomDev_Varnish/blob/228b7b1bdaae15c1895f2533667fffa515447915/src/shell/ecomdev-varnish.php#L197-L211
222,804
EcomDev/EcomDev_Varnish
src/shell/ecomdev-varnish.php
EcomDev_Varnish_Shell.runCacheBanList
protected function runCacheBanList() { $connector = Mage::getSingleton('ecomdev_varnish/connector'); foreach ($connector->getVarnishPool()->getServers() as $server) { fwrite(STDOUT, sprintf('Ban list for server %s %s', (string)$server, PHP_EOL)); fwrite(STDOUT, $server->execute('ban.list')); } }
php
protected function runCacheBanList() { $connector = Mage::getSingleton('ecomdev_varnish/connector'); foreach ($connector->getVarnishPool()->getServers() as $server) { fwrite(STDOUT, sprintf('Ban list for server %s %s', (string)$server, PHP_EOL)); fwrite(STDOUT, $server->execute('ban.list')); } }
[ "protected", "function", "runCacheBanList", "(", ")", "{", "$", "connector", "=", "Mage", "::", "getSingleton", "(", "'ecomdev_varnish/connector'", ")", ";", "foreach", "(", "$", "connector", "->", "getVarnishPool", "(", ")", "->", "getServers", "(", ")", "as", "$", "server", ")", "{", "fwrite", "(", "STDOUT", ",", "sprintf", "(", "'Ban list for server %s %s'", ",", "(", "string", ")", "$", "server", ",", "PHP_EOL", ")", ")", ";", "fwrite", "(", "STDOUT", ",", "$", "server", "->", "execute", "(", "'ban.list'", ")", ")", ";", "}", "}" ]
Bans cache list
[ "Bans", "cache", "list" ]
228b7b1bdaae15c1895f2533667fffa515447915
https://github.com/EcomDev/EcomDev_Varnish/blob/228b7b1bdaae15c1895f2533667fffa515447915/src/shell/ecomdev-varnish.php#L227-L234
222,805
EcomDev/EcomDev_Varnish
src/app/code/community/EcomDev/Varnish/controllers/AjaxController.php
EcomDev_Varnish_AjaxController.preDispatch
public function preDispatch() { $this->_getHelper()->disableSessionForControllerAction('token', $this); parent::preDispatch(); $this->_getHelper()->setIsEsiAllowed(false); $this->_getHelper()->setIsInternal(true); Mage::app()->setUseSessionVar(false); Mage::app()->setUseSessionInUrl(false); // Disallow any non AJAX requests to this url if (!$this->getRequest()->isXmlHttpRequest()) { $this->getResponse()->setHttpResponseCode(403); $this->getResponse()->setBody('Forbidden'); $this->setFlag($this->getRequest()->getActionName(), self::FLAG_NO_DISPATCH, true); } return $this; }
php
public function preDispatch() { $this->_getHelper()->disableSessionForControllerAction('token', $this); parent::preDispatch(); $this->_getHelper()->setIsEsiAllowed(false); $this->_getHelper()->setIsInternal(true); Mage::app()->setUseSessionVar(false); Mage::app()->setUseSessionInUrl(false); // Disallow any non AJAX requests to this url if (!$this->getRequest()->isXmlHttpRequest()) { $this->getResponse()->setHttpResponseCode(403); $this->getResponse()->setBody('Forbidden'); $this->setFlag($this->getRequest()->getActionName(), self::FLAG_NO_DISPATCH, true); } return $this; }
[ "public", "function", "preDispatch", "(", ")", "{", "$", "this", "->", "_getHelper", "(", ")", "->", "disableSessionForControllerAction", "(", "'token'", ",", "$", "this", ")", ";", "parent", "::", "preDispatch", "(", ")", ";", "$", "this", "->", "_getHelper", "(", ")", "->", "setIsEsiAllowed", "(", "false", ")", ";", "$", "this", "->", "_getHelper", "(", ")", "->", "setIsInternal", "(", "true", ")", ";", "Mage", "::", "app", "(", ")", "->", "setUseSessionVar", "(", "false", ")", ";", "Mage", "::", "app", "(", ")", "->", "setUseSessionInUrl", "(", "false", ")", ";", "// Disallow any non AJAX requests to this url", "if", "(", "!", "$", "this", "->", "getRequest", "(", ")", "->", "isXmlHttpRequest", "(", ")", ")", "{", "$", "this", "->", "getResponse", "(", ")", "->", "setHttpResponseCode", "(", "403", ")", ";", "$", "this", "->", "getResponse", "(", ")", "->", "setBody", "(", "'Forbidden'", ")", ";", "$", "this", "->", "setFlag", "(", "$", "this", "->", "getRequest", "(", ")", "->", "getActionName", "(", ")", ",", "self", "::", "FLAG_NO_DISPATCH", ",", "true", ")", ";", "}", "return", "$", "this", ";", "}" ]
Disables ESI processing and marks request as internal @return $this
[ "Disables", "ESI", "processing", "and", "marks", "request", "as", "internal" ]
228b7b1bdaae15c1895f2533667fffa515447915
https://github.com/EcomDev/EcomDev_Varnish/blob/228b7b1bdaae15c1895f2533667fffa515447915/src/app/code/community/EcomDev/Varnish/controllers/AjaxController.php#L39-L58
222,806
EcomDev/EcomDev_Varnish
src/app/code/community/EcomDev/Varnish/Block/Messages.php
EcomDev_Varnish_Block_Messages.getGroupedHtml
public function getGroupedHtml() { $name = $this->getNameInLayout(); $htmlId = uniqid($name); $types = []; foreach ($this->_usedStorageTypes as $type) { $type = $this->getVarnishMessageModel()->getMessageTypeByStorage($type); if (!$type) { continue; } $types[] = $type; } return sprintf( $this->getMessageContainerFormat(), json_encode($htmlId), json_encode($this->getUrl('varnish/ajax/message', array( '_secure' => Mage::app()->getStore()->isCurrentlySecure() ))), json_encode($types), json_encode(EcomDev_Varnish_Model_Message::COOKIE_NAME), json_encode(array( 'path' => Mage::getSingleton('core/cookie')->getPath(), 'domain' => Mage::getSingleton('core/cookie')->getDomain() )) ); }
php
public function getGroupedHtml() { $name = $this->getNameInLayout(); $htmlId = uniqid($name); $types = []; foreach ($this->_usedStorageTypes as $type) { $type = $this->getVarnishMessageModel()->getMessageTypeByStorage($type); if (!$type) { continue; } $types[] = $type; } return sprintf( $this->getMessageContainerFormat(), json_encode($htmlId), json_encode($this->getUrl('varnish/ajax/message', array( '_secure' => Mage::app()->getStore()->isCurrentlySecure() ))), json_encode($types), json_encode(EcomDev_Varnish_Model_Message::COOKIE_NAME), json_encode(array( 'path' => Mage::getSingleton('core/cookie')->getPath(), 'domain' => Mage::getSingleton('core/cookie')->getDomain() )) ); }
[ "public", "function", "getGroupedHtml", "(", ")", "{", "$", "name", "=", "$", "this", "->", "getNameInLayout", "(", ")", ";", "$", "htmlId", "=", "uniqid", "(", "$", "name", ")", ";", "$", "types", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "_usedStorageTypes", "as", "$", "type", ")", "{", "$", "type", "=", "$", "this", "->", "getVarnishMessageModel", "(", ")", "->", "getMessageTypeByStorage", "(", "$", "type", ")", ";", "if", "(", "!", "$", "type", ")", "{", "continue", ";", "}", "$", "types", "[", "]", "=", "$", "type", ";", "}", "return", "sprintf", "(", "$", "this", "->", "getMessageContainerFormat", "(", ")", ",", "json_encode", "(", "$", "htmlId", ")", ",", "json_encode", "(", "$", "this", "->", "getUrl", "(", "'varnish/ajax/message'", ",", "array", "(", "'_secure'", "=>", "Mage", "::", "app", "(", ")", "->", "getStore", "(", ")", "->", "isCurrentlySecure", "(", ")", ")", ")", ")", ",", "json_encode", "(", "$", "types", ")", ",", "json_encode", "(", "EcomDev_Varnish_Model_Message", "::", "COOKIE_NAME", ")", ",", "json_encode", "(", "array", "(", "'path'", "=>", "Mage", "::", "getSingleton", "(", "'core/cookie'", ")", "->", "getPath", "(", ")", ",", "'domain'", "=>", "Mage", "::", "getSingleton", "(", "'core/cookie'", ")", "->", "getDomain", "(", ")", ")", ")", ")", ";", "}" ]
Returns JS that is required to load messages @return string
[ "Returns", "JS", "that", "is", "required", "to", "load", "messages" ]
228b7b1bdaae15c1895f2533667fffa515447915
https://github.com/EcomDev/EcomDev_Varnish/blob/228b7b1bdaae15c1895f2533667fffa515447915/src/app/code/community/EcomDev/Varnish/Block/Messages.php#L41-L68
222,807
EcomDev/EcomDev_Varnish
src/app/code/community/EcomDev/Varnish/Block/Messages.php
EcomDev_Varnish_Block_Messages.addStorageType
public function addStorageType($type) { parent::addStorageType($type); if (!is_string($type)) { return $this; } foreach ($this->getMessageCollection()->getItems() as $item) { $this->storageMessages[$type][] = $item; } $this->getMessageCollection()->clear(); return $this; }
php
public function addStorageType($type) { parent::addStorageType($type); if (!is_string($type)) { return $this; } foreach ($this->getMessageCollection()->getItems() as $item) { $this->storageMessages[$type][] = $item; } $this->getMessageCollection()->clear(); return $this; }
[ "public", "function", "addStorageType", "(", "$", "type", ")", "{", "parent", "::", "addStorageType", "(", "$", "type", ")", ";", "if", "(", "!", "is_string", "(", "$", "type", ")", ")", "{", "return", "$", "this", ";", "}", "foreach", "(", "$", "this", "->", "getMessageCollection", "(", ")", "->", "getItems", "(", ")", "as", "$", "item", ")", "{", "$", "this", "->", "storageMessages", "[", "$", "type", "]", "[", "]", "=", "$", "item", ";", "}", "$", "this", "->", "getMessageCollection", "(", ")", "->", "clear", "(", ")", ";", "return", "$", "this", ";", "}" ]
Add used storage type @param string $type @return $this
[ "Add", "used", "storage", "type" ]
228b7b1bdaae15c1895f2533667fffa515447915
https://github.com/EcomDev/EcomDev_Varnish/blob/228b7b1bdaae15c1895f2533667fffa515447915/src/app/code/community/EcomDev/Varnish/Block/Messages.php#L102-L116
222,808
stanislav-web/phalcon-uploader
src/Uploader/Uploader.php
Uploader.setRules
public function setRules(array $rules) { foreach ($rules as $key => $values) { if ((is_array($values) === true && empty($values) === false) || is_callable($values)) { $this->rules[$key] = $values; } else { $this->rules[$key] = trim($values); } } return $this; }
php
public function setRules(array $rules) { foreach ($rules as $key => $values) { if ((is_array($values) === true && empty($values) === false) || is_callable($values)) { $this->rules[$key] = $values; } else { $this->rules[$key] = trim($values); } } return $this; }
[ "public", "function", "setRules", "(", "array", "$", "rules", ")", "{", "foreach", "(", "$", "rules", "as", "$", "key", "=>", "$", "values", ")", "{", "if", "(", "(", "is_array", "(", "$", "values", ")", "===", "true", "&&", "empty", "(", "$", "values", ")", "===", "false", ")", "||", "is_callable", "(", "$", "values", ")", ")", "{", "$", "this", "->", "rules", "[", "$", "key", "]", "=", "$", "values", ";", "}", "else", "{", "$", "this", "->", "rules", "[", "$", "key", "]", "=", "trim", "(", "$", "values", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Setting up rules for uploaded files @param array $rules @return Uploader
[ "Setting", "up", "rules", "for", "uploaded", "files" ]
3e46aba5d6f51b52b7830eae21c0d3fe1e524c90
https://github.com/stanislav-web/phalcon-uploader/blob/3e46aba5d6f51b52b7830eae21c0d3fe1e524c90/src/Uploader/Uploader.php#L76-L88
222,809
stanislav-web/phalcon-uploader
src/Uploader/Uploader.php
Uploader.truncate
public function truncate() { if (empty($this->info) === false) { foreach ($this->info as $n => $file) { if (file_exists($file['path'])) { unlink($file['path']); } } } }
php
public function truncate() { if (empty($this->info) === false) { foreach ($this->info as $n => $file) { if (file_exists($file['path'])) { unlink($file['path']); } } } }
[ "public", "function", "truncate", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "info", ")", "===", "false", ")", "{", "foreach", "(", "$", "this", "->", "info", "as", "$", "n", "=>", "$", "file", ")", "{", "if", "(", "file_exists", "(", "$", "file", "[", "'path'", "]", ")", ")", "{", "unlink", "(", "$", "file", "[", "'path'", "]", ")", ";", "}", "}", "}", "}" ]
Truncate uploaded files
[ "Truncate", "uploaded", "files" ]
3e46aba5d6f51b52b7830eae21c0d3fe1e524c90
https://github.com/stanislav-web/phalcon-uploader/blob/3e46aba5d6f51b52b7830eae21c0d3fe1e524c90/src/Uploader/Uploader.php#L200-L209
222,810
univicosa/laravel-openid-client
Providers/OpenIdServiceProvider.php
OpenIdServiceProvider.registerGuard
protected function registerGuard() { \Auth::extend('openid', function ($app, $name, array $config) { return new CustomSessionGuard($app['session.store']); }); \Auth::extend('basic-api', function ($app, $name, array $config) { return new CustomTokenGuard(); }); }
php
protected function registerGuard() { \Auth::extend('openid', function ($app, $name, array $config) { return new CustomSessionGuard($app['session.store']); }); \Auth::extend('basic-api', function ($app, $name, array $config) { return new CustomTokenGuard(); }); }
[ "protected", "function", "registerGuard", "(", ")", "{", "\\", "Auth", "::", "extend", "(", "'openid'", ",", "function", "(", "$", "app", ",", "$", "name", ",", "array", "$", "config", ")", "{", "return", "new", "CustomSessionGuard", "(", "$", "app", "[", "'session.store'", "]", ")", ";", "}", ")", ";", "\\", "Auth", "::", "extend", "(", "'basic-api'", ",", "function", "(", "$", "app", ",", "$", "name", ",", "array", "$", "config", ")", "{", "return", "new", "CustomTokenGuard", "(", ")", ";", "}", ")", ";", "}" ]
Register Guard Session @return void
[ "Register", "Guard", "Session" ]
42ac511de250b597ba12ef0216f1d493fd7a2def
https://github.com/univicosa/laravel-openid-client/blob/42ac511de250b597ba12ef0216f1d493fd7a2def/Providers/OpenIdServiceProvider.php#L76-L85
222,811
digiaonline/lumen-dynamodb
src/Console/CreateTablesCommand.php
CreateTablesCommand.createTables
protected function createTables() { if (empty( self::$tables )) { throw new \Exception('Cannot create tables, as no configuration file given, or the ::$tables is not overridden.'); } $client = $this->dynamoDb->getClient(); foreach (self::$tables as $tableData) { $tableName = $tableData['TableName']; if ( ! $this->tableExists($tableName)) { $this->comment(sprintf('Creating table %s', $tableName)); $client->createTable($tableData); $client->waitUntil('TableExists', array( 'TableName' => $tableName, )); $this->info(sprintf('Table "%s" created.', $tableName)); } else { $this->warn(sprintf('Table "%s" already exists.', $tableName)); } } }
php
protected function createTables() { if (empty( self::$tables )) { throw new \Exception('Cannot create tables, as no configuration file given, or the ::$tables is not overridden.'); } $client = $this->dynamoDb->getClient(); foreach (self::$tables as $tableData) { $tableName = $tableData['TableName']; if ( ! $this->tableExists($tableName)) { $this->comment(sprintf('Creating table %s', $tableName)); $client->createTable($tableData); $client->waitUntil('TableExists', array( 'TableName' => $tableName, )); $this->info(sprintf('Table "%s" created.', $tableName)); } else { $this->warn(sprintf('Table "%s" already exists.', $tableName)); } } }
[ "protected", "function", "createTables", "(", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "tables", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Cannot create tables, as no configuration file given, or the ::$tables is not overridden.'", ")", ";", "}", "$", "client", "=", "$", "this", "->", "dynamoDb", "->", "getClient", "(", ")", ";", "foreach", "(", "self", "::", "$", "tables", "as", "$", "tableData", ")", "{", "$", "tableName", "=", "$", "tableData", "[", "'TableName'", "]", ";", "if", "(", "!", "$", "this", "->", "tableExists", "(", "$", "tableName", ")", ")", "{", "$", "this", "->", "comment", "(", "sprintf", "(", "'Creating table %s'", ",", "$", "tableName", ")", ")", ";", "$", "client", "->", "createTable", "(", "$", "tableData", ")", ";", "$", "client", "->", "waitUntil", "(", "'TableExists'", ",", "array", "(", "'TableName'", "=>", "$", "tableName", ",", ")", ")", ";", "$", "this", "->", "info", "(", "sprintf", "(", "'Table \"%s\" created.'", ",", "$", "tableName", ")", ")", ";", "}", "else", "{", "$", "this", "->", "warn", "(", "sprintf", "(", "'Table \"%s\" already exists.'", ",", "$", "tableName", ")", ")", ";", "}", "}", "}" ]
Creates the tables defined in configuration file, or overridden. @throws \Exception
[ "Creates", "the", "tables", "defined", "in", "configuration", "file", "or", "overridden", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Console/CreateTablesCommand.php#L60-L84
222,812
fage1151/swoole-worker
Worker.php
Worker.parseCommand
protected static function parseCommand() { global $argv; // Check argv; $start_file = $argv[0]; if (!isset($argv[1])) { exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n"); } // Get command. $command = trim($argv[1]); $command2 = isset($argv[2]) ? $argv[2] : ''; // Start command. $mode = ''; if ($command === 'start') { if ($command2 === '-d' || Worker::$daemonize) { $mode = 'in DAEMON mode'; } else { $mode = 'in DEBUG mode'; } } self::log("Workerman[$start_file] $command $mode"); // Get master process PID. $master_pid = is_file(self::$pidFile) ? file_get_contents(self::$pidFile) : 0; $master_is_alive = $master_pid && @swoole_process::kill($master_pid, 0); // Master is still alive? if ($master_is_alive) { if ($command === 'start' && getmypid() != $master_pid) { self::log("Workerman[$start_file] already running"); exit; } } elseif ($command !== 'start' && $command !== 'restart') { self::log("Workerman[$start_file] not run"); exit; } // execute command. switch ($command) { case 'start': if ($command2 === '-d') { Worker::$daemonize = true; } break; case 'status': if (is_file(self::$_statisticsFile)) { @unlink(self::$_statisticsFile); } // Master process will send status signal to all child processes. swoole_process::kill($master_pid, SIGUSR2); // Waiting amoment. usleep(500000); // Display statisitcs data from a disk file. @readfile(self::$_statisticsFile); exit(0); case 'restart': case 'stop': self::log("Workerman[$start_file] is stoping ..."); // Send stop signal to master process. $master_pid && swoole_process::kill($master_pid, SIGINT); // Timeout. $timeout = 5; $start_time = time(); // Check master process is still alive? while (1) { $master_is_alive = $master_pid && swoole_process::kill($master_pid, 0); if ($master_is_alive) { // Timeout? if (time() - $start_time >= $timeout) { self::log("Workerman[$start_file] stop fail"); exit; } // Waiting amoment. usleep(10000); continue; } // Stop success. self::log("Workerman[$start_file] stop success"); if ($command === 'stop') { exit(0); } if ($command2 === '-d') { Worker::$daemonize = true; } break; } break; case 'reload': swoole_process::kill($master_pid, SIGUSR1); self::log("Workerman[$start_file] reload"); exit; default : exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n"); } }
php
protected static function parseCommand() { global $argv; // Check argv; $start_file = $argv[0]; if (!isset($argv[1])) { exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n"); } // Get command. $command = trim($argv[1]); $command2 = isset($argv[2]) ? $argv[2] : ''; // Start command. $mode = ''; if ($command === 'start') { if ($command2 === '-d' || Worker::$daemonize) { $mode = 'in DAEMON mode'; } else { $mode = 'in DEBUG mode'; } } self::log("Workerman[$start_file] $command $mode"); // Get master process PID. $master_pid = is_file(self::$pidFile) ? file_get_contents(self::$pidFile) : 0; $master_is_alive = $master_pid && @swoole_process::kill($master_pid, 0); // Master is still alive? if ($master_is_alive) { if ($command === 'start' && getmypid() != $master_pid) { self::log("Workerman[$start_file] already running"); exit; } } elseif ($command !== 'start' && $command !== 'restart') { self::log("Workerman[$start_file] not run"); exit; } // execute command. switch ($command) { case 'start': if ($command2 === '-d') { Worker::$daemonize = true; } break; case 'status': if (is_file(self::$_statisticsFile)) { @unlink(self::$_statisticsFile); } // Master process will send status signal to all child processes. swoole_process::kill($master_pid, SIGUSR2); // Waiting amoment. usleep(500000); // Display statisitcs data from a disk file. @readfile(self::$_statisticsFile); exit(0); case 'restart': case 'stop': self::log("Workerman[$start_file] is stoping ..."); // Send stop signal to master process. $master_pid && swoole_process::kill($master_pid, SIGINT); // Timeout. $timeout = 5; $start_time = time(); // Check master process is still alive? while (1) { $master_is_alive = $master_pid && swoole_process::kill($master_pid, 0); if ($master_is_alive) { // Timeout? if (time() - $start_time >= $timeout) { self::log("Workerman[$start_file] stop fail"); exit; } // Waiting amoment. usleep(10000); continue; } // Stop success. self::log("Workerman[$start_file] stop success"); if ($command === 'stop') { exit(0); } if ($command2 === '-d') { Worker::$daemonize = true; } break; } break; case 'reload': swoole_process::kill($master_pid, SIGUSR1); self::log("Workerman[$start_file] reload"); exit; default : exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n"); } }
[ "protected", "static", "function", "parseCommand", "(", ")", "{", "global", "$", "argv", ";", "// Check argv;", "$", "start_file", "=", "$", "argv", "[", "0", "]", ";", "if", "(", "!", "isset", "(", "$", "argv", "[", "1", "]", ")", ")", "{", "exit", "(", "\"Usage: php yourfile.php {start|stop|restart|reload|status}\\n\"", ")", ";", "}", "// Get command.", "$", "command", "=", "trim", "(", "$", "argv", "[", "1", "]", ")", ";", "$", "command2", "=", "isset", "(", "$", "argv", "[", "2", "]", ")", "?", "$", "argv", "[", "2", "]", ":", "''", ";", "// Start command.", "$", "mode", "=", "''", ";", "if", "(", "$", "command", "===", "'start'", ")", "{", "if", "(", "$", "command2", "===", "'-d'", "||", "Worker", "::", "$", "daemonize", ")", "{", "$", "mode", "=", "'in DAEMON mode'", ";", "}", "else", "{", "$", "mode", "=", "'in DEBUG mode'", ";", "}", "}", "self", "::", "log", "(", "\"Workerman[$start_file] $command $mode\"", ")", ";", "// Get master process PID.", "$", "master_pid", "=", "is_file", "(", "self", "::", "$", "pidFile", ")", "?", "file_get_contents", "(", "self", "::", "$", "pidFile", ")", ":", "0", ";", "$", "master_is_alive", "=", "$", "master_pid", "&&", "@", "swoole_process", "::", "kill", "(", "$", "master_pid", ",", "0", ")", ";", "// Master is still alive?", "if", "(", "$", "master_is_alive", ")", "{", "if", "(", "$", "command", "===", "'start'", "&&", "getmypid", "(", ")", "!=", "$", "master_pid", ")", "{", "self", "::", "log", "(", "\"Workerman[$start_file] already running\"", ")", ";", "exit", ";", "}", "}", "elseif", "(", "$", "command", "!==", "'start'", "&&", "$", "command", "!==", "'restart'", ")", "{", "self", "::", "log", "(", "\"Workerman[$start_file] not run\"", ")", ";", "exit", ";", "}", "// execute command.", "switch", "(", "$", "command", ")", "{", "case", "'start'", ":", "if", "(", "$", "command2", "===", "'-d'", ")", "{", "Worker", "::", "$", "daemonize", "=", "true", ";", "}", "break", ";", "case", "'status'", ":", "if", "(", "is_file", "(", "self", "::", "$", "_statisticsFile", ")", ")", "{", "@", "unlink", "(", "self", "::", "$", "_statisticsFile", ")", ";", "}", "// Master process will send status signal to all child processes.", "swoole_process", "::", "kill", "(", "$", "master_pid", ",", "SIGUSR2", ")", ";", "// Waiting amoment.", "usleep", "(", "500000", ")", ";", "// Display statisitcs data from a disk file.", "@", "readfile", "(", "self", "::", "$", "_statisticsFile", ")", ";", "exit", "(", "0", ")", ";", "case", "'restart'", ":", "case", "'stop'", ":", "self", "::", "log", "(", "\"Workerman[$start_file] is stoping ...\"", ")", ";", "// Send stop signal to master process.", "$", "master_pid", "&&", "swoole_process", "::", "kill", "(", "$", "master_pid", ",", "SIGINT", ")", ";", "// Timeout.", "$", "timeout", "=", "5", ";", "$", "start_time", "=", "time", "(", ")", ";", "// Check master process is still alive?", "while", "(", "1", ")", "{", "$", "master_is_alive", "=", "$", "master_pid", "&&", "swoole_process", "::", "kill", "(", "$", "master_pid", ",", "0", ")", ";", "if", "(", "$", "master_is_alive", ")", "{", "// Timeout?", "if", "(", "time", "(", ")", "-", "$", "start_time", ">=", "$", "timeout", ")", "{", "self", "::", "log", "(", "\"Workerman[$start_file] stop fail\"", ")", ";", "exit", ";", "}", "// Waiting amoment.", "usleep", "(", "10000", ")", ";", "continue", ";", "}", "// Stop success.", "self", "::", "log", "(", "\"Workerman[$start_file] stop success\"", ")", ";", "if", "(", "$", "command", "===", "'stop'", ")", "{", "exit", "(", "0", ")", ";", "}", "if", "(", "$", "command2", "===", "'-d'", ")", "{", "Worker", "::", "$", "daemonize", "=", "true", ";", "}", "break", ";", "}", "break", ";", "case", "'reload'", ":", "swoole_process", "::", "kill", "(", "$", "master_pid", ",", "SIGUSR1", ")", ";", "self", "::", "log", "(", "\"Workerman[$start_file] reload\"", ")", ";", "exit", ";", "default", ":", "exit", "(", "\"Usage: php yourfile.php {start|stop|restart|reload|status}\\n\"", ")", ";", "}", "}" ]
Parse command. php yourfile.php start | stop | restart | reload | status @return void
[ "Parse", "command", ".", "php", "yourfile", ".", "php", "start", "|", "stop", "|", "restart", "|", "reload", "|", "status" ]
ade6e29ffb400129380d56e9a2e6656f19dceb17
https://github.com/fage1151/swoole-worker/blob/ade6e29ffb400129380d56e9a2e6656f19dceb17/Worker.php#L625-L720
222,813
fage1151/swoole-worker
Worker.php
Worker.exitAndClearAll
protected static function exitAndClearAll() { foreach (self::$_workers as $worker) { $socket_name = $worker->getSocketName(); if ($worker->transport === 'unix' && $socket_name) { list(, $address) = explode(':', $socket_name, 2); @unlink($address); } } @unlink(self::$pidFile); self::log("Workerman[" . basename(self::$_startFile) . "] has been stopped"); if (self::$onMasterStop) { call_user_func(self::$onMasterStop); } exit(0); }
php
protected static function exitAndClearAll() { foreach (self::$_workers as $worker) { $socket_name = $worker->getSocketName(); if ($worker->transport === 'unix' && $socket_name) { list(, $address) = explode(':', $socket_name, 2); @unlink($address); } } @unlink(self::$pidFile); self::log("Workerman[" . basename(self::$_startFile) . "] has been stopped"); if (self::$onMasterStop) { call_user_func(self::$onMasterStop); } exit(0); }
[ "protected", "static", "function", "exitAndClearAll", "(", ")", "{", "foreach", "(", "self", "::", "$", "_workers", "as", "$", "worker", ")", "{", "$", "socket_name", "=", "$", "worker", "->", "getSocketName", "(", ")", ";", "if", "(", "$", "worker", "->", "transport", "===", "'unix'", "&&", "$", "socket_name", ")", "{", "list", "(", ",", "$", "address", ")", "=", "explode", "(", "':'", ",", "$", "socket_name", ",", "2", ")", ";", "@", "unlink", "(", "$", "address", ")", ";", "}", "}", "@", "unlink", "(", "self", "::", "$", "pidFile", ")", ";", "self", "::", "log", "(", "\"Workerman[\"", ".", "basename", "(", "self", "::", "$", "_startFile", ")", ".", "\"] has been stopped\"", ")", ";", "if", "(", "self", "::", "$", "onMasterStop", ")", "{", "call_user_func", "(", "self", "::", "$", "onMasterStop", ")", ";", "}", "exit", "(", "0", ")", ";", "}" ]
Exit current process. @return void
[ "Exit", "current", "process", "." ]
ade6e29ffb400129380d56e9a2e6656f19dceb17
https://github.com/fage1151/swoole-worker/blob/ade6e29ffb400129380d56e9a2e6656f19dceb17/Worker.php#L1036-L1051
222,814
fage1151/swoole-worker
Worker.php
Worker.listen
public function listen() { if (!$this->_socketName || $this->_mainSocket) { return; } // Autoload. Autoloader::setRootPath($this->_autoloadRootPath); // Get the application layer communication protocol and listening address. list($scheme, $address) = explode(':', $this->_socketName, 2); // Check application layer protocol class. if (!isset(self::$_builtinTransports[$scheme])) { if(class_exists($scheme)){ $this->protocol = $scheme; } else { $scheme = ucfirst($scheme); $this->protocol = '\\Protocols\\' . $scheme; if (!class_exists($this->protocol)) { $this->protocol = "\\Workerman\\Protocols\\$scheme"; if (!class_exists($this->protocol)) { throw new Exception("class \\Protocols\\$scheme not exist"); } } } if (!isset(self::$_builtinTransports[$this->transport])) { throw new \Exception('Bad worker->transport ' . var_export($this->transport, true)); } } else { $this->transport = $scheme; } $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address; // Flag. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN; $errno = 0; $errmsg = ''; // SO_REUSEPORT. if ($this->reusePort) { stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1); } // Create an Internet or Unix domain server socket. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context); if (!$this->_mainSocket) { throw new Exception($errmsg); } if ($this->transport === 'ssl') { stream_socket_enable_crypto($this->_mainSocket, false); } // Try to open keepalive for tcp and disable Nagle algorithm. if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') { $socket = socket_import_stream($this->_mainSocket); @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1); } // Non blocking. stream_set_blocking($this->_mainSocket, 0); // Register a listener to be notified when server socket is ready to read. if (self::$globalEvent) { if ($this->transport !== 'udp') { self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection')); } else { self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptUdpConnection')); } } }
php
public function listen() { if (!$this->_socketName || $this->_mainSocket) { return; } // Autoload. Autoloader::setRootPath($this->_autoloadRootPath); // Get the application layer communication protocol and listening address. list($scheme, $address) = explode(':', $this->_socketName, 2); // Check application layer protocol class. if (!isset(self::$_builtinTransports[$scheme])) { if(class_exists($scheme)){ $this->protocol = $scheme; } else { $scheme = ucfirst($scheme); $this->protocol = '\\Protocols\\' . $scheme; if (!class_exists($this->protocol)) { $this->protocol = "\\Workerman\\Protocols\\$scheme"; if (!class_exists($this->protocol)) { throw new Exception("class \\Protocols\\$scheme not exist"); } } } if (!isset(self::$_builtinTransports[$this->transport])) { throw new \Exception('Bad worker->transport ' . var_export($this->transport, true)); } } else { $this->transport = $scheme; } $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address; // Flag. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN; $errno = 0; $errmsg = ''; // SO_REUSEPORT. if ($this->reusePort) { stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1); } // Create an Internet or Unix domain server socket. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context); if (!$this->_mainSocket) { throw new Exception($errmsg); } if ($this->transport === 'ssl') { stream_socket_enable_crypto($this->_mainSocket, false); } // Try to open keepalive for tcp and disable Nagle algorithm. if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') { $socket = socket_import_stream($this->_mainSocket); @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1); } // Non blocking. stream_set_blocking($this->_mainSocket, 0); // Register a listener to be notified when server socket is ready to read. if (self::$globalEvent) { if ($this->transport !== 'udp') { self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection')); } else { self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptUdpConnection')); } } }
[ "public", "function", "listen", "(", ")", "{", "if", "(", "!", "$", "this", "->", "_socketName", "||", "$", "this", "->", "_mainSocket", ")", "{", "return", ";", "}", "// Autoload.", "Autoloader", "::", "setRootPath", "(", "$", "this", "->", "_autoloadRootPath", ")", ";", "// Get the application layer communication protocol and listening address.", "list", "(", "$", "scheme", ",", "$", "address", ")", "=", "explode", "(", "':'", ",", "$", "this", "->", "_socketName", ",", "2", ")", ";", "// Check application layer protocol class.", "if", "(", "!", "isset", "(", "self", "::", "$", "_builtinTransports", "[", "$", "scheme", "]", ")", ")", "{", "if", "(", "class_exists", "(", "$", "scheme", ")", ")", "{", "$", "this", "->", "protocol", "=", "$", "scheme", ";", "}", "else", "{", "$", "scheme", "=", "ucfirst", "(", "$", "scheme", ")", ";", "$", "this", "->", "protocol", "=", "'\\\\Protocols\\\\'", ".", "$", "scheme", ";", "if", "(", "!", "class_exists", "(", "$", "this", "->", "protocol", ")", ")", "{", "$", "this", "->", "protocol", "=", "\"\\\\Workerman\\\\Protocols\\\\$scheme\"", ";", "if", "(", "!", "class_exists", "(", "$", "this", "->", "protocol", ")", ")", "{", "throw", "new", "Exception", "(", "\"class \\\\Protocols\\\\$scheme not exist\"", ")", ";", "}", "}", "}", "if", "(", "!", "isset", "(", "self", "::", "$", "_builtinTransports", "[", "$", "this", "->", "transport", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Bad worker->transport '", ".", "var_export", "(", "$", "this", "->", "transport", ",", "true", ")", ")", ";", "}", "}", "else", "{", "$", "this", "->", "transport", "=", "$", "scheme", ";", "}", "$", "local_socket", "=", "self", "::", "$", "_builtinTransports", "[", "$", "this", "->", "transport", "]", ".", "\":\"", ".", "$", "address", ";", "// Flag.", "$", "flags", "=", "$", "this", "->", "transport", "===", "'udp'", "?", "STREAM_SERVER_BIND", ":", "STREAM_SERVER_BIND", "|", "STREAM_SERVER_LISTEN", ";", "$", "errno", "=", "0", ";", "$", "errmsg", "=", "''", ";", "// SO_REUSEPORT.", "if", "(", "$", "this", "->", "reusePort", ")", "{", "stream_context_set_option", "(", "$", "this", "->", "_context", ",", "'socket'", ",", "'so_reuseport'", ",", "1", ")", ";", "}", "// Create an Internet or Unix domain server socket.", "$", "this", "->", "_mainSocket", "=", "stream_socket_server", "(", "$", "local_socket", ",", "$", "errno", ",", "$", "errmsg", ",", "$", "flags", ",", "$", "this", "->", "_context", ")", ";", "if", "(", "!", "$", "this", "->", "_mainSocket", ")", "{", "throw", "new", "Exception", "(", "$", "errmsg", ")", ";", "}", "if", "(", "$", "this", "->", "transport", "===", "'ssl'", ")", "{", "stream_socket_enable_crypto", "(", "$", "this", "->", "_mainSocket", ",", "false", ")", ";", "}", "// Try to open keepalive for tcp and disable Nagle algorithm.", "if", "(", "function_exists", "(", "'socket_import_stream'", ")", "&&", "self", "::", "$", "_builtinTransports", "[", "$", "this", "->", "transport", "]", "===", "'tcp'", ")", "{", "$", "socket", "=", "socket_import_stream", "(", "$", "this", "->", "_mainSocket", ")", ";", "@", "socket_set_option", "(", "$", "socket", ",", "SOL_SOCKET", ",", "SO_KEEPALIVE", ",", "1", ")", ";", "@", "socket_set_option", "(", "$", "socket", ",", "SOL_TCP", ",", "TCP_NODELAY", ",", "1", ")", ";", "}", "// Non blocking.", "stream_set_blocking", "(", "$", "this", "->", "_mainSocket", ",", "0", ")", ";", "// Register a listener to be notified when server socket is ready to read.", "if", "(", "self", "::", "$", "globalEvent", ")", "{", "if", "(", "$", "this", "->", "transport", "!==", "'udp'", ")", "{", "self", "::", "$", "globalEvent", "->", "add", "(", "$", "this", "->", "_mainSocket", ",", "EventInterface", "::", "EV_READ", ",", "array", "(", "$", "this", ",", "'acceptConnection'", ")", ")", ";", "}", "else", "{", "self", "::", "$", "globalEvent", "->", "add", "(", "$", "this", "->", "_mainSocket", ",", "EventInterface", "::", "EV_READ", ",", "array", "(", "$", "this", ",", "'acceptUdpConnection'", ")", ")", ";", "}", "}", "}" ]
Listen port. @throws Exception
[ "Listen", "port", "." ]
ade6e29ffb400129380d56e9a2e6656f19dceb17
https://github.com/fage1151/swoole-worker/blob/ade6e29ffb400129380d56e9a2e6656f19dceb17/Worker.php#L1366-L1439
222,815
sgpatil/oriquent
src/Sgpatil/Orientdb/Schema/Blueprint.php
Blueprint.integer
public function integer($column, $autoIncrement = false, $unsigned = false) { return $this->addColumn('INTEGER', $column, compact('autoIncrement', 'unsigned')); }
php
public function integer($column, $autoIncrement = false, $unsigned = false) { return $this->addColumn('INTEGER', $column, compact('autoIncrement', 'unsigned')); }
[ "public", "function", "integer", "(", "$", "column", ",", "$", "autoIncrement", "=", "false", ",", "$", "unsigned", "=", "false", ")", "{", "return", "$", "this", "->", "addColumn", "(", "'INTEGER'", ",", "$", "column", ",", "compact", "(", "'autoIncrement'", ",", "'unsigned'", ")", ")", ";", "}" ]
Create a new integer column on the table. @param string $column @param bool $autoIncrement @param bool $unsigned @return \Illuminate\Support\Fluent
[ "Create", "a", "new", "integer", "column", "on", "the", "table", "." ]
cf0f2ba688496260946f569a20c351e91f287c32
https://github.com/sgpatil/oriquent/blob/cf0f2ba688496260946f569a20c351e91f287c32/src/Sgpatil/Orientdb/Schema/Blueprint.php#L402-L404
222,816
sgpatil/oriquent
src/Sgpatil/Orientdb/Eloquent/Edges/Finder.php
Finder.first
public function first(Model $parentModel, Model $relatedModel, $type, $direction = 'any') { // First we get the first relationship instance between the two models // absed on the given direction. $relation = $this->firstRelation($parentModel, $relatedModel, $type, $direction); // Let's stop here if there is no relationship between them. if (is_null($relation)) return null; // Now we can return the determined edge out of the relation and direction. return $this->edgeFromRelationWithDirection($relation, $parentModel, $relatedModel, $direction); }
php
public function first(Model $parentModel, Model $relatedModel, $type, $direction = 'any') { // First we get the first relationship instance between the two models // absed on the given direction. $relation = $this->firstRelation($parentModel, $relatedModel, $type, $direction); // Let's stop here if there is no relationship between them. if (is_null($relation)) return null; // Now we can return the determined edge out of the relation and direction. return $this->edgeFromRelationWithDirection($relation, $parentModel, $relatedModel, $direction); }
[ "public", "function", "first", "(", "Model", "$", "parentModel", ",", "Model", "$", "relatedModel", ",", "$", "type", ",", "$", "direction", "=", "'any'", ")", "{", "// First we get the first relationship instance between the two models", "// absed on the given direction.", "$", "relation", "=", "$", "this", "->", "firstRelation", "(", "$", "parentModel", ",", "$", "relatedModel", ",", "$", "type", ",", "$", "direction", ")", ";", "// Let's stop here if there is no relationship between them.", "if", "(", "is_null", "(", "$", "relation", ")", ")", "return", "null", ";", "// Now we can return the determined edge out of the relation and direction.", "return", "$", "this", "->", "edgeFromRelationWithDirection", "(", "$", "relation", ",", "$", "parentModel", ",", "$", "relatedModel", ",", "$", "direction", ")", ";", "}" ]
Get the first edge relationship between two models. @param \Sgpatil\Orientdb\Eloquent\Model $parentModel @param \Sgpatil\Orientdb\Eloquent\Model $relatedModel @param string $direction @return \Sgpatil\Orientdb\Eloquent\Edges\Edge[In|Out]|null
[ "Get", "the", "first", "edge", "relationship", "between", "two", "models", "." ]
cf0f2ba688496260946f569a20c351e91f287c32
https://github.com/sgpatil/oriquent/blob/cf0f2ba688496260946f569a20c351e91f287c32/src/Sgpatil/Orientdb/Eloquent/Edges/Finder.php#L70-L81
222,817
teresko/palladium
src/Palladium/Service/Search.php
Search.findIdentityById
public function findIdentityById(int $identityId): Entity\Identity { $identity = new Entity\Identity; $identity->setId($identityId); $this->repository->load($identity, Entity\Identity::class); if ($identity->getAccountId() === null) { $this->logger->notice('identity not found', [ 'input' => [ 'id' => $identityId, ], ]); throw new IdentityNotFound; } return $identity; }
php
public function findIdentityById(int $identityId): Entity\Identity { $identity = new Entity\Identity; $identity->setId($identityId); $this->repository->load($identity, Entity\Identity::class); if ($identity->getAccountId() === null) { $this->logger->notice('identity not found', [ 'input' => [ 'id' => $identityId, ], ]); throw new IdentityNotFound; } return $identity; }
[ "public", "function", "findIdentityById", "(", "int", "$", "identityId", ")", ":", "Entity", "\\", "Identity", "{", "$", "identity", "=", "new", "Entity", "\\", "Identity", ";", "$", "identity", "->", "setId", "(", "$", "identityId", ")", ";", "$", "this", "->", "repository", "->", "load", "(", "$", "identity", ",", "Entity", "\\", "Identity", "::", "class", ")", ";", "if", "(", "$", "identity", "->", "getAccountId", "(", ")", "===", "null", ")", "{", "$", "this", "->", "logger", "->", "notice", "(", "'identity not found'", ",", "[", "'input'", "=>", "[", "'id'", "=>", "$", "identityId", ",", "]", ",", "]", ")", ";", "throw", "new", "IdentityNotFound", ";", "}", "return", "$", "identity", ";", "}" ]
Locates identity based on ID @throws IdentityNotFound if identity was not found
[ "Locates", "identity", "based", "on", "ID" ]
0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8
https://github.com/teresko/palladium/blob/0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8/src/Palladium/Service/Search.php#L38-L56
222,818
teresko/palladium
src/Palladium/Service/Search.php
Search.findStandardIdentityByIdentifier
public function findStandardIdentityByIdentifier(string $identifier): Entity\StandardIdentity { $identity = new Entity\StandardIdentity; $identity->setIdentifier($identifier); $this->repository->load($identity); if ($identity->getId() === null) { $this->logger->notice('identity not found', [ 'input' => [ 'identifier' => $identifier, ], ]); throw new IdentityNotFound; } return $identity; }
php
public function findStandardIdentityByIdentifier(string $identifier): Entity\StandardIdentity { $identity = new Entity\StandardIdentity; $identity->setIdentifier($identifier); $this->repository->load($identity); if ($identity->getId() === null) { $this->logger->notice('identity not found', [ 'input' => [ 'identifier' => $identifier, ], ]); throw new IdentityNotFound; } return $identity; }
[ "public", "function", "findStandardIdentityByIdentifier", "(", "string", "$", "identifier", ")", ":", "Entity", "\\", "StandardIdentity", "{", "$", "identity", "=", "new", "Entity", "\\", "StandardIdentity", ";", "$", "identity", "->", "setIdentifier", "(", "$", "identifier", ")", ";", "$", "this", "->", "repository", "->", "load", "(", "$", "identity", ")", ";", "if", "(", "$", "identity", "->", "getId", "(", ")", "===", "null", ")", "{", "$", "this", "->", "logger", "->", "notice", "(", "'identity not found'", ",", "[", "'input'", "=>", "[", "'identifier'", "=>", "$", "identifier", ",", "]", ",", "]", ")", ";", "throw", "new", "IdentityNotFound", ";", "}", "return", "$", "identity", ";", "}" ]
Locates identity based on email address @throws IdentityNotFound if identity was not found
[ "Locates", "identity", "based", "on", "email", "address" ]
0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8
https://github.com/teresko/palladium/blob/0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8/src/Palladium/Service/Search.php#L64-L82
222,819
chillerlan/php-database
src/Drivers/MySQLiDrv.php
MySQLiDrv.getReferences
protected function getReferences(array $row){ $references = []; $types = []; foreach($row as &$field){ $type = gettype($field); if($type === 'integer'){ $types[] = 'i'; } elseif($type === 'double'){ $types[] = 'd'; } else{ $types[] = 's'; } $references[] = &$field; } array_unshift($references, implode('', $types)); return $references; }
php
protected function getReferences(array $row){ $references = []; $types = []; foreach($row as &$field){ $type = gettype($field); if($type === 'integer'){ $types[] = 'i'; } elseif($type === 'double'){ $types[] = 'd'; } else{ $types[] = 's'; } $references[] = &$field; } array_unshift($references, implode('', $types)); return $references; }
[ "protected", "function", "getReferences", "(", "array", "$", "row", ")", "{", "$", "references", "=", "[", "]", ";", "$", "types", "=", "[", "]", ";", "foreach", "(", "$", "row", "as", "&", "$", "field", ")", "{", "$", "type", "=", "gettype", "(", "$", "field", ")", ";", "if", "(", "$", "type", "===", "'integer'", ")", "{", "$", "types", "[", "]", "=", "'i'", ";", "}", "elseif", "(", "$", "type", "===", "'double'", ")", "{", "$", "types", "[", "]", "=", "'d'", ";", "}", "else", "{", "$", "types", "[", "]", "=", "'s'", ";", "}", "$", "references", "[", "]", "=", "&", "$", "field", ";", "}", "array_unshift", "(", "$", "references", ",", "implode", "(", "''", ",", "$", "types", ")", ")", ";", "return", "$", "references", ";", "}" ]
Copies an array to an array of referenced values @param array $row @return array @see http://php.net/manual/mysqli-stmt.bind-param.php
[ "Copies", "an", "array", "to", "an", "array", "of", "referenced", "values" ]
e0fd75d8e99875d748e62bfd89be87ea7cea1f5c
https://github.com/chillerlan/php-database/blob/e0fd75d8e99875d748e62bfd89be87ea7cea1f5c/src/Drivers/MySQLiDrv.php#L237-L260
222,820
corneltek/FormKit
src/Widget/BaseWidget.php
BaseWidget.getSerialId
public function getSerialId() { if($this->id) return $this->id; $id = $this->generateSerialId(); $this->setId( $id ); return $id; }
php
public function getSerialId() { if($this->id) return $this->id; $id = $this->generateSerialId(); $this->setId( $id ); return $id; }
[ "public", "function", "getSerialId", "(", ")", "{", "if", "(", "$", "this", "->", "id", ")", "return", "$", "this", "->", "id", ";", "$", "id", "=", "$", "this", "->", "generateSerialId", "(", ")", ";", "$", "this", "->", "setId", "(", "$", "id", ")", ";", "return", "$", "id", ";", "}" ]
Get a new serial id
[ "Get", "a", "new", "serial", "id" ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Widget/BaseWidget.php#L220-L227
222,821
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.find
public static function find($id, array $columns = []) { $model = static::getInstance(); $key = static::getModelKey($id, $model); $query = [ 'ConsistentRead' => true, 'TableName' => $model->getTable(), 'Key' => $key, ]; if ( ! empty( $columns )) { $query['AttributesToGet'] = $columns; } $item = $model->client->getItem($query); $item = array_get($item->toArray(), 'Item'); if (empty( $item )) { return null; } $item = $model->unmarshalItem($item); $model->fill($item); // Set the model id field. $model->setId($id); $model->exists = true; $model->syncOriginal(); return $model; }
php
public static function find($id, array $columns = []) { $model = static::getInstance(); $key = static::getModelKey($id, $model); $query = [ 'ConsistentRead' => true, 'TableName' => $model->getTable(), 'Key' => $key, ]; if ( ! empty( $columns )) { $query['AttributesToGet'] = $columns; } $item = $model->client->getItem($query); $item = array_get($item->toArray(), 'Item'); if (empty( $item )) { return null; } $item = $model->unmarshalItem($item); $model->fill($item); // Set the model id field. $model->setId($id); $model->exists = true; $model->syncOriginal(); return $model; }
[ "public", "static", "function", "find", "(", "$", "id", ",", "array", "$", "columns", "=", "[", "]", ")", "{", "$", "model", "=", "static", "::", "getInstance", "(", ")", ";", "$", "key", "=", "static", "::", "getModelKey", "(", "$", "id", ",", "$", "model", ")", ";", "$", "query", "=", "[", "'ConsistentRead'", "=>", "true", ",", "'TableName'", "=>", "$", "model", "->", "getTable", "(", ")", ",", "'Key'", "=>", "$", "key", ",", "]", ";", "if", "(", "!", "empty", "(", "$", "columns", ")", ")", "{", "$", "query", "[", "'AttributesToGet'", "]", "=", "$", "columns", ";", "}", "$", "item", "=", "$", "model", "->", "client", "->", "getItem", "(", "$", "query", ")", ";", "$", "item", "=", "array_get", "(", "$", "item", "->", "toArray", "(", ")", ",", "'Item'", ")", ";", "if", "(", "empty", "(", "$", "item", ")", ")", "{", "return", "null", ";", "}", "$", "item", "=", "$", "model", "->", "unmarshalItem", "(", "$", "item", ")", ";", "$", "model", "->", "fill", "(", "$", "item", ")", ";", "// Set the model id field.", "$", "model", "->", "setId", "(", "$", "id", ")", ";", "$", "model", "->", "exists", "=", "true", ";", "$", "model", "->", "syncOriginal", "(", ")", ";", "return", "$", "model", ";", "}" ]
Find a record. @param mixed $id The id to find. @param array $columns List of columns to get. @return DynamoDbModel|null The model, or null if nothing found.
[ "Find", "a", "record", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L247-L272
222,822
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.first
public static function first($columns = []) { $model = static::getInstance(); $item = $model->getAll($columns, 1); return $item->first(); }
php
public static function first($columns = []) { $model = static::getInstance(); $item = $model->getAll($columns, 1); return $item->first(); }
[ "public", "static", "function", "first", "(", "$", "columns", "=", "[", "]", ")", "{", "$", "model", "=", "static", "::", "getInstance", "(", ")", ";", "$", "item", "=", "$", "model", "->", "getAll", "(", "$", "columns", ",", "1", ")", ";", "return", "$", "item", "->", "first", "(", ")", ";", "}" ]
Return the first result. @param array $columns Columns to get. @return mixed
[ "Return", "the", "first", "result", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L296-L302
222,823
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.where
public static function where($column, $operator = null, $value = null, $boolean = 'and') { if ($boolean !== 'and') { throw new NotSupportedException('Only support "and" in where clause'); } $model = static::getInstance(); // If the column is an array, we will assume it is an array of key-value pairs // and can add them each as a where clause. We will maintain the boolean we // received when the method was called and pass it into the nested where. if (is_array($column)) { foreach ($column as $key => $value) { $model->addWhere($key, '=', $value, $boolean); } return $model; } $model->addWhere($column, $operator, $value, $boolean); return $model; }
php
public static function where($column, $operator = null, $value = null, $boolean = 'and') { if ($boolean !== 'and') { throw new NotSupportedException('Only support "and" in where clause'); } $model = static::getInstance(); // If the column is an array, we will assume it is an array of key-value pairs // and can add them each as a where clause. We will maintain the boolean we // received when the method was called and pass it into the nested where. if (is_array($column)) { foreach ($column as $key => $value) { $model->addWhere($key, '=', $value, $boolean); } return $model; } $model->addWhere($column, $operator, $value, $boolean); return $model; }
[ "public", "static", "function", "where", "(", "$", "column", ",", "$", "operator", "=", "null", ",", "$", "value", "=", "null", ",", "$", "boolean", "=", "'and'", ")", "{", "if", "(", "$", "boolean", "!==", "'and'", ")", "{", "throw", "new", "NotSupportedException", "(", "'Only support \"and\" in where clause'", ")", ";", "}", "$", "model", "=", "static", "::", "getInstance", "(", ")", ";", "// If the column is an array, we will assume it is an array of key-value pairs", "// and can add them each as a where clause. We will maintain the boolean we", "// received when the method was called and pass it into the nested where.", "if", "(", "is_array", "(", "$", "column", ")", ")", "{", "foreach", "(", "$", "column", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "model", "->", "addWhere", "(", "$", "key", ",", "'='", ",", "$", "value", ",", "$", "boolean", ")", ";", "}", "return", "$", "model", ";", "}", "$", "model", "->", "addWhere", "(", "$", "column", ",", "$", "operator", ",", "$", "value", ",", "$", "boolean", ")", ";", "return", "$", "model", ";", "}" ]
Static where function, adds where conditions to the model. @param string|array $column @param string|null $operator @param string|null $value @param string $boolean @return DynamoDbModel @throws NotSupportedException
[ "Static", "where", "function", "adds", "where", "conditions", "to", "the", "model", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L315-L335
222,824
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.sort
public function sort($direction) { if (strtolower($direction) === self::DIRECTION_DESC) { $this->scanIndexForward = false; } else { $this->scanIndexForward = true; } }
php
public function sort($direction) { if (strtolower($direction) === self::DIRECTION_DESC) { $this->scanIndexForward = false; } else { $this->scanIndexForward = true; } }
[ "public", "function", "sort", "(", "$", "direction", ")", "{", "if", "(", "strtolower", "(", "$", "direction", ")", "===", "self", "::", "DIRECTION_DESC", ")", "{", "$", "this", "->", "scanIndexForward", "=", "false", ";", "}", "else", "{", "$", "this", "->", "scanIndexForward", "=", "true", ";", "}", "}" ]
Set the sort order for the current search query. @param string $direction The direction to sort.
[ "Set", "the", "sort", "order", "for", "the", "current", "search", "query", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L395-L402
222,825
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.getAll
protected function getAll(array $columns = [], $limit = - 1) { $query = [ 'TableName' => $this->getTable(), ]; $op = 'Scan'; if ($limit > - 1) { $query['limit'] = $limit; } if ( ! empty( $columns )) { $query['AttributesToGet'] = $columns; } // If the $where is not empty, we run getIterator. if ( ! empty( $this->where )) { // Primary key or index key condition exists, then use Query instead of Scan. // However, Query only supports a few conditions. if ($key = $this->conditionsContainIndexKey()) { $condition = array_get($this->where, "$key.ComparisonOperator"); if (ComparisonOperator::isValidQueryDynamoDbOperator($condition)) { $op = 'Query'; $query['IndexName'] = $this->dynamoDbIndexKeys[$key]; $query['KeyConditions'] = $this->where; } } $query['ScanFilter'] = $this->where; } // Sorting. $query['ScanIndexForward'] = $this->scanIndexForward; $iterator = $this->client->getIterator($op, $query); $results = []; foreach ($iterator as $item) { $item = $this->unmarshalItem($item); $model = new static($item, static::$dynamoDb); $model->setUnfillableAttributes($item); $model->exists = true; $model->syncOriginal(); $results[] = $model; } return new Collection($results); }
php
protected function getAll(array $columns = [], $limit = - 1) { $query = [ 'TableName' => $this->getTable(), ]; $op = 'Scan'; if ($limit > - 1) { $query['limit'] = $limit; } if ( ! empty( $columns )) { $query['AttributesToGet'] = $columns; } // If the $where is not empty, we run getIterator. if ( ! empty( $this->where )) { // Primary key or index key condition exists, then use Query instead of Scan. // However, Query only supports a few conditions. if ($key = $this->conditionsContainIndexKey()) { $condition = array_get($this->where, "$key.ComparisonOperator"); if (ComparisonOperator::isValidQueryDynamoDbOperator($condition)) { $op = 'Query'; $query['IndexName'] = $this->dynamoDbIndexKeys[$key]; $query['KeyConditions'] = $this->where; } } $query['ScanFilter'] = $this->where; } // Sorting. $query['ScanIndexForward'] = $this->scanIndexForward; $iterator = $this->client->getIterator($op, $query); $results = []; foreach ($iterator as $item) { $item = $this->unmarshalItem($item); $model = new static($item, static::$dynamoDb); $model->setUnfillableAttributes($item); $model->exists = true; $model->syncOriginal(); $results[] = $model; } return new Collection($results); }
[ "protected", "function", "getAll", "(", "array", "$", "columns", "=", "[", "]", ",", "$", "limit", "=", "-", "1", ")", "{", "$", "query", "=", "[", "'TableName'", "=>", "$", "this", "->", "getTable", "(", ")", ",", "]", ";", "$", "op", "=", "'Scan'", ";", "if", "(", "$", "limit", ">", "-", "1", ")", "{", "$", "query", "[", "'limit'", "]", "=", "$", "limit", ";", "}", "if", "(", "!", "empty", "(", "$", "columns", ")", ")", "{", "$", "query", "[", "'AttributesToGet'", "]", "=", "$", "columns", ";", "}", "// If the $where is not empty, we run getIterator.", "if", "(", "!", "empty", "(", "$", "this", "->", "where", ")", ")", "{", "// Primary key or index key condition exists, then use Query instead of Scan.", "// However, Query only supports a few conditions.", "if", "(", "$", "key", "=", "$", "this", "->", "conditionsContainIndexKey", "(", ")", ")", "{", "$", "condition", "=", "array_get", "(", "$", "this", "->", "where", ",", "\"$key.ComparisonOperator\"", ")", ";", "if", "(", "ComparisonOperator", "::", "isValidQueryDynamoDbOperator", "(", "$", "condition", ")", ")", "{", "$", "op", "=", "'Query'", ";", "$", "query", "[", "'IndexName'", "]", "=", "$", "this", "->", "dynamoDbIndexKeys", "[", "$", "key", "]", ";", "$", "query", "[", "'KeyConditions'", "]", "=", "$", "this", "->", "where", ";", "}", "}", "$", "query", "[", "'ScanFilter'", "]", "=", "$", "this", "->", "where", ";", "}", "// Sorting.", "$", "query", "[", "'ScanIndexForward'", "]", "=", "$", "this", "->", "scanIndexForward", ";", "$", "iterator", "=", "$", "this", "->", "client", "->", "getIterator", "(", "$", "op", ",", "$", "query", ")", ";", "$", "results", "=", "[", "]", ";", "foreach", "(", "$", "iterator", "as", "$", "item", ")", "{", "$", "item", "=", "$", "this", "->", "unmarshalItem", "(", "$", "item", ")", ";", "$", "model", "=", "new", "static", "(", "$", "item", ",", "static", "::", "$", "dynamoDb", ")", ";", "$", "model", "->", "setUnfillableAttributes", "(", "$", "item", ")", ";", "$", "model", "->", "exists", "=", "true", ";", "$", "model", "->", "syncOriginal", "(", ")", ";", "$", "results", "[", "]", "=", "$", "model", ";", "}", "return", "new", "Collection", "(", "$", "results", ")", ";", "}" ]
Gets all values for given columns. @param array $columns List of columns to get. @param int $limit Limit the result. @return Collection
[ "Gets", "all", "values", "for", "given", "columns", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L424-L467
222,826
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.conditionsContainIndexKey
protected function conditionsContainIndexKey() { if (empty( $this->where )) { return false; } foreach ($this->dynamoDbIndexKeys as $key => $name) { if (isset( $this->where[$key] )) { return $key; } } return false; }
php
protected function conditionsContainIndexKey() { if (empty( $this->where )) { return false; } foreach ($this->dynamoDbIndexKeys as $key => $name) { if (isset( $this->where[$key] )) { return $key; } } return false; }
[ "protected", "function", "conditionsContainIndexKey", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "where", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "this", "->", "dynamoDbIndexKeys", "as", "$", "key", "=>", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "where", "[", "$", "key", "]", ")", ")", "{", "return", "$", "key", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the conditions contains an index key. @return bool|mixed The key if found, false otherwise.
[ "Checks", "if", "the", "conditions", "contains", "an", "index", "key", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L474-L486
222,827
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.getSpecificDynamoDbKey
protected static function getSpecificDynamoDbKey(DynamoDbModel $model, $keyName, $value) { $idKey = $model->marshalItem([ $keyName => $value, ]); return [$keyName => $idKey[$keyName]]; }
php
protected static function getSpecificDynamoDbKey(DynamoDbModel $model, $keyName, $value) { $idKey = $model->marshalItem([ $keyName => $value, ]); return [$keyName => $idKey[$keyName]]; }
[ "protected", "static", "function", "getSpecificDynamoDbKey", "(", "DynamoDbModel", "$", "model", ",", "$", "keyName", ",", "$", "value", ")", "{", "$", "idKey", "=", "$", "model", "->", "marshalItem", "(", "[", "$", "keyName", "=>", "$", "value", ",", "]", ")", ";", "return", "[", "$", "keyName", "=>", "$", "idKey", "[", "$", "keyName", "]", "]", ";", "}" ]
Get a specific DynamoDb key. @param DynamoDbModel $model The DynamoDb model. @param string $keyName The key name. @param string $value The key value. @return array The DynamoDb key, keyName => value.
[ "Get", "a", "specific", "DynamoDb", "key", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L510-L517
222,828
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.getModelKey
protected static function getModelKey($id, DynamoDbModel $model) { if (is_array($id)) { $key = []; foreach ($id as $name => $value) { $specific_key = static::getSpecificDynamoDbKey($model, $name, $value); foreach ($specific_key as $keyName => $keyValue) { $key[$keyName] = $keyValue; } } return $key; } return static::getDynamoDbPrimaryKey($model, $id); }
php
protected static function getModelKey($id, DynamoDbModel $model) { if (is_array($id)) { $key = []; foreach ($id as $name => $value) { $specific_key = static::getSpecificDynamoDbKey($model, $name, $value); foreach ($specific_key as $keyName => $keyValue) { $key[$keyName] = $keyValue; } } return $key; } return static::getDynamoDbPrimaryKey($model, $id); }
[ "protected", "static", "function", "getModelKey", "(", "$", "id", ",", "DynamoDbModel", "$", "model", ")", "{", "if", "(", "is_array", "(", "$", "id", ")", ")", "{", "$", "key", "=", "[", "]", ";", "foreach", "(", "$", "id", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "specific_key", "=", "static", "::", "getSpecificDynamoDbKey", "(", "$", "model", ",", "$", "name", ",", "$", "value", ")", ";", "foreach", "(", "$", "specific_key", "as", "$", "keyName", "=>", "$", "keyValue", ")", "{", "$", "key", "[", "$", "keyName", "]", "=", "$", "keyValue", ";", "}", "}", "return", "$", "key", ";", "}", "return", "static", "::", "getDynamoDbPrimaryKey", "(", "$", "model", ",", "$", "id", ")", ";", "}" ]
Get the key for this model whether composite or simple. @param mixed $id The ID. @param DynamoDbModel $model The DynamoDb model. @return array The DynamoDb key, keyName => value.
[ "Get", "the", "key", "for", "this", "model", "whether", "composite", "or", "simple", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L527-L542
222,829
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.getKeyAsArray
protected function getKeyAsArray() { $result = []; if ( ! empty( $this->compositeKey )) { foreach ($this->compositeKey as $key) { $result[$key] = $this->{$key}; } } else { $result[$this->getKeyName()] = $this->getKey(); } return $result; }
php
protected function getKeyAsArray() { $result = []; if ( ! empty( $this->compositeKey )) { foreach ($this->compositeKey as $key) { $result[$key] = $this->{$key}; } } else { $result[$this->getKeyName()] = $this->getKey(); } return $result; }
[ "protected", "function", "getKeyAsArray", "(", ")", "{", "$", "result", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "compositeKey", ")", ")", "{", "foreach", "(", "$", "this", "->", "compositeKey", "as", "$", "key", ")", "{", "$", "result", "[", "$", "key", "]", "=", "$", "this", "->", "{", "$", "key", "}", ";", "}", "}", "else", "{", "$", "result", "[", "$", "this", "->", "getKeyName", "(", ")", "]", "=", "$", "this", "->", "getKey", "(", ")", ";", "}", "return", "$", "result", ";", "}" ]
Get a key as array. @return array The key, keyName => value.
[ "Get", "a", "key", "as", "array", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L549-L561
222,830
digiaonline/lumen-dynamodb
src/Domain/Model/DynamoDbModel.php
DynamoDbModel.setUnfillableAttributes
protected function setUnfillableAttributes(array $attributes = []) { if ( ! empty( $attributes )) { $keysToFill = array_diff(array_keys($attributes), $this->fillable); foreach ($keysToFill as $key) { $this->setAttribute($key, $attributes[$key]); } } }
php
protected function setUnfillableAttributes(array $attributes = []) { if ( ! empty( $attributes )) { $keysToFill = array_diff(array_keys($attributes), $this->fillable); foreach ($keysToFill as $key) { $this->setAttribute($key, $attributes[$key]); } } }
[ "protected", "function", "setUnfillableAttributes", "(", "array", "$", "attributes", "=", "[", "]", ")", "{", "if", "(", "!", "empty", "(", "$", "attributes", ")", ")", "{", "$", "keysToFill", "=", "array_diff", "(", "array_keys", "(", "$", "attributes", ")", ",", "$", "this", "->", "fillable", ")", ";", "foreach", "(", "$", "keysToFill", "as", "$", "key", ")", "{", "$", "this", "->", "setAttribute", "(", "$", "key", ",", "$", "attributes", "[", "$", "key", "]", ")", ";", "}", "}", "}" ]
Sets the unfillable attributes. @param array $attributes List of attributes.
[ "Sets", "the", "unfillable", "attributes", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Domain/Model/DynamoDbModel.php#L568-L576
222,831
corneltek/FormKit
src/Element.php
Element.setAttributeValue
public function setAttributeValue($name,$arg) { if ( property_exists($this, $name) ) { $this->$name = $arg; } else { $this->_attributes[ $name ] = $arg; } }
php
public function setAttributeValue($name,$arg) { if ( property_exists($this, $name) ) { $this->$name = $arg; } else { $this->_attributes[ $name ] = $arg; } }
[ "public", "function", "setAttributeValue", "(", "$", "name", ",", "$", "arg", ")", "{", "if", "(", "property_exists", "(", "$", "this", ",", "$", "name", ")", ")", "{", "$", "this", "->", "$", "name", "=", "$", "arg", ";", "}", "else", "{", "$", "this", "->", "_attributes", "[", "$", "name", "]", "=", "$", "arg", ";", "}", "}" ]
Check property and set attribute value without type checking. If there is a property with the same name Then the value will be set to the property. Or the value will be stored in $this->_attributes array. This is for internal use. @param string $name @param mixed $arg
[ "Check", "property", "and", "set", "attribute", "value", "without", "type", "checking", "." ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Element.php#L115-L122
222,832
corneltek/FormKit
src/Element.php
Element.setAttribute
public function setAttribute($name,$args) { if ($this->isIgnoredAttribute($name)) { return; } // check if it's registered. if (isset($this->_supportedAttributes[ $name ])) { $c = count($args); $t = $this->_supportedAttributes[ $name ]; if( $t != self::ATTR_FLAG && $c == 0 ) { throw new Exception( 'Attribute value is required.' ); } switch( $t ) { case self::ATTR_ANY: $this->setAttributeValue( $name, $args[0] ); break; case self::ATTR_ARRAY: if( $c > 1 ) { $this->setAttributeValue( $name, $args ); } elseif( is_array($args[0]) ) { $this->setAttributeValue( $name , $args[0] ); } else { $this->setAttributeValue( $name , (array) $args[0] ); } break; case self::ATTR_STRING: if( is_string($args[0]) ) { $this->setAttributeValue($name,$args[0]); } else { throw new Exception("attribute value of $name is not a string."); } break; case self::ATTR_INTEGER: if( is_integer($args[0])) { $this->setAttributeValue( $name , $args[0] ); } else { throw new Exception("attribute value of $name is not a integer."); } break; case self::ATTR_CALLABLE: /** * handle for __invoke, array($obj,$name), 'function_name */ if( is_callable($args[0]) ) { $this->setAttributeValue( $name, $args[0] ); } else { throw new Exception("attribute value of $name is not callable type."); } break; case self::ATTR_FLAG: $this->setAttributeValue($name,true); break; default: throw new Exception("Unsupported attribute type: $name"); } return $this; } // save unknown attribute by default else if( $this->allowUndefinedAttribute ) { $this->setAttributeValue( $name, $args[0] ); } else { throw new Exception("Undefined attribute $name, Do you want to use allowUndefinedAttribute option?"); } }
php
public function setAttribute($name,$args) { if ($this->isIgnoredAttribute($name)) { return; } // check if it's registered. if (isset($this->_supportedAttributes[ $name ])) { $c = count($args); $t = $this->_supportedAttributes[ $name ]; if( $t != self::ATTR_FLAG && $c == 0 ) { throw new Exception( 'Attribute value is required.' ); } switch( $t ) { case self::ATTR_ANY: $this->setAttributeValue( $name, $args[0] ); break; case self::ATTR_ARRAY: if( $c > 1 ) { $this->setAttributeValue( $name, $args ); } elseif( is_array($args[0]) ) { $this->setAttributeValue( $name , $args[0] ); } else { $this->setAttributeValue( $name , (array) $args[0] ); } break; case self::ATTR_STRING: if( is_string($args[0]) ) { $this->setAttributeValue($name,$args[0]); } else { throw new Exception("attribute value of $name is not a string."); } break; case self::ATTR_INTEGER: if( is_integer($args[0])) { $this->setAttributeValue( $name , $args[0] ); } else { throw new Exception("attribute value of $name is not a integer."); } break; case self::ATTR_CALLABLE: /** * handle for __invoke, array($obj,$name), 'function_name */ if( is_callable($args[0]) ) { $this->setAttributeValue( $name, $args[0] ); } else { throw new Exception("attribute value of $name is not callable type."); } break; case self::ATTR_FLAG: $this->setAttributeValue($name,true); break; default: throw new Exception("Unsupported attribute type: $name"); } return $this; } // save unknown attribute by default else if( $this->allowUndefinedAttribute ) { $this->setAttributeValue( $name, $args[0] ); } else { throw new Exception("Undefined attribute $name, Do you want to use allowUndefinedAttribute option?"); } }
[ "public", "function", "setAttribute", "(", "$", "name", ",", "$", "args", ")", "{", "if", "(", "$", "this", "->", "isIgnoredAttribute", "(", "$", "name", ")", ")", "{", "return", ";", "}", "// check if it's registered.", "if", "(", "isset", "(", "$", "this", "->", "_supportedAttributes", "[", "$", "name", "]", ")", ")", "{", "$", "c", "=", "count", "(", "$", "args", ")", ";", "$", "t", "=", "$", "this", "->", "_supportedAttributes", "[", "$", "name", "]", ";", "if", "(", "$", "t", "!=", "self", "::", "ATTR_FLAG", "&&", "$", "c", "==", "0", ")", "{", "throw", "new", "Exception", "(", "'Attribute value is required.'", ")", ";", "}", "switch", "(", "$", "t", ")", "{", "case", "self", "::", "ATTR_ANY", ":", "$", "this", "->", "setAttributeValue", "(", "$", "name", ",", "$", "args", "[", "0", "]", ")", ";", "break", ";", "case", "self", "::", "ATTR_ARRAY", ":", "if", "(", "$", "c", ">", "1", ")", "{", "$", "this", "->", "setAttributeValue", "(", "$", "name", ",", "$", "args", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "args", "[", "0", "]", ")", ")", "{", "$", "this", "->", "setAttributeValue", "(", "$", "name", ",", "$", "args", "[", "0", "]", ")", ";", "}", "else", "{", "$", "this", "->", "setAttributeValue", "(", "$", "name", ",", "(", "array", ")", "$", "args", "[", "0", "]", ")", ";", "}", "break", ";", "case", "self", "::", "ATTR_STRING", ":", "if", "(", "is_string", "(", "$", "args", "[", "0", "]", ")", ")", "{", "$", "this", "->", "setAttributeValue", "(", "$", "name", ",", "$", "args", "[", "0", "]", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"attribute value of $name is not a string.\"", ")", ";", "}", "break", ";", "case", "self", "::", "ATTR_INTEGER", ":", "if", "(", "is_integer", "(", "$", "args", "[", "0", "]", ")", ")", "{", "$", "this", "->", "setAttributeValue", "(", "$", "name", ",", "$", "args", "[", "0", "]", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"attribute value of $name is not a integer.\"", ")", ";", "}", "break", ";", "case", "self", "::", "ATTR_CALLABLE", ":", "/**\n * handle for __invoke, array($obj,$name), 'function_name \n */", "if", "(", "is_callable", "(", "$", "args", "[", "0", "]", ")", ")", "{", "$", "this", "->", "setAttributeValue", "(", "$", "name", ",", "$", "args", "[", "0", "]", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"attribute value of $name is not callable type.\"", ")", ";", "}", "break", ";", "case", "self", "::", "ATTR_FLAG", ":", "$", "this", "->", "setAttributeValue", "(", "$", "name", ",", "true", ")", ";", "break", ";", "default", ":", "throw", "new", "Exception", "(", "\"Unsupported attribute type: $name\"", ")", ";", "}", "return", "$", "this", ";", "}", "// save unknown attribute by default", "else", "if", "(", "$", "this", "->", "allowUndefinedAttribute", ")", "{", "$", "this", "->", "setAttributeValue", "(", "$", "name", ",", "$", "args", "[", "0", "]", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"Undefined attribute $name, Do you want to use allowUndefinedAttribute option?\"", ")", ";", "}", "}" ]
Check if the attribute is registered if it's registered, the type registered will change the behavior of setting values. @param string $name @param array $args
[ "Check", "if", "the", "attribute", "is", "registered", "if", "it", "s", "registered", "the", "type", "registered", "will", "change", "the", "behavior", "of", "setting", "values", "." ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Element.php#L144-L227
222,833
corneltek/FormKit
src/Element.php
Element.registerCustomAttributes
public function registerCustomAttributes($attributes) { if( is_string($attributes) ) { $attributes = explode(' ',$attributes); } $this->customAttributes = array_merge( $this->customAttributes , (array) $attributes ); return $this; }
php
public function registerCustomAttributes($attributes) { if( is_string($attributes) ) { $attributes = explode(' ',$attributes); } $this->customAttributes = array_merge( $this->customAttributes , (array) $attributes ); return $this; }
[ "public", "function", "registerCustomAttributes", "(", "$", "attributes", ")", "{", "if", "(", "is_string", "(", "$", "attributes", ")", ")", "{", "$", "attributes", "=", "explode", "(", "' '", ",", "$", "attributes", ")", ";", "}", "$", "this", "->", "customAttributes", "=", "array_merge", "(", "$", "this", "->", "customAttributes", ",", "(", "array", ")", "$", "attributes", ")", ";", "return", "$", "this", ";", "}" ]
Add attribute to customAttribute list @param string|array $attributes $this->addAttributes('id class for');
[ "Add", "attribute", "to", "customAttribute", "list" ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Element.php#L370-L377
222,834
corneltek/FormKit
src/Element.php
Element.setAttributes
public function setAttributes($attributes) { foreach ($attributes as $k => $val) { if ($this->isIgnoredAttribute($k)) { continue; } // this is for adding new class name with // +=newClass if( is_string($val) && strpos($val ,'+=') !== false ) { $origValue = $this->getAttributeValue($k); if( is_string($origValue) ) { $origValue .= ' ' . substr($val,2); } elseif ( is_array($origValue) ) { $origValue[] = substr($val,2); } elseif ( is_object($origValue) ) { throw new Exception('Invalid Object for attribute: ' . get_class($origValue) ); } else { throw new Exception('Unknown attribute value type.'); } $this->setAttributeValue($k,$origValue); } else { $this->setAttributeValue($k, $val); } } }
php
public function setAttributes($attributes) { foreach ($attributes as $k => $val) { if ($this->isIgnoredAttribute($k)) { continue; } // this is for adding new class name with // +=newClass if( is_string($val) && strpos($val ,'+=') !== false ) { $origValue = $this->getAttributeValue($k); if( is_string($origValue) ) { $origValue .= ' ' . substr($val,2); } elseif ( is_array($origValue) ) { $origValue[] = substr($val,2); } elseif ( is_object($origValue) ) { throw new Exception('Invalid Object for attribute: ' . get_class($origValue) ); } else { throw new Exception('Unknown attribute value type.'); } $this->setAttributeValue($k,$origValue); } else { $this->setAttributeValue($k, $val); } } }
[ "public", "function", "setAttributes", "(", "$", "attributes", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "k", "=>", "$", "val", ")", "{", "if", "(", "$", "this", "->", "isIgnoredAttribute", "(", "$", "k", ")", ")", "{", "continue", ";", "}", "// this is for adding new class name with", "// +=newClass", "if", "(", "is_string", "(", "$", "val", ")", "&&", "strpos", "(", "$", "val", ",", "'+='", ")", "!==", "false", ")", "{", "$", "origValue", "=", "$", "this", "->", "getAttributeValue", "(", "$", "k", ")", ";", "if", "(", "is_string", "(", "$", "origValue", ")", ")", "{", "$", "origValue", ".=", "' '", ".", "substr", "(", "$", "val", ",", "2", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "origValue", ")", ")", "{", "$", "origValue", "[", "]", "=", "substr", "(", "$", "val", ",", "2", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "origValue", ")", ")", "{", "throw", "new", "Exception", "(", "'Invalid Object for attribute: '", ".", "get_class", "(", "$", "origValue", ")", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "'Unknown attribute value type.'", ")", ";", "}", "$", "this", "->", "setAttributeValue", "(", "$", "k", ",", "$", "origValue", ")", ";", "}", "else", "{", "$", "this", "->", "setAttributeValue", "(", "$", "k", ",", "$", "val", ")", ";", "}", "}", "}" ]
Set attributes from array @param array $attributes
[ "Set", "attributes", "from", "array" ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Element.php#L586-L613
222,835
corneltek/FormKit
src/Element.php
Element.renderAttributes
public function renderAttributes() { return $this->_renderAttributes($this->standardAttributes) . $this->_renderAttributes($this->customAttributes) . $this->_renderAttributes(array_keys($this->_attributes)); }
php
public function renderAttributes() { return $this->_renderAttributes($this->standardAttributes) . $this->_renderAttributes($this->customAttributes) . $this->_renderAttributes(array_keys($this->_attributes)); }
[ "public", "function", "renderAttributes", "(", ")", "{", "return", "$", "this", "->", "_renderAttributes", "(", "$", "this", "->", "standardAttributes", ")", ".", "$", "this", "->", "_renderAttributes", "(", "$", "this", "->", "customAttributes", ")", ".", "$", "this", "->", "_renderAttributes", "(", "array_keys", "(", "$", "this", "->", "_attributes", ")", ")", ";", "}" ]
Render attributes string @return string Standard Attribute string
[ "Render", "attributes", "string" ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Element.php#L620-L625
222,836
corneltek/FormKit
src/Element.php
Element.open
public function open( $attributes = array() ) { $this->setAttributes( $attributes ); $html = '<' . $this->tagName . $this->renderAttributes() ; // should we close it ? if( $this->closeEmpty || $this->hasChildren() ) { $html .= '>'; } else { $html .= '/>'; } return $html; }
php
public function open( $attributes = array() ) { $this->setAttributes( $attributes ); $html = '<' . $this->tagName . $this->renderAttributes() ; // should we close it ? if( $this->closeEmpty || $this->hasChildren() ) { $html .= '>'; } else { $html .= '/>'; } return $html; }
[ "public", "function", "open", "(", "$", "attributes", "=", "array", "(", ")", ")", "{", "$", "this", "->", "setAttributes", "(", "$", "attributes", ")", ";", "$", "html", "=", "'<'", ".", "$", "this", "->", "tagName", ".", "$", "this", "->", "renderAttributes", "(", ")", ";", "// should we close it ?", "if", "(", "$", "this", "->", "closeEmpty", "||", "$", "this", "->", "hasChildren", "(", ")", ")", "{", "$", "html", ".=", "'>'", ";", "}", "else", "{", "$", "html", ".=", "'/>'", ";", "}", "return", "$", "html", ";", "}" ]
Render open tag $form->open(); $form->renderChildren(); $form->close();
[ "Render", "open", "tag" ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Element.php#L699-L711
222,837
corneltek/FormKit
src/Element.php
Element.close
public function close() { $html = ''; if( $this->closeEmpty || $this->hasChildren() ) { $html .= '</' . $this->tagName . '>'; } return $html; }
php
public function close() { $html = ''; if( $this->closeEmpty || $this->hasChildren() ) { $html .= '</' . $this->tagName . '>'; } return $html; }
[ "public", "function", "close", "(", ")", "{", "$", "html", "=", "''", ";", "if", "(", "$", "this", "->", "closeEmpty", "||", "$", "this", "->", "hasChildren", "(", ")", ")", "{", "$", "html", ".=", "'</'", ".", "$", "this", "->", "tagName", ".", "'>'", ";", "}", "return", "$", "html", ";", "}" ]
Render close tag
[ "Render", "close", "tag" ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Element.php#L717-L723
222,838
corneltek/FormKit
src/Element.php
Element.render
public function render( $attributes = array() ) { if( ! $this->tagName ) { throw new Exception('tagName is not defined.'); } $html = $this->open( $attributes ); // render close tag if( $this->hasChildren() ) { $html .= $this->renderChildren(); } $html .= $this->close(); return $html; }
php
public function render( $attributes = array() ) { if( ! $this->tagName ) { throw new Exception('tagName is not defined.'); } $html = $this->open( $attributes ); // render close tag if( $this->hasChildren() ) { $html .= $this->renderChildren(); } $html .= $this->close(); return $html; }
[ "public", "function", "render", "(", "$", "attributes", "=", "array", "(", ")", ")", "{", "if", "(", "!", "$", "this", "->", "tagName", ")", "{", "throw", "new", "Exception", "(", "'tagName is not defined.'", ")", ";", "}", "$", "html", "=", "$", "this", "->", "open", "(", "$", "attributes", ")", ";", "// render close tag", "if", "(", "$", "this", "->", "hasChildren", "(", ")", ")", "{", "$", "html", ".=", "$", "this", "->", "renderChildren", "(", ")", ";", "}", "$", "html", ".=", "$", "this", "->", "close", "(", ")", ";", "return", "$", "html", ";", "}" ]
Render the whole element. @param array $attributes attributes to override. @param string HTML
[ "Render", "the", "whole", "element", "." ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Element.php#L732-L747
222,839
rikbruil/Doctrine-Specification
spec/SpecificationRepositorySpec.php
SpecificationRepositorySpec.prepare
private function prepare( SpecificationInterface $specification, EntityManager $entityManager, QueryBuilder $queryBuilder, AbstractQuery $query ) { $entityManager->createQueryBuilder()->willReturn($queryBuilder); $specification->modify($queryBuilder, $this->dqlAlias)->willReturn($this->expression); $queryBuilder->select($this->dqlAlias)->willreturn($queryBuilder); $queryBuilder->from(Argument::any(), $this->dqlAlias, Argument::any())->willReturn($queryBuilder); $queryBuilder->where($this->expression)->willReturn($queryBuilder); $queryBuilder->getQuery()->willReturn($query); $query->execute()->willReturn($this->result); }
php
private function prepare( SpecificationInterface $specification, EntityManager $entityManager, QueryBuilder $queryBuilder, AbstractQuery $query ) { $entityManager->createQueryBuilder()->willReturn($queryBuilder); $specification->modify($queryBuilder, $this->dqlAlias)->willReturn($this->expression); $queryBuilder->select($this->dqlAlias)->willreturn($queryBuilder); $queryBuilder->from(Argument::any(), $this->dqlAlias, Argument::any())->willReturn($queryBuilder); $queryBuilder->where($this->expression)->willReturn($queryBuilder); $queryBuilder->getQuery()->willReturn($query); $query->execute()->willReturn($this->result); }
[ "private", "function", "prepare", "(", "SpecificationInterface", "$", "specification", ",", "EntityManager", "$", "entityManager", ",", "QueryBuilder", "$", "queryBuilder", ",", "AbstractQuery", "$", "query", ")", "{", "$", "entityManager", "->", "createQueryBuilder", "(", ")", "->", "willReturn", "(", "$", "queryBuilder", ")", ";", "$", "specification", "->", "modify", "(", "$", "queryBuilder", ",", "$", "this", "->", "dqlAlias", ")", "->", "willReturn", "(", "$", "this", "->", "expression", ")", ";", "$", "queryBuilder", "->", "select", "(", "$", "this", "->", "dqlAlias", ")", "->", "willreturn", "(", "$", "queryBuilder", ")", ";", "$", "queryBuilder", "->", "from", "(", "Argument", "::", "any", "(", ")", ",", "$", "this", "->", "dqlAlias", ",", "Argument", "::", "any", "(", ")", ")", "->", "willReturn", "(", "$", "queryBuilder", ")", ";", "$", "queryBuilder", "->", "where", "(", "$", "this", "->", "expression", ")", "->", "willReturn", "(", "$", "queryBuilder", ")", ";", "$", "queryBuilder", "->", "getQuery", "(", ")", "->", "willReturn", "(", "$", "query", ")", ";", "$", "query", "->", "execute", "(", ")", "->", "willReturn", "(", "$", "this", "->", "result", ")", ";", "}" ]
Prepare mocks. @param SpecificationInterface $specification @param EntityManager $entityManager @param QueryBuilder $queryBuilder @param AbstractQuery $query
[ "Prepare", "mocks", "." ]
e61fb801c46107b0a9ce22086448557def7fa532
https://github.com/rikbruil/Doctrine-Specification/blob/e61fb801c46107b0a9ce22086448557def7fa532/spec/SpecificationRepositorySpec.php#L113-L130
222,840
teresko/palladium
src/Palladium/Service/Identification.php
Identification.checkCookieKey
private function checkCookieKey(Entity\CookieIdentity $identity, string $key) { if ($identity->matchKey($key) === true) { return; } $this->changeIdentityStatus($identity, Entity\Identity::STATUS_BLOCKED); $this->logger->warning('compromised cookie', $this->assembleCookieLogDetails($identity)); throw new CompromisedCookie; }
php
private function checkCookieKey(Entity\CookieIdentity $identity, string $key) { if ($identity->matchKey($key) === true) { return; } $this->changeIdentityStatus($identity, Entity\Identity::STATUS_BLOCKED); $this->logger->warning('compromised cookie', $this->assembleCookieLogDetails($identity)); throw new CompromisedCookie; }
[ "private", "function", "checkCookieKey", "(", "Entity", "\\", "CookieIdentity", "$", "identity", ",", "string", "$", "key", ")", "{", "if", "(", "$", "identity", "->", "matchKey", "(", "$", "key", ")", "===", "true", ")", "{", "return", ";", "}", "$", "this", "->", "changeIdentityStatus", "(", "$", "identity", ",", "Entity", "\\", "Identity", "::", "STATUS_BLOCKED", ")", ";", "$", "this", "->", "logger", "->", "warning", "(", "'compromised cookie'", ",", "$", "this", "->", "assembleCookieLogDetails", "(", "$", "identity", ")", ")", ";", "throw", "new", "CompromisedCookie", ";", "}" ]
Verify that the cookie based identity matches the key and, if verification is failed, disable this given identity @throws \Palladium\Exception\CompromisedCookie if key does not match
[ "Verify", "that", "the", "cookie", "based", "identity", "matches", "the", "key", "and", "if", "verification", "is", "failed", "disable", "this", "given", "identity" ]
0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8
https://github.com/teresko/palladium/blob/0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8/src/Palladium/Service/Identification.php#L182-L192
222,841
teresko/palladium
src/Palladium/Component/Collection.php
Collection.addBlueprint
public function addBlueprint(array $parameters) { $instance = $this->buildEntity(); $this->populateEntity($instance, $parameters); $this->addEntity($instance); return $instance; }
php
public function addBlueprint(array $parameters) { $instance = $this->buildEntity(); $this->populateEntity($instance, $parameters); $this->addEntity($instance); return $instance; }
[ "public", "function", "addBlueprint", "(", "array", "$", "parameters", ")", "{", "$", "instance", "=", "$", "this", "->", "buildEntity", "(", ")", ";", "$", "this", "->", "populateEntity", "(", "$", "instance", ",", "$", "parameters", ")", ";", "$", "this", "->", "addEntity", "(", "$", "instance", ")", ";", "return", "$", "instance", ";", "}" ]
Add new domain entity, that is constructed using array as values. Each array key will be attempted top match with entity's setter method and provided with the respective array value. It returns the newly created entity. @param array $parameters @return HasId
[ "Add", "new", "domain", "entity", "that", "is", "constructed", "using", "array", "as", "values", ".", "Each", "array", "key", "will", "be", "attempted", "top", "match", "with", "entity", "s", "setter", "method", "and", "provided", "with", "the", "respective", "array", "value", ".", "It", "returns", "the", "newly", "created", "entity", "." ]
0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8
https://github.com/teresko/palladium/blob/0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8/src/Palladium/Component/Collection.php#L41-L49
222,842
teresko/palladium
src/Palladium/Component/Collection.php
Collection.populateEntity
private function populateEntity($instance, array $parameters) { foreach ($parameters as $key => $value) { $method = 'set' . str_replace('_', '', $key); if (method_exists($instance, $method)) { $instance->{$method}($value); } } }
php
private function populateEntity($instance, array $parameters) { foreach ($parameters as $key => $value) { $method = 'set' . str_replace('_', '', $key); if (method_exists($instance, $method)) { $instance->{$method}($value); } } }
[ "private", "function", "populateEntity", "(", "$", "instance", ",", "array", "$", "parameters", ")", "{", "foreach", "(", "$", "parameters", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "method", "=", "'set'", ".", "str_replace", "(", "'_'", ",", "''", ",", "$", "key", ")", ";", "if", "(", "method_exists", "(", "$", "instance", ",", "$", "method", ")", ")", "{", "$", "instance", "->", "{", "$", "method", "}", "(", "$", "value", ")", ";", "}", "}", "}" ]
code that does the actual population of data from the given array in blueprint
[ "code", "that", "does", "the", "actual", "population", "of", "data", "from", "the", "given", "array", "in", "blueprint" ]
0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8
https://github.com/teresko/palladium/blob/0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8/src/Palladium/Component/Collection.php#L53-L61
222,843
teresko/palladium
src/Palladium/Component/Collection.php
Collection.addEntity
public function addEntity(HasId $entity, $key = null) { if (is_null($key) === false) { $this->replaceEntity($entity, $key); return; } $entityId = $entity->getId(); $this->pool[] = $entity; $this->indexed[$entityId] = $entity; $this->map[$entityId] = $this->retrieveLastPoolKey(); }
php
public function addEntity(HasId $entity, $key = null) { if (is_null($key) === false) { $this->replaceEntity($entity, $key); return; } $entityId = $entity->getId(); $this->pool[] = $entity; $this->indexed[$entityId] = $entity; $this->map[$entityId] = $this->retrieveLastPoolKey(); }
[ "public", "function", "addEntity", "(", "HasId", "$", "entity", ",", "$", "key", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "key", ")", "===", "false", ")", "{", "$", "this", "->", "replaceEntity", "(", "$", "entity", ",", "$", "key", ")", ";", "return", ";", "}", "$", "entityId", "=", "$", "entity", "->", "getId", "(", ")", ";", "$", "this", "->", "pool", "[", "]", "=", "$", "entity", ";", "$", "this", "->", "indexed", "[", "$", "entityId", "]", "=", "$", "entity", ";", "$", "this", "->", "map", "[", "$", "entityId", "]", "=", "$", "this", "->", "retrieveLastPoolKey", "(", ")", ";", "}" ]
Method for adding already existing domain entity to the collection. @param HasId $entity
[ "Method", "for", "adding", "already", "existing", "domain", "entity", "to", "the", "collection", "." ]
0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8
https://github.com/teresko/palladium/blob/0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8/src/Palladium/Component/Collection.php#L69-L83
222,844
teresko/palladium
src/Palladium/Component/Collection.php
Collection.replaceWith
public function replaceWith(Collection $replacement) { $this->pool = []; $this->map = []; $this->indexed = []; foreach ($replacement as $entity) { $this->addEntity($entity); } }
php
public function replaceWith(Collection $replacement) { $this->pool = []; $this->map = []; $this->indexed = []; foreach ($replacement as $entity) { $this->addEntity($entity); } }
[ "public", "function", "replaceWith", "(", "Collection", "$", "replacement", ")", "{", "$", "this", "->", "pool", "=", "[", "]", ";", "$", "this", "->", "map", "=", "[", "]", ";", "$", "this", "->", "indexed", "=", "[", "]", ";", "foreach", "(", "$", "replacement", "as", "$", "entity", ")", "{", "$", "this", "->", "addEntity", "(", "$", "entity", ")", ";", "}", "}" ]
Replaces all of the domain entities with a content of some other collection @param Collection $replacement
[ "Replaces", "all", "of", "the", "domain", "entities", "with", "a", "content", "of", "some", "other", "collection" ]
0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8
https://github.com/teresko/palladium/blob/0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8/src/Palladium/Component/Collection.php#L140-L149
222,845
teresko/palladium
src/Palladium/Component/Collection.php
Collection.removeEntity
public function removeEntity(HasId $entity) { $key = $entity->getId(); if ($key !== null) { unset($this->pool[$this->map[$key]]); $this->removeIndexEntry($key); } }
php
public function removeEntity(HasId $entity) { $key = $entity->getId(); if ($key !== null) { unset($this->pool[$this->map[$key]]); $this->removeIndexEntry($key); } }
[ "public", "function", "removeEntity", "(", "HasId", "$", "entity", ")", "{", "$", "key", "=", "$", "entity", "->", "getId", "(", ")", ";", "if", "(", "$", "key", "!==", "null", ")", "{", "unset", "(", "$", "this", "->", "pool", "[", "$", "this", "->", "map", "[", "$", "key", "]", "]", ")", ";", "$", "this", "->", "removeIndexEntry", "(", "$", "key", ")", ";", "}", "}" ]
Removes an entity from collection. @param HasId $entity
[ "Removes", "an", "entity", "from", "collection", "." ]
0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8
https://github.com/teresko/palladium/blob/0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8/src/Palladium/Component/Collection.php#L157-L165
222,846
sgpatil/oriquent
src/Sgpatil/Orientdb/Eloquent/Relations/HasOneOrMany.php
HasOneOrMany.saveMany
public function saveMany($models) { // We will collect the edges returned by save() in an Eloquent Database Collection // and return them when done. $edges = new Collection; foreach ($models as $model) { $edges->push($this->save($model, $properties)); } return $edges; }
php
public function saveMany($models) { // We will collect the edges returned by save() in an Eloquent Database Collection // and return them when done. $edges = new Collection; foreach ($models as $model) { $edges->push($this->save($model, $properties)); } return $edges; }
[ "public", "function", "saveMany", "(", "$", "models", ")", "{", "// We will collect the edges returned by save() in an Eloquent Database Collection", "// and return them when done.", "$", "edges", "=", "new", "Collection", ";", "foreach", "(", "$", "models", "as", "$", "model", ")", "{", "$", "edges", "->", "push", "(", "$", "this", "->", "save", "(", "$", "model", ",", "$", "properties", ")", ")", ";", "}", "return", "$", "edges", ";", "}" ]
Attach an array of models to the parent instance. @param array $models @param arra $properties The relationship properties @return array
[ "Attach", "an", "array", "of", "models", "to", "the", "parent", "instance", "." ]
cf0f2ba688496260946f569a20c351e91f287c32
https://github.com/sgpatil/oriquent/blob/cf0f2ba688496260946f569a20c351e91f287c32/src/Sgpatil/Orientdb/Eloquent/Relations/HasOneOrMany.php#L199-L209
222,847
silverstripe/silverstripe-registry
src/RegistryPageController.php
RegistryPageController.QueryLink
public function QueryLink() { $vars = $this->queryVars(); unset($vars['Sort']); unset($vars['Dir']); return Convert::raw2xml($this->Link('RegistryFilterForm') . '?' . http_build_query($vars)); }
php
public function QueryLink() { $vars = $this->queryVars(); unset($vars['Sort']); unset($vars['Dir']); return Convert::raw2xml($this->Link('RegistryFilterForm') . '?' . http_build_query($vars)); }
[ "public", "function", "QueryLink", "(", ")", "{", "$", "vars", "=", "$", "this", "->", "queryVars", "(", ")", ";", "unset", "(", "$", "vars", "[", "'Sort'", "]", ")", ";", "unset", "(", "$", "vars", "[", "'Dir'", "]", ")", ";", "return", "Convert", "::", "raw2xml", "(", "$", "this", "->", "Link", "(", "'RegistryFilterForm'", ")", ".", "'?'", ".", "http_build_query", "(", "$", "vars", ")", ")", ";", "}" ]
Get all search query vars except Sort and Dir, compiled into a query link. This will escape all the variables to avoid XSS. @return string
[ "Get", "all", "search", "query", "vars", "except", "Sort", "and", "Dir", "compiled", "into", "a", "query", "link", ".", "This", "will", "escape", "all", "the", "variables", "to", "avoid", "XSS", "." ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryPageController.php#L55-L62
222,848
silverstripe/silverstripe-registry
src/RegistryPageController.php
RegistryPageController.OppositeDirection
public function OppositeDirection() { // If direction is set, then just reverse it. $direction = $this->request->getVar('Dir'); if ($direction) { if ($direction == 'ASC') { return 'DESC'; } return 'ASC'; } // If the sort column is set, then we're sorting by ASC (default is omitted) if ($this->request->getVar('Sort')) { return 'DESC'; } // Otherwise we're not sorting at all so default to ASC. return 'ASC'; }
php
public function OppositeDirection() { // If direction is set, then just reverse it. $direction = $this->request->getVar('Dir'); if ($direction) { if ($direction == 'ASC') { return 'DESC'; } return 'ASC'; } // If the sort column is set, then we're sorting by ASC (default is omitted) if ($this->request->getVar('Sort')) { return 'DESC'; } // Otherwise we're not sorting at all so default to ASC. return 'ASC'; }
[ "public", "function", "OppositeDirection", "(", ")", "{", "// If direction is set, then just reverse it.", "$", "direction", "=", "$", "this", "->", "request", "->", "getVar", "(", "'Dir'", ")", ";", "if", "(", "$", "direction", ")", "{", "if", "(", "$", "direction", "==", "'ASC'", ")", "{", "return", "'DESC'", ";", "}", "return", "'ASC'", ";", "}", "// If the sort column is set, then we're sorting by ASC (default is omitted)", "if", "(", "$", "this", "->", "request", "->", "getVar", "(", "'Sort'", ")", ")", "{", "return", "'DESC'", ";", "}", "// Otherwise we're not sorting at all so default to ASC.", "return", "'ASC'", ";", "}" ]
Return the opposite direction from the currently sorted column's direction. @return string
[ "Return", "the", "opposite", "direction", "from", "the", "currently", "sorted", "column", "s", "direction", "." ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryPageController.php#L73-L91
222,849
silverstripe/silverstripe-registry
src/RegistryPageController.php
RegistryPageController.canSortBy
public function canSortBy($property) { $canSort = false; $singleton = $this->dataRecord->getDataSingleton(); if ($singleton) { $properties = explode('.', $property); $relationClass = $singleton->getRelationClass($properties[0]); if ($relationClass) { if (count($properties) <= 2 && singleton($relationClass)->hasDatabaseField($properties[1])) { $canSort = true; } } elseif ($singleton instanceof DataObject) { if ($singleton->hasDatabaseField($property)) { $canSort = true; } } } return $canSort; }
php
public function canSortBy($property) { $canSort = false; $singleton = $this->dataRecord->getDataSingleton(); if ($singleton) { $properties = explode('.', $property); $relationClass = $singleton->getRelationClass($properties[0]); if ($relationClass) { if (count($properties) <= 2 && singleton($relationClass)->hasDatabaseField($properties[1])) { $canSort = true; } } elseif ($singleton instanceof DataObject) { if ($singleton->hasDatabaseField($property)) { $canSort = true; } } } return $canSort; }
[ "public", "function", "canSortBy", "(", "$", "property", ")", "{", "$", "canSort", "=", "false", ";", "$", "singleton", "=", "$", "this", "->", "dataRecord", "->", "getDataSingleton", "(", ")", ";", "if", "(", "$", "singleton", ")", "{", "$", "properties", "=", "explode", "(", "'.'", ",", "$", "property", ")", ";", "$", "relationClass", "=", "$", "singleton", "->", "getRelationClass", "(", "$", "properties", "[", "0", "]", ")", ";", "if", "(", "$", "relationClass", ")", "{", "if", "(", "count", "(", "$", "properties", ")", "<=", "2", "&&", "singleton", "(", "$", "relationClass", ")", "->", "hasDatabaseField", "(", "$", "properties", "[", "1", "]", ")", ")", "{", "$", "canSort", "=", "true", ";", "}", "}", "elseif", "(", "$", "singleton", "instanceof", "DataObject", ")", "{", "if", "(", "$", "singleton", "->", "hasDatabaseField", "(", "$", "property", ")", ")", "{", "$", "canSort", "=", "true", ";", "}", "}", "}", "return", "$", "canSort", ";", "}" ]
Loosely check if the record can be sorted by a property @param string $property @return boolean
[ "Loosely", "check", "if", "the", "record", "can", "be", "sorted", "by", "a", "property" ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryPageController.php#L179-L200
222,850
silverstripe/silverstripe-registry
src/RegistryPageController.php
RegistryPageController.Columns
public function Columns($id = null) { $singleton = $this->dataRecord->getDataSingleton(); $columns = $singleton->summaryFields(); $list = ArrayList::create(); $result = null; if ($id) { $result = $this->queryList()->byId($id); } foreach ($columns as $name => $title) { // Check for unwanted parameters if (preg_match('/[()]/', $name)) { throw new RegistryException(_t( 'SilverStripe\\Registry\\RegistryPageController.UNWANTEDCOLUMNPARAMETERS', "Columns do not accept parameters" )); } // Get dot deliniated properties $properties = explode('.', $name); // Increment properties for value $context = $result; foreach ($properties as $property) { if ($context instanceof ViewableData) { $context = $context->obj($property); } } // Check for link $link = null; $useLink = $singleton->config()->get('use_link'); if ($useLink !== false) { if ($result && $result->hasMethod('Link')) { $link = $result->Link(); } } // Format column $list->push(ArrayData::create([ 'Name' => $name, 'Title' => $title, 'Link' => $link, 'Value' => $context, 'CanSort' => $this->canSortBy($name) ])); } return $list; }
php
public function Columns($id = null) { $singleton = $this->dataRecord->getDataSingleton(); $columns = $singleton->summaryFields(); $list = ArrayList::create(); $result = null; if ($id) { $result = $this->queryList()->byId($id); } foreach ($columns as $name => $title) { // Check for unwanted parameters if (preg_match('/[()]/', $name)) { throw new RegistryException(_t( 'SilverStripe\\Registry\\RegistryPageController.UNWANTEDCOLUMNPARAMETERS', "Columns do not accept parameters" )); } // Get dot deliniated properties $properties = explode('.', $name); // Increment properties for value $context = $result; foreach ($properties as $property) { if ($context instanceof ViewableData) { $context = $context->obj($property); } } // Check for link $link = null; $useLink = $singleton->config()->get('use_link'); if ($useLink !== false) { if ($result && $result->hasMethod('Link')) { $link = $result->Link(); } } // Format column $list->push(ArrayData::create([ 'Name' => $name, 'Title' => $title, 'Link' => $link, 'Value' => $context, 'CanSort' => $this->canSortBy($name) ])); } return $list; }
[ "public", "function", "Columns", "(", "$", "id", "=", "null", ")", "{", "$", "singleton", "=", "$", "this", "->", "dataRecord", "->", "getDataSingleton", "(", ")", ";", "$", "columns", "=", "$", "singleton", "->", "summaryFields", "(", ")", ";", "$", "list", "=", "ArrayList", "::", "create", "(", ")", ";", "$", "result", "=", "null", ";", "if", "(", "$", "id", ")", "{", "$", "result", "=", "$", "this", "->", "queryList", "(", ")", "->", "byId", "(", "$", "id", ")", ";", "}", "foreach", "(", "$", "columns", "as", "$", "name", "=>", "$", "title", ")", "{", "// Check for unwanted parameters", "if", "(", "preg_match", "(", "'/[()]/'", ",", "$", "name", ")", ")", "{", "throw", "new", "RegistryException", "(", "_t", "(", "'SilverStripe\\\\Registry\\\\RegistryPageController.UNWANTEDCOLUMNPARAMETERS'", ",", "\"Columns do not accept parameters\"", ")", ")", ";", "}", "// Get dot deliniated properties", "$", "properties", "=", "explode", "(", "'.'", ",", "$", "name", ")", ";", "// Increment properties for value", "$", "context", "=", "$", "result", ";", "foreach", "(", "$", "properties", "as", "$", "property", ")", "{", "if", "(", "$", "context", "instanceof", "ViewableData", ")", "{", "$", "context", "=", "$", "context", "->", "obj", "(", "$", "property", ")", ";", "}", "}", "// Check for link", "$", "link", "=", "null", ";", "$", "useLink", "=", "$", "singleton", "->", "config", "(", ")", "->", "get", "(", "'use_link'", ")", ";", "if", "(", "$", "useLink", "!==", "false", ")", "{", "if", "(", "$", "result", "&&", "$", "result", "->", "hasMethod", "(", "'Link'", ")", ")", "{", "$", "link", "=", "$", "result", "->", "Link", "(", ")", ";", "}", "}", "// Format column", "$", "list", "->", "push", "(", "ArrayData", "::", "create", "(", "[", "'Name'", "=>", "$", "name", ",", "'Title'", "=>", "$", "title", ",", "'Link'", "=>", "$", "link", ",", "'Value'", "=>", "$", "context", ",", "'CanSort'", "=>", "$", "this", "->", "canSortBy", "(", "$", "name", ")", "]", ")", ")", ";", "}", "return", "$", "list", ";", "}" ]
Format a set of columns, used for headings and row data @param int $id The result ID to reference @return ArrayList
[ "Format", "a", "set", "of", "columns", "used", "for", "headings", "and", "row", "data" ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryPageController.php#L207-L257
222,851
silverstripe/silverstripe-registry
src/RegistryPageController.php
RegistryPageController.export
public function export($request) { $dataClass = $this->dataRecord->getDataClass(); $resultColumns = $this->dataRecord->getDataSingleton()->fieldLabels(); // Used for the browser, not stored on the server $filepath = sprintf('export-%s.csv', date('Y-m-dHis')); // Allocates up to 1M of memory storage to write to, then will fail over to a temporary file on the filesystem $handle = fopen('php://temp/maxmemory:' . (1024 * 1024), 'w'); $cols = array_keys($resultColumns); // put the headers in the first row fputcsv($handle, $cols); // put the data in the rows after foreach ($this->RegistryEntries(false) as $result) { $item = []; foreach ($cols as $col) { $item[] = $result->$col; } fputcsv($handle, $item); } rewind($handle); // if the headers can't be sent (i.e. running a unit test, or something) // just return the file path so the user can manually download the csv if (!headers_sent() && $this->config()->get('output_headers')) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $filepath); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . fstat($handle)['size']); ob_clean(); flush(); echo stream_get_contents($handle); fclose($handle); } else { $contents = stream_get_contents($handle); fclose($handle); return $contents; } }
php
public function export($request) { $dataClass = $this->dataRecord->getDataClass(); $resultColumns = $this->dataRecord->getDataSingleton()->fieldLabels(); // Used for the browser, not stored on the server $filepath = sprintf('export-%s.csv', date('Y-m-dHis')); // Allocates up to 1M of memory storage to write to, then will fail over to a temporary file on the filesystem $handle = fopen('php://temp/maxmemory:' . (1024 * 1024), 'w'); $cols = array_keys($resultColumns); // put the headers in the first row fputcsv($handle, $cols); // put the data in the rows after foreach ($this->RegistryEntries(false) as $result) { $item = []; foreach ($cols as $col) { $item[] = $result->$col; } fputcsv($handle, $item); } rewind($handle); // if the headers can't be sent (i.e. running a unit test, or something) // just return the file path so the user can manually download the csv if (!headers_sent() && $this->config()->get('output_headers')) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $filepath); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . fstat($handle)['size']); ob_clean(); flush(); echo stream_get_contents($handle); fclose($handle); } else { $contents = stream_get_contents($handle); fclose($handle); return $contents; } }
[ "public", "function", "export", "(", "$", "request", ")", "{", "$", "dataClass", "=", "$", "this", "->", "dataRecord", "->", "getDataClass", "(", ")", ";", "$", "resultColumns", "=", "$", "this", "->", "dataRecord", "->", "getDataSingleton", "(", ")", "->", "fieldLabels", "(", ")", ";", "// Used for the browser, not stored on the server", "$", "filepath", "=", "sprintf", "(", "'export-%s.csv'", ",", "date", "(", "'Y-m-dHis'", ")", ")", ";", "// Allocates up to 1M of memory storage to write to, then will fail over to a temporary file on the filesystem", "$", "handle", "=", "fopen", "(", "'php://temp/maxmemory:'", ".", "(", "1024", "*", "1024", ")", ",", "'w'", ")", ";", "$", "cols", "=", "array_keys", "(", "$", "resultColumns", ")", ";", "// put the headers in the first row", "fputcsv", "(", "$", "handle", ",", "$", "cols", ")", ";", "// put the data in the rows after", "foreach", "(", "$", "this", "->", "RegistryEntries", "(", "false", ")", "as", "$", "result", ")", "{", "$", "item", "=", "[", "]", ";", "foreach", "(", "$", "cols", "as", "$", "col", ")", "{", "$", "item", "[", "]", "=", "$", "result", "->", "$", "col", ";", "}", "fputcsv", "(", "$", "handle", ",", "$", "item", ")", ";", "}", "rewind", "(", "$", "handle", ")", ";", "// if the headers can't be sent (i.e. running a unit test, or something)", "// just return the file path so the user can manually download the csv", "if", "(", "!", "headers_sent", "(", ")", "&&", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'output_headers'", ")", ")", "{", "header", "(", "'Content-Description: File Transfer'", ")", ";", "header", "(", "'Content-Type: application/octet-stream'", ")", ";", "header", "(", "'Content-Disposition: attachment; filename='", ".", "$", "filepath", ")", ";", "header", "(", "'Content-Transfer-Encoding: binary'", ")", ";", "header", "(", "'Expires: 0'", ")", ";", "header", "(", "'Cache-Control: must-revalidate, post-check=0, pre-check=0'", ")", ";", "header", "(", "'Pragma: public'", ")", ";", "header", "(", "'Content-Length: '", ".", "fstat", "(", "$", "handle", ")", "[", "'size'", "]", ")", ";", "ob_clean", "(", ")", ";", "flush", "(", ")", ";", "echo", "stream_get_contents", "(", "$", "handle", ")", ";", "fclose", "(", "$", "handle", ")", ";", "}", "else", "{", "$", "contents", "=", "stream_get_contents", "(", "$", "handle", ")", ";", "fclose", "(", "$", "handle", ")", ";", "return", "$", "contents", ";", "}", "}" ]
Exports out all the data for the current search results. Sends the data to the browser as a CSV file.
[ "Exports", "out", "all", "the", "data", "for", "the", "current", "search", "results", ".", "Sends", "the", "data", "to", "the", "browser", "as", "a", "CSV", "file", "." ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryPageController.php#L263-L313
222,852
silverstripe/silverstripe-registry
src/RegistryPageController.php
RegistryPageController.queryList
protected function queryList() { // Sanity check $dataClass = $this->dataRecord->getDataClass(); if (!$dataClass) { return ArrayList::create(); } // Setup $singleton = $this->dataRecord->getDataSingleton(); // Create list $list = $singleton->get(); // Setup filters $filters = []; foreach ($singleton->config()->get('searchable_fields') as $field) { $value = $this->getRequest()->getVar(str_replace('.', '_', $field)); if (!$value) { continue; } // if the searchable field is a relationship, it must be an exact match (ID match) if not partial is fine. $matchType = $this->instanceHasRelationship($singleton, $field) ? "ExactMatch" : "PartialMatch"; $filters[$field . ':' . $matchType] = $value; } $list = $list->filter($filters); // Sort $sort = $this->getRequest()->getVar('Sort'); if ($sort) { $dir = 'ASC'; if ($this->getRequest()->getVar('Dir')) { $dir = $this->getRequest()->getVar('Dir'); } $list = $list->sort($sort, $dir); } return $list; }
php
protected function queryList() { // Sanity check $dataClass = $this->dataRecord->getDataClass(); if (!$dataClass) { return ArrayList::create(); } // Setup $singleton = $this->dataRecord->getDataSingleton(); // Create list $list = $singleton->get(); // Setup filters $filters = []; foreach ($singleton->config()->get('searchable_fields') as $field) { $value = $this->getRequest()->getVar(str_replace('.', '_', $field)); if (!$value) { continue; } // if the searchable field is a relationship, it must be an exact match (ID match) if not partial is fine. $matchType = $this->instanceHasRelationship($singleton, $field) ? "ExactMatch" : "PartialMatch"; $filters[$field . ':' . $matchType] = $value; } $list = $list->filter($filters); // Sort $sort = $this->getRequest()->getVar('Sort'); if ($sort) { $dir = 'ASC'; if ($this->getRequest()->getVar('Dir')) { $dir = $this->getRequest()->getVar('Dir'); } $list = $list->sort($sort, $dir); } return $list; }
[ "protected", "function", "queryList", "(", ")", "{", "// Sanity check", "$", "dataClass", "=", "$", "this", "->", "dataRecord", "->", "getDataClass", "(", ")", ";", "if", "(", "!", "$", "dataClass", ")", "{", "return", "ArrayList", "::", "create", "(", ")", ";", "}", "// Setup", "$", "singleton", "=", "$", "this", "->", "dataRecord", "->", "getDataSingleton", "(", ")", ";", "// Create list", "$", "list", "=", "$", "singleton", "->", "get", "(", ")", ";", "// Setup filters", "$", "filters", "=", "[", "]", ";", "foreach", "(", "$", "singleton", "->", "config", "(", ")", "->", "get", "(", "'searchable_fields'", ")", "as", "$", "field", ")", "{", "$", "value", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getVar", "(", "str_replace", "(", "'.'", ",", "'_'", ",", "$", "field", ")", ")", ";", "if", "(", "!", "$", "value", ")", "{", "continue", ";", "}", "// if the searchable field is a relationship, it must be an exact match (ID match) if not partial is fine.", "$", "matchType", "=", "$", "this", "->", "instanceHasRelationship", "(", "$", "singleton", ",", "$", "field", ")", "?", "\"ExactMatch\"", ":", "\"PartialMatch\"", ";", "$", "filters", "[", "$", "field", ".", "':'", ".", "$", "matchType", "]", "=", "$", "value", ";", "}", "$", "list", "=", "$", "list", "->", "filter", "(", "$", "filters", ")", ";", "// Sort", "$", "sort", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getVar", "(", "'Sort'", ")", ";", "if", "(", "$", "sort", ")", "{", "$", "dir", "=", "'ASC'", ";", "if", "(", "$", "this", "->", "getRequest", "(", ")", "->", "getVar", "(", "'Dir'", ")", ")", "{", "$", "dir", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getVar", "(", "'Dir'", ")", ";", "}", "$", "list", "=", "$", "list", "->", "sort", "(", "$", "sort", ",", "$", "dir", ")", ";", "}", "return", "$", "list", ";", "}" ]
Perform a search against the data table. @return SS_List
[ "Perform", "a", "search", "against", "the", "data", "table", "." ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryPageController.php#L337-L376
222,853
silverstripe/silverstripe-registry
src/RegistryPageController.php
RegistryPageController.queryVars
protected function queryVars() { $resultColumns = $this->dataRecord->getDataSingleton()->getSearchFields(); $columns = []; foreach ($resultColumns as $field) { $columns[$field->getName()] = ''; } $arr = array_merge( $columns, [ 'action_doRegistryFilter' => 'Filter', 'Sort' => '', 'Dir' => '' ] ); foreach ($arr as $key => $val) { if (isset($_GET[$key])) { $arr[$key] = $_GET[$key]; } } return $arr; }
php
protected function queryVars() { $resultColumns = $this->dataRecord->getDataSingleton()->getSearchFields(); $columns = []; foreach ($resultColumns as $field) { $columns[$field->getName()] = ''; } $arr = array_merge( $columns, [ 'action_doRegistryFilter' => 'Filter', 'Sort' => '', 'Dir' => '' ] ); foreach ($arr as $key => $val) { if (isset($_GET[$key])) { $arr[$key] = $_GET[$key]; } } return $arr; }
[ "protected", "function", "queryVars", "(", ")", "{", "$", "resultColumns", "=", "$", "this", "->", "dataRecord", "->", "getDataSingleton", "(", ")", "->", "getSearchFields", "(", ")", ";", "$", "columns", "=", "[", "]", ";", "foreach", "(", "$", "resultColumns", "as", "$", "field", ")", "{", "$", "columns", "[", "$", "field", "->", "getName", "(", ")", "]", "=", "''", ";", "}", "$", "arr", "=", "array_merge", "(", "$", "columns", ",", "[", "'action_doRegistryFilter'", "=>", "'Filter'", ",", "'Sort'", "=>", "''", ",", "'Dir'", "=>", "''", "]", ")", ";", "foreach", "(", "$", "arr", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "isset", "(", "$", "_GET", "[", "$", "key", "]", ")", ")", "{", "$", "arr", "[", "$", "key", "]", "=", "$", "_GET", "[", "$", "key", "]", ";", "}", "}", "return", "$", "arr", ";", "}" ]
Compiles all available GET variables for the result columns into an array. Used internally, not to be used directly with the templates or outside classes. This will NOT escape values to avoid XSS. @return array
[ "Compiles", "all", "available", "GET", "variables", "for", "the", "result", "columns", "into", "an", "array", ".", "Used", "internally", "not", "to", "be", "used", "directly", "with", "the", "templates", "or", "outside", "classes", "." ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryPageController.php#L423-L447
222,854
sgpatil/oriquent
src/Sgpatil/Orientdb/Eloquent/Model.php
Model.getDefaultNodeLabel
public function getDefaultNodeLabel() { // by default we take the $label, otherwise we consider $table // for Eloquent's backward compatibility $label = (empty($this->label)) ? $this->table : $this->label; // The label is accepted as an array for a convenience so we need to // convert it to a string separated by ':' following Orientdb's labels if (is_array($label) && ! empty($label)) return $label; // since this is not an array, it is assumed to be a string // we check to see if it follows Orientdb's labels naming (User:Fan) // and return an array exploded from the ':' if ( ! empty($label)) { $label = array_filter(explode(':', $label)); // This trick re-indexes the array array_splice($label, 0, 0); return $label; } // Since there was no label for this model // we take the fully qualified (namespaced) class name and // pluck out backslashes to get a clean 'WordsUp' class name and use it as default return array(str_replace('\\', '', get_class($this))); }
php
public function getDefaultNodeLabel() { // by default we take the $label, otherwise we consider $table // for Eloquent's backward compatibility $label = (empty($this->label)) ? $this->table : $this->label; // The label is accepted as an array for a convenience so we need to // convert it to a string separated by ':' following Orientdb's labels if (is_array($label) && ! empty($label)) return $label; // since this is not an array, it is assumed to be a string // we check to see if it follows Orientdb's labels naming (User:Fan) // and return an array exploded from the ':' if ( ! empty($label)) { $label = array_filter(explode(':', $label)); // This trick re-indexes the array array_splice($label, 0, 0); return $label; } // Since there was no label for this model // we take the fully qualified (namespaced) class name and // pluck out backslashes to get a clean 'WordsUp' class name and use it as default return array(str_replace('\\', '', get_class($this))); }
[ "public", "function", "getDefaultNodeLabel", "(", ")", "{", "// by default we take the $label, otherwise we consider $table", "// for Eloquent's backward compatibility", "$", "label", "=", "(", "empty", "(", "$", "this", "->", "label", ")", ")", "?", "$", "this", "->", "table", ":", "$", "this", "->", "label", ";", "// The label is accepted as an array for a convenience so we need to", "// convert it to a string separated by ':' following Orientdb's labels", "if", "(", "is_array", "(", "$", "label", ")", "&&", "!", "empty", "(", "$", "label", ")", ")", "return", "$", "label", ";", "// since this is not an array, it is assumed to be a string", "// we check to see if it follows Orientdb's labels naming (User:Fan)", "// and return an array exploded from the ':'", "if", "(", "!", "empty", "(", "$", "label", ")", ")", "{", "$", "label", "=", "array_filter", "(", "explode", "(", "':'", ",", "$", "label", ")", ")", ";", "// This trick re-indexes the array", "array_splice", "(", "$", "label", ",", "0", ",", "0", ")", ";", "return", "$", "label", ";", "}", "// Since there was no label for this model", "// we take the fully qualified (namespaced) class name and", "// pluck out backslashes to get a clean 'WordsUp' class name and use it as default", "return", "array", "(", "str_replace", "(", "'\\\\'", ",", "''", ",", "get_class", "(", "$", "this", ")", ")", ")", ";", "}" ]
Get the node labels @return array
[ "Get", "the", "node", "labels" ]
cf0f2ba688496260946f569a20c351e91f287c32
https://github.com/sgpatil/oriquent/blob/cf0f2ba688496260946f569a20c351e91f287c32/src/Sgpatil/Orientdb/Eloquent/Model.php#L92-L119
222,855
silverstripe/silverstripe-registry
src/RegistryAdmin.php
RegistryAdmin.canView
public function canView($member = null) { $managedModels = $this->getManagedModels(); if (count($managedModels) == 0) { return false; } return parent::canView($member); }
php
public function canView($member = null) { $managedModels = $this->getManagedModels(); if (count($managedModels) == 0) { return false; } return parent::canView($member); }
[ "public", "function", "canView", "(", "$", "member", "=", "null", ")", "{", "$", "managedModels", "=", "$", "this", "->", "getManagedModels", "(", ")", ";", "if", "(", "count", "(", "$", "managedModels", ")", "==", "0", ")", "{", "return", "false", ";", "}", "return", "parent", "::", "canView", "(", "$", "member", ")", ";", "}" ]
Hide the registry section completely if we have no registries to manage. {@inheritDoc}
[ "Hide", "the", "registry", "section", "completely", "if", "we", "have", "no", "registries", "to", "manage", "." ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryAdmin.php#L20-L28
222,856
silverstripe/silverstripe-registry
src/RegistryAdmin.php
RegistryAdmin.getCsvImportFilename
public function getCsvImportFilename() { $feed = RegistryImportFeed::singleton(); return sprintf('%s/%s', $feed->getStoragePath($this->modelClass), $feed->getImportFilename()); }
php
public function getCsvImportFilename() { $feed = RegistryImportFeed::singleton(); return sprintf('%s/%s', $feed->getStoragePath($this->modelClass), $feed->getImportFilename()); }
[ "public", "function", "getCsvImportFilename", "(", ")", "{", "$", "feed", "=", "RegistryImportFeed", "::", "singleton", "(", ")", ";", "return", "sprintf", "(", "'%s/%s'", ",", "$", "feed", "->", "getStoragePath", "(", "$", "this", "->", "modelClass", ")", ",", "$", "feed", "->", "getImportFilename", "(", ")", ")", ";", "}" ]
Gets a unique filename to use for importing the uploaded CSV data @return string
[ "Gets", "a", "unique", "filename", "to", "use", "for", "importing", "the", "uploaded", "CSV", "data" ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryAdmin.php#L58-L63
222,857
php-kit/ext-pdo
src/ExtPDO.php
ExtPDO.create
static public function create ($driver, array $settings, array $optionsOverride = null) { switch ($driver) { case 'mysql': return new MysqlExtPDO ($settings, $optionsOverride); case 'pgsql': return new PostgreSqlExtPDO ($settings, $optionsOverride); case 'sqlite': return new SqliteExtPDO ($settings, $optionsOverride); case 'sqlsrv': return new SqlserverExtPDO ($settings, $optionsOverride); } throw new \RuntimeException ("Unsupported driver: $driver"); }
php
static public function create ($driver, array $settings, array $optionsOverride = null) { switch ($driver) { case 'mysql': return new MysqlExtPDO ($settings, $optionsOverride); case 'pgsql': return new PostgreSqlExtPDO ($settings, $optionsOverride); case 'sqlite': return new SqliteExtPDO ($settings, $optionsOverride); case 'sqlsrv': return new SqlserverExtPDO ($settings, $optionsOverride); } throw new \RuntimeException ("Unsupported driver: $driver"); }
[ "static", "public", "function", "create", "(", "$", "driver", ",", "array", "$", "settings", ",", "array", "$", "optionsOverride", "=", "null", ")", "{", "switch", "(", "$", "driver", ")", "{", "case", "'mysql'", ":", "return", "new", "MysqlExtPDO", "(", "$", "settings", ",", "$", "optionsOverride", ")", ";", "case", "'pgsql'", ":", "return", "new", "PostgreSqlExtPDO", "(", "$", "settings", ",", "$", "optionsOverride", ")", ";", "case", "'sqlite'", ":", "return", "new", "SqliteExtPDO", "(", "$", "settings", ",", "$", "optionsOverride", ")", ";", "case", "'sqlsrv'", ":", "return", "new", "SqlserverExtPDO", "(", "$", "settings", ",", "$", "optionsOverride", ")", ";", "}", "throw", "new", "\\", "RuntimeException", "(", "\"Unsupported driver: $driver\"", ")", ";", "}" ]
Creates an instance of an ExtPDO subclass that matches the given driver name. @param string $driver One of: mysql | pgsql | sqlite | sqlsrv @param array $settings A configuration array that may have the following keys (depending on the driver):<p> <table cellspacing=0 cellpadding=0> <tr><kbd>database <td>The database name. <tr><kbd>host <td>The database server's host IP or domain name. <tr><kbd>port <td>The database server's port (optional). <tr><kbd>unixSocket &nbsp; <td>The connection's UNIX socket (optional). <tr><kbd>charset <td>The database charset (optional), ex: 'utf8'. <tr><kbd>collation <td>The database collation (optional), ex:'utf8_unicode_ci'. <tr><kbd>username <td>The username. <tr><kbd>password <td>The password. </table> @param array|null $optionsOverride Entries on this array override the default PDO connection options. @return ExtPDOInterface
[ "Creates", "an", "instance", "of", "an", "ExtPDO", "subclass", "that", "matches", "the", "given", "driver", "name", "." ]
b94bf1805b75ba114e4a216dbca441ca7dc893be
https://github.com/php-kit/ext-pdo/blob/b94bf1805b75ba114e4a216dbca441ca7dc893be/src/ExtPDO.php#L35-L48
222,858
teresko/palladium
src/Palladium/Component/MapperFactory.php
MapperFactory.create
public function create(string $className) { if (array_key_exists($className, $this->cache)) { return $this->cache[$className]; } if (!class_exists($className)) { throw new RuntimeException("Mapper not found. Attempted to load '{$className}'."); } $instance = new $className($this->connection, $this->table); $this->cache[$className] = $instance; return $instance; }
php
public function create(string $className) { if (array_key_exists($className, $this->cache)) { return $this->cache[$className]; } if (!class_exists($className)) { throw new RuntimeException("Mapper not found. Attempted to load '{$className}'."); } $instance = new $className($this->connection, $this->table); $this->cache[$className] = $instance; return $instance; }
[ "public", "function", "create", "(", "string", "$", "className", ")", "{", "if", "(", "array_key_exists", "(", "$", "className", ",", "$", "this", "->", "cache", ")", ")", "{", "return", "$", "this", "->", "cache", "[", "$", "className", "]", ";", "}", "if", "(", "!", "class_exists", "(", "$", "className", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Mapper not found. Attempted to load '{$className}'.\"", ")", ";", "}", "$", "instance", "=", "new", "$", "className", "(", "$", "this", "->", "connection", ",", "$", "this", "->", "table", ")", ";", "$", "this", "->", "cache", "[", "$", "className", "]", "=", "$", "instance", ";", "return", "$", "instance", ";", "}" ]
Method for retrieving an SQL data mapper instance @param string $className Fully qualified class name of the mapper @throws RuntimeException if mapper's class can't be found @return DataMapper
[ "Method", "for", "retrieving", "an", "SQL", "data", "mapper", "instance" ]
0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8
https://github.com/teresko/palladium/blob/0ebb6dc3c52946c7f6d9967701ea6196eb7f45a8/src/Palladium/Component/MapperFactory.php#L39-L53
222,859
jstewmc/php-helpers
src/Str.php
Str.rand
public static function rand($length, $charsets = array('alpha', 'number', 'symbol')) { $rand = ''; // if $length and $charsets are given if ($length !== null && $charsets !== null) { // if $length is an integer if (is_numeric($length) && is_int(+$length)) { // if $charsets is a string or array if (is_string($charsets) || is_array($charsets)) { // if $charsets is a string, array-ify it if (is_string($charsets)) { $charsets = (array) $charsets; } // define the possible charsets $lower = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); $upper = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); $number = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); $symbol = array('!', '@', '#', '*', '(', ')', '-', '_', '+', '=', '[', ']'); // create an array of possible chars $chars = array(); foreach ($charsets as $charset) { if (isset($$charset)) { $chars = array_merge($chars, $$charset); } elseif ($charset === 'alpha') { $chars = array_merge($chars, $lower, $upper); } else { throw new \InvalidArgumentException( __METHOD__." expects parameter two to be a string charset name or an array ". "of charset names such as 'lower', 'upper', 'alpha', 'number', or 'symbol'" ); } } // shuffle the chars shuffle($chars); // pick $length random chars for ($i = 0; $i < $length; ++$i) { $rand .= $chars[array_rand($chars)]; } } else { throw new \InvalidArgumentException( __METHOD__." expects the second parameter, charsets, to be a string charset ". "name or an array of charset names" ); } } else { throw new \InvalidArgumentException( __METHOD__." expects the first parameter, length, to be an integer" ); } } else { throw new \BadMethodCallException( __METHOD__." expects at least one argument, length" ); } return $rand; }
php
public static function rand($length, $charsets = array('alpha', 'number', 'symbol')) { $rand = ''; // if $length and $charsets are given if ($length !== null && $charsets !== null) { // if $length is an integer if (is_numeric($length) && is_int(+$length)) { // if $charsets is a string or array if (is_string($charsets) || is_array($charsets)) { // if $charsets is a string, array-ify it if (is_string($charsets)) { $charsets = (array) $charsets; } // define the possible charsets $lower = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); $upper = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); $number = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); $symbol = array('!', '@', '#', '*', '(', ')', '-', '_', '+', '=', '[', ']'); // create an array of possible chars $chars = array(); foreach ($charsets as $charset) { if (isset($$charset)) { $chars = array_merge($chars, $$charset); } elseif ($charset === 'alpha') { $chars = array_merge($chars, $lower, $upper); } else { throw new \InvalidArgumentException( __METHOD__." expects parameter two to be a string charset name or an array ". "of charset names such as 'lower', 'upper', 'alpha', 'number', or 'symbol'" ); } } // shuffle the chars shuffle($chars); // pick $length random chars for ($i = 0; $i < $length; ++$i) { $rand .= $chars[array_rand($chars)]; } } else { throw new \InvalidArgumentException( __METHOD__." expects the second parameter, charsets, to be a string charset ". "name or an array of charset names" ); } } else { throw new \InvalidArgumentException( __METHOD__." expects the first parameter, length, to be an integer" ); } } else { throw new \BadMethodCallException( __METHOD__." expects at least one argument, length" ); } return $rand; }
[ "public", "static", "function", "rand", "(", "$", "length", ",", "$", "charsets", "=", "array", "(", "'alpha'", ",", "'number'", ",", "'symbol'", ")", ")", "{", "$", "rand", "=", "''", ";", "// if $length and $charsets are given\r", "if", "(", "$", "length", "!==", "null", "&&", "$", "charsets", "!==", "null", ")", "{", "// if $length is an integer\r", "if", "(", "is_numeric", "(", "$", "length", ")", "&&", "is_int", "(", "+", "$", "length", ")", ")", "{", "// if $charsets is a string or array\r", "if", "(", "is_string", "(", "$", "charsets", ")", "||", "is_array", "(", "$", "charsets", ")", ")", "{", "// if $charsets is a string, array-ify it\r", "if", "(", "is_string", "(", "$", "charsets", ")", ")", "{", "$", "charsets", "=", "(", "array", ")", "$", "charsets", ";", "}", "// define the possible charsets\r", "$", "lower", "=", "array", "(", "'a'", ",", "'b'", ",", "'c'", ",", "'d'", ",", "'e'", ",", "'f'", ",", "'g'", ",", "'h'", ",", "'i'", ",", "'j'", ",", "'k'", ",", "'l'", ",", "'m'", ",", "'n'", ",", "'o'", ",", "'p'", ",", "'q'", ",", "'r'", ",", "'s'", ",", "'t'", ",", "'u'", ",", "'v'", ",", "'w'", ",", "'x'", ",", "'y'", ",", "'z'", ")", ";", "$", "upper", "=", "array", "(", "'A'", ",", "'B'", ",", "'C'", ",", "'D'", ",", "'E'", ",", "'F'", ",", "'G'", ",", "'H'", ",", "'I'", ",", "'J'", ",", "'K'", ",", "'L'", ",", "'M'", ",", "'N'", ",", "'O'", ",", "'P'", ",", "'Q'", ",", "'R'", ",", "'S'", ",", "'T'", ",", "'U'", ",", "'V'", ",", "'W'", ",", "'X'", ",", "'Y'", ",", "'Z'", ")", ";", "$", "number", "=", "array", "(", "'0'", ",", "'1'", ",", "'2'", ",", "'3'", ",", "'4'", ",", "'5'", ",", "'6'", ",", "'7'", ",", "'8'", ",", "'9'", ")", ";", "$", "symbol", "=", "array", "(", "'!'", ",", "'@'", ",", "'#'", ",", "'*'", ",", "'('", ",", "')'", ",", "'-'", ",", "'_'", ",", "'+'", ",", "'='", ",", "'['", ",", "']'", ")", ";", "// create an array of possible chars\r", "$", "chars", "=", "array", "(", ")", ";", "foreach", "(", "$", "charsets", "as", "$", "charset", ")", "{", "if", "(", "isset", "(", "$", "$", "charset", ")", ")", "{", "$", "chars", "=", "array_merge", "(", "$", "chars", ",", "$", "$", "charset", ")", ";", "}", "elseif", "(", "$", "charset", "===", "'alpha'", ")", "{", "$", "chars", "=", "array_merge", "(", "$", "chars", ",", "$", "lower", ",", "$", "upper", ")", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\" expects parameter two to be a string charset name or an array \"", ".", "\"of charset names such as 'lower', 'upper', 'alpha', 'number', or 'symbol'\"", ")", ";", "}", "}", "// shuffle the chars\r", "shuffle", "(", "$", "chars", ")", ";", "// pick $length random chars\r", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "++", "$", "i", ")", "{", "$", "rand", ".=", "$", "chars", "[", "array_rand", "(", "$", "chars", ")", "]", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\" expects the second parameter, charsets, to be a string charset \"", ".", "\"name or an array of charset names\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\" expects the first parameter, length, to be an integer\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\" expects at least one argument, length\"", ")", ";", "}", "return", "$", "rand", ";", "}" ]
Returns a random string For example: echo Str::rand(8, 'alpha'); // example 'hbdrckso' echo Str::rand(8, ['lower', 'number']); // example 'k987hb54' echo Str::rand(8, ['upper', 'symbol']); // example 'HG!V*X]@' @since 0.1.0 @param int $length the length of the string to return @param mixed $charsets a string charset name or an array of charset names (possible values are are 'lower', 'upper', 'alpha' (a combination of 'upper' and 'lower'), 'number', and 'symbol') (optional; if omitted, defaults to ['alpha', 'number', 'symbol']) @return string a random string @throws \BadMethodCallException if $length or $charset is null @throws \InvalidArgumentException if $length is not an integer @throws \InvalidArgumentException if $charsets is not a string or array @throws \InvalidArgumentException if a given $charset is not a valid charset
[ "Returns", "a", "random", "string" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Str.php#L340-L403
222,860
jstewmc/php-helpers
src/Str.php
Str.splitOnFirstAlpha
public static function splitOnFirstAlpha($string) { $pieces = array(); // if $string is not null if ($string !== null) { // if $string is actually a string if (is_string($string)) { // if the trimmed string isn't empty $string = trim($string); if ($string !== '') { $pieces = array_map('trim', preg_split('/(?=[a-zA-Z])/i', $string, 2)); } else { $pieces = array(); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects one parameter, a string" ); } return $pieces; }
php
public static function splitOnFirstAlpha($string) { $pieces = array(); // if $string is not null if ($string !== null) { // if $string is actually a string if (is_string($string)) { // if the trimmed string isn't empty $string = trim($string); if ($string !== '') { $pieces = array_map('trim', preg_split('/(?=[a-zA-Z])/i', $string, 2)); } else { $pieces = array(); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects one parameter, a string" ); } return $pieces; }
[ "public", "static", "function", "splitOnFirstAlpha", "(", "$", "string", ")", "{", "$", "pieces", "=", "array", "(", ")", ";", "// if $string is not null\r", "if", "(", "$", "string", "!==", "null", ")", "{", "// if $string is actually a string\r", "if", "(", "is_string", "(", "$", "string", ")", ")", "{", "// if the trimmed string isn't empty\r", "$", "string", "=", "trim", "(", "$", "string", ")", ";", "if", "(", "$", "string", "!==", "''", ")", "{", "$", "pieces", "=", "array_map", "(", "'trim'", ",", "preg_split", "(", "'/(?=[a-zA-Z])/i'", ",", "$", "string", ",", "2", ")", ")", ";", "}", "else", "{", "$", "pieces", "=", "array", "(", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one to be a string\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\"() expects one parameter, a string\"", ")", ";", "}", "return", "$", "pieces", ";", "}" ]
Splits a string on the first alpha character I'll return an array with two parts. The first element is the string part before the first alpha character, and the second part is everything after and including the first alpha character. For example: Str::splitOnFirstAlpha("123"); // returns ["123"] Str::splitOnFirstAlpha("abc"); // returns ["", "abc"] Str::splitOnFirstAlpha("123 abc"); // returns ["123", "abc"] Str::splitOnFirstAlpha("1 2 3 abc"); // returns ["1 2 3 4", "abc"] @since 0.1.0 @param string $string the string to split @return string[] an array @throws \BadMethodCallException if $string is null @throws \InvalidArgumentException if $string is not a string @see http://stackoverflow.com/a/18990341 FrankieTheKneeMan's answer to "Split string on first occurrence of a letter" on StackOverflow (version using Regex lookahead)
[ "Splits", "a", "string", "on", "the", "first", "alpha", "character" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Str.php#L432-L459
222,861
jstewmc/php-helpers
src/Str.php
Str.strtobytes
public static function strtobytes($string) { $val = false; // if $string is given if ($string !== null) { // if $string is actually a string if (is_string($string)) { // get the string's last character $val = trim($string); $last = strtolower($val[strlen($val) - 1]); switch ($last) { case 'g': $val *= 1024; // no break case 'm': $val *= 1024; // no break case 'k': $val *= 1024; break; default: throw new \InvalidArgumentException( __METHOD__." expects the first parameter to end in 'k', 'm', or 'g'" ); } } else { throw new \InvalidArgumentException( __METHOD__." expects the first parameter to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__." expects one parameter" ); } return $val; }
php
public static function strtobytes($string) { $val = false; // if $string is given if ($string !== null) { // if $string is actually a string if (is_string($string)) { // get the string's last character $val = trim($string); $last = strtolower($val[strlen($val) - 1]); switch ($last) { case 'g': $val *= 1024; // no break case 'm': $val *= 1024; // no break case 'k': $val *= 1024; break; default: throw new \InvalidArgumentException( __METHOD__." expects the first parameter to end in 'k', 'm', or 'g'" ); } } else { throw new \InvalidArgumentException( __METHOD__." expects the first parameter to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__." expects one parameter" ); } return $val; }
[ "public", "static", "function", "strtobytes", "(", "$", "string", ")", "{", "$", "val", "=", "false", ";", "// if $string is given\r", "if", "(", "$", "string", "!==", "null", ")", "{", "// if $string is actually a string\r", "if", "(", "is_string", "(", "$", "string", ")", ")", "{", "// get the string's last character\r", "$", "val", "=", "trim", "(", "$", "string", ")", ";", "$", "last", "=", "strtolower", "(", "$", "val", "[", "strlen", "(", "$", "val", ")", "-", "1", "]", ")", ";", "switch", "(", "$", "last", ")", "{", "case", "'g'", ":", "$", "val", "*=", "1024", ";", "// no break\r", "case", "'m'", ":", "$", "val", "*=", "1024", ";", "// no break\r", "case", "'k'", ":", "$", "val", "*=", "1024", ";", "break", ";", "default", ":", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\" expects the first parameter to end in 'k', 'm', or 'g'\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\" expects the first parameter to be a string\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\" expects one parameter\"", ")", ";", "}", "return", "$", "val", ";", "}" ]
Converts a php.ini-like byte notation shorthand to a number of bytes In the php.ini configuration file, byte values are sote in shorthand notation (e.g., "8M"). PHP's native ini_get() function will return the exact string stored in php.ini and not its integer equivalent. I will return the integer equivalent. For example: Str::strtobytes('1K'); // returns 1024 Str::strtobytes('1M'); // returns 1048576 Str::strtobytes('1G'); // returns 1073741824 @since 0.1.0 @param string $string the string to convert @return int|float the number of bytes @throws \BadMethodCallException if $string is null @throws \InvalidArgumentException if $string is not a string @throws \InvalidArgumentException if $string does not end in 'k', 'm', or 'g' @see http://www.php.net/manual/en/function.ini-get.php ini_get() man page
[ "Converts", "a", "php", ".", "ini", "-", "like", "byte", "notation", "shorthand", "to", "a", "number", "of", "bytes" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Str.php#L553-L596
222,862
jstewmc/php-helpers
src/Str.php
Str.strtocamelcase
public static function strtocamelcase($string) { // if $string is given if ($string !== null) { // if $string is actually a string if (is_string($string)) { // if $string is not empty if (strlen($string)) { // trim the string $string = trim($string); // replace underscores ("_") and hyphens ("-") with spaces (" ") $string = str_replace(array('-', '_'), ' ', $string); // lower-case everything $string = strtolower($string); // capitalize each word $string = ucwords($string); // remove spaces $string = str_replace(' ', '', $string); // lower-case the first word $string = lcfirst($string); // remove any non-alphanumeric characters $string = preg_replace("#[^a-zA-Z0-9]+#", '', $string); } } else { throw new \InvalidArgumentException( __METHOD__." expects the first parameter, the string, to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__." expects one parameter, a string to camel-case" ); } return $string; }
php
public static function strtocamelcase($string) { // if $string is given if ($string !== null) { // if $string is actually a string if (is_string($string)) { // if $string is not empty if (strlen($string)) { // trim the string $string = trim($string); // replace underscores ("_") and hyphens ("-") with spaces (" ") $string = str_replace(array('-', '_'), ' ', $string); // lower-case everything $string = strtolower($string); // capitalize each word $string = ucwords($string); // remove spaces $string = str_replace(' ', '', $string); // lower-case the first word $string = lcfirst($string); // remove any non-alphanumeric characters $string = preg_replace("#[^a-zA-Z0-9]+#", '', $string); } } else { throw new \InvalidArgumentException( __METHOD__." expects the first parameter, the string, to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__." expects one parameter, a string to camel-case" ); } return $string; }
[ "public", "static", "function", "strtocamelcase", "(", "$", "string", ")", "{", "// if $string is given\r", "if", "(", "$", "string", "!==", "null", ")", "{", "// if $string is actually a string\r", "if", "(", "is_string", "(", "$", "string", ")", ")", "{", "// if $string is not empty\r", "if", "(", "strlen", "(", "$", "string", ")", ")", "{", "// trim the string\r", "$", "string", "=", "trim", "(", "$", "string", ")", ";", "// replace underscores (\"_\") and hyphens (\"-\") with spaces (\" \")\r", "$", "string", "=", "str_replace", "(", "array", "(", "'-'", ",", "'_'", ")", ",", "' '", ",", "$", "string", ")", ";", "// lower-case everything\r", "$", "string", "=", "strtolower", "(", "$", "string", ")", ";", "// capitalize each word\r", "$", "string", "=", "ucwords", "(", "$", "string", ")", ";", "// remove spaces\r", "$", "string", "=", "str_replace", "(", "' '", ",", "''", ",", "$", "string", ")", ";", "// lower-case the first word\r", "$", "string", "=", "lcfirst", "(", "$", "string", ")", ";", "// remove any non-alphanumeric characters\r", "$", "string", "=", "preg_replace", "(", "\"#[^a-zA-Z0-9]+#\"", ",", "''", ",", "$", "string", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\" expects the first parameter, the string, to be a string\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\" expects one parameter, a string to camel-case\"", ")", ";", "}", "return", "$", "string", ";", "}" ]
Returns a string in camel case For example: Str::strtocamelcase('Hello world'); // returns "helloWorld" Str::strtocamelcase('H3LLO WORLD!'); // returns "helloWorld" Str::strtocamelcase('hello_world'); // returns "helloWorld" @since 0.1.0 @param string $string the string to camel-case @return string the camel-cased string @throws \BadMethodCallException if $string is empty @throws \InvalidArgumentException if $string is not a string
[ "Returns", "a", "string", "in", "camel", "case" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Str.php#L616-L657
222,863
sastrawi/sentence-detector
src/Sastrawi/SentenceDetector/Util/StringUtil.php
StringUtil.getNextWhitespace
public static function getNextWhitespace($string, $start = -1) { while ($start < (strlen($string) - 1) && !self::isWhitespace($string[$start + 1])) { $start++; } if ($start === (strlen($string) - 1)) { return false; } $start++; return $start; }
php
public static function getNextWhitespace($string, $start = -1) { while ($start < (strlen($string) - 1) && !self::isWhitespace($string[$start + 1])) { $start++; } if ($start === (strlen($string) - 1)) { return false; } $start++; return $start; }
[ "public", "static", "function", "getNextWhitespace", "(", "$", "string", ",", "$", "start", "=", "-", "1", ")", "{", "while", "(", "$", "start", "<", "(", "strlen", "(", "$", "string", ")", "-", "1", ")", "&&", "!", "self", "::", "isWhitespace", "(", "$", "string", "[", "$", "start", "+", "1", "]", ")", ")", "{", "$", "start", "++", ";", "}", "if", "(", "$", "start", "===", "(", "strlen", "(", "$", "string", ")", "-", "1", ")", ")", "{", "return", "false", ";", "}", "$", "start", "++", ";", "return", "$", "start", ";", "}" ]
Get next first whitespace character. @param string $string Text to search whitespace character @param int $start Position index to start from @return false|int Return the position of next first whitespace character. False if not found.
[ "Get", "next", "first", "whitespace", "character", "." ]
a7741aea1b78afa0c77e4af1cf36c0eee05dab6f
https://github.com/sastrawi/sentence-detector/blob/a7741aea1b78afa0c77e4af1cf36c0eee05dab6f/src/Sastrawi/SentenceDetector/Util/StringUtil.php#L40-L53
222,864
sastrawi/sentence-detector
src/Sastrawi/SentenceDetector/Util/StringUtil.php
StringUtil.getPrevWhitespace
public static function getPrevWhitespace($string, $start = null) { $start = ($start !== null) ? $start : strlen($string); while ($start > 0 && !self::isWhitespace($string[$start - 1])) { $start--; } if ($start === 0) { return false; } $start--; return $start; }
php
public static function getPrevWhitespace($string, $start = null) { $start = ($start !== null) ? $start : strlen($string); while ($start > 0 && !self::isWhitespace($string[$start - 1])) { $start--; } if ($start === 0) { return false; } $start--; return $start; }
[ "public", "static", "function", "getPrevWhitespace", "(", "$", "string", ",", "$", "start", "=", "null", ")", "{", "$", "start", "=", "(", "$", "start", "!==", "null", ")", "?", "$", "start", ":", "strlen", "(", "$", "string", ")", ";", "while", "(", "$", "start", ">", "0", "&&", "!", "self", "::", "isWhitespace", "(", "$", "string", "[", "$", "start", "-", "1", "]", ")", ")", "{", "$", "start", "--", ";", "}", "if", "(", "$", "start", "===", "0", ")", "{", "return", "false", ";", "}", "$", "start", "--", ";", "return", "$", "start", ";", "}" ]
Get previous first whitespace character. @param string $string Text to search whitespace character @param int $start Position index to start from @return false|int Return the position of previous first whitespace character. False if not found.
[ "Get", "previous", "first", "whitespace", "character", "." ]
a7741aea1b78afa0c77e4af1cf36c0eee05dab6f
https://github.com/sastrawi/sentence-detector/blob/a7741aea1b78afa0c77e4af1cf36c0eee05dab6f/src/Sastrawi/SentenceDetector/Util/StringUtil.php#L62-L77
222,865
sastrawi/sentence-detector
src/Sastrawi/SentenceDetector/Util/StringUtil.php
StringUtil.getNextNonWhitespace
public static function getNextNonWhitespace($string, $start = -1) { while ($start < (strlen($string) - 1) && self::isWhitespace($string[$start + 1])) { $start++; } if ($start === (strlen($string) - 1)) { return false; } $start++; return $start; }
php
public static function getNextNonWhitespace($string, $start = -1) { while ($start < (strlen($string) - 1) && self::isWhitespace($string[$start + 1])) { $start++; } if ($start === (strlen($string) - 1)) { return false; } $start++; return $start; }
[ "public", "static", "function", "getNextNonWhitespace", "(", "$", "string", ",", "$", "start", "=", "-", "1", ")", "{", "while", "(", "$", "start", "<", "(", "strlen", "(", "$", "string", ")", "-", "1", ")", "&&", "self", "::", "isWhitespace", "(", "$", "string", "[", "$", "start", "+", "1", "]", ")", ")", "{", "$", "start", "++", ";", "}", "if", "(", "$", "start", "===", "(", "strlen", "(", "$", "string", ")", "-", "1", ")", ")", "{", "return", "false", ";", "}", "$", "start", "++", ";", "return", "$", "start", ";", "}" ]
Get next first non whitespace character. @param string $string Text to search non whitespace character @param int $start Position index to start from @return false|int Return the position of next first non whitespace character. False if not found.
[ "Get", "next", "first", "non", "whitespace", "character", "." ]
a7741aea1b78afa0c77e4af1cf36c0eee05dab6f
https://github.com/sastrawi/sentence-detector/blob/a7741aea1b78afa0c77e4af1cf36c0eee05dab6f/src/Sastrawi/SentenceDetector/Util/StringUtil.php#L86-L99
222,866
sastrawi/sentence-detector
src/Sastrawi/SentenceDetector/Util/StringUtil.php
StringUtil.getPrevNonWhitespace
public static function getPrevNonWhitespace($string, $start = null) { $start = ($start !== null) ? $start : strlen($string); while ($start > 0 && self::isWhitespace($string[$start - 1])) { $start--; } if ($start === 0) { return false; } $start--; return $start; }
php
public static function getPrevNonWhitespace($string, $start = null) { $start = ($start !== null) ? $start : strlen($string); while ($start > 0 && self::isWhitespace($string[$start - 1])) { $start--; } if ($start === 0) { return false; } $start--; return $start; }
[ "public", "static", "function", "getPrevNonWhitespace", "(", "$", "string", ",", "$", "start", "=", "null", ")", "{", "$", "start", "=", "(", "$", "start", "!==", "null", ")", "?", "$", "start", ":", "strlen", "(", "$", "string", ")", ";", "while", "(", "$", "start", ">", "0", "&&", "self", "::", "isWhitespace", "(", "$", "string", "[", "$", "start", "-", "1", "]", ")", ")", "{", "$", "start", "--", ";", "}", "if", "(", "$", "start", "===", "0", ")", "{", "return", "false", ";", "}", "$", "start", "--", ";", "return", "$", "start", ";", "}" ]
Get previous first non whitespace character. @param string $string Text to search non whitespace character @param int $start Position index to start from @return false|int Return the position of previous first non whitespace character. False if not found.
[ "Get", "previous", "first", "non", "whitespace", "character", "." ]
a7741aea1b78afa0c77e4af1cf36c0eee05dab6f
https://github.com/sastrawi/sentence-detector/blob/a7741aea1b78afa0c77e4af1cf36c0eee05dab6f/src/Sastrawi/SentenceDetector/Util/StringUtil.php#L108-L123
222,867
fage1151/swoole-worker
Lib/Timer.php
Timer.delAll
public static function delAll() { if (count(self::$_tasks) > 0) { foreach (self::$_tasks as $k => $v) { swoole_timer_clear($k); } self::$_tasks = array(); } }
php
public static function delAll() { if (count(self::$_tasks) > 0) { foreach (self::$_tasks as $k => $v) { swoole_timer_clear($k); } self::$_tasks = array(); } }
[ "public", "static", "function", "delAll", "(", ")", "{", "if", "(", "count", "(", "self", "::", "$", "_tasks", ")", ">", "0", ")", "{", "foreach", "(", "self", "::", "$", "_tasks", "as", "$", "k", "=>", "$", "v", ")", "{", "swoole_timer_clear", "(", "$", "k", ")", ";", "}", "self", "::", "$", "_tasks", "=", "array", "(", ")", ";", "}", "}" ]
Remove all timers. @return void
[ "Remove", "all", "timers", "." ]
ade6e29ffb400129380d56e9a2e6656f19dceb17
https://github.com/fage1151/swoole-worker/blob/ade6e29ffb400129380d56e9a2e6656f19dceb17/Lib/Timer.php#L114-L122
222,868
sgpatil/oriquent
src/Sgpatil/Orientdb/Query/Builder.php
Builder.createWith
public function createWith(array $model, array $related) { $cypher = $this->grammar->compileCreateWith($this, compact('model', 'related')); // Indicate that we need the result returned as is. $result = true; return $this->connection->statement($cypher, [], $result); }
php
public function createWith(array $model, array $related) { $cypher = $this->grammar->compileCreateWith($this, compact('model', 'related')); // Indicate that we need the result returned as is. $result = true; return $this->connection->statement($cypher, [], $result); }
[ "public", "function", "createWith", "(", "array", "$", "model", ",", "array", "$", "related", ")", "{", "$", "cypher", "=", "$", "this", "->", "grammar", "->", "compileCreateWith", "(", "$", "this", ",", "compact", "(", "'model'", ",", "'related'", ")", ")", ";", "// Indicate that we need the result returned as is.", "$", "result", "=", "true", ";", "return", "$", "this", "->", "connection", "->", "statement", "(", "$", "cypher", ",", "[", "]", ",", "$", "result", ")", ";", "}" ]
Create a new node with related nodes with one database hit. @param array $model @param array $related @return \Sgpatil\Orientdb\Eloquent\Model
[ "Create", "a", "new", "node", "with", "related", "nodes", "with", "one", "database", "hit", "." ]
cf0f2ba688496260946f569a20c351e91f287c32
https://github.com/sgpatil/oriquent/blob/cf0f2ba688496260946f569a20c351e91f287c32/src/Sgpatil/Orientdb/Query/Builder.php#L365-L371
222,869
digiaonline/lumen-dynamodb
src/Console/DynamoDbCommand.php
DynamoDbCommand.tableExists
protected function tableExists($tableName) { $found = false; $iterator = $this->dynamoDb->getClient()->getIterator('ListTables'); foreach ($iterator as $table) { if ($table === $tableName) { $found = true; } } return $found; }
php
protected function tableExists($tableName) { $found = false; $iterator = $this->dynamoDb->getClient()->getIterator('ListTables'); foreach ($iterator as $table) { if ($table === $tableName) { $found = true; } } return $found; }
[ "protected", "function", "tableExists", "(", "$", "tableName", ")", "{", "$", "found", "=", "false", ";", "$", "iterator", "=", "$", "this", "->", "dynamoDb", "->", "getClient", "(", ")", "->", "getIterator", "(", "'ListTables'", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "table", ")", "{", "if", "(", "$", "table", "===", "$", "tableName", ")", "{", "$", "found", "=", "true", ";", "}", "}", "return", "$", "found", ";", "}" ]
Checks if the given table exists. @param string $tableName The table name to check. @return bool True if the table exists, false otherwise.
[ "Checks", "if", "the", "given", "table", "exists", "." ]
d29edefbe461af0bc902037e397cc8586a2ec87c
https://github.com/digiaonline/lumen-dynamodb/blob/d29edefbe461af0bc902037e397cc8586a2ec87c/src/Console/DynamoDbCommand.php#L50-L61
222,870
rikbruil/Doctrine-Specification
src/SpecificationRepositoryTrait.php
SpecificationRepositoryTrait.modifyQueryBuilder
private function modifyQueryBuilder(QueryBuilder $queryBuilder, SpecificationInterface $specification) { $condition = $specification->modify($queryBuilder, $this->dqlAlias); if (empty($condition)) { return; } $queryBuilder->where($condition); }
php
private function modifyQueryBuilder(QueryBuilder $queryBuilder, SpecificationInterface $specification) { $condition = $specification->modify($queryBuilder, $this->dqlAlias); if (empty($condition)) { return; } $queryBuilder->where($condition); }
[ "private", "function", "modifyQueryBuilder", "(", "QueryBuilder", "$", "queryBuilder", ",", "SpecificationInterface", "$", "specification", ")", "{", "$", "condition", "=", "$", "specification", "->", "modify", "(", "$", "queryBuilder", ",", "$", "this", "->", "dqlAlias", ")", ";", "if", "(", "empty", "(", "$", "condition", ")", ")", "{", "return", ";", "}", "$", "queryBuilder", "->", "where", "(", "$", "condition", ")", ";", "}" ]
Modifies the QueryBuilder according to the passed Specification. Will also set the condition for this query if needed. @param QueryBuilder $queryBuilder @param SpecificationInterface $specification @internal param string $dqlAlias
[ "Modifies", "the", "QueryBuilder", "according", "to", "the", "passed", "Specification", ".", "Will", "also", "set", "the", "condition", "for", "this", "query", "if", "needed", "." ]
e61fb801c46107b0a9ce22086448557def7fa532
https://github.com/rikbruil/Doctrine-Specification/blob/e61fb801c46107b0a9ce22086448557def7fa532/src/SpecificationRepositoryTrait.php#L54-L63
222,871
corneltek/FormKit
src/Element/Table.php
Table.addRow
public function addRow($rows = null) { if( ! is_array($rows) ) { $rows = func_get_args(); } $row = new TableRow; foreach( $rows as $arg ) { $cell = new TableCell; $cell->addChild( $arg ); $row->addChild( $cell ); } $this->addChild($row); return $row; }
php
public function addRow($rows = null) { if( ! is_array($rows) ) { $rows = func_get_args(); } $row = new TableRow; foreach( $rows as $arg ) { $cell = new TableCell; $cell->addChild( $arg ); $row->addChild( $cell ); } $this->addChild($row); return $row; }
[ "public", "function", "addRow", "(", "$", "rows", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "rows", ")", ")", "{", "$", "rows", "=", "func_get_args", "(", ")", ";", "}", "$", "row", "=", "new", "TableRow", ";", "foreach", "(", "$", "rows", "as", "$", "arg", ")", "{", "$", "cell", "=", "new", "TableCell", ";", "$", "cell", "->", "addChild", "(", "$", "arg", ")", ";", "$", "row", "->", "addChild", "(", "$", "cell", ")", ";", "}", "$", "this", "->", "addChild", "(", "$", "row", ")", ";", "return", "$", "row", ";", "}" ]
Add elements to a new row $table->addRow( $element1, $element2 , $element3 ); $table->addRow( array( $element1, $element2 , $element3 ) ); @return TableRow
[ "Add", "elements", "to", "a", "new", "row" ]
c8963d494b8bd7d7f63928002057db86e5873c26
https://github.com/corneltek/FormKit/blob/c8963d494b8bd7d7f63928002057db86e5873c26/src/Element/Table.php#L22-L34
222,872
silverstripe/silverstripe-registry
src/RegistryImportFeed.php
RegistryImportFeed.setAssetHandler
public function setAssetHandler(GeneratedAssetHandler $handler) { $handler->getFilesystem()->addPlugin(new ListFiles); $this->assetHandler = $handler; return $this; }
php
public function setAssetHandler(GeneratedAssetHandler $handler) { $handler->getFilesystem()->addPlugin(new ListFiles); $this->assetHandler = $handler; return $this; }
[ "public", "function", "setAssetHandler", "(", "GeneratedAssetHandler", "$", "handler", ")", "{", "$", "handler", "->", "getFilesystem", "(", ")", "->", "addPlugin", "(", "new", "ListFiles", ")", ";", "$", "this", "->", "assetHandler", "=", "$", "handler", ";", "return", "$", "this", ";", "}" ]
Set the handler used to manipulate the filesystem, and add the ListFiles plugin from Flysystem to inspect the contents of a directory @param GeneratedAssetHandler $handler @return $this
[ "Set", "the", "handler", "used", "to", "manipulate", "the", "filesystem", "and", "add", "the", "ListFiles", "plugin", "from", "Flysystem", "to", "inspect", "the", "contents", "of", "a", "directory" ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryImportFeed.php#L81-L88
222,873
silverstripe/silverstripe-registry
src/RegistryImportFeed.php
RegistryImportFeed.getStoragePath
public function getStoragePath($modelClass = null) { $sanitisedClassName = $this->sanitiseClassName($modelClass ?: $this->modelClass); return str_replace('{model}', $sanitisedClassName, $this->config()->get('storage_path')); }
php
public function getStoragePath($modelClass = null) { $sanitisedClassName = $this->sanitiseClassName($modelClass ?: $this->modelClass); return str_replace('{model}', $sanitisedClassName, $this->config()->get('storage_path')); }
[ "public", "function", "getStoragePath", "(", "$", "modelClass", "=", "null", ")", "{", "$", "sanitisedClassName", "=", "$", "this", "->", "sanitiseClassName", "(", "$", "modelClass", "?", ":", "$", "this", "->", "modelClass", ")", ";", "return", "str_replace", "(", "'{model}'", ",", "$", "sanitisedClassName", ",", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'storage_path'", ")", ")", ";", "}" ]
Get the path that import files will be stored for this model @param string $modelClass If null, the current model class will be used @return string
[ "Get", "the", "path", "that", "import", "files", "will", "be", "stored", "for", "this", "model" ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryImportFeed.php#L106-L110
222,874
silverstripe/silverstripe-registry
src/RegistryImportFeed.php
RegistryImportFeed.getImportFilename
public function getImportFilename() { // Note: CLDR date format see DBDatetime $datetime = DBDatetime::now()->Format('y-MM-dd-HHmmss'); return str_replace('{date}', $datetime, $this->config()->get('storage_filename')); }
php
public function getImportFilename() { // Note: CLDR date format see DBDatetime $datetime = DBDatetime::now()->Format('y-MM-dd-HHmmss'); return str_replace('{date}', $datetime, $this->config()->get('storage_filename')); }
[ "public", "function", "getImportFilename", "(", ")", "{", "// Note: CLDR date format see DBDatetime", "$", "datetime", "=", "DBDatetime", "::", "now", "(", ")", "->", "Format", "(", "'y-MM-dd-HHmmss'", ")", ";", "return", "str_replace", "(", "'{date}'", ",", "$", "datetime", ",", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'storage_filename'", ")", ")", ";", "}" ]
Returns a relatively unique filename to storage imported data feeds as @return string
[ "Returns", "a", "relatively", "unique", "filename", "to", "storage", "imported", "data", "feeds", "as" ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryImportFeed.php#L141-L146
222,875
sgpatil/oriquent
src/Sgpatil/Orientdb/Eloquent/Builder.php
Builder.createWith
public function createWith(array $attributes, array $relations) { // Collect the model attributes and label in the form of ['label' => $label, 'attributes' => $attributes] // as expected by the Query Builder. $attributes = $this->prepareForCreation($this->model, $attributes); $model = ['label' => $this->model->getTable(), 'attributes' => $attributes]; /** * Collect the related models in the following for as expected by the Query Builder: * * [ * 'label' => ['Permission'], * 'relation' => [ * 'name' => 'photos', * 'type' => 'PHOTO', * 'direction' => 'out', * ], * 'values' => [ * // A mix of models and attributes, doesn't matter really.. * ['url' => '', 'caption' => ''], * ['url' => '', 'caption' => ''] * ] * ] */ $related = []; foreach ($relations as $relation => $values) { $name = $relation; // Get the relation by calling the model's relationship function. if (!method_exists($this->model, $relation)) throw new QueryException("The relation method $relation() does not exist on " . get_class($this->model)); $relationship = $this->model->$relation(); // Bring the model from the relationship. $relatedModel = $relationship->getRelated(); // We will first check to see what the dev have passed as values // so that we make sure that we have an array moving forward // In the case of a model Id or an associative array or a Model instance it means that // this is probably a One-To-One relationship or the dev decided not to add // multiple records as relations so we'll wrap it up in an array. if (!is_array($values) || Helpers::isAssocArray($values) || $values instanceof Model) $values = [$values]; $label = $relationship->getRelated()->getTable(); $direction = $relationship->getEdgeDirection(); $type = $relationship->getRelationType(); // Hold the models that we need to attach $attach = []; // Hold the models that we need to create $create = []; // Separate the models that needs to be attached from the ones that needs // to be created. foreach ($values as $value) { // If this is a Model then the $exists property will indicate what we need // so we'll add its id to be attached. if ($value instanceof Model and $value->exists === true) { $attach[] = $value->getKey(); } // Next we will check whether we got a Collection in so that we deal with it // accordingly, which guarantees sending an Eloquent result straight in would work. elseif ($value instanceof Collection) { $attach = array_merge($attach, $value->lists('id')); } // Or in the case where the attributes are neither an array nor a model instance // then this is assumed to be the model Id that the dev means to attach and since // Orientdb node Ids are always an int then we take that as a value. elseif (!is_array($value) && !$value instanceof Model) { $attach[] = intval($value); } // In this case the record is considered to be new to the market so let's create it. else $create[] = $this->prepareForCreation($relatedModel, $value); } $relation = compact('name', 'type', 'direction'); $related[] = compact('relation', 'label', 'create', 'attach'); } $result = $this->query->createWith($model, $related); $models = $this->resultsToModels($this->model->getConnectionName(), $result); return (!empty($models)) ? reset($models) : null; }
php
public function createWith(array $attributes, array $relations) { // Collect the model attributes and label in the form of ['label' => $label, 'attributes' => $attributes] // as expected by the Query Builder. $attributes = $this->prepareForCreation($this->model, $attributes); $model = ['label' => $this->model->getTable(), 'attributes' => $attributes]; /** * Collect the related models in the following for as expected by the Query Builder: * * [ * 'label' => ['Permission'], * 'relation' => [ * 'name' => 'photos', * 'type' => 'PHOTO', * 'direction' => 'out', * ], * 'values' => [ * // A mix of models and attributes, doesn't matter really.. * ['url' => '', 'caption' => ''], * ['url' => '', 'caption' => ''] * ] * ] */ $related = []; foreach ($relations as $relation => $values) { $name = $relation; // Get the relation by calling the model's relationship function. if (!method_exists($this->model, $relation)) throw new QueryException("The relation method $relation() does not exist on " . get_class($this->model)); $relationship = $this->model->$relation(); // Bring the model from the relationship. $relatedModel = $relationship->getRelated(); // We will first check to see what the dev have passed as values // so that we make sure that we have an array moving forward // In the case of a model Id or an associative array or a Model instance it means that // this is probably a One-To-One relationship or the dev decided not to add // multiple records as relations so we'll wrap it up in an array. if (!is_array($values) || Helpers::isAssocArray($values) || $values instanceof Model) $values = [$values]; $label = $relationship->getRelated()->getTable(); $direction = $relationship->getEdgeDirection(); $type = $relationship->getRelationType(); // Hold the models that we need to attach $attach = []; // Hold the models that we need to create $create = []; // Separate the models that needs to be attached from the ones that needs // to be created. foreach ($values as $value) { // If this is a Model then the $exists property will indicate what we need // so we'll add its id to be attached. if ($value instanceof Model and $value->exists === true) { $attach[] = $value->getKey(); } // Next we will check whether we got a Collection in so that we deal with it // accordingly, which guarantees sending an Eloquent result straight in would work. elseif ($value instanceof Collection) { $attach = array_merge($attach, $value->lists('id')); } // Or in the case where the attributes are neither an array nor a model instance // then this is assumed to be the model Id that the dev means to attach and since // Orientdb node Ids are always an int then we take that as a value. elseif (!is_array($value) && !$value instanceof Model) { $attach[] = intval($value); } // In this case the record is considered to be new to the market so let's create it. else $create[] = $this->prepareForCreation($relatedModel, $value); } $relation = compact('name', 'type', 'direction'); $related[] = compact('relation', 'label', 'create', 'attach'); } $result = $this->query->createWith($model, $related); $models = $this->resultsToModels($this->model->getConnectionName(), $result); return (!empty($models)) ? reset($models) : null; }
[ "public", "function", "createWith", "(", "array", "$", "attributes", ",", "array", "$", "relations", ")", "{", "// Collect the model attributes and label in the form of ['label' => $label, 'attributes' => $attributes]", "// as expected by the Query Builder.", "$", "attributes", "=", "$", "this", "->", "prepareForCreation", "(", "$", "this", "->", "model", ",", "$", "attributes", ")", ";", "$", "model", "=", "[", "'label'", "=>", "$", "this", "->", "model", "->", "getTable", "(", ")", ",", "'attributes'", "=>", "$", "attributes", "]", ";", "/**\n * Collect the related models in the following for as expected by the Query Builder:\n *\n * [\n * 'label' => ['Permission'],\n * 'relation' => [\n * 'name' => 'photos',\n * 'type' => 'PHOTO',\n * 'direction' => 'out',\n * ],\n * 'values' => [\n * // A mix of models and attributes, doesn't matter really..\n * ['url' => '', 'caption' => ''],\n * ['url' => '', 'caption' => '']\n * ]\n * ]\n */", "$", "related", "=", "[", "]", ";", "foreach", "(", "$", "relations", "as", "$", "relation", "=>", "$", "values", ")", "{", "$", "name", "=", "$", "relation", ";", "// Get the relation by calling the model's relationship function.", "if", "(", "!", "method_exists", "(", "$", "this", "->", "model", ",", "$", "relation", ")", ")", "throw", "new", "QueryException", "(", "\"The relation method $relation() does not exist on \"", ".", "get_class", "(", "$", "this", "->", "model", ")", ")", ";", "$", "relationship", "=", "$", "this", "->", "model", "->", "$", "relation", "(", ")", ";", "// Bring the model from the relationship.", "$", "relatedModel", "=", "$", "relationship", "->", "getRelated", "(", ")", ";", "// We will first check to see what the dev have passed as values", "// so that we make sure that we have an array moving forward", "// In the case of a model Id or an associative array or a Model instance it means that", "// this is probably a One-To-One relationship or the dev decided not to add", "// multiple records as relations so we'll wrap it up in an array.", "if", "(", "!", "is_array", "(", "$", "values", ")", "||", "Helpers", "::", "isAssocArray", "(", "$", "values", ")", "||", "$", "values", "instanceof", "Model", ")", "$", "values", "=", "[", "$", "values", "]", ";", "$", "label", "=", "$", "relationship", "->", "getRelated", "(", ")", "->", "getTable", "(", ")", ";", "$", "direction", "=", "$", "relationship", "->", "getEdgeDirection", "(", ")", ";", "$", "type", "=", "$", "relationship", "->", "getRelationType", "(", ")", ";", "// Hold the models that we need to attach", "$", "attach", "=", "[", "]", ";", "// Hold the models that we need to create", "$", "create", "=", "[", "]", ";", "// Separate the models that needs to be attached from the ones that needs", "// to be created.", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "// If this is a Model then the $exists property will indicate what we need", "// so we'll add its id to be attached.", "if", "(", "$", "value", "instanceof", "Model", "and", "$", "value", "->", "exists", "===", "true", ")", "{", "$", "attach", "[", "]", "=", "$", "value", "->", "getKey", "(", ")", ";", "}", "// Next we will check whether we got a Collection in so that we deal with it", "// accordingly, which guarantees sending an Eloquent result straight in would work.", "elseif", "(", "$", "value", "instanceof", "Collection", ")", "{", "$", "attach", "=", "array_merge", "(", "$", "attach", ",", "$", "value", "->", "lists", "(", "'id'", ")", ")", ";", "}", "// Or in the case where the attributes are neither an array nor a model instance", "// then this is assumed to be the model Id that the dev means to attach and since", "// Orientdb node Ids are always an int then we take that as a value.", "elseif", "(", "!", "is_array", "(", "$", "value", ")", "&&", "!", "$", "value", "instanceof", "Model", ")", "{", "$", "attach", "[", "]", "=", "intval", "(", "$", "value", ")", ";", "}", "// In this case the record is considered to be new to the market so let's create it.", "else", "$", "create", "[", "]", "=", "$", "this", "->", "prepareForCreation", "(", "$", "relatedModel", ",", "$", "value", ")", ";", "}", "$", "relation", "=", "compact", "(", "'name'", ",", "'type'", ",", "'direction'", ")", ";", "$", "related", "[", "]", "=", "compact", "(", "'relation'", ",", "'label'", ",", "'create'", ",", "'attach'", ")", ";", "}", "$", "result", "=", "$", "this", "->", "query", "->", "createWith", "(", "$", "model", ",", "$", "related", ")", ";", "$", "models", "=", "$", "this", "->", "resultsToModels", "(", "$", "this", "->", "model", "->", "getConnectionName", "(", ")", ",", "$", "result", ")", ";", "return", "(", "!", "empty", "(", "$", "models", ")", ")", "?", "reset", "(", "$", "models", ")", ":", "null", ";", "}" ]
Create a new record from the parent Model and new related records with it. @param array $attributes @param array $relations @return \Sgpatil\Orientdb\Eloquent\Model
[ "Create", "a", "new", "record", "from", "the", "parent", "Model", "and", "new", "related", "records", "with", "it", "." ]
cf0f2ba688496260946f569a20c351e91f287c32
https://github.com/sgpatil/oriquent/blob/cf0f2ba688496260946f569a20c351e91f287c32/src/Sgpatil/Orientdb/Eloquent/Builder.php#L575-L657
222,876
silverstripe/silverstripe-registry
src/RegistryPage.php
RegistryPage.Breadcrumbs
public function Breadcrumbs( $maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false, $delimiter = '&raquo;' ) { $page = $this; $pages = []; while ($page && (!$maxDepth || count($pages) < $maxDepth) && (!$stopAtPageType || $page->ClassName != $stopAtPageType) ) { if ($showHidden || $page->ShowInMenus || ($page->ID == $this->ID)) { $pages[] = $page; } $page = $page->Parent; } // Add on the item we're currently showing. $controller = Controller::curr(); if ($controller) { $request = $controller->getRequest(); if ($request->param('Action') == 'show') { $id = $request->param('ID'); if ($id) { $object = DataObject::get_by_id($this->getDataClass(), $id); array_unshift($pages, $object); } } } $template = SSViewer::create('BreadcrumbsTemplate'); return $template->process($this->customise(ArrayData::create([ 'Pages' => ArrayList::create(array_reverse($pages)) ]))); }
php
public function Breadcrumbs( $maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false, $delimiter = '&raquo;' ) { $page = $this; $pages = []; while ($page && (!$maxDepth || count($pages) < $maxDepth) && (!$stopAtPageType || $page->ClassName != $stopAtPageType) ) { if ($showHidden || $page->ShowInMenus || ($page->ID == $this->ID)) { $pages[] = $page; } $page = $page->Parent; } // Add on the item we're currently showing. $controller = Controller::curr(); if ($controller) { $request = $controller->getRequest(); if ($request->param('Action') == 'show') { $id = $request->param('ID'); if ($id) { $object = DataObject::get_by_id($this->getDataClass(), $id); array_unshift($pages, $object); } } } $template = SSViewer::create('BreadcrumbsTemplate'); return $template->process($this->customise(ArrayData::create([ 'Pages' => ArrayList::create(array_reverse($pages)) ]))); }
[ "public", "function", "Breadcrumbs", "(", "$", "maxDepth", "=", "20", ",", "$", "unlinked", "=", "false", ",", "$", "stopAtPageType", "=", "false", ",", "$", "showHidden", "=", "false", ",", "$", "delimiter", "=", "'&raquo;'", ")", "{", "$", "page", "=", "$", "this", ";", "$", "pages", "=", "[", "]", ";", "while", "(", "$", "page", "&&", "(", "!", "$", "maxDepth", "||", "count", "(", "$", "pages", ")", "<", "$", "maxDepth", ")", "&&", "(", "!", "$", "stopAtPageType", "||", "$", "page", "->", "ClassName", "!=", "$", "stopAtPageType", ")", ")", "{", "if", "(", "$", "showHidden", "||", "$", "page", "->", "ShowInMenus", "||", "(", "$", "page", "->", "ID", "==", "$", "this", "->", "ID", ")", ")", "{", "$", "pages", "[", "]", "=", "$", "page", ";", "}", "$", "page", "=", "$", "page", "->", "Parent", ";", "}", "// Add on the item we're currently showing.", "$", "controller", "=", "Controller", "::", "curr", "(", ")", ";", "if", "(", "$", "controller", ")", "{", "$", "request", "=", "$", "controller", "->", "getRequest", "(", ")", ";", "if", "(", "$", "request", "->", "param", "(", "'Action'", ")", "==", "'show'", ")", "{", "$", "id", "=", "$", "request", "->", "param", "(", "'ID'", ")", ";", "if", "(", "$", "id", ")", "{", "$", "object", "=", "DataObject", "::", "get_by_id", "(", "$", "this", "->", "getDataClass", "(", ")", ",", "$", "id", ")", ";", "array_unshift", "(", "$", "pages", ",", "$", "object", ")", ";", "}", "}", "}", "$", "template", "=", "SSViewer", "::", "create", "(", "'BreadcrumbsTemplate'", ")", ";", "return", "$", "template", "->", "process", "(", "$", "this", "->", "customise", "(", "ArrayData", "::", "create", "(", "[", "'Pages'", "=>", "ArrayList", "::", "create", "(", "array_reverse", "(", "$", "pages", ")", ")", "]", ")", ")", ")", ";", "}" ]
Modified version of Breadcrumbs, to cater for viewing items.
[ "Modified", "version", "of", "Breadcrumbs", "to", "cater", "for", "viewing", "items", "." ]
36f97a5eda09132c82a4ef6b858f6fed14bfd368
https://github.com/silverstripe/silverstripe-registry/blob/36f97a5eda09132c82a4ef6b858f6fed14bfd368/src/RegistryPage.php#L99-L138
222,877
jstewmc/php-helpers
src/Dir.php
Dir.copy
public static function copy($source, $destination, $mode = 0777) { $isSuccess = false; // if $source and $destination are given if ($source !== null && $destination !== null && $mode !== null) { // if $source is a string if (is_string($source)) { // if $destination is a string if (is_string($destination)) { // if $mode is an integer or false if (is_integer($mode) || $mode === false) { // if the source directory exists and is a directory if (is_dir($source)) { // if the source directory is readable if (is_readable($source)) { // if the destination directory does not exist and we're ok to create it if ( ! file_exists($destination) && is_integer($mode)) { mkdir($destination, $mode, true); } // if the destination directory exists and is a directory if (is_dir($destination)) { // if the destination directory is writable if (is_writable($destination)) { // open the source directory $sourceDir = opendir($source); // loop through the entities in the source directory $entity = readdir($sourceDir); while ($entity !== false) { // if not the special entities "." and ".." if ($entity != '.' && $entity != '..') { // if the file is a dir if (is_dir($source.DIRECTORY_SEPARATOR.$entity)) { // recursively copy the dir $isSuccess = self::copy( $source.DIRECTORY_SEPARATOR.$entity, $destination.DIRECTORY_SEPARATOR.$entity, $mode ); } else { // otherwise, just copy the file $isSuccess = copy( $source.DIRECTORY_SEPARATOR.$entity, $destination.DIRECTORY_SEPARATOR.$entity ); } // if an error occurs, stop if ( ! $isSuccess) { break; } } else { // there was nothing to remove // set $isSuccess to true in case the directory is empty // if it's not empty, $isSuccess will be overwritten on the next iteration // $isSuccess = true; } // advance to the next file $entity = readdir($sourceDir); } // close the source directory closedir($sourceDir); } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, destination, to be a writable directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, destination, to be an existing directory ". "(or it expects parameter three, mode, to be an integer)" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, source, to be a readable directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, source, to be an existing directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, mode, to be an integer or false" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, destination, to be a string" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, source, to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters: source, destination, and mode" ); } return $isSuccess; }
php
public static function copy($source, $destination, $mode = 0777) { $isSuccess = false; // if $source and $destination are given if ($source !== null && $destination !== null && $mode !== null) { // if $source is a string if (is_string($source)) { // if $destination is a string if (is_string($destination)) { // if $mode is an integer or false if (is_integer($mode) || $mode === false) { // if the source directory exists and is a directory if (is_dir($source)) { // if the source directory is readable if (is_readable($source)) { // if the destination directory does not exist and we're ok to create it if ( ! file_exists($destination) && is_integer($mode)) { mkdir($destination, $mode, true); } // if the destination directory exists and is a directory if (is_dir($destination)) { // if the destination directory is writable if (is_writable($destination)) { // open the source directory $sourceDir = opendir($source); // loop through the entities in the source directory $entity = readdir($sourceDir); while ($entity !== false) { // if not the special entities "." and ".." if ($entity != '.' && $entity != '..') { // if the file is a dir if (is_dir($source.DIRECTORY_SEPARATOR.$entity)) { // recursively copy the dir $isSuccess = self::copy( $source.DIRECTORY_SEPARATOR.$entity, $destination.DIRECTORY_SEPARATOR.$entity, $mode ); } else { // otherwise, just copy the file $isSuccess = copy( $source.DIRECTORY_SEPARATOR.$entity, $destination.DIRECTORY_SEPARATOR.$entity ); } // if an error occurs, stop if ( ! $isSuccess) { break; } } else { // there was nothing to remove // set $isSuccess to true in case the directory is empty // if it's not empty, $isSuccess will be overwritten on the next iteration // $isSuccess = true; } // advance to the next file $entity = readdir($sourceDir); } // close the source directory closedir($sourceDir); } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, destination, to be a writable directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, destination, to be an existing directory ". "(or it expects parameter three, mode, to be an integer)" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, source, to be a readable directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, source, to be an existing directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, mode, to be an integer or false" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, destination, to be a string" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, source, to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters: source, destination, and mode" ); } return $isSuccess; }
[ "public", "static", "function", "copy", "(", "$", "source", ",", "$", "destination", ",", "$", "mode", "=", "0777", ")", "{", "$", "isSuccess", "=", "false", ";", "// if $source and $destination are given\r", "if", "(", "$", "source", "!==", "null", "&&", "$", "destination", "!==", "null", "&&", "$", "mode", "!==", "null", ")", "{", "// if $source is a string\r", "if", "(", "is_string", "(", "$", "source", ")", ")", "{", "// if $destination is a string\r", "if", "(", "is_string", "(", "$", "destination", ")", ")", "{", "// if $mode is an integer or false\r", "if", "(", "is_integer", "(", "$", "mode", ")", "||", "$", "mode", "===", "false", ")", "{", "// if the source directory exists and is a directory\r", "if", "(", "is_dir", "(", "$", "source", ")", ")", "{", "// if the source directory is readable\r", "if", "(", "is_readable", "(", "$", "source", ")", ")", "{", "// if the destination directory does not exist and we're ok to create it\r", "if", "(", "!", "file_exists", "(", "$", "destination", ")", "&&", "is_integer", "(", "$", "mode", ")", ")", "{", "mkdir", "(", "$", "destination", ",", "$", "mode", ",", "true", ")", ";", "}", "// if the destination directory exists and is a directory\r", "if", "(", "is_dir", "(", "$", "destination", ")", ")", "{", "// if the destination directory is writable\r", "if", "(", "is_writable", "(", "$", "destination", ")", ")", "{", "// open the source directory\r", "$", "sourceDir", "=", "opendir", "(", "$", "source", ")", ";", "// loop through the entities in the source directory\r", "$", "entity", "=", "readdir", "(", "$", "sourceDir", ")", ";", "while", "(", "$", "entity", "!==", "false", ")", "{", "// if not the special entities \".\" and \"..\"\r", "if", "(", "$", "entity", "!=", "'.'", "&&", "$", "entity", "!=", "'..'", ")", "{", "// if the file is a dir\r", "if", "(", "is_dir", "(", "$", "source", ".", "DIRECTORY_SEPARATOR", ".", "$", "entity", ")", ")", "{", "// recursively copy the dir\r", "$", "isSuccess", "=", "self", "::", "copy", "(", "$", "source", ".", "DIRECTORY_SEPARATOR", ".", "$", "entity", ",", "$", "destination", ".", "DIRECTORY_SEPARATOR", ".", "$", "entity", ",", "$", "mode", ")", ";", "}", "else", "{", "// otherwise, just copy the file\r", "$", "isSuccess", "=", "copy", "(", "$", "source", ".", "DIRECTORY_SEPARATOR", ".", "$", "entity", ",", "$", "destination", ".", "DIRECTORY_SEPARATOR", ".", "$", "entity", ")", ";", "}", "// if an error occurs, stop\r", "if", "(", "!", "$", "isSuccess", ")", "{", "break", ";", "}", "}", "else", "{", "// there was nothing to remove\r", "// set $isSuccess to true in case the directory is empty\r", "// if it's not empty, $isSuccess will be overwritten on the next iteration\r", "//\r", "$", "isSuccess", "=", "true", ";", "}", "// advance to the next file\r", "$", "entity", "=", "readdir", "(", "$", "sourceDir", ")", ";", "}", "// close the source directory\r", "closedir", "(", "$", "sourceDir", ")", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two, destination, to be a writable directory\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two, destination, to be an existing directory \"", ".", "\"(or it expects parameter three, mode, to be an integer)\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one, source, to be a readable directory\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one, source, to be an existing directory\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter three, mode, to be an integer or false\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two, destination, to be a string\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one, source, to be a string\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\"() expects two or three parameters: source, destination, and mode\"", ")", ";", "}", "return", "$", "isSuccess", ";", "}" ]
Copies files or directory to the filesystem PHP's native copy() function only copies files, not directories. I will recursively copy a directory and all of its files and sub-directories. If the $destination exists, I will overwrite any existing files with the corresponding file in the $source directory. If $destination does not exist, and $mode is set to false I will throw an InvalidArgumentException. If $mode is an integer (or omitted), I attempt to create the destination directory. I will recursively create destination directories as needed. To copy a file, use PHP's native copy() method. @since 0.1.0 @param string $source the source directory path @param string $destination the destination directory path @param int $mode the mode of the destination directory as an octal number with a leading zero (ignored on Windows) (optional; if omitted, defaults to 0777, the widest possible access) (set to false to throw an exception if the destination directory does not exist) @return bool true if successful @throws \BadMethodCallException if $source, $destination, or $mode is null @throws \InvalidArgumentException if $source is not a string @throws \InvalidArgumentException if $destination is not a string @throws \InvalidArgumentException if $mode is not an integer or false @throws \InvalidArgumentException if $source does not exist or is not a directory @throws \InvalidArgumentException if $source is not readable @throws \InvalidArgumentException if $destination does not exist or it could not be created successfully @throws \InvalidArgumentException if $destination is not writeable @see http://stackoverflow.com/a/2050909 Felix King's answer to "Copy entire contents of a directory to another using php" on StackOverflow
[ "Copies", "files", "or", "directory", "to", "the", "filesystem" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Dir.php#L115-L220
222,878
jstewmc/php-helpers
src/Dir.php
Dir.remove
public static function remove($directory, $container) { $isSuccess = false; // if $directory and $container are given if ($directory !== null && $container !== null) { // if $directory is a string if (is_string($directory)) { // if $container is a string if (is_string($container)) { // if the $directory argument is a dir if (is_dir($directory)) { // if $directory is writable if (is_writable($directory)) { // if the $directory is in the $container if (\Jstewmc\PhpHelpers\Str::startsWith($directory, $container)) { // open the directory $dir = opendir($directory); // read the first entity $entity = readdir($dir); // loop through the dir's entities while ($entity !== false) { // if the entity is not the special chars "." and ".." if ($entity != '.' && $entity != '..') { // if the entity is a sub-directory if (is_dir($directory.DIRECTORY_SEPARATOR.$entity)) { // clear and delete the sub-directory $isSuccess = self::remove( $directory.DIRECTORY_SEPARATOR.$entity, $container ); } else { // otheriwse, the entity is a file; delete it $isSuccess = unlink($directory.DIRECTORY_SEPARATOR.$entity); } // if an error occurs, stop if ( ! $isSuccess) { break; } } else { // there was nothing to remove // set $isSuccess true in case the directory is empty // if it's not empty, $isSuccess will be overwritten anyway // $isSuccess = true; } // advance to the next entity $entity = readdir($dir); } // close and remove the directory closedir($dir); $isSuccess = rmdir($directory.DIRECTORY_SEPARATOR.$entity); } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, container, to contain the directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, directory, to be a writable directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, directory, to be a valid directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects the second parameter, container, to be a string" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects the first parameter, directory, to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two string parameters, directory and container" ); } return $isSuccess; }
php
public static function remove($directory, $container) { $isSuccess = false; // if $directory and $container are given if ($directory !== null && $container !== null) { // if $directory is a string if (is_string($directory)) { // if $container is a string if (is_string($container)) { // if the $directory argument is a dir if (is_dir($directory)) { // if $directory is writable if (is_writable($directory)) { // if the $directory is in the $container if (\Jstewmc\PhpHelpers\Str::startsWith($directory, $container)) { // open the directory $dir = opendir($directory); // read the first entity $entity = readdir($dir); // loop through the dir's entities while ($entity !== false) { // if the entity is not the special chars "." and ".." if ($entity != '.' && $entity != '..') { // if the entity is a sub-directory if (is_dir($directory.DIRECTORY_SEPARATOR.$entity)) { // clear and delete the sub-directory $isSuccess = self::remove( $directory.DIRECTORY_SEPARATOR.$entity, $container ); } else { // otheriwse, the entity is a file; delete it $isSuccess = unlink($directory.DIRECTORY_SEPARATOR.$entity); } // if an error occurs, stop if ( ! $isSuccess) { break; } } else { // there was nothing to remove // set $isSuccess true in case the directory is empty // if it's not empty, $isSuccess will be overwritten anyway // $isSuccess = true; } // advance to the next entity $entity = readdir($dir); } // close and remove the directory closedir($dir); $isSuccess = rmdir($directory.DIRECTORY_SEPARATOR.$entity); } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, container, to contain the directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, directory, to be a writable directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, directory, to be a valid directory" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects the second parameter, container, to be a string" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects the first parameter, directory, to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two string parameters, directory and container" ); } return $isSuccess; }
[ "public", "static", "function", "remove", "(", "$", "directory", ",", "$", "container", ")", "{", "$", "isSuccess", "=", "false", ";", "// if $directory and $container are given\r", "if", "(", "$", "directory", "!==", "null", "&&", "$", "container", "!==", "null", ")", "{", "// if $directory is a string\r", "if", "(", "is_string", "(", "$", "directory", ")", ")", "{", "// if $container is a string\r", "if", "(", "is_string", "(", "$", "container", ")", ")", "{", "// if the $directory argument is a dir\r", "if", "(", "is_dir", "(", "$", "directory", ")", ")", "{", "// if $directory is writable\r", "if", "(", "is_writable", "(", "$", "directory", ")", ")", "{", "// if the $directory is in the $container\r", "if", "(", "\\", "Jstewmc", "\\", "PhpHelpers", "\\", "Str", "::", "startsWith", "(", "$", "directory", ",", "$", "container", ")", ")", "{", "// open the directory\r", "$", "dir", "=", "opendir", "(", "$", "directory", ")", ";", "// read the first entity\r", "$", "entity", "=", "readdir", "(", "$", "dir", ")", ";", "// loop through the dir's entities\r", "while", "(", "$", "entity", "!==", "false", ")", "{", "// if the entity is not the special chars \".\" and \"..\"\r", "if", "(", "$", "entity", "!=", "'.'", "&&", "$", "entity", "!=", "'..'", ")", "{", "// if the entity is a sub-directory\r", "if", "(", "is_dir", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "$", "entity", ")", ")", "{", "// clear and delete the sub-directory\r", "$", "isSuccess", "=", "self", "::", "remove", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "$", "entity", ",", "$", "container", ")", ";", "}", "else", "{", "// otheriwse, the entity is a file; delete it\r", "$", "isSuccess", "=", "unlink", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "$", "entity", ")", ";", "}", "// if an error occurs, stop\r", "if", "(", "!", "$", "isSuccess", ")", "{", "break", ";", "}", "}", "else", "{", "// there was nothing to remove\r", "// set $isSuccess true in case the directory is empty\r", "// if it's not empty, $isSuccess will be overwritten anyway\r", "//\r", "$", "isSuccess", "=", "true", ";", "}", "// advance to the next entity\r", "$", "entity", "=", "readdir", "(", "$", "dir", ")", ";", "}", "// close and remove the directory\r", "closedir", "(", "$", "dir", ")", ";", "$", "isSuccess", "=", "rmdir", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "$", "entity", ")", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two, container, to contain the directory\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one, directory, to be a writable directory\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one, directory, to be a valid directory\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects the second parameter, container, to be a string\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects the first parameter, directory, to be a string\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\"() expects two string parameters, directory and container\"", ")", ";", "}", "return", "$", "isSuccess", ";", "}" ]
Deletes a non-empty directory and its sub-directories PHP's native rmdir() function requires the directory to be empty. I'll recursively delete a directory's files and sub-directories. BE CAREFUL! Use the $container argument to be safe. @since 0.1.0 @param string $directory the path of the directory to remove @param string $container an ancestor directory of $directory @return bool true if success @throws \BadMethodCallException if $directory or $container is null @throws \InvalidArgumentException if $directory is not a string @throws \InvalidArgumentException if $container is not a string @throws \InvalidArgumentException if $directory is not a valid directory path @throws \InvalidArgumentException if $directory is not writeable @throws \InvalidArgumentException if $directory is not contained in $container @see http://stackoverflow.com/a/11614201 donald123's answer to "Remove all files, folders, and their subfolders with php" on StackOverflow @see http://us1.php.net/rmdir rmdir() man page
[ "Deletes", "a", "non", "-", "empty", "directory", "and", "its", "sub", "-", "directories" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Dir.php#L260-L344
222,879
TheFrozenFire/PHP-Swagger-Parser
src/Swagger/SchemaResolver.php
SchemaResolver.parseType
public function parseType(Object\TypeObjectInterface $type, $data) { if($type instanceof Object\ReferentialInterface && $type->hasRef()) { $objectType = $type->getRef(); $type = $this->resolveReference($type); } else { try { $objectType = $type->getType(); } catch(SwaggerException\MissingDocumentPropertyException $e) { $objectType = null; } } if($objectType == 'array') { $schemaObject = []; $arrayItemType = $type->getItems(); foreach($data as $key => $value) { $schemaObject[$key] = $this->parseType($arrayItemType, $value); } } elseif($type instanceof Object\Schema) { $schemaObject = new SchemaObject($objectType); foreach(array_keys(get_object_vars($data)) as $propertyKey) { try { $propertySchema = $this->findSchemaForProperty($type, $propertyKey); } catch(SwaggerException\MissingDocumentPropertyException $e) { throw (new SwaggerException\UndefinedPropertySchemaException) ->setPropertyName($name) ->setSchema($type); } $propertyValue = $this->parseType( $propertySchema, $data->$propertyKey ); $schemaObject->setProperty($propertyKey, $propertyValue); } } else { $schemaObject = $data; } return $schemaObject; }
php
public function parseType(Object\TypeObjectInterface $type, $data) { if($type instanceof Object\ReferentialInterface && $type->hasRef()) { $objectType = $type->getRef(); $type = $this->resolveReference($type); } else { try { $objectType = $type->getType(); } catch(SwaggerException\MissingDocumentPropertyException $e) { $objectType = null; } } if($objectType == 'array') { $schemaObject = []; $arrayItemType = $type->getItems(); foreach($data as $key => $value) { $schemaObject[$key] = $this->parseType($arrayItemType, $value); } } elseif($type instanceof Object\Schema) { $schemaObject = new SchemaObject($objectType); foreach(array_keys(get_object_vars($data)) as $propertyKey) { try { $propertySchema = $this->findSchemaForProperty($type, $propertyKey); } catch(SwaggerException\MissingDocumentPropertyException $e) { throw (new SwaggerException\UndefinedPropertySchemaException) ->setPropertyName($name) ->setSchema($type); } $propertyValue = $this->parseType( $propertySchema, $data->$propertyKey ); $schemaObject->setProperty($propertyKey, $propertyValue); } } else { $schemaObject = $data; } return $schemaObject; }
[ "public", "function", "parseType", "(", "Object", "\\", "TypeObjectInterface", "$", "type", ",", "$", "data", ")", "{", "if", "(", "$", "type", "instanceof", "Object", "\\", "ReferentialInterface", "&&", "$", "type", "->", "hasRef", "(", ")", ")", "{", "$", "objectType", "=", "$", "type", "->", "getRef", "(", ")", ";", "$", "type", "=", "$", "this", "->", "resolveReference", "(", "$", "type", ")", ";", "}", "else", "{", "try", "{", "$", "objectType", "=", "$", "type", "->", "getType", "(", ")", ";", "}", "catch", "(", "SwaggerException", "\\", "MissingDocumentPropertyException", "$", "e", ")", "{", "$", "objectType", "=", "null", ";", "}", "}", "if", "(", "$", "objectType", "==", "'array'", ")", "{", "$", "schemaObject", "=", "[", "]", ";", "$", "arrayItemType", "=", "$", "type", "->", "getItems", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "schemaObject", "[", "$", "key", "]", "=", "$", "this", "->", "parseType", "(", "$", "arrayItemType", ",", "$", "value", ")", ";", "}", "}", "elseif", "(", "$", "type", "instanceof", "Object", "\\", "Schema", ")", "{", "$", "schemaObject", "=", "new", "SchemaObject", "(", "$", "objectType", ")", ";", "foreach", "(", "array_keys", "(", "get_object_vars", "(", "$", "data", ")", ")", "as", "$", "propertyKey", ")", "{", "try", "{", "$", "propertySchema", "=", "$", "this", "->", "findSchemaForProperty", "(", "$", "type", ",", "$", "propertyKey", ")", ";", "}", "catch", "(", "SwaggerException", "\\", "MissingDocumentPropertyException", "$", "e", ")", "{", "throw", "(", "new", "SwaggerException", "\\", "UndefinedPropertySchemaException", ")", "->", "setPropertyName", "(", "$", "name", ")", "->", "setSchema", "(", "$", "type", ")", ";", "}", "$", "propertyValue", "=", "$", "this", "->", "parseType", "(", "$", "propertySchema", ",", "$", "data", "->", "$", "propertyKey", ")", ";", "$", "schemaObject", "->", "setProperty", "(", "$", "propertyKey", ",", "$", "propertyValue", ")", ";", "}", "}", "else", "{", "$", "schemaObject", "=", "$", "data", ";", "}", "return", "$", "schemaObject", ";", "}" ]
Parse a type-object with data into its respective structure @param Object\TypeObjectInterface $type - The schema for the type @param \stdClass $data - The input data @return SchemaObject|array
[ "Parse", "a", "type", "-", "object", "with", "data", "into", "its", "respective", "structure" ]
7070e63c7687ee764b392b3a3150931de97966bc
https://github.com/TheFrozenFire/PHP-Swagger-Parser/blob/7070e63c7687ee764b392b3a3150931de97966bc/src/Swagger/SchemaResolver.php#L34-L79
222,880
jstewmc/php-helpers
src/Arr.php
Arr.filterBykey
public static function filterBykey($array, $callback) { $filtered = array(); // if $array and $callback are given if ($array !== null && $callback !== null) { // if the input arr is actually an arr if (is_array($array)) { // if $callback is callable if (is_callable($callback)) { // if $array is not empty if ( ! empty($array)) { // if there are keys that pass the filter $keys = array_filter(array_keys($array), $callback); if ( ! empty($keys)) { $filtered = array_intersect_key($array, array_flip($keys)); } } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two to be a callable function" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects paramater one to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two parameters, an array and a callable function" ); } return $filtered; }
php
public static function filterBykey($array, $callback) { $filtered = array(); // if $array and $callback are given if ($array !== null && $callback !== null) { // if the input arr is actually an arr if (is_array($array)) { // if $callback is callable if (is_callable($callback)) { // if $array is not empty if ( ! empty($array)) { // if there are keys that pass the filter $keys = array_filter(array_keys($array), $callback); if ( ! empty($keys)) { $filtered = array_intersect_key($array, array_flip($keys)); } } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two to be a callable function" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects paramater one to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two parameters, an array and a callable function" ); } return $filtered; }
[ "public", "static", "function", "filterBykey", "(", "$", "array", ",", "$", "callback", ")", "{", "$", "filtered", "=", "array", "(", ")", ";", "// if $array and $callback are given\r", "if", "(", "$", "array", "!==", "null", "&&", "$", "callback", "!==", "null", ")", "{", "// if the input arr is actually an arr\r", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "// if $callback is callable\r", "if", "(", "is_callable", "(", "$", "callback", ")", ")", "{", "// if $array is not empty\r", "if", "(", "!", "empty", "(", "$", "array", ")", ")", "{", "// if there are keys that pass the filter\r", "$", "keys", "=", "array_filter", "(", "array_keys", "(", "$", "array", ")", ",", "$", "callback", ")", ";", "if", "(", "!", "empty", "(", "$", "keys", ")", ")", "{", "$", "filtered", "=", "array_intersect_key", "(", "$", "array", ",", "array_flip", "(", "$", "keys", ")", ")", ";", "}", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two to be a callable function\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects paramater one to be an array\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\"() expects two parameters, an array and a callable function\"", ")", ";", "}", "return", "$", "filtered", ";", "}" ]
Filters an array by key I'll iterate over each key in $array passing it to the $callback function. If the callback function returns true, the current value from $array is added to the result array. Array keys are preserved. For example: $a = ['foo', 'bar', 'baz']; Arr::filterByKey($a, function ($k) { return $k > 1; }); // returns ['baz'] @since 0.1.0 @param array $array the array to filter @param callback $callback the function to call for each key in $array @return array the filtered array @throws \BadMethodCallException if $array or $callback is null @throws \InvalidArgumentException if $array is not an array @throws \InvalidArgumentException if $callback is not a callable function @see http://php.net/manual/en/function.array-filter.php#99073 Acid24's filter by key function on on array_filter() man page
[ "Filters", "an", "array", "by", "key" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Arr.php#L120-L155
222,881
jstewmc/php-helpers
src/Arr.php
Arr.filterByKeyPrefix
public static function filterByKeyPrefix($array, $prefix) { $filtered = array(); // if $array and $prefix are given if ($array !== null && $prefix !== null) { // if $array is actually an array if (is_array($array)) { // if $prefix is a string if (is_string($prefix)) { // if $array is not empty if ( ! empty($array)) { // filter the array by the key's prefix $filtered = self::filterByKey($array, function ($k) use ($prefix) { return strpos($k, $prefix) === 0; }); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two to be a string prefix" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two parameters, an array and a string prefix" ); } return $filtered; }
php
public static function filterByKeyPrefix($array, $prefix) { $filtered = array(); // if $array and $prefix are given if ($array !== null && $prefix !== null) { // if $array is actually an array if (is_array($array)) { // if $prefix is a string if (is_string($prefix)) { // if $array is not empty if ( ! empty($array)) { // filter the array by the key's prefix $filtered = self::filterByKey($array, function ($k) use ($prefix) { return strpos($k, $prefix) === 0; }); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two to be a string prefix" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two parameters, an array and a string prefix" ); } return $filtered; }
[ "public", "static", "function", "filterByKeyPrefix", "(", "$", "array", ",", "$", "prefix", ")", "{", "$", "filtered", "=", "array", "(", ")", ";", "// if $array and $prefix are given\r", "if", "(", "$", "array", "!==", "null", "&&", "$", "prefix", "!==", "null", ")", "{", "// if $array is actually an array\r", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "// if $prefix is a string\r", "if", "(", "is_string", "(", "$", "prefix", ")", ")", "{", "// if $array is not empty\r", "if", "(", "!", "empty", "(", "$", "array", ")", ")", "{", "// filter the array by the key's prefix\r", "$", "filtered", "=", "self", "::", "filterByKey", "(", "$", "array", ",", "function", "(", "$", "k", ")", "use", "(", "$", "prefix", ")", "{", "return", "strpos", "(", "$", "k", ",", "$", "prefix", ")", "===", "0", ";", "}", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two to be a string prefix\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one to be an array\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\"() expects two parameters, an array and a string prefix\"", ")", ";", "}", "return", "$", "filtered", ";", "}" ]
Filters an array by a key prefix I'll iterate over each key in $array. If the key starts with $prefix, I'll add it to the result array. Array keys are preserved. For example: $a = ['foo' => 'bar', 'baz' => 'qux']; Arr::filterByKeyPrefix($a, 'b'); // returns ['baz'] @since 0.1.0 @param array $array the array to filter @param string $prefix the key's prefix to filter @return array the filtered array @throws \BadMethodCallException if $array or $prefix is null @throws \InvalidArgumentException if $array is not an array @throws \InvalidArgumentException if $prefix is not a string
[ "Filters", "an", "array", "by", "a", "key", "prefix" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Arr.php#L178-L212
222,882
jstewmc/php-helpers
src/Arr.php
Arr.inArray
public static function inArray($needle, $haystack, $wildcard = '*') { $inArray = false; // if $needle, $haystack, and $wildcard are given if ($needle !== null && $haystack !== null && $wildcard !== null) { // if $needle is a string if (is_string($needle)) { // if $haystack is an array if (is_array($haystack)) { // if $wildcard is a string if (is_string($wildcard)) { // if $needle contains the wildcard character if (strpos($needle, $wildcard) !== false) { // determine if the neeedle starts or ends with the wildcard $startsWith = \Jstewmc\PhpHelpers\Str::startsWith($needle, $wildcard); $endsWith = \Jstewmc\PhpHelpers\Str::endsWith($needle, $wildcard); // set the *actual* needle $needle = str_ireplace($wildcard, '', $needle); // loop through the haystack foreach ($haystack as $value) { if ($startsWith && $endsWith) { $inArray = strpos($value, $needle) !== false; } elseif ($startsWith) { $inArray = \Jstewmc\PhpHelpers\Str::endsWith($value, $needle); } else { $inArray = \Jstewmc\PhpHelpers\Str::startsWith($value, $needle); } // if the needle is in the array, stop looking if ($inArray) { break; } } } else { $inArray = in_array($needle, $haystack); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, the wildcard character, to be a string" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, the haystack, to be an array" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, the needle, to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters: needle, haystack, and wildcard" ); } return $inArray; }
php
public static function inArray($needle, $haystack, $wildcard = '*') { $inArray = false; // if $needle, $haystack, and $wildcard are given if ($needle !== null && $haystack !== null && $wildcard !== null) { // if $needle is a string if (is_string($needle)) { // if $haystack is an array if (is_array($haystack)) { // if $wildcard is a string if (is_string($wildcard)) { // if $needle contains the wildcard character if (strpos($needle, $wildcard) !== false) { // determine if the neeedle starts or ends with the wildcard $startsWith = \Jstewmc\PhpHelpers\Str::startsWith($needle, $wildcard); $endsWith = \Jstewmc\PhpHelpers\Str::endsWith($needle, $wildcard); // set the *actual* needle $needle = str_ireplace($wildcard, '', $needle); // loop through the haystack foreach ($haystack as $value) { if ($startsWith && $endsWith) { $inArray = strpos($value, $needle) !== false; } elseif ($startsWith) { $inArray = \Jstewmc\PhpHelpers\Str::endsWith($value, $needle); } else { $inArray = \Jstewmc\PhpHelpers\Str::startsWith($value, $needle); } // if the needle is in the array, stop looking if ($inArray) { break; } } } else { $inArray = in_array($needle, $haystack); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, the wildcard character, to be a string" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, the haystack, to be an array" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, the needle, to be a string" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters: needle, haystack, and wildcard" ); } return $inArray; }
[ "public", "static", "function", "inArray", "(", "$", "needle", ",", "$", "haystack", ",", "$", "wildcard", "=", "'*'", ")", "{", "$", "inArray", "=", "false", ";", "// if $needle, $haystack, and $wildcard are given\r", "if", "(", "$", "needle", "!==", "null", "&&", "$", "haystack", "!==", "null", "&&", "$", "wildcard", "!==", "null", ")", "{", "// if $needle is a string\r", "if", "(", "is_string", "(", "$", "needle", ")", ")", "{", "// if $haystack is an array\r", "if", "(", "is_array", "(", "$", "haystack", ")", ")", "{", "// if $wildcard is a string\r", "if", "(", "is_string", "(", "$", "wildcard", ")", ")", "{", "// if $needle contains the wildcard character\r", "if", "(", "strpos", "(", "$", "needle", ",", "$", "wildcard", ")", "!==", "false", ")", "{", "// determine if the neeedle starts or ends with the wildcard\r", "$", "startsWith", "=", "\\", "Jstewmc", "\\", "PhpHelpers", "\\", "Str", "::", "startsWith", "(", "$", "needle", ",", "$", "wildcard", ")", ";", "$", "endsWith", "=", "\\", "Jstewmc", "\\", "PhpHelpers", "\\", "Str", "::", "endsWith", "(", "$", "needle", ",", "$", "wildcard", ")", ";", "// set the *actual* needle\r", "$", "needle", "=", "str_ireplace", "(", "$", "wildcard", ",", "''", ",", "$", "needle", ")", ";", "// loop through the haystack\r", "foreach", "(", "$", "haystack", "as", "$", "value", ")", "{", "if", "(", "$", "startsWith", "&&", "$", "endsWith", ")", "{", "$", "inArray", "=", "strpos", "(", "$", "value", ",", "$", "needle", ")", "!==", "false", ";", "}", "elseif", "(", "$", "startsWith", ")", "{", "$", "inArray", "=", "\\", "Jstewmc", "\\", "PhpHelpers", "\\", "Str", "::", "endsWith", "(", "$", "value", ",", "$", "needle", ")", ";", "}", "else", "{", "$", "inArray", "=", "\\", "Jstewmc", "\\", "PhpHelpers", "\\", "Str", "::", "startsWith", "(", "$", "value", ",", "$", "needle", ")", ";", "}", "// if the needle is in the array, stop looking\r", "if", "(", "$", "inArray", ")", "{", "break", ";", "}", "}", "}", "else", "{", "$", "inArray", "=", "in_array", "(", "$", "needle", ",", "$", "haystack", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter three, the wildcard character, to be a string\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two, the haystack, to be an array\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one, the needle, to be a string\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\"() expects two or three parameters: needle, haystack, and wildcard\"", ")", ";", "}", "return", "$", "inArray", ";", "}" ]
Wildcard search for a value in an array I'll search $haystack for $needle. Unlike PHP's native in_array() method, I'll accept begins-with (e.g., "foo*"), ends-with (e.g., "*foo"), and contains (e.g., "*foo*") wildcard notation. For example: Arr::inArray('foo', ['foo', 'bar']); // returns true Arr::inArray('qux', ['foo', 'bar']); // returns false Arr::inArray('fo*', ['foo', 'bar']); // returns true Arr::inArray('*oo', ['foo', 'bar']); // returns true Arr::inArray('*o*', ['foo', 'bar']); // returns true @since 0.1.0 @param string $needle the needle to find @param string[] $haystack the haystack to search @param string $wildcard the wildcard character (optional; if omitted, defaults to '*') @return bool true if the needle exists in haystack @throws \BadMethodCallException if $needle, $haystack, or $wildcard is null @throws \InvalidArgumentException if $needle is not a string @throws \InvalidArgumentException if $haystack is not an array @throws \InvalidArgumentException if $wildcard is not a string
[ "Wildcard", "search", "for", "a", "value", "in", "an", "array" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Arr.php#L243-L301
222,883
jstewmc/php-helpers
src/Arr.php
Arr.permute
public static function permute(Array $set) { $perms = []; $j = 0; $size = count($set) - 1; $perm = range(0, $size); do { foreach ($perm as $i) { $perms[$j][] = $set[$i]; } } while ($perm = self::getNextPermutation($perm, $size) and ++$j); return $perms; }
php
public static function permute(Array $set) { $perms = []; $j = 0; $size = count($set) - 1; $perm = range(0, $size); do { foreach ($perm as $i) { $perms[$j][] = $set[$i]; } } while ($perm = self::getNextPermutation($perm, $size) and ++$j); return $perms; }
[ "public", "static", "function", "permute", "(", "Array", "$", "set", ")", "{", "$", "perms", "=", "[", "]", ";", "$", "j", "=", "0", ";", "$", "size", "=", "count", "(", "$", "set", ")", "-", "1", ";", "$", "perm", "=", "range", "(", "0", ",", "$", "size", ")", ";", "do", "{", "foreach", "(", "$", "perm", "as", "$", "i", ")", "{", "$", "perms", "[", "$", "j", "]", "[", "]", "=", "$", "set", "[", "$", "i", "]", ";", "}", "}", "while", "(", "$", "perm", "=", "self", "::", "getNextPermutation", "(", "$", "perm", ",", "$", "size", ")", "and", "++", "$", "j", ")", ";", "return", "$", "perms", ";", "}" ]
Returns an array of this array's permutations @param string[] $array an array of strings @return string[] an array of $array's permutations @see http://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm an example from O'Reilly's PHPCookbook @since 0.1.2
[ "Returns", "an", "array", "of", "this", "array", "s", "permutations" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Arr.php#L514-L529
222,884
jstewmc/php-helpers
src/Arr.php
Arr.sortByField
public static function sortByField($array, $field, $sort = 'asc') { // if $array, $field, and $sort are given if ($array !== null && $field !== null && $sort !== null) { // if $array is actually an array if (is_array($array)) { // if $field is a string if (is_string($field)) { // if $sort is a string if (is_string($sort)) { // if $sort is a valid sort if (in_array(strtolower($sort), array('asc', 'ascending', 'desc', 'descending'))) { // if $array is an array of arrays with $field key $passed = array_filter($array, function ($v) use ($field) { return is_array($v) && array_key_exists($field, $v); }); if (count($array) === count($passed)) { // sort the array using the field's value // by default, usort() will return results in ascending order // usort($array, function ($a, $b) use ($field) { if ($a[$field] < $b[$field]) { return -1; } elseif ($a[$field] > $b[$field]) { return 1; } else { return 0; } }); // if the sort order is descending $sort = strtolower($sort); if ($sort === 'desc' || $sort === 'descending') { $array = array_reverse($array); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be an array of arrays with the key '$field'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be 'asc[ending]' or 'desc[ending]'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be a string sort order" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, field, to be a string field name" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, array, to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters" ); } return $array; }
php
public static function sortByField($array, $field, $sort = 'asc') { // if $array, $field, and $sort are given if ($array !== null && $field !== null && $sort !== null) { // if $array is actually an array if (is_array($array)) { // if $field is a string if (is_string($field)) { // if $sort is a string if (is_string($sort)) { // if $sort is a valid sort if (in_array(strtolower($sort), array('asc', 'ascending', 'desc', 'descending'))) { // if $array is an array of arrays with $field key $passed = array_filter($array, function ($v) use ($field) { return is_array($v) && array_key_exists($field, $v); }); if (count($array) === count($passed)) { // sort the array using the field's value // by default, usort() will return results in ascending order // usort($array, function ($a, $b) use ($field) { if ($a[$field] < $b[$field]) { return -1; } elseif ($a[$field] > $b[$field]) { return 1; } else { return 0; } }); // if the sort order is descending $sort = strtolower($sort); if ($sort === 'desc' || $sort === 'descending') { $array = array_reverse($array); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be an array of arrays with the key '$field'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be 'asc[ending]' or 'desc[ending]'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be a string sort order" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, field, to be a string field name" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, array, to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters" ); } return $array; }
[ "public", "static", "function", "sortByField", "(", "$", "array", ",", "$", "field", ",", "$", "sort", "=", "'asc'", ")", "{", "// if $array, $field, and $sort are given\r", "if", "(", "$", "array", "!==", "null", "&&", "$", "field", "!==", "null", "&&", "$", "sort", "!==", "null", ")", "{", "// if $array is actually an array\r", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "// if $field is a string\r", "if", "(", "is_string", "(", "$", "field", ")", ")", "{", "// if $sort is a string\r", "if", "(", "is_string", "(", "$", "sort", ")", ")", "{", "// if $sort is a valid sort\r", "if", "(", "in_array", "(", "strtolower", "(", "$", "sort", ")", ",", "array", "(", "'asc'", ",", "'ascending'", ",", "'desc'", ",", "'descending'", ")", ")", ")", "{", "// if $array is an array of arrays with $field key\r", "$", "passed", "=", "array_filter", "(", "$", "array", ",", "function", "(", "$", "v", ")", "use", "(", "$", "field", ")", "{", "return", "is_array", "(", "$", "v", ")", "&&", "array_key_exists", "(", "$", "field", ",", "$", "v", ")", ";", "}", ")", ";", "if", "(", "count", "(", "$", "array", ")", "===", "count", "(", "$", "passed", ")", ")", "{", "// sort the array using the field's value\r", "// by default, usort() will return results in ascending order\r", "//\r", "usort", "(", "$", "array", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "field", ")", "{", "if", "(", "$", "a", "[", "$", "field", "]", "<", "$", "b", "[", "$", "field", "]", ")", "{", "return", "-", "1", ";", "}", "elseif", "(", "$", "a", "[", "$", "field", "]", ">", "$", "b", "[", "$", "field", "]", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}", ")", ";", "// if the sort order is descending\r", "$", "sort", "=", "strtolower", "(", "$", "sort", ")", ";", "if", "(", "$", "sort", "===", "'desc'", "||", "$", "sort", "===", "'descending'", ")", "{", "$", "array", "=", "array_reverse", "(", "$", "array", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one to be an array of arrays with the key '$field'\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter three, sort, to be 'asc[ending]' or 'desc[ending]'\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter three, sort, to be a string sort order\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two, field, to be a string field name\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one, array, to be an array\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\"() expects two or three parameters\"", ")", ";", "}", "return", "$", "array", ";", "}" ]
Sorts an array of associative arrays by a field's value Oftentimes, you have a 0-indexed array of associative arrays. For example, a SELECT sql query result or a display-friendly data array. I'll sort a 0-based array of associative arrays by a field's value. For example: $a = [['a' => 3], ['a' => 1], ['a' => 2]]; Arr::usort_field($a, 'a'); // returns [['a' => 1], ['a' => 2], ['a' => 3]] @since 0.1.0 @param array[] $array the array of associative arrays to sort @param string $field the associative array's field name (aka, key) @param string $sort the sort order (possible values 'asc[ending]' or 'desc[ending]) (optional; if omitted, defaults to 'asc') (case-insensitive) @return array[] the sorted array @throws \BadMethodCallException if $array, $field, or $sort is null @throws \InvalidArgumentException if $array is not an array @throws \InvalidArgumentException if $field is not a string @throws \InvalidArgumentException if $sort is not a string @throws \InvalidArgumentException if $sort is not the string 'asc[ending]' or 'desc[ending]' @throws \InvalidArgumentException if $array is not an array of arrays with the key $field
[ "Sorts", "an", "array", "of", "associative", "arrays", "by", "a", "field", "s", "value" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Arr.php#L561-L627
222,885
jstewmc/php-helpers
src/Arr.php
Arr.sortByProperty
public static function sortByProperty($array, $property, $sort = 'asc') { // if $array, $property, and $sort are given if ($array !== null && $property !== null && $sort !== null) { // if $array is actually an array if (is_array($array)) { // if $property is a string if (is_string($property)) { // if $sort is a string if (is_string($sort)) { // if $sort is a valid sort if (in_array(strtolower($sort), array('asc', 'ascending', 'desc', 'descending'))) { // if $array is an array of objects with $property // use property_exists() to allow null values of explicit public properties // use isset() to allow "magic" properties via the __get() magic method // $passed = array_filter($array, function ($v) use ($property) { return is_object($v) && (property_exists($v, $property) || isset($v->$property)); }); if (count($array) === count($passed)) { // sort the array using the property's value // by default, usort() will return results in ascending order // usort($array, function ($a, $b) use ($property) { if ($a->$property < $b->$property) { return -1; } elseif ($a->$property > $b->$property) { return 1; } else { return 0; } }); // if the sort order is descending $sort = strtolower($sort); if ($sort === 'desc' || $sort === 'descending') { $array = array_reverse($array); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be an array of objects with public property '$property'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be 'asc[ending]' or 'desc[ending]'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be a string sort order" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, property, to be a string public property name" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, array, to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters" ); } return $array; }
php
public static function sortByProperty($array, $property, $sort = 'asc') { // if $array, $property, and $sort are given if ($array !== null && $property !== null && $sort !== null) { // if $array is actually an array if (is_array($array)) { // if $property is a string if (is_string($property)) { // if $sort is a string if (is_string($sort)) { // if $sort is a valid sort if (in_array(strtolower($sort), array('asc', 'ascending', 'desc', 'descending'))) { // if $array is an array of objects with $property // use property_exists() to allow null values of explicit public properties // use isset() to allow "magic" properties via the __get() magic method // $passed = array_filter($array, function ($v) use ($property) { return is_object($v) && (property_exists($v, $property) || isset($v->$property)); }); if (count($array) === count($passed)) { // sort the array using the property's value // by default, usort() will return results in ascending order // usort($array, function ($a, $b) use ($property) { if ($a->$property < $b->$property) { return -1; } elseif ($a->$property > $b->$property) { return 1; } else { return 0; } }); // if the sort order is descending $sort = strtolower($sort); if ($sort === 'desc' || $sort === 'descending') { $array = array_reverse($array); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be an array of objects with public property '$property'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be 'asc[ending]' or 'desc[ending]'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be a string sort order" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, property, to be a string public property name" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, array, to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters" ); } return $array; }
[ "public", "static", "function", "sortByProperty", "(", "$", "array", ",", "$", "property", ",", "$", "sort", "=", "'asc'", ")", "{", "// if $array, $property, and $sort are given\r", "if", "(", "$", "array", "!==", "null", "&&", "$", "property", "!==", "null", "&&", "$", "sort", "!==", "null", ")", "{", "// if $array is actually an array\r", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "// if $property is a string\r", "if", "(", "is_string", "(", "$", "property", ")", ")", "{", "// if $sort is a string\r", "if", "(", "is_string", "(", "$", "sort", ")", ")", "{", "// if $sort is a valid sort\r", "if", "(", "in_array", "(", "strtolower", "(", "$", "sort", ")", ",", "array", "(", "'asc'", ",", "'ascending'", ",", "'desc'", ",", "'descending'", ")", ")", ")", "{", "// if $array is an array of objects with $property\r", "// use property_exists() to allow null values of explicit public properties\r", "// use isset() to allow \"magic\" properties via the __get() magic method\r", "//\r", "$", "passed", "=", "array_filter", "(", "$", "array", ",", "function", "(", "$", "v", ")", "use", "(", "$", "property", ")", "{", "return", "is_object", "(", "$", "v", ")", "&&", "(", "property_exists", "(", "$", "v", ",", "$", "property", ")", "||", "isset", "(", "$", "v", "->", "$", "property", ")", ")", ";", "}", ")", ";", "if", "(", "count", "(", "$", "array", ")", "===", "count", "(", "$", "passed", ")", ")", "{", "// sort the array using the property's value\r", "// by default, usort() will return results in ascending order\r", "//\r", "usort", "(", "$", "array", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "property", ")", "{", "if", "(", "$", "a", "->", "$", "property", "<", "$", "b", "->", "$", "property", ")", "{", "return", "-", "1", ";", "}", "elseif", "(", "$", "a", "->", "$", "property", ">", "$", "b", "->", "$", "property", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}", ")", ";", "// if the sort order is descending\r", "$", "sort", "=", "strtolower", "(", "$", "sort", ")", ";", "if", "(", "$", "sort", "===", "'desc'", "||", "$", "sort", "===", "'descending'", ")", "{", "$", "array", "=", "array_reverse", "(", "$", "array", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one to be an array of objects with public property '$property'\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter three, sort, to be 'asc[ending]' or 'desc[ending]'\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter three, sort, to be a string sort order\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two, property, to be a string public property name\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one, array, to be an array\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\"() expects two or three parameters\"", ")", ";", "}", "return", "$", "array", ";", "}" ]
Sorts an array of objects using a public property's value @since 0.1.0 @param object[] $array the array of objects to sort @param string $property the object's public property name (may be a magic public property via the object's __get() method) @param string $sort the sort order (possible values 'asc[ending]' or 'desc[ending]) (optional; if omitted, defaults to 'asc') (case-insensitive) @return object[] the sorted array @throws \BadMethodCallException if $array, $property, or $sort is null @throws \InvalidArgumentException if $array is not an array @throws \InvalidArgumentException if $property is not a string @throws \InvalidArgumentException if $sort is not a string @throws \InvalidArgumentException if $sort is not the string 'asc[ending]' or 'desc[ending]' @throws \InvalidArgumentException if $array is not an array of objects with the public property $property
[ "Sorts", "an", "array", "of", "objects", "using", "a", "public", "property", "s", "value" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Arr.php#L651-L721
222,886
jstewmc/php-helpers
src/Arr.php
Arr.sortByMethod
public static function sortByMethod($array, $method, $sort = 'asc') { // if $array, $method, and $sort are given if ($array !== null && $method !== null && $sort !== null) { // if $array is actually an array if (is_array($array)) { // if $method is a string if (is_string($method)) { // if $sort is a string if (is_string($sort)) { // if $sort is a valid sort if (in_array(strtolower($sort), array('asc', 'ascending', 'desc', 'descending'))) { // if $array is an array of objects with public method $method // use is_callable() to allow "magic" methods // $passed = array_filter($array, function ($v) use ($method) { return is_object($v) && is_callable(array($v, $method)); }); if (count($array) === count($passed)) { // sort the array using the property's value // by default, usort() will return results in ascending order // usort($array, function ($a, $b) use ($method) { if ($a->$method() < $b->$method()) { return -1; } elseif ($a->$method() > $b->$method()) { return 1; } else { return 0; } }); // if the sort order is descending $sort = strtolower($sort); if ($sort === 'desc' || $sort === 'descending') { $array = array_reverse($array); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be an array of objects with public method '$method'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be 'asc[ending]' or 'desc[ending]'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be a string sort order" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, method, to be the string name of a public method" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, array, to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters" ); } return $array; }
php
public static function sortByMethod($array, $method, $sort = 'asc') { // if $array, $method, and $sort are given if ($array !== null && $method !== null && $sort !== null) { // if $array is actually an array if (is_array($array)) { // if $method is a string if (is_string($method)) { // if $sort is a string if (is_string($sort)) { // if $sort is a valid sort if (in_array(strtolower($sort), array('asc', 'ascending', 'desc', 'descending'))) { // if $array is an array of objects with public method $method // use is_callable() to allow "magic" methods // $passed = array_filter($array, function ($v) use ($method) { return is_object($v) && is_callable(array($v, $method)); }); if (count($array) === count($passed)) { // sort the array using the property's value // by default, usort() will return results in ascending order // usort($array, function ($a, $b) use ($method) { if ($a->$method() < $b->$method()) { return -1; } elseif ($a->$method() > $b->$method()) { return 1; } else { return 0; } }); // if the sort order is descending $sort = strtolower($sort); if ($sort === 'desc' || $sort === 'descending') { $array = array_reverse($array); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one to be an array of objects with public method '$method'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be 'asc[ending]' or 'desc[ending]'" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter three, sort, to be a string sort order" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter two, method, to be the string name of a public method" ); } } else { throw new \InvalidArgumentException( __METHOD__."() expects parameter one, array, to be an array" ); } } else { throw new \BadMethodCallException( __METHOD__."() expects two or three parameters" ); } return $array; }
[ "public", "static", "function", "sortByMethod", "(", "$", "array", ",", "$", "method", ",", "$", "sort", "=", "'asc'", ")", "{", "// if $array, $method, and $sort are given\r", "if", "(", "$", "array", "!==", "null", "&&", "$", "method", "!==", "null", "&&", "$", "sort", "!==", "null", ")", "{", "// if $array is actually an array\r", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "// if $method is a string\r", "if", "(", "is_string", "(", "$", "method", ")", ")", "{", "// if $sort is a string\r", "if", "(", "is_string", "(", "$", "sort", ")", ")", "{", "// if $sort is a valid sort\r", "if", "(", "in_array", "(", "strtolower", "(", "$", "sort", ")", ",", "array", "(", "'asc'", ",", "'ascending'", ",", "'desc'", ",", "'descending'", ")", ")", ")", "{", "// if $array is an array of objects with public method $method\r", "// use is_callable() to allow \"magic\" methods\r", "//\r", "$", "passed", "=", "array_filter", "(", "$", "array", ",", "function", "(", "$", "v", ")", "use", "(", "$", "method", ")", "{", "return", "is_object", "(", "$", "v", ")", "&&", "is_callable", "(", "array", "(", "$", "v", ",", "$", "method", ")", ")", ";", "}", ")", ";", "if", "(", "count", "(", "$", "array", ")", "===", "count", "(", "$", "passed", ")", ")", "{", "// sort the array using the property's value\r", "// by default, usort() will return results in ascending order\r", "//\r", "usort", "(", "$", "array", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "method", ")", "{", "if", "(", "$", "a", "->", "$", "method", "(", ")", "<", "$", "b", "->", "$", "method", "(", ")", ")", "{", "return", "-", "1", ";", "}", "elseif", "(", "$", "a", "->", "$", "method", "(", ")", ">", "$", "b", "->", "$", "method", "(", ")", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}", ")", ";", "// if the sort order is descending\r", "$", "sort", "=", "strtolower", "(", "$", "sort", ")", ";", "if", "(", "$", "sort", "===", "'desc'", "||", "$", "sort", "===", "'descending'", ")", "{", "$", "array", "=", "array_reverse", "(", "$", "array", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one to be an array of objects with public method '$method'\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter three, sort, to be 'asc[ending]' or 'desc[ending]'\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter three, sort, to be a string sort order\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter two, method, to be the string name of a public method\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "__METHOD__", ".", "\"() expects parameter one, array, to be an array\"", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "__METHOD__", ".", "\"() expects two or three parameters\"", ")", ";", "}", "return", "$", "array", ";", "}" ]
Sorts an array of objects using a method's return value @since 0.1.0 @param object[] $array the array of objects to sort @param string $method the name of the public method to use (may be a "magic" method via the object's __call() magic method) @param string $sort the sort order (possible values 'asc[ending]' or 'desc[ending]) (optional; if omitted, defaults to 'asc') (case-insensitive) @return object[] the sorted array @throws \BadMethodCallException if $array, $property, or $sort is null @throws \InvalidArgumentException if $array is not an array @throws \InvalidArgumentException if $property is not a string @throws \InvalidArgumentException if $sort is not a string @throws \InvalidArgumentException if $sort is not the string 'asc[ending]' or 'desc[ending]' @throws \InvalidArgumentException if $array is not an array of objects with the public property $property
[ "Sorts", "an", "array", "of", "objects", "using", "a", "method", "s", "return", "value" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Arr.php#L745-L813
222,887
jstewmc/php-helpers
src/Arr.php
Arr.getNextPermutation
protected static function getNextPermutation($p, $size) { // slide down the array looking for where we're smaller than the next guy for ($i = $size - 1; $i >= 0 && $p[$i] >= $p[$i+1]; --$i) { } // if this doesn't occur, we've finished our permutations // the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1) if ($i == -1) { return false; } // slide down the array looking for a bigger number than what we found before for ($j = $size; $j >= 0 && $p[$j] <= $p[$i]; --$j) { } // swap them $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; // now reverse the elements in between by swapping the ends for (++$i, $j = $size; $i < $j; ++$i, --$j) { $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; } return $p; }
php
protected static function getNextPermutation($p, $size) { // slide down the array looking for where we're smaller than the next guy for ($i = $size - 1; $i >= 0 && $p[$i] >= $p[$i+1]; --$i) { } // if this doesn't occur, we've finished our permutations // the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1) if ($i == -1) { return false; } // slide down the array looking for a bigger number than what we found before for ($j = $size; $j >= 0 && $p[$j] <= $p[$i]; --$j) { } // swap them $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; // now reverse the elements in between by swapping the ends for (++$i, $j = $size; $i < $j; ++$i, --$j) { $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; } return $p; }
[ "protected", "static", "function", "getNextPermutation", "(", "$", "p", ",", "$", "size", ")", "{", "// slide down the array looking for where we're smaller than the next guy\r", "for", "(", "$", "i", "=", "$", "size", "-", "1", ";", "$", "i", ">=", "0", "&&", "$", "p", "[", "$", "i", "]", ">=", "$", "p", "[", "$", "i", "+", "1", "]", ";", "--", "$", "i", ")", "{", "}", "// if this doesn't occur, we've finished our permutations\r", "// the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1)\r", "if", "(", "$", "i", "==", "-", "1", ")", "{", "return", "false", ";", "}", "// slide down the array looking for a bigger number than what we found before\r", "for", "(", "$", "j", "=", "$", "size", ";", "$", "j", ">=", "0", "&&", "$", "p", "[", "$", "j", "]", "<=", "$", "p", "[", "$", "i", "]", ";", "--", "$", "j", ")", "{", "}", "// swap them\r", "$", "tmp", "=", "$", "p", "[", "$", "i", "]", ";", "$", "p", "[", "$", "i", "]", "=", "$", "p", "[", "$", "j", "]", ";", "$", "p", "[", "$", "j", "]", "=", "$", "tmp", ";", "// now reverse the elements in between by swapping the ends\r", "for", "(", "++", "$", "i", ",", "$", "j", "=", "$", "size", ";", "$", "i", "<", "$", "j", ";", "++", "$", "i", ",", "--", "$", "j", ")", "{", "$", "tmp", "=", "$", "p", "[", "$", "i", "]", ";", "$", "p", "[", "$", "i", "]", "=", "$", "p", "[", "$", "j", "]", ";", "$", "p", "[", "$", "j", "]", "=", "$", "tmp", ";", "}", "return", "$", "p", ";", "}" ]
Returns the next permutation @see self:permute()
[ "Returns", "the", "next", "permutation" ]
b019194778683035ecd5ad177f5d6d4ee3705aed
https://github.com/jstewmc/php-helpers/blob/b019194778683035ecd5ad177f5d6d4ee3705aed/src/Arr.php#L823-L844
222,888
nadar/php-composer-reader
src/ComposerReader.php
ComposerReader.getContent
public function getContent() { if ($this->_content === null) { if (!$this->canRead()) { throw new Exception("Unable to read config file {$this->file}."); } $buffer = $this->getFileContent($this->file); $this->_content = $this->jsonDecode($buffer); } return $this->_content; }
php
public function getContent() { if ($this->_content === null) { if (!$this->canRead()) { throw new Exception("Unable to read config file {$this->file}."); } $buffer = $this->getFileContent($this->file); $this->_content = $this->jsonDecode($buffer); } return $this->_content; }
[ "public", "function", "getContent", "(", ")", "{", "if", "(", "$", "this", "->", "_content", "===", "null", ")", "{", "if", "(", "!", "$", "this", "->", "canRead", "(", ")", ")", "{", "throw", "new", "Exception", "(", "\"Unable to read config file {$this->file}.\"", ")", ";", "}", "$", "buffer", "=", "$", "this", "->", "getFileContent", "(", "$", "this", "->", "file", ")", ";", "$", "this", "->", "_content", "=", "$", "this", "->", "jsonDecode", "(", "$", "buffer", ")", ";", "}", "return", "$", "this", "->", "_content", ";", "}" ]
The content of the json file as array. @throws Exception @return array The composer.json file as array.
[ "The", "content", "of", "the", "json", "file", "as", "array", "." ]
1498c172313c5402357f43066c3e07f310f69076
https://github.com/nadar/php-composer-reader/blob/1498c172313c5402357f43066c3e07f310f69076/src/ComposerReader.php#L76-L88
222,889
nadar/php-composer-reader
src/ComposerReader.php
ComposerReader.writeContent
public function writeContent(array $content) { if (!$this->canWrite()) { throw new Exception("Unable to write file {this->file}."); } $json = $this->jsonEncode($content); return $this->writeFileContent($this->file, $json); }
php
public function writeContent(array $content) { if (!$this->canWrite()) { throw new Exception("Unable to write file {this->file}."); } $json = $this->jsonEncode($content); return $this->writeFileContent($this->file, $json); }
[ "public", "function", "writeContent", "(", "array", "$", "content", ")", "{", "if", "(", "!", "$", "this", "->", "canWrite", "(", ")", ")", "{", "throw", "new", "Exception", "(", "\"Unable to write file {this->file}.\"", ")", ";", "}", "$", "json", "=", "$", "this", "->", "jsonEncode", "(", "$", "content", ")", ";", "return", "$", "this", "->", "writeFileContent", "(", "$", "this", "->", "file", ",", "$", "json", ")", ";", "}" ]
Write the content into the composer.json. @param array $content The content to write. @throws Exception @return boolean Whether writting was successfull or not.
[ "Write", "the", "content", "into", "the", "composer", ".", "json", "." ]
1498c172313c5402357f43066c3e07f310f69076
https://github.com/nadar/php-composer-reader/blob/1498c172313c5402357f43066c3e07f310f69076/src/ComposerReader.php#L97-L106
222,890
nadar/php-composer-reader
src/ComposerReader.php
ComposerReader.runCommand
public function runCommand($command) { $folder = dirname($this->file); $olddir = getcwd(); chdir($folder); ob_start(); $output = null; $cmd = system('composer ' . $command, $output); $output = ob_end_clean(); chdir($olddir); return $cmd === false ? false : true; }
php
public function runCommand($command) { $folder = dirname($this->file); $olddir = getcwd(); chdir($folder); ob_start(); $output = null; $cmd = system('composer ' . $command, $output); $output = ob_end_clean(); chdir($olddir); return $cmd === false ? false : true; }
[ "public", "function", "runCommand", "(", "$", "command", ")", "{", "$", "folder", "=", "dirname", "(", "$", "this", "->", "file", ")", ";", "$", "olddir", "=", "getcwd", "(", ")", ";", "chdir", "(", "$", "folder", ")", ";", "ob_start", "(", ")", ";", "$", "output", "=", "null", ";", "$", "cmd", "=", "system", "(", "'composer '", ".", "$", "command", ",", "$", "output", ")", ";", "$", "output", "=", "ob_end_clean", "(", ")", ";", "chdir", "(", "$", "olddir", ")", ";", "return", "$", "cmd", "===", "false", "?", "false", ":", "true", ";", "}" ]
Run a composer command in the given composer.json. Example usage ```php $reader = new ComposerReader('path/to/composer.json'); $reader->runCommand('dump-autoload'); // equals to `composer dump-autoload` ``` @param string $command @return boolean
[ "Run", "a", "composer", "command", "in", "the", "given", "composer", ".", "json", "." ]
1498c172313c5402357f43066c3e07f310f69076
https://github.com/nadar/php-composer-reader/blob/1498c172313c5402357f43066c3e07f310f69076/src/ComposerReader.php#L165-L178
222,891
nadar/php-composer-reader
src/ComposerReader.php
ComposerReader.writeFileContent
protected function writeFileContent($file, $data) { $handler = file_put_contents($file, $data); return $handler === false ? false : true; }
php
protected function writeFileContent($file, $data) { $handler = file_put_contents($file, $data); return $handler === false ? false : true; }
[ "protected", "function", "writeFileContent", "(", "$", "file", ",", "$", "data", ")", "{", "$", "handler", "=", "file_put_contents", "(", "$", "file", ",", "$", "data", ")", ";", "return", "$", "handler", "===", "false", "?", "false", ":", "true", ";", "}" ]
Write the file content. @param string $file @param string $data @return boolean
[ "Write", "the", "file", "content", "." ]
1498c172313c5402357f43066c3e07f310f69076
https://github.com/nadar/php-composer-reader/blob/1498c172313c5402357f43066c3e07f310f69076/src/ComposerReader.php#L198-L203
222,892
nadar/php-composer-reader
src/ComposerReader.php
ComposerReader.jsonDecode
protected function jsonDecode($json) { $content = json_decode((string) $json, true); $this->handleJsonError(json_last_error()); return $content; }
php
protected function jsonDecode($json) { $content = json_decode((string) $json, true); $this->handleJsonError(json_last_error()); return $content; }
[ "protected", "function", "jsonDecode", "(", "$", "json", ")", "{", "$", "content", "=", "json_decode", "(", "(", "string", ")", "$", "json", ",", "true", ")", ";", "$", "this", "->", "handleJsonError", "(", "json_last_error", "(", ")", ")", ";", "return", "$", "content", ";", "}" ]
Decodes a json string into php structure. @param string $json @return array
[ "Decodes", "a", "json", "string", "into", "php", "structure", "." ]
1498c172313c5402357f43066c3e07f310f69076
https://github.com/nadar/php-composer-reader/blob/1498c172313c5402357f43066c3e07f310f69076/src/ComposerReader.php#L211-L217
222,893
nadar/php-composer-reader
src/ComposerReader.php
ComposerReader.jsonEncode
protected function jsonEncode(array $data) { set_error_handler(function () { $this->handleJsonError(JSON_ERROR_SYNTAX); }, E_WARNING); $json = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT); restore_error_handler(); $this->handleJsonError(json_last_error()); return $json; }
php
protected function jsonEncode(array $data) { set_error_handler(function () { $this->handleJsonError(JSON_ERROR_SYNTAX); }, E_WARNING); $json = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT); restore_error_handler(); $this->handleJsonError(json_last_error()); return $json; }
[ "protected", "function", "jsonEncode", "(", "array", "$", "data", ")", "{", "set_error_handler", "(", "function", "(", ")", "{", "$", "this", "->", "handleJsonError", "(", "JSON_ERROR_SYNTAX", ")", ";", "}", ",", "E_WARNING", ")", ";", "$", "json", "=", "json_encode", "(", "$", "data", ",", "JSON_UNESCAPED_SLASHES", "|", "JSON_PRETTY_PRINT", ")", ";", "restore_error_handler", "(", ")", ";", "$", "this", "->", "handleJsonError", "(", "json_last_error", "(", ")", ")", ";", "return", "$", "json", ";", "}" ]
Encodes a php array structure into a json string. @param array $data @return string
[ "Encodes", "a", "php", "array", "structure", "into", "a", "json", "string", "." ]
1498c172313c5402357f43066c3e07f310f69076
https://github.com/nadar/php-composer-reader/blob/1498c172313c5402357f43066c3e07f310f69076/src/ComposerReader.php#L225-L236
222,894
nadar/php-composer-reader
src/ComposerReader.php
ComposerReader.handleJsonError
protected function handleJsonError($error) { switch ($error) { case JSON_ERROR_NONE: break; // handle nothing case JSON_ERROR_DEPTH: throw new Exception("Maximum stack depth exceeded"); case JSON_ERROR_STATE_MISMATCH: throw new Exception("Underflow or the modes mismatch"); case JSON_ERROR_CTRL_CHAR: throw new Exception("Unexpected control character found"); case JSON_ERROR_SYNTAX: throw new Exception("Syntax error, malformed JSON"); case JSON_ERROR_UTF8: throw new Exception("Malformed UTF-8 characters, possibly incorrectly encoded"); default: throw new Exception("Unknown error"); } }
php
protected function handleJsonError($error) { switch ($error) { case JSON_ERROR_NONE: break; // handle nothing case JSON_ERROR_DEPTH: throw new Exception("Maximum stack depth exceeded"); case JSON_ERROR_STATE_MISMATCH: throw new Exception("Underflow or the modes mismatch"); case JSON_ERROR_CTRL_CHAR: throw new Exception("Unexpected control character found"); case JSON_ERROR_SYNTAX: throw new Exception("Syntax error, malformed JSON"); case JSON_ERROR_UTF8: throw new Exception("Malformed UTF-8 characters, possibly incorrectly encoded"); default: throw new Exception("Unknown error"); } }
[ "protected", "function", "handleJsonError", "(", "$", "error", ")", "{", "switch", "(", "$", "error", ")", "{", "case", "JSON_ERROR_NONE", ":", "break", ";", "// handle nothing", "case", "JSON_ERROR_DEPTH", ":", "throw", "new", "Exception", "(", "\"Maximum stack depth exceeded\"", ")", ";", "case", "JSON_ERROR_STATE_MISMATCH", ":", "throw", "new", "Exception", "(", "\"Underflow or the modes mismatch\"", ")", ";", "case", "JSON_ERROR_CTRL_CHAR", ":", "throw", "new", "Exception", "(", "\"Unexpected control character found\"", ")", ";", "case", "JSON_ERROR_SYNTAX", ":", "throw", "new", "Exception", "(", "\"Syntax error, malformed JSON\"", ")", ";", "case", "JSON_ERROR_UTF8", ":", "throw", "new", "Exception", "(", "\"Malformed UTF-8 characters, possibly incorrectly encoded\"", ")", ";", "default", ":", "throw", "new", "Exception", "(", "\"Unknown error\"", ")", ";", "}", "}" ]
Handle json parsing errors. @param integer $error @throws Exception
[ "Handle", "json", "parsing", "errors", "." ]
1498c172313c5402357f43066c3e07f310f69076
https://github.com/nadar/php-composer-reader/blob/1498c172313c5402357f43066c3e07f310f69076/src/ComposerReader.php#L244-L255
222,895
fage1151/swoole-worker
Connection/AsyncTcpConnection.php
AsyncTcpConnection.connect
public function connect() { if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING && $this->_status !== self::STATUS_CLOSED) { return; } $this->_status = self::STATUS_CONNECTING; $this->_connectStartTime = microtime(true); // Open socket connection asynchronously. if ($this->_contextOption) { $context = stream_context_create($this->_contextOption); $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT, $context); } else { $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT); } // If failed attempt to emit onError callback. if (!$this->_socket) { $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr); if ($this->_status === self::STATUS_CLOSING) { $this->destroy(); } if ($this->_status === self::STATUS_CLOSED) { $this->onConnect = null; } return; } // Add socket to global event loop waiting connection is successfully established or faild. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection')); // For windows. if(DIRECTORY_SEPARATOR === '\\') { Worker::$globalEvent->add($this->_socket, EventInterface::EV_EXCEPT, array($this, 'checkConnection')); } }
php
public function connect() { if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING && $this->_status !== self::STATUS_CLOSED) { return; } $this->_status = self::STATUS_CONNECTING; $this->_connectStartTime = microtime(true); // Open socket connection asynchronously. if ($this->_contextOption) { $context = stream_context_create($this->_contextOption); $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT, $context); } else { $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT); } // If failed attempt to emit onError callback. if (!$this->_socket) { $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr); if ($this->_status === self::STATUS_CLOSING) { $this->destroy(); } if ($this->_status === self::STATUS_CLOSED) { $this->onConnect = null; } return; } // Add socket to global event loop waiting connection is successfully established or faild. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection')); // For windows. if(DIRECTORY_SEPARATOR === '\\') { Worker::$globalEvent->add($this->_socket, EventInterface::EV_EXCEPT, array($this, 'checkConnection')); } }
[ "public", "function", "connect", "(", ")", "{", "if", "(", "$", "this", "->", "_status", "!==", "self", "::", "STATUS_INITIAL", "&&", "$", "this", "->", "_status", "!==", "self", "::", "STATUS_CLOSING", "&&", "$", "this", "->", "_status", "!==", "self", "::", "STATUS_CLOSED", ")", "{", "return", ";", "}", "$", "this", "->", "_status", "=", "self", "::", "STATUS_CONNECTING", ";", "$", "this", "->", "_connectStartTime", "=", "microtime", "(", "true", ")", ";", "// Open socket connection asynchronously.", "if", "(", "$", "this", "->", "_contextOption", ")", "{", "$", "context", "=", "stream_context_create", "(", "$", "this", "->", "_contextOption", ")", ";", "$", "this", "->", "_socket", "=", "stream_socket_client", "(", "\"{$this->transport}://{$this->_remoteAddress}\"", ",", "$", "errno", ",", "$", "errstr", ",", "0", ",", "STREAM_CLIENT_ASYNC_CONNECT", ",", "$", "context", ")", ";", "}", "else", "{", "$", "this", "->", "_socket", "=", "stream_socket_client", "(", "\"{$this->transport}://{$this->_remoteAddress}\"", ",", "$", "errno", ",", "$", "errstr", ",", "0", ",", "STREAM_CLIENT_ASYNC_CONNECT", ")", ";", "}", "// If failed attempt to emit onError callback.", "if", "(", "!", "$", "this", "->", "_socket", ")", "{", "$", "this", "->", "emitError", "(", "WORKERMAN_CONNECT_FAIL", ",", "$", "errstr", ")", ";", "if", "(", "$", "this", "->", "_status", "===", "self", "::", "STATUS_CLOSING", ")", "{", "$", "this", "->", "destroy", "(", ")", ";", "}", "if", "(", "$", "this", "->", "_status", "===", "self", "::", "STATUS_CLOSED", ")", "{", "$", "this", "->", "onConnect", "=", "null", ";", "}", "return", ";", "}", "// Add socket to global event loop waiting connection is successfully established or faild. ", "Worker", "::", "$", "globalEvent", "->", "add", "(", "$", "this", "->", "_socket", ",", "EventInterface", "::", "EV_WRITE", ",", "array", "(", "$", "this", ",", "'checkConnection'", ")", ")", ";", "// For windows.", "if", "(", "DIRECTORY_SEPARATOR", "===", "'\\\\'", ")", "{", "Worker", "::", "$", "globalEvent", "->", "add", "(", "$", "this", "->", "_socket", ",", "EventInterface", "::", "EV_EXCEPT", ",", "array", "(", "$", "this", ",", "'checkConnection'", ")", ")", ";", "}", "}" ]
Do connect. @return void
[ "Do", "connect", "." ]
ade6e29ffb400129380d56e9a2e6656f19dceb17
https://github.com/fage1151/swoole-worker/blob/ade6e29ffb400129380d56e9a2e6656f19dceb17/Connection/AsyncTcpConnection.php#L157-L191
222,896
meysampg/intldate
IntlDateTrait.php
IntlDateTrait.asDateTime
public function asDateTime($pattern = 'yyyy/MM/dd, HH:mm:ss') { $this->setFinalPattern($this->parsePattern($pattern)); return $this->getIntlDateFormatter()->format($this->getIntlCalendar()); }
php
public function asDateTime($pattern = 'yyyy/MM/dd, HH:mm:ss') { $this->setFinalPattern($this->parsePattern($pattern)); return $this->getIntlDateFormatter()->format($this->getIntlCalendar()); }
[ "public", "function", "asDateTime", "(", "$", "pattern", "=", "'yyyy/MM/dd, HH:mm:ss'", ")", "{", "$", "this", "->", "setFinalPattern", "(", "$", "this", "->", "parsePattern", "(", "$", "pattern", ")", ")", ";", "return", "$", "this", "->", "getIntlDateFormatter", "(", ")", "->", "format", "(", "$", "this", "->", "getIntlCalendar", "(", ")", ")", ";", "}" ]
Return final date and time on supplied format. @param string $pattern pattern of datetime based on ICU standards @return string @since 1.0.0
[ "Return", "final", "date", "and", "time", "on", "supplied", "format", "." ]
cb5abc65562f6151520f640480d14cc9a31c18e0
https://github.com/meysampg/intldate/blob/cb5abc65562f6151520f640480d14cc9a31c18e0/IntlDateTrait.php#L52-L57
222,897
meysampg/intldate
IntlDateTrait.php
IntlDateTrait.fromTimestamp
public function fromTimestamp($timestamp, $timezone = 'UTC') { // [TODO] use DateTime object for parse timestamp $oldTz = date_default_timezone_get(); date_default_timezone_set($timezone); $timestamp = mktime(date('H', $timestamp), date('i', $timestamp), date('s', $timestamp), date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp)); date_default_timezone_set('UTC'); $utcDT = gmdate('c', $timestamp); $dateArray = getdate(strtotime(gmdate('c', $timestamp))); date_default_timezone_set($oldTz); unset($dateArray[0]); $this->from($dateArray, 'en_US', null, $timezone); return $this; }
php
public function fromTimestamp($timestamp, $timezone = 'UTC') { // [TODO] use DateTime object for parse timestamp $oldTz = date_default_timezone_get(); date_default_timezone_set($timezone); $timestamp = mktime(date('H', $timestamp), date('i', $timestamp), date('s', $timestamp), date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp)); date_default_timezone_set('UTC'); $utcDT = gmdate('c', $timestamp); $dateArray = getdate(strtotime(gmdate('c', $timestamp))); date_default_timezone_set($oldTz); unset($dateArray[0]); $this->from($dateArray, 'en_US', null, $timezone); return $this; }
[ "public", "function", "fromTimestamp", "(", "$", "timestamp", ",", "$", "timezone", "=", "'UTC'", ")", "{", "// [TODO] use DateTime object for parse timestamp", "$", "oldTz", "=", "date_default_timezone_get", "(", ")", ";", "date_default_timezone_set", "(", "$", "timezone", ")", ";", "$", "timestamp", "=", "mktime", "(", "date", "(", "'H'", ",", "$", "timestamp", ")", ",", "date", "(", "'i'", ",", "$", "timestamp", ")", ",", "date", "(", "'s'", ",", "$", "timestamp", ")", ",", "date", "(", "'n'", ",", "$", "timestamp", ")", ",", "date", "(", "'j'", ",", "$", "timestamp", ")", ",", "date", "(", "'Y'", ",", "$", "timestamp", ")", ")", ";", "date_default_timezone_set", "(", "'UTC'", ")", ";", "$", "utcDT", "=", "gmdate", "(", "'c'", ",", "$", "timestamp", ")", ";", "$", "dateArray", "=", "getdate", "(", "strtotime", "(", "gmdate", "(", "'c'", ",", "$", "timestamp", ")", ")", ")", ";", "date_default_timezone_set", "(", "$", "oldTz", ")", ";", "unset", "(", "$", "dateArray", "[", "0", "]", ")", ";", "$", "this", "->", "from", "(", "$", "dateArray", ",", "'en_US'", ",", "null", ",", "$", "timezone", ")", ";", "return", "$", "this", ";", "}" ]
Get datetime as a timestamp. @param int $timestamp timestamp on origin @return static @since 1.0.3
[ "Get", "datetime", "as", "a", "timestamp", "." ]
cb5abc65562f6151520f640480d14cc9a31c18e0
https://github.com/meysampg/intldate/blob/cb5abc65562f6151520f640480d14cc9a31c18e0/IntlDateTrait.php#L80-L95
222,898
meysampg/intldate
IntlDateTrait.php
IntlDateTrait.from
public function from( $datetime = [], $locale = 'en_US', $calendar = null, $timezone = 'UTC' ) { $datetime = $this->parseDateTime($datetime); $calendar = $calendar ?: self::$CAL_GREGORIAN; $this->setIntlCalendar() ->setFromCalendar($calendar)->setFromLocale($locale) ->setOriginCalendar($this->getFromLocaleAndCalendar()) ->setOriginTimeZone($timezone) ->setOriginDate($datetime); return $this; }
php
public function from( $datetime = [], $locale = 'en_US', $calendar = null, $timezone = 'UTC' ) { $datetime = $this->parseDateTime($datetime); $calendar = $calendar ?: self::$CAL_GREGORIAN; $this->setIntlCalendar() ->setFromCalendar($calendar)->setFromLocale($locale) ->setOriginCalendar($this->getFromLocaleAndCalendar()) ->setOriginTimeZone($timezone) ->setOriginDate($datetime); return $this; }
[ "public", "function", "from", "(", "$", "datetime", "=", "[", "]", ",", "$", "locale", "=", "'en_US'", ",", "$", "calendar", "=", "null", ",", "$", "timezone", "=", "'UTC'", ")", "{", "$", "datetime", "=", "$", "this", "->", "parseDateTime", "(", "$", "datetime", ")", ";", "$", "calendar", "=", "$", "calendar", "?", ":", "self", "::", "$", "CAL_GREGORIAN", ";", "$", "this", "->", "setIntlCalendar", "(", ")", "->", "setFromCalendar", "(", "$", "calendar", ")", "->", "setFromLocale", "(", "$", "locale", ")", "->", "setOriginCalendar", "(", "$", "this", "->", "getFromLocaleAndCalendar", "(", ")", ")", "->", "setOriginTimeZone", "(", "$", "timezone", ")", "->", "setOriginDate", "(", "$", "datetime", ")", ";", "return", "$", "this", ";", "}" ]
Get information of datetime on origin. @param array $datetime Array contains datetime information. Its elements are [year, month, day, hour, minute, second]. @param string $locale locale for showing datetime on it (e.g. `en_US` or `fa_IR`, 'es_US', ...) @param string $calendar Calendar on origin @param string $timezone Timezone on origin @return static @since 1.0.0
[ "Get", "information", "of", "datetime", "on", "origin", "." ]
cb5abc65562f6151520f640480d14cc9a31c18e0
https://github.com/meysampg/intldate/blob/cb5abc65562f6151520f640480d14cc9a31c18e0/IntlDateTrait.php#L111-L127
222,899
meysampg/intldate
IntlDateTrait.php
IntlDateTrait.to
public function to( $locale = 'en_US', $calendar = null, $timezone = 'UTC' ) { $calendar = $calendar !== null ? $calendar : self::$CAL_PERSIAN; $this->setIntlDateFormatter() ->setToCalendar($calendar)->setToLocale($locale) ->setFinalTimeZone($timezone) ->setFinalCalendar($this->getToLocaleAndCalendar()); if ($calendar == self::$CAL_GREGORIAN) { $this->setFinalCalendarType(IntlDateFormatter::GREGORIAN); } else { $this->setFinalCalendarType(IntlDateFormatter::TRADITIONAL); } return $this; }
php
public function to( $locale = 'en_US', $calendar = null, $timezone = 'UTC' ) { $calendar = $calendar !== null ? $calendar : self::$CAL_PERSIAN; $this->setIntlDateFormatter() ->setToCalendar($calendar)->setToLocale($locale) ->setFinalTimeZone($timezone) ->setFinalCalendar($this->getToLocaleAndCalendar()); if ($calendar == self::$CAL_GREGORIAN) { $this->setFinalCalendarType(IntlDateFormatter::GREGORIAN); } else { $this->setFinalCalendarType(IntlDateFormatter::TRADITIONAL); } return $this; }
[ "public", "function", "to", "(", "$", "locale", "=", "'en_US'", ",", "$", "calendar", "=", "null", ",", "$", "timezone", "=", "'UTC'", ")", "{", "$", "calendar", "=", "$", "calendar", "!==", "null", "?", "$", "calendar", ":", "self", "::", "$", "CAL_PERSIAN", ";", "$", "this", "->", "setIntlDateFormatter", "(", ")", "->", "setToCalendar", "(", "$", "calendar", ")", "->", "setToLocale", "(", "$", "locale", ")", "->", "setFinalTimeZone", "(", "$", "timezone", ")", "->", "setFinalCalendar", "(", "$", "this", "->", "getToLocaleAndCalendar", "(", ")", ")", ";", "if", "(", "$", "calendar", "==", "self", "::", "$", "CAL_GREGORIAN", ")", "{", "$", "this", "->", "setFinalCalendarType", "(", "IntlDateFormatter", "::", "GREGORIAN", ")", ";", "}", "else", "{", "$", "this", "->", "setFinalCalendarType", "(", "IntlDateFormatter", "::", "TRADITIONAL", ")", ";", "}", "return", "$", "this", ";", "}" ]
Convert datetime to a desired calendar. @param string $locale locale for showing new datetime @param mixed $calendar calendar system for showing new datetime @param string $timezone timezone of destination @return static
[ "Convert", "datetime", "to", "a", "desired", "calendar", "." ]
cb5abc65562f6151520f640480d14cc9a31c18e0
https://github.com/meysampg/intldate/blob/cb5abc65562f6151520f640480d14cc9a31c18e0/IntlDateTrait.php#L138-L157