repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
acasademont/wurfl
WURFL/WURFLManagerFactory.php
WURFL_WURFLManagerFactory.deviceRepository
private function deviceRepository($persistenceStorage, $userAgentHandlerChain) { $devicePatcher = new WURFL_Xml_DevicePatcher(); $deviceRepositoryBuilder = new WURFL_DeviceRepositoryBuilder($persistenceStorage, $userAgentHandlerChain, $devicePatcher); return $deviceRepositoryBuilder->build($this->wurflConfig->wurflFile, $this->wurflConfig->wurflPatches, $this->wurflConfig->capabilityFilter); }
php
private function deviceRepository($persistenceStorage, $userAgentHandlerChain) { $devicePatcher = new WURFL_Xml_DevicePatcher(); $deviceRepositoryBuilder = new WURFL_DeviceRepositoryBuilder($persistenceStorage, $userAgentHandlerChain, $devicePatcher); return $deviceRepositoryBuilder->build($this->wurflConfig->wurflFile, $this->wurflConfig->wurflPatches, $this->wurflConfig->capabilityFilter); }
[ "private", "function", "deviceRepository", "(", "$", "persistenceStorage", ",", "$", "userAgentHandlerChain", ")", "{", "$", "devicePatcher", "=", "new", "WURFL_Xml_DevicePatcher", "(", ")", ";", "$", "deviceRepositoryBuilder", "=", "new", "WURFL_DeviceRepositoryBuilder", "(", "$", "persistenceStorage", ",", "$", "userAgentHandlerChain", ",", "$", "devicePatcher", ")", ";", "return", "$", "deviceRepositoryBuilder", "->", "build", "(", "$", "this", "->", "wurflConfig", "->", "wurflFile", ",", "$", "this", "->", "wurflConfig", "->", "wurflPatches", ",", "$", "this", "->", "wurflConfig", "->", "capabilityFilter", ")", ";", "}" ]
Returns a WURFL device repository @param WURFL_Storage_Base $persistenceStorage @param WURFL_UserAgentHandlerChain $userAgentHandlerChain @return WURFL_CustomDeviceRepository Device repository @see WURFL_DeviceRepositoryBuilder::build()
[ "Returns", "a", "WURFL", "device", "repository" ]
train
https://github.com/acasademont/wurfl/blob/0f4fb6e06b452ba95ad1d15e7d8226d0974b60c2/WURFL/WURFLManagerFactory.php#L173-L178
fuzz-productions/laravel-api-data
src/Schema/SchemaUtility.php
SchemaUtility.commentTable
public static function commentTable($table, $comment, $connection = null) { if (is_null($connection)) { $connection = DB::connection(); } if ($connection->getDriverName() === 'sqlite') { return; } $connection->statement( sprintf( 'ALTER TABLE `%s` COMMENT = "%s"', $table, addslashes($comment) ) ); }
php
public static function commentTable($table, $comment, $connection = null) { if (is_null($connection)) { $connection = DB::connection(); } if ($connection->getDriverName() === 'sqlite') { return; } $connection->statement( sprintf( 'ALTER TABLE `%s` COMMENT = "%s"', $table, addslashes($comment) ) ); }
[ "public", "static", "function", "commentTable", "(", "$", "table", ",", "$", "comment", ",", "$", "connection", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "connection", ")", ")", "{", "$", "connection", "=", "DB", "::", "connection", "(", ")", ";", "}", "if", "(", "$", "connection", "->", "getDriverName", "(", ")", "===", "'sqlite'", ")", "{", "return", ";", "}", "$", "connection", "->", "statement", "(", "sprintf", "(", "'ALTER TABLE `%s` COMMENT = \"%s\"'", ",", "$", "table", ",", "addslashes", "(", "$", "comment", ")", ")", ")", ";", "}" ]
Add a comment at the level of a table. @param string $table @param string $comment @param Connection $connection @return void
[ "Add", "a", "comment", "at", "the", "level", "of", "a", "table", "." ]
train
https://github.com/fuzz-productions/laravel-api-data/blob/25e181860d2f269b3b212195944c2bca95b411bb/src/Schema/SchemaUtility.php#L18-L33
fuzz-productions/laravel-api-data
src/Schema/SchemaUtility.php
SchemaUtility.describeTable
public static function describeTable($table, $connection = null) { if (is_null($connection)) { $connection = DB::connection(); } if ($connection->getDriverName() === 'sqlite') { $result = $connection->select(sprintf('PRAGMA table_info(%s)', $table)); $column_key = 'name'; } else { $result = $connection->select( sprintf( 'SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = \'%s\' and TABLE_SCHEMA = \'%s\'', $table, $connection->getDatabaseName() ) ); $column_key = 'COLUMN_NAME'; } return array_map( function ($item) use ($column_key) { return $item->$column_key; }, $result ); }
php
public static function describeTable($table, $connection = null) { if (is_null($connection)) { $connection = DB::connection(); } if ($connection->getDriverName() === 'sqlite') { $result = $connection->select(sprintf('PRAGMA table_info(%s)', $table)); $column_key = 'name'; } else { $result = $connection->select( sprintf( 'SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = \'%s\' and TABLE_SCHEMA = \'%s\'', $table, $connection->getDatabaseName() ) ); $column_key = 'COLUMN_NAME'; } return array_map( function ($item) use ($column_key) { return $item->$column_key; }, $result ); }
[ "public", "static", "function", "describeTable", "(", "$", "table", ",", "$", "connection", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "connection", ")", ")", "{", "$", "connection", "=", "DB", "::", "connection", "(", ")", ";", "}", "if", "(", "$", "connection", "->", "getDriverName", "(", ")", "===", "'sqlite'", ")", "{", "$", "result", "=", "$", "connection", "->", "select", "(", "sprintf", "(", "'PRAGMA table_info(%s)'", ",", "$", "table", ")", ")", ";", "$", "column_key", "=", "'name'", ";", "}", "else", "{", "$", "result", "=", "$", "connection", "->", "select", "(", "sprintf", "(", "'SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = \\'%s\\' and TABLE_SCHEMA = \\'%s\\''", ",", "$", "table", ",", "$", "connection", "->", "getDatabaseName", "(", ")", ")", ")", ";", "$", "column_key", "=", "'COLUMN_NAME'", ";", "}", "return", "array_map", "(", "function", "(", "$", "item", ")", "use", "(", "$", "column_key", ")", "{", "return", "$", "item", "->", "$", "column_key", ";", "}", ",", "$", "result", ")", ";", "}" ]
Describe a table's columns. @param string $table @param Connection $connection @return array
[ "Describe", "a", "table", "s", "columns", "." ]
train
https://github.com/fuzz-productions/laravel-api-data/blob/25e181860d2f269b3b212195944c2bca95b411bb/src/Schema/SchemaUtility.php#L42-L65
okvpn/fixture-bundle
src/Migration/Loader/DataFixturesLoader.php
DataFixturesLoader.isFixtureAlreadyLoaded
protected function isFixtureAlreadyLoaded($fixtureObject) { if (!$this->loadedFixtures) { $this->loadedFixtures = []; $loadedFixtures = $this->em->getRepository('OkvpnFixtureBundle:DataFixture')->findAll(); /** @var DataFixture $fixture */ foreach ($loadedFixtures as $fixture) { $this->loadedFixtures[$fixture->getClassName()] = $fixture->getVersion() ?: '0.0'; } } $alreadyLoaded = false; if (isset($this->loadedFixtures[get_class($fixtureObject)])) { $alreadyLoaded = true; $loadedVersion = $this->loadedFixtures[get_class($fixtureObject)]; if ($fixtureObject instanceof VersionedFixtureInterface && version_compare($loadedVersion, $fixtureObject->getVersion()) == -1 ) { if ($fixtureObject instanceof LoadedFixtureVersionAwareInterface) { $fixtureObject->setLoadedVersion($loadedVersion); } $alreadyLoaded = false; } } return $alreadyLoaded; }
php
protected function isFixtureAlreadyLoaded($fixtureObject) { if (!$this->loadedFixtures) { $this->loadedFixtures = []; $loadedFixtures = $this->em->getRepository('OkvpnFixtureBundle:DataFixture')->findAll(); /** @var DataFixture $fixture */ foreach ($loadedFixtures as $fixture) { $this->loadedFixtures[$fixture->getClassName()] = $fixture->getVersion() ?: '0.0'; } } $alreadyLoaded = false; if (isset($this->loadedFixtures[get_class($fixtureObject)])) { $alreadyLoaded = true; $loadedVersion = $this->loadedFixtures[get_class($fixtureObject)]; if ($fixtureObject instanceof VersionedFixtureInterface && version_compare($loadedVersion, $fixtureObject->getVersion()) == -1 ) { if ($fixtureObject instanceof LoadedFixtureVersionAwareInterface) { $fixtureObject->setLoadedVersion($loadedVersion); } $alreadyLoaded = false; } } return $alreadyLoaded; }
[ "protected", "function", "isFixtureAlreadyLoaded", "(", "$", "fixtureObject", ")", "{", "if", "(", "!", "$", "this", "->", "loadedFixtures", ")", "{", "$", "this", "->", "loadedFixtures", "=", "[", "]", ";", "$", "loadedFixtures", "=", "$", "this", "->", "em", "->", "getRepository", "(", "'OkvpnFixtureBundle:DataFixture'", ")", "->", "findAll", "(", ")", ";", "/** @var DataFixture $fixture */", "foreach", "(", "$", "loadedFixtures", "as", "$", "fixture", ")", "{", "$", "this", "->", "loadedFixtures", "[", "$", "fixture", "->", "getClassName", "(", ")", "]", "=", "$", "fixture", "->", "getVersion", "(", ")", "?", ":", "'0.0'", ";", "}", "}", "$", "alreadyLoaded", "=", "false", ";", "if", "(", "isset", "(", "$", "this", "->", "loadedFixtures", "[", "get_class", "(", "$", "fixtureObject", ")", "]", ")", ")", "{", "$", "alreadyLoaded", "=", "true", ";", "$", "loadedVersion", "=", "$", "this", "->", "loadedFixtures", "[", "get_class", "(", "$", "fixtureObject", ")", "]", ";", "if", "(", "$", "fixtureObject", "instanceof", "VersionedFixtureInterface", "&&", "version_compare", "(", "$", "loadedVersion", ",", "$", "fixtureObject", "->", "getVersion", "(", ")", ")", "==", "-", "1", ")", "{", "if", "(", "$", "fixtureObject", "instanceof", "LoadedFixtureVersionAwareInterface", ")", "{", "$", "fixtureObject", "->", "setLoadedVersion", "(", "$", "loadedVersion", ")", ";", "}", "$", "alreadyLoaded", "=", "false", ";", "}", "}", "return", "$", "alreadyLoaded", ";", "}" ]
Determines whether the given data fixture is already loaded or not @param object $fixtureObject @return bool
[ "Determines", "whether", "the", "given", "data", "fixture", "is", "already", "loaded", "or", "not" ]
train
https://github.com/okvpn/fixture-bundle/blob/243b5e4dff9773e97fa447280e929c936a5d66ae/src/Migration/Loader/DataFixturesLoader.php#L81-L109
fuelphp/display
src/Parser/Php.php
Php.parse
public function parse($file, array $data = []) { $obCleanRoom = function ($__file, $__data) { extract($__data, EXTR_REFS); ob_start(); try { // Load the view within the current scope include $__file; } catch (Exception $exception) { // Delete the output buffer ob_end_clean(); // Re-throw the exception throw $exception; } // Get the captured output and close the buffer return ob_get_clean(); }; return $obCleanRoom($file, $data); }
php
public function parse($file, array $data = []) { $obCleanRoom = function ($__file, $__data) { extract($__data, EXTR_REFS); ob_start(); try { // Load the view within the current scope include $__file; } catch (Exception $exception) { // Delete the output buffer ob_end_clean(); // Re-throw the exception throw $exception; } // Get the captured output and close the buffer return ob_get_clean(); }; return $obCleanRoom($file, $data); }
[ "public", "function", "parse", "(", "$", "file", ",", "array", "$", "data", "=", "[", "]", ")", "{", "$", "obCleanRoom", "=", "function", "(", "$", "__file", ",", "$", "__data", ")", "{", "extract", "(", "$", "__data", ",", "EXTR_REFS", ")", ";", "ob_start", "(", ")", ";", "try", "{", "// Load the view within the current scope", "include", "$", "__file", ";", "}", "catch", "(", "Exception", "$", "exception", ")", "{", "// Delete the output buffer", "ob_end_clean", "(", ")", ";", "// Re-throw the exception", "throw", "$", "exception", ";", "}", "// Get the captured output and close the buffer", "return", "ob_get_clean", "(", ")", ";", "}", ";", "return", "$", "obCleanRoom", "(", "$", "file", ",", "$", "data", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fuelphp/display/blob/d9a3eddbf80f0fd81beb40d9f4507600ac6611a4/src/Parser/Php.php#L23-L49
WebDevTmas/date-repetition
src/DateRepetition/HourlyDateRepetition.php
HourlyDateRepetition.setMinute
public function setMinute($minute) { if(! in_array($minute, range(0, 59))) { throw new InvalidArgumentException('Minute must be between 0 and 59'); } $this->minute = $minute; return $this; }
php
public function setMinute($minute) { if(! in_array($minute, range(0, 59))) { throw new InvalidArgumentException('Minute must be between 0 and 59'); } $this->minute = $minute; return $this; }
[ "public", "function", "setMinute", "(", "$", "minute", ")", "{", "if", "(", "!", "in_array", "(", "$", "minute", ",", "range", "(", "0", ",", "59", ")", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Minute must be between 0 and 59'", ")", ";", "}", "$", "this", "->", "minute", "=", "$", "minute", ";", "return", "$", "this", ";", "}" ]
Sets minutes in repetition @param integer minutes @return this
[ "Sets", "minutes", "in", "repetition" ]
train
https://github.com/WebDevTmas/date-repetition/blob/3ebd59f4ab3aab4b7497ebd767a57fad08277c6d/src/DateRepetition/HourlyDateRepetition.php#L59-L66
Atlantic18/CoralCoreBundle
Service/Connector/AbstractConnector.php
AbstractConnector.doPostRequest
public function doPostRequest($uri, $data = null) { return $this->doRequest(Request::POST, $uri, $data); }
php
public function doPostRequest($uri, $data = null) { return $this->doRequest(Request::POST, $uri, $data); }
[ "public", "function", "doPostRequest", "(", "$", "uri", ",", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "doRequest", "(", "Request", "::", "POST", ",", "$", "uri", ",", "$", "data", ")", ";", "}" ]
Create POST request to CORAL backend @param string $uri Service URI @param array $data Datat to be sent @return JsonResponse Response
[ "Create", "POST", "request", "to", "CORAL", "backend" ]
train
https://github.com/Atlantic18/CoralCoreBundle/blob/7d74ffaf51046ad13cbfc2b0b69d656a499f38ab/Service/Connector/AbstractConnector.php#L26-L29
etki/opencart-core-installer
src/FileJunglist.php
FileJunglist.saveModifiedFiles
public function saveModifiedFiles($installPath) { DebugPrinter::log('Saving modified items'); $tmpRoot = sys_get_temp_dir() . DIRECTORY_SEPARATOR; $installPath = trim($installPath, '\\/') . DIRECTORY_SEPARATOR; $fsm = new Filesystem; DebugPrinter::log( 'Items to search: %s', implode(', ', $this->modifiableFiles) ); foreach ($this->modifiableFiles as $file) { $source = $installPath . $file; $target = $tmpRoot . md5($source); if (!$fsm->exists($source)) { DebugPrinter::log('Item `%s` is missing, skipping it', $source); continue; } $args = array($source, $target,); DebugPrinter::log('Saving `%s` to `%s`', $args); if (is_dir($source)) { $fsm->mirror($source, $target); } else { $fsm->copy($source, $target); } } DebugPrinter::log('Finished saving modified items'); }
php
public function saveModifiedFiles($installPath) { DebugPrinter::log('Saving modified items'); $tmpRoot = sys_get_temp_dir() . DIRECTORY_SEPARATOR; $installPath = trim($installPath, '\\/') . DIRECTORY_SEPARATOR; $fsm = new Filesystem; DebugPrinter::log( 'Items to search: %s', implode(', ', $this->modifiableFiles) ); foreach ($this->modifiableFiles as $file) { $source = $installPath . $file; $target = $tmpRoot . md5($source); if (!$fsm->exists($source)) { DebugPrinter::log('Item `%s` is missing, skipping it', $source); continue; } $args = array($source, $target,); DebugPrinter::log('Saving `%s` to `%s`', $args); if (is_dir($source)) { $fsm->mirror($source, $target); } else { $fsm->copy($source, $target); } } DebugPrinter::log('Finished saving modified items'); }
[ "public", "function", "saveModifiedFiles", "(", "$", "installPath", ")", "{", "DebugPrinter", "::", "log", "(", "'Saving modified items'", ")", ";", "$", "tmpRoot", "=", "sys_get_temp_dir", "(", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "installPath", "=", "trim", "(", "$", "installPath", ",", "'\\\\/'", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "fsm", "=", "new", "Filesystem", ";", "DebugPrinter", "::", "log", "(", "'Items to search: %s'", ",", "implode", "(", "', '", ",", "$", "this", "->", "modifiableFiles", ")", ")", ";", "foreach", "(", "$", "this", "->", "modifiableFiles", "as", "$", "file", ")", "{", "$", "source", "=", "$", "installPath", ".", "$", "file", ";", "$", "target", "=", "$", "tmpRoot", ".", "md5", "(", "$", "source", ")", ";", "if", "(", "!", "$", "fsm", "->", "exists", "(", "$", "source", ")", ")", "{", "DebugPrinter", "::", "log", "(", "'Item `%s` is missing, skipping it'", ",", "$", "source", ")", ";", "continue", ";", "}", "$", "args", "=", "array", "(", "$", "source", ",", "$", "target", ",", ")", ";", "DebugPrinter", "::", "log", "(", "'Saving `%s` to `%s`'", ",", "$", "args", ")", ";", "if", "(", "is_dir", "(", "$", "source", ")", ")", "{", "$", "fsm", "->", "mirror", "(", "$", "source", ",", "$", "target", ")", ";", "}", "else", "{", "$", "fsm", "->", "copy", "(", "$", "source", ",", "$", "target", ")", ";", "}", "}", "DebugPrinter", "::", "log", "(", "'Finished saving modified items'", ")", ";", "}" ]
Saves config files during install. @param string $installPath Opencart install path. @return void @since 0.1.0
[ "Saves", "config", "files", "during", "install", "." ]
train
https://github.com/etki/opencart-core-installer/blob/e651c94982afe966cd36977bbdc2ff4f7e785475/src/FileJunglist.php#L58-L84
etki/opencart-core-installer
src/FileJunglist.php
FileJunglist.restoreModifiedFiles
public function restoreModifiedFiles($installPath) { DebugPrinter::log('Restoring modified items'); $tmpRoot = sys_get_temp_dir() . DIRECTORY_SEPARATOR; $installPath = trim($installPath, '\\/') . DIRECTORY_SEPARATOR; $fsm = new Filesystem; DebugPrinter::log( 'Items to search: %s', implode(', ', $this->modifiableFiles) ); foreach ($this->modifiableFiles as $file) { $target = $installPath . $file; $source = $tmpRoot . md5($target); if (!$fsm->exists($source)) { DebugPrinter::log('Item `%s` is missing, skipping it', $source); continue; } $args = array($source, $target,); DebugPrinter::log('Restoring `%s` to `%s`', $args); if ($fsm->exists($target)) { $fsm->remove($target); } $fsm->rename($source, $target, true); } DebugPrinter::log('Finished restoring modified items'); }
php
public function restoreModifiedFiles($installPath) { DebugPrinter::log('Restoring modified items'); $tmpRoot = sys_get_temp_dir() . DIRECTORY_SEPARATOR; $installPath = trim($installPath, '\\/') . DIRECTORY_SEPARATOR; $fsm = new Filesystem; DebugPrinter::log( 'Items to search: %s', implode(', ', $this->modifiableFiles) ); foreach ($this->modifiableFiles as $file) { $target = $installPath . $file; $source = $tmpRoot . md5($target); if (!$fsm->exists($source)) { DebugPrinter::log('Item `%s` is missing, skipping it', $source); continue; } $args = array($source, $target,); DebugPrinter::log('Restoring `%s` to `%s`', $args); if ($fsm->exists($target)) { $fsm->remove($target); } $fsm->rename($source, $target, true); } DebugPrinter::log('Finished restoring modified items'); }
[ "public", "function", "restoreModifiedFiles", "(", "$", "installPath", ")", "{", "DebugPrinter", "::", "log", "(", "'Restoring modified items'", ")", ";", "$", "tmpRoot", "=", "sys_get_temp_dir", "(", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "installPath", "=", "trim", "(", "$", "installPath", ",", "'\\\\/'", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "fsm", "=", "new", "Filesystem", ";", "DebugPrinter", "::", "log", "(", "'Items to search: %s'", ",", "implode", "(", "', '", ",", "$", "this", "->", "modifiableFiles", ")", ")", ";", "foreach", "(", "$", "this", "->", "modifiableFiles", "as", "$", "file", ")", "{", "$", "target", "=", "$", "installPath", ".", "$", "file", ";", "$", "source", "=", "$", "tmpRoot", ".", "md5", "(", "$", "target", ")", ";", "if", "(", "!", "$", "fsm", "->", "exists", "(", "$", "source", ")", ")", "{", "DebugPrinter", "::", "log", "(", "'Item `%s` is missing, skipping it'", ",", "$", "source", ")", ";", "continue", ";", "}", "$", "args", "=", "array", "(", "$", "source", ",", "$", "target", ",", ")", ";", "DebugPrinter", "::", "log", "(", "'Restoring `%s` to `%s`'", ",", "$", "args", ")", ";", "if", "(", "$", "fsm", "->", "exists", "(", "$", "target", ")", ")", "{", "$", "fsm", "->", "remove", "(", "$", "target", ")", ";", "}", "$", "fsm", "->", "rename", "(", "$", "source", ",", "$", "target", ",", "true", ")", ";", "}", "DebugPrinter", "::", "log", "(", "'Finished restoring modified items'", ")", ";", "}" ]
Restores previously saved config files. @param string $installPath Opencart installation path. @return void @since 0.1.1
[ "Restores", "previously", "saved", "config", "files", "." ]
train
https://github.com/etki/opencart-core-installer/blob/e651c94982afe966cd36977bbdc2ff4f7e785475/src/FileJunglist.php#L94-L119
etki/opencart-core-installer
src/FileJunglist.php
FileJunglist.setPermissions
protected function setPermissions($installPath, $basePerms = 0644) { $fsm = new Filesystem; foreach ($this->chmodNodes as $fsNode) { $path = $installPath . DIRECTORY_SEPARATOR . $fsNode; $isFile = is_file($path); $isDir = is_dir($path); if (!$isFile && !$isDir) { DebugPrinter::log('Filesystem node %s not found', $path); continue; } $perms = $basePerms; if ($isDir) { $perms |= 0111; } $args = array($path, decoct($perms),); DebugPrinter::log('Chmodding `%s` to `%s`', $args); $fsm->chmod($path, $perms); } }
php
protected function setPermissions($installPath, $basePerms = 0644) { $fsm = new Filesystem; foreach ($this->chmodNodes as $fsNode) { $path = $installPath . DIRECTORY_SEPARATOR . $fsNode; $isFile = is_file($path); $isDir = is_dir($path); if (!$isFile && !$isDir) { DebugPrinter::log('Filesystem node %s not found', $path); continue; } $perms = $basePerms; if ($isDir) { $perms |= 0111; } $args = array($path, decoct($perms),); DebugPrinter::log('Chmodding `%s` to `%s`', $args); $fsm->chmod($path, $perms); } }
[ "protected", "function", "setPermissions", "(", "$", "installPath", ",", "$", "basePerms", "=", "0644", ")", "{", "$", "fsm", "=", "new", "Filesystem", ";", "foreach", "(", "$", "this", "->", "chmodNodes", "as", "$", "fsNode", ")", "{", "$", "path", "=", "$", "installPath", ".", "DIRECTORY_SEPARATOR", ".", "$", "fsNode", ";", "$", "isFile", "=", "is_file", "(", "$", "path", ")", ";", "$", "isDir", "=", "is_dir", "(", "$", "path", ")", ";", "if", "(", "!", "$", "isFile", "&&", "!", "$", "isDir", ")", "{", "DebugPrinter", "::", "log", "(", "'Filesystem node %s not found'", ",", "$", "path", ")", ";", "continue", ";", "}", "$", "perms", "=", "$", "basePerms", ";", "if", "(", "$", "isDir", ")", "{", "$", "perms", "|=", "0111", ";", "}", "$", "args", "=", "array", "(", "$", "path", ",", "decoct", "(", "$", "perms", ")", ",", ")", ";", "DebugPrinter", "::", "log", "(", "'Chmodding `%s` to `%s`'", ",", "$", "args", ")", ";", "$", "fsm", "->", "chmod", "(", "$", "path", ",", "$", "perms", ")", ";", "}", "}" ]
Sets Opencart folder permissions as required in manual. @param string $installPath Opencart install path. @param int $basePerms Base permissions. Please note that all directories permissions will be masked by 111 (this will set all three ugo executive bits). @return void @since 0.1.1
[ "Sets", "Opencart", "folder", "permissions", "as", "required", "in", "manual", "." ]
train
https://github.com/etki/opencart-core-installer/blob/e651c94982afe966cd36977bbdc2ff4f7e785475/src/FileJunglist.php#L132-L151
etki/opencart-core-installer
src/FileJunglist.php
FileJunglist.rotateInstalledFiles
public function rotateInstalledFiles($installPath) { $fsm = new Filesystem; $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('oci-'); DebugPrinter::log('Rotating files using `%s` dir', $tempDir); // unzipped contents may or may not contain `upload.*` directory, // which holds actual opencart contents. $dirs = glob($installPath . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR); foreach ($dirs as $key => $dir) { if ($dir[0] === '.') { unset($dirs[$key]); } } if (sizeof($dirs) === 1) { $subDirectory = $tempDir . DIRECTORY_SEPARATOR . dirname(reset($dirs)); $fsm->rename($installPath, $tempDir); $fsm->rename($subDirectory, $installPath); $fsm->remove($tempDir); } }
php
public function rotateInstalledFiles($installPath) { $fsm = new Filesystem; $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('oci-'); DebugPrinter::log('Rotating files using `%s` dir', $tempDir); // unzipped contents may or may not contain `upload.*` directory, // which holds actual opencart contents. $dirs = glob($installPath . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR); foreach ($dirs as $key => $dir) { if ($dir[0] === '.') { unset($dirs[$key]); } } if (sizeof($dirs) === 1) { $subDirectory = $tempDir . DIRECTORY_SEPARATOR . dirname(reset($dirs)); $fsm->rename($installPath, $tempDir); $fsm->rename($subDirectory, $installPath); $fsm->remove($tempDir); } }
[ "public", "function", "rotateInstalledFiles", "(", "$", "installPath", ")", "{", "$", "fsm", "=", "new", "Filesystem", ";", "$", "tempDir", "=", "sys_get_temp_dir", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "uniqid", "(", "'oci-'", ")", ";", "DebugPrinter", "::", "log", "(", "'Rotating files using `%s` dir'", ",", "$", "tempDir", ")", ";", "// unzipped contents may or may not contain `upload.*` directory,", "// which holds actual opencart contents.", "$", "dirs", "=", "glob", "(", "$", "installPath", ".", "DIRECTORY_SEPARATOR", ".", "'*'", ",", "GLOB_ONLYDIR", ")", ";", "foreach", "(", "$", "dirs", "as", "$", "key", "=>", "$", "dir", ")", "{", "if", "(", "$", "dir", "[", "0", "]", "===", "'.'", ")", "{", "unset", "(", "$", "dirs", "[", "$", "key", "]", ")", ";", "}", "}", "if", "(", "sizeof", "(", "$", "dirs", ")", "===", "1", ")", "{", "$", "subDirectory", "=", "$", "tempDir", ".", "DIRECTORY_SEPARATOR", ".", "dirname", "(", "reset", "(", "$", "dirs", ")", ")", ";", "$", "fsm", "->", "rename", "(", "$", "installPath", ",", "$", "tempDir", ")", ";", "$", "fsm", "->", "rename", "(", "$", "subDirectory", ",", "$", "installPath", ")", ";", "$", "fsm", "->", "remove", "(", "$", "tempDir", ")", ";", "}", "}" ]
Moves installed files out of `upload` dir. @param string $installPath Opencart installation path. @return void @since 0.1.0
[ "Moves", "installed", "files", "out", "of", "upload", "dir", "." ]
train
https://github.com/etki/opencart-core-installer/blob/e651c94982afe966cd36977bbdc2ff4f7e785475/src/FileJunglist.php#L161-L181
etki/opencart-core-installer
src/FileJunglist.php
FileJunglist.copyConfigFiles
public function copyConfigFiles($installPath) { $filesystem = new Filesystem; $configFiles = array('/config', '/admin/config',); foreach ($configFiles as $configFile) { $source = $installPath . $configFile . '-dist.php'; $target = $installPath . $configFile . '.php'; if ($filesystem->exists($source)) { $filesystem->copy($source, $target); } else { DebugPrinter::log( 'File `%s` doesn\'t exist, though i am sure it should', $source ); } } }
php
public function copyConfigFiles($installPath) { $filesystem = new Filesystem; $configFiles = array('/config', '/admin/config',); foreach ($configFiles as $configFile) { $source = $installPath . $configFile . '-dist.php'; $target = $installPath . $configFile . '.php'; if ($filesystem->exists($source)) { $filesystem->copy($source, $target); } else { DebugPrinter::log( 'File `%s` doesn\'t exist, though i am sure it should', $source ); } } }
[ "public", "function", "copyConfigFiles", "(", "$", "installPath", ")", "{", "$", "filesystem", "=", "new", "Filesystem", ";", "$", "configFiles", "=", "array", "(", "'/config'", ",", "'/admin/config'", ",", ")", ";", "foreach", "(", "$", "configFiles", "as", "$", "configFile", ")", "{", "$", "source", "=", "$", "installPath", ".", "$", "configFile", ".", "'-dist.php'", ";", "$", "target", "=", "$", "installPath", ".", "$", "configFile", ".", "'.php'", ";", "if", "(", "$", "filesystem", "->", "exists", "(", "$", "source", ")", ")", "{", "$", "filesystem", "->", "copy", "(", "$", "source", ",", "$", "target", ")", ";", "}", "else", "{", "DebugPrinter", "::", "log", "(", "'File `%s` doesn\\'t exist, though i am sure it should'", ",", "$", "source", ")", ";", "}", "}", "}" ]
Copies configuration files from their dists as specified by installation notes. @param string $installPath Opencart installation path. @return void @since 0.1.0
[ "Copies", "configuration", "files", "from", "their", "dists", "as", "specified", "by", "installation", "notes", "." ]
train
https://github.com/etki/opencart-core-installer/blob/e651c94982afe966cd36977bbdc2ff4f7e785475/src/FileJunglist.php#L192-L208
muxtor/yii2-pkk5-module
src/controllers/Pkk5Controller.php
Pkk5Controller.actionIndex
public function actionIndex() { $model = new ParseForm(); if ($model->load(Yii::$app->request->post())) { if ($model->parse()) { $this->refresh(); } } $searchModel = new Pkk5kadastrSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'model'=>$model ]); }
php
public function actionIndex() { $model = new ParseForm(); if ($model->load(Yii::$app->request->post())) { if ($model->parse()) { $this->refresh(); } } $searchModel = new Pkk5kadastrSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'model'=>$model ]); }
[ "public", "function", "actionIndex", "(", ")", "{", "$", "model", "=", "new", "ParseForm", "(", ")", ";", "if", "(", "$", "model", "->", "load", "(", "Yii", "::", "$", "app", "->", "request", "->", "post", "(", ")", ")", ")", "{", "if", "(", "$", "model", "->", "parse", "(", ")", ")", "{", "$", "this", "->", "refresh", "(", ")", ";", "}", "}", "$", "searchModel", "=", "new", "Pkk5kadastrSearch", "(", ")", ";", "$", "dataProvider", "=", "$", "searchModel", "->", "search", "(", "Yii", "::", "$", "app", "->", "request", "->", "queryParams", ")", ";", "return", "$", "this", "->", "render", "(", "'index'", ",", "[", "'searchModel'", "=>", "$", "searchModel", ",", "'dataProvider'", "=>", "$", "dataProvider", ",", "'model'", "=>", "$", "model", "]", ")", ";", "}" ]
Lists all Pkk5kadastr models. @return mixed
[ "Lists", "all", "Pkk5kadastr", "models", "." ]
train
https://github.com/muxtor/yii2-pkk5-module/blob/09be77ddd171c66df53ec89d229d0cc5c0a9ad94/src/controllers/Pkk5Controller.php#L45-L62
esperecyan/dictionary-php
src/validator/LightweightMarkupValidator.php
LightweightMarkupValidator.isURLWithHTTPScheme
public static function isURLWithHTTPScheme(string $value): bool { try { $url = new URL($value); } catch (TypeError $exception) { return false; } return in_array($url->protocol, ['http:', 'https:']); }
php
public static function isURLWithHTTPScheme(string $value): bool { try { $url = new URL($value); } catch (TypeError $exception) { return false; } return in_array($url->protocol, ['http:', 'https:']); }
[ "public", "static", "function", "isURLWithHTTPScheme", "(", "string", "$", "value", ")", ":", "bool", "{", "try", "{", "$", "url", "=", "new", "URL", "(", "$", "value", ")", ";", "}", "catch", "(", "TypeError", "$", "exception", ")", "{", "return", "false", ";", "}", "return", "in_array", "(", "$", "url", "->", "protocol", ",", "[", "'http:'", ",", "'https:'", "]", ")", ";", "}" ]
与えられた文字列が絶対URL、または素片付き絶対URL、かつスキームが「http」「https」のいずれかであれば真を返します。 @param string $value @return bool
[ "与えられた文字列が絶対URL、または素片付き絶対URL、かつスキームが「http」「https」のいずれかであれば真を返します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/validator/LightweightMarkupValidator.php#L69-L77
esperecyan/dictionary-php
src/validator/LightweightMarkupValidator.php
LightweightMarkupValidator.createHTMLFilter
protected function createHTMLFilter(): HTMLFilter { $filter = new HTMLFilter( $this->source ? static::SOURCE_WHITELIST : static::DESCRIPTION_WHITELIST, ['before' => $this->source ? null : function (\DOMElement $body): void { foreach (['img', 'audio', 'video'] as $elementName) { foreach ($body->getElementsByTagName($elementName) as $element) { if ($element->hasAttribute('src')) { $fileLocationValidator = new \esperecyan\dictionary_php\validator\FileLocationValidator( $elementName === 'img' ? 'image' : $elementName, $this->filenames ); $fileLocationValidator->setLogger($this); $element ->setAttribute('src', $fileLocationValidator->correct($element->getAttribute('src'))); } } } }] ); $filter->setLogger($this); return $filter; }
php
protected function createHTMLFilter(): HTMLFilter { $filter = new HTMLFilter( $this->source ? static::SOURCE_WHITELIST : static::DESCRIPTION_WHITELIST, ['before' => $this->source ? null : function (\DOMElement $body): void { foreach (['img', 'audio', 'video'] as $elementName) { foreach ($body->getElementsByTagName($elementName) as $element) { if ($element->hasAttribute('src')) { $fileLocationValidator = new \esperecyan\dictionary_php\validator\FileLocationValidator( $elementName === 'img' ? 'image' : $elementName, $this->filenames ); $fileLocationValidator->setLogger($this); $element ->setAttribute('src', $fileLocationValidator->correct($element->getAttribute('src'))); } } } }] ); $filter->setLogger($this); return $filter; }
[ "protected", "function", "createHTMLFilter", "(", ")", ":", "HTMLFilter", "{", "$", "filter", "=", "new", "HTMLFilter", "(", "$", "this", "->", "source", "?", "static", "::", "SOURCE_WHITELIST", ":", "static", "::", "DESCRIPTION_WHITELIST", ",", "[", "'before'", "=>", "$", "this", "->", "source", "?", "null", ":", "function", "(", "\\", "DOMElement", "$", "body", ")", ":", "void", "{", "foreach", "(", "[", "'img'", ",", "'audio'", ",", "'video'", "]", "as", "$", "elementName", ")", "{", "foreach", "(", "$", "body", "->", "getElementsByTagName", "(", "$", "elementName", ")", "as", "$", "element", ")", "{", "if", "(", "$", "element", "->", "hasAttribute", "(", "'src'", ")", ")", "{", "$", "fileLocationValidator", "=", "new", "\\", "esperecyan", "\\", "dictionary_php", "\\", "validator", "\\", "FileLocationValidator", "(", "$", "elementName", "===", "'img'", "?", "'image'", ":", "$", "elementName", ",", "$", "this", "->", "filenames", ")", ";", "$", "fileLocationValidator", "->", "setLogger", "(", "$", "this", ")", ";", "$", "element", "->", "setAttribute", "(", "'src'", ",", "$", "fileLocationValidator", "->", "correct", "(", "$", "element", "->", "getAttribute", "(", "'src'", ")", ")", ")", ";", "}", "}", "}", "}", "]", ")", ";", "$", "filter", "->", "setLogger", "(", "$", "this", ")", ";", "return", "$", "filter", ";", "}" ]
HTMLフィルターを生成します。 @return HTMLFilter
[ "HTMLフィルターを生成します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/validator/LightweightMarkupValidator.php#L108-L130
Wonail/wocenter
traits/ExtensionTrait.php
ExtensionTrait.runMigrate
protected function runMigrate($type) { if (FileHelper::isDir(Yii::getAlias($this->migrationPath))) { $action = "migrate/"; switch ($type) { case 'up': $action .= 'up'; break; case 'down': $action .= 'down'; break; default: throw new InvalidParamException('The "type" property is invalid.'); } $cmd = "%s {$action} --migrationPath=%s --interactive=0 all"; //执行 WebConsoleHelper::run(sprintf($cmd, Yii::getAlias(WebConsoleHelper::getYiiCommand()), Yii::getAlias($this->migrationPath) ), false); } }
php
protected function runMigrate($type) { if (FileHelper::isDir(Yii::getAlias($this->migrationPath))) { $action = "migrate/"; switch ($type) { case 'up': $action .= 'up'; break; case 'down': $action .= 'down'; break; default: throw new InvalidParamException('The "type" property is invalid.'); } $cmd = "%s {$action} --migrationPath=%s --interactive=0 all"; //执行 WebConsoleHelper::run(sprintf($cmd, Yii::getAlias(WebConsoleHelper::getYiiCommand()), Yii::getAlias($this->migrationPath) ), false); } }
[ "protected", "function", "runMigrate", "(", "$", "type", ")", "{", "if", "(", "FileHelper", "::", "isDir", "(", "Yii", "::", "getAlias", "(", "$", "this", "->", "migrationPath", ")", ")", ")", "{", "$", "action", "=", "\"migrate/\"", ";", "switch", "(", "$", "type", ")", "{", "case", "'up'", ":", "$", "action", ".=", "'up'", ";", "break", ";", "case", "'down'", ":", "$", "action", ".=", "'down'", ";", "break", ";", "default", ":", "throw", "new", "InvalidParamException", "(", "'The \"type\" property is invalid.'", ")", ";", "}", "$", "cmd", "=", "\"%s {$action} --migrationPath=%s --interactive=0 all\"", ";", "//执行", "WebConsoleHelper", "::", "run", "(", "sprintf", "(", "$", "cmd", ",", "Yii", "::", "getAlias", "(", "WebConsoleHelper", "::", "getYiiCommand", "(", ")", ")", ",", "Yii", "::", "getAlias", "(", "$", "this", "->", "migrationPath", ")", ")", ",", "false", ")", ";", "}", "}" ]
执行migrate操作 @param string $type 操作类型
[ "执行migrate操作" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/traits/ExtensionTrait.php#L25-L46
pipelinersales/pipeliner-php-sdk
src/PipelinerSales/ApiClient/Http/Response.php
Response.decodeJson
public function decodeJson($assoc = false) { $result = json_decode($this->body, $assoc); if (json_last_error() !== JSON_ERROR_NONE) { throw new PipelinerHttpException($this, "Error while parsing returned JSON"); } return $result; }
php
public function decodeJson($assoc = false) { $result = json_decode($this->body, $assoc); if (json_last_error() !== JSON_ERROR_NONE) { throw new PipelinerHttpException($this, "Error while parsing returned JSON"); } return $result; }
[ "public", "function", "decodeJson", "(", "$", "assoc", "=", "false", ")", "{", "$", "result", "=", "json_decode", "(", "$", "this", "->", "body", ",", "$", "assoc", ")", ";", "if", "(", "json_last_error", "(", ")", "!==", "JSON_ERROR_NONE", ")", "{", "throw", "new", "PipelinerHttpException", "(", "$", "this", ",", "\"Error while parsing returned JSON\"", ")", ";", "}", "return", "$", "result", ";", "}" ]
Decodes the response's body into an object. @param boolean $assoc when true, returned objects will be converted into associative arrays. @return \stdClass|array @throws PipelinerHttpException on error while decoding the json string
[ "Decodes", "the", "response", "s", "body", "into", "an", "object", "." ]
train
https://github.com/pipelinersales/pipeliner-php-sdk/blob/a020149ffde815be17634542010814cf854c3d5f/src/PipelinerSales/ApiClient/Http/Response.php#L70-L79
huasituo/hstcms
src/Console/Commands/HstcmsInfoCommand.php
HstcmsInfoCommand.handle
public function handle() { $t = $this->option('t'); switch ($t) { case 'version': $this->info($this->hstcms->version()); break; default: $this->info('Welcome to use Hstcms'); $this->info('https://www.huasituo.com'); break; } }
php
public function handle() { $t = $this->option('t'); switch ($t) { case 'version': $this->info($this->hstcms->version()); break; default: $this->info('Welcome to use Hstcms'); $this->info('https://www.huasituo.com'); break; } }
[ "public", "function", "handle", "(", ")", "{", "$", "t", "=", "$", "this", "->", "option", "(", "'t'", ")", ";", "switch", "(", "$", "t", ")", "{", "case", "'version'", ":", "$", "this", "->", "info", "(", "$", "this", "->", "hstcms", "->", "version", "(", ")", ")", ";", "break", ";", "default", ":", "$", "this", "->", "info", "(", "'Welcome to use Hstcms'", ")", ";", "$", "this", "->", "info", "(", "'https://www.huasituo.com'", ")", ";", "break", ";", "}", "}" ]
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Console/Commands/HstcmsInfoCommand.php#L50-L62
kabirbaidhya/AwesomeCache
src/ConfigurableObject.php
ConfigurableObject.config
public static function config($config = null) { if(is_array($config)) { # Setting Configurations static::$config = $config + static::$config; $pathWithoutTrailingSlash = rtrim(static::$config['directory'], '/'); static::$config['directory'] = $pathWithoutTrailingSlash.'/'; } elseif(is_string($config)) { # Getting Single Config item return isset(static::$config[$config]) ? static::$config[$config] : null; } elseif(!$config) { # Getting All configurations return static::$config; } else { throw new CacheException('Invalid parameter provided for Cache::config()'); } }
php
public static function config($config = null) { if(is_array($config)) { # Setting Configurations static::$config = $config + static::$config; $pathWithoutTrailingSlash = rtrim(static::$config['directory'], '/'); static::$config['directory'] = $pathWithoutTrailingSlash.'/'; } elseif(is_string($config)) { # Getting Single Config item return isset(static::$config[$config]) ? static::$config[$config] : null; } elseif(!$config) { # Getting All configurations return static::$config; } else { throw new CacheException('Invalid parameter provided for Cache::config()'); } }
[ "public", "static", "function", "config", "(", "$", "config", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "config", ")", ")", "{", "# Setting Configurations", "static", "::", "$", "config", "=", "$", "config", "+", "static", "::", "$", "config", ";", "$", "pathWithoutTrailingSlash", "=", "rtrim", "(", "static", "::", "$", "config", "[", "'directory'", "]", ",", "'/'", ")", ";", "static", "::", "$", "config", "[", "'directory'", "]", "=", "$", "pathWithoutTrailingSlash", ".", "'/'", ";", "}", "elseif", "(", "is_string", "(", "$", "config", ")", ")", "{", "# Getting Single Config item", "return", "isset", "(", "static", "::", "$", "config", "[", "$", "config", "]", ")", "?", "static", "::", "$", "config", "[", "$", "config", "]", ":", "null", ";", "}", "elseif", "(", "!", "$", "config", ")", "{", "# Getting All configurations", "return", "static", "::", "$", "config", ";", "}", "else", "{", "throw", "new", "CacheException", "(", "'Invalid parameter provided for Cache::config()'", ")", ";", "}", "}" ]
Gets/Sets the Caching configurations Getting: $allConfig = Cache::config(); $configValue = Cache::config('configName'); Setting: $config = array(); Cache::config($config); @param mixed $config (optional) @return mixed
[ "Gets", "/", "Sets", "the", "Caching", "configurations" ]
train
https://github.com/kabirbaidhya/AwesomeCache/blob/ecf6293f3bcb3855133b1a8962c53170af1ebc32/src/ConfigurableObject.php#L31-L52
czim/laravel-pxlcms
src/Generator/ModelWriter.php
ModelWriter.appendRelatedModelsToModelData
protected function appendRelatedModelsToModelData(array $model) { $relationships = array_merge( array_get($model, 'relationships.normal'), array_get($model, 'relationships.reverse') ); $model['related_models'] = []; foreach ($relationships as $name => $relationship) { $relatedModelId = $relationship['model']; if (isset($model['related_models'][ $relatedModelId ])) continue; $model['related_models'][ $relatedModelId ] = $this->data['models'][ $relatedModelId ]; } return $model; }
php
protected function appendRelatedModelsToModelData(array $model) { $relationships = array_merge( array_get($model, 'relationships.normal'), array_get($model, 'relationships.reverse') ); $model['related_models'] = []; foreach ($relationships as $name => $relationship) { $relatedModelId = $relationship['model']; if (isset($model['related_models'][ $relatedModelId ])) continue; $model['related_models'][ $relatedModelId ] = $this->data['models'][ $relatedModelId ]; } return $model; }
[ "protected", "function", "appendRelatedModelsToModelData", "(", "array", "$", "model", ")", "{", "$", "relationships", "=", "array_merge", "(", "array_get", "(", "$", "model", ",", "'relationships.normal'", ")", ",", "array_get", "(", "$", "model", ",", "'relationships.reverse'", ")", ")", ";", "$", "model", "[", "'related_models'", "]", "=", "[", "]", ";", "foreach", "(", "$", "relationships", "as", "$", "name", "=>", "$", "relationship", ")", "{", "$", "relatedModelId", "=", "$", "relationship", "[", "'model'", "]", ";", "if", "(", "isset", "(", "$", "model", "[", "'related_models'", "]", "[", "$", "relatedModelId", "]", ")", ")", "continue", ";", "$", "model", "[", "'related_models'", "]", "[", "$", "relatedModelId", "]", "=", "$", "this", "->", "data", "[", "'models'", "]", "[", "$", "relatedModelId", "]", ";", "}", "return", "$", "model", ";", "}" ]
Append 'related' model data for related models @param array $model @return array
[ "Append", "related", "model", "data", "for", "related", "models" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/ModelWriter.php#L145-L164
czim/laravel-pxlcms
src/Generator/ModelWriter.php
ModelWriter.makeTranslatedDataFromModelData
protected function makeTranslatedDataFromModelData(array $model) { // translated model is sluggable if model is, but on translated property or column $sluggable = ($model['sluggable'] && array_get($model, 'sluggable_setup.translated')); return [ 'module' => $model['module'], 'name' => $model['name'] . config('pxlcms.generator.models.translation_model_postfix'), 'table' => ! empty($model['table']) ? $model['table'] . snake_case(config('pxlcms.tables.translation_postfix', '_ml')) : null, 'cached' => $model['cached'], 'is_translated' => false, 'is_translation' => true, // only true if it is a Translation model itself 'is_listified' => false, 'order_by' => [], // attributes 'normal_fillable' => $model['translated_attributes'], 'translated_fillable' => [], 'hidden' => [], 'casts' => [], 'dates' => [], 'defaults' => [], 'normal_attributes' => [], 'translated_attributes' => [], 'timestamps' => null, // categories 'categories_module' => null, // relations 'relations_config' => [], 'relationships' => [ 'normal' => [], 'reverse' => [], 'image' => [], 'file' => [], 'checkbox' => [], ], // special 'sluggable' => $sluggable, 'sluggable_setup' => $sluggable ? $model['sluggable_setup'] : [], 'scope_active' => false, 'scope_position' => false, ]; }
php
protected function makeTranslatedDataFromModelData(array $model) { // translated model is sluggable if model is, but on translated property or column $sluggable = ($model['sluggable'] && array_get($model, 'sluggable_setup.translated')); return [ 'module' => $model['module'], 'name' => $model['name'] . config('pxlcms.generator.models.translation_model_postfix'), 'table' => ! empty($model['table']) ? $model['table'] . snake_case(config('pxlcms.tables.translation_postfix', '_ml')) : null, 'cached' => $model['cached'], 'is_translated' => false, 'is_translation' => true, // only true if it is a Translation model itself 'is_listified' => false, 'order_by' => [], // attributes 'normal_fillable' => $model['translated_attributes'], 'translated_fillable' => [], 'hidden' => [], 'casts' => [], 'dates' => [], 'defaults' => [], 'normal_attributes' => [], 'translated_attributes' => [], 'timestamps' => null, // categories 'categories_module' => null, // relations 'relations_config' => [], 'relationships' => [ 'normal' => [], 'reverse' => [], 'image' => [], 'file' => [], 'checkbox' => [], ], // special 'sluggable' => $sluggable, 'sluggable_setup' => $sluggable ? $model['sluggable_setup'] : [], 'scope_active' => false, 'scope_position' => false, ]; }
[ "protected", "function", "makeTranslatedDataFromModelData", "(", "array", "$", "model", ")", "{", "// translated model is sluggable if model is, but on translated property or column", "$", "sluggable", "=", "(", "$", "model", "[", "'sluggable'", "]", "&&", "array_get", "(", "$", "model", ",", "'sluggable_setup.translated'", ")", ")", ";", "return", "[", "'module'", "=>", "$", "model", "[", "'module'", "]", ",", "'name'", "=>", "$", "model", "[", "'name'", "]", ".", "config", "(", "'pxlcms.generator.models.translation_model_postfix'", ")", ",", "'table'", "=>", "!", "empty", "(", "$", "model", "[", "'table'", "]", ")", "?", "$", "model", "[", "'table'", "]", ".", "snake_case", "(", "config", "(", "'pxlcms.tables.translation_postfix'", ",", "'_ml'", ")", ")", ":", "null", ",", "'cached'", "=>", "$", "model", "[", "'cached'", "]", ",", "'is_translated'", "=>", "false", ",", "'is_translation'", "=>", "true", ",", "// only true if it is a Translation model itself", "'is_listified'", "=>", "false", ",", "'order_by'", "=>", "[", "]", ",", "// attributes", "'normal_fillable'", "=>", "$", "model", "[", "'translated_attributes'", "]", ",", "'translated_fillable'", "=>", "[", "]", ",", "'hidden'", "=>", "[", "]", ",", "'casts'", "=>", "[", "]", ",", "'dates'", "=>", "[", "]", ",", "'defaults'", "=>", "[", "]", ",", "'normal_attributes'", "=>", "[", "]", ",", "'translated_attributes'", "=>", "[", "]", ",", "'timestamps'", "=>", "null", ",", "// categories", "'categories_module'", "=>", "null", ",", "// relations", "'relations_config'", "=>", "[", "]", ",", "'relationships'", "=>", "[", "'normal'", "=>", "[", "]", ",", "'reverse'", "=>", "[", "]", ",", "'image'", "=>", "[", "]", ",", "'file'", "=>", "[", "]", ",", "'checkbox'", "=>", "[", "]", ",", "]", ",", "// special", "'sluggable'", "=>", "$", "sluggable", ",", "'sluggable_setup'", "=>", "$", "sluggable", "?", "$", "model", "[", "'sluggable_setup'", "]", ":", "[", "]", ",", "'scope_active'", "=>", "false", ",", "'scope_position'", "=>", "false", ",", "]", ";", "}" ]
Make model data array for translation model @param array $model @return array
[ "Make", "model", "data", "array", "for", "translation", "model" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/ModelWriter.php#L173-L216
vcn/enum
src/Enum/Matcher.php
Matcher.whenMatch
private function whenMatch(Enum $enum, Match $match) { if (!$enum instanceof $this->subject) { $classSubject = get_class($this->subject); $classArgument = get_class($enum); throw new InvalidArgumentException( "This map is already mapping an instance of {$classSubject}, " . "yet this invocation is trying to map an instance of {$classArgument}." ); } if (array_key_exists($enum->getName(), $this->matches)) { throw new InvalidArgumentException( "This map has already mapped instance {$enum} to a value." ); } /** @noinspection PhpInternalEntityUsedInspection */ $this->matches[$enum->getName()] = $match; return $this; }
php
private function whenMatch(Enum $enum, Match $match) { if (!$enum instanceof $this->subject) { $classSubject = get_class($this->subject); $classArgument = get_class($enum); throw new InvalidArgumentException( "This map is already mapping an instance of {$classSubject}, " . "yet this invocation is trying to map an instance of {$classArgument}." ); } if (array_key_exists($enum->getName(), $this->matches)) { throw new InvalidArgumentException( "This map has already mapped instance {$enum} to a value." ); } /** @noinspection PhpInternalEntityUsedInspection */ $this->matches[$enum->getName()] = $match; return $this; }
[ "private", "function", "whenMatch", "(", "Enum", "$", "enum", ",", "Match", "$", "match", ")", "{", "if", "(", "!", "$", "enum", "instanceof", "$", "this", "->", "subject", ")", "{", "$", "classSubject", "=", "get_class", "(", "$", "this", "->", "subject", ")", ";", "$", "classArgument", "=", "get_class", "(", "$", "enum", ")", ";", "throw", "new", "InvalidArgumentException", "(", "\"This map is already mapping an instance of {$classSubject}, \"", ".", "\"yet this invocation is trying to map an instance of {$classArgument}.\"", ")", ";", "}", "if", "(", "array_key_exists", "(", "$", "enum", "->", "getName", "(", ")", ",", "$", "this", "->", "matches", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"This map has already mapped instance {$enum} to a value.\"", ")", ";", "}", "/** @noinspection PhpInternalEntityUsedInspection */", "$", "this", "->", "matches", "[", "$", "enum", "->", "getName", "(", ")", "]", "=", "$", "match", ";", "return", "$", "this", ";", "}" ]
@param Enum $enum @param Match $match @return Matcher
[ "@param", "Enum", "$enum", "@param", "Match", "$match" ]
train
https://github.com/vcn/enum/blob/ced38687b6140858956778140915d5d5a6397f23/src/Enum/Matcher.php#L54-L76
vcn/enum
src/Enum/Matcher.php
Matcher.when
public function when(Enum $enum, $value) { /** @noinspection PhpInternalEntityUsedInspection */ return $this->whenMatch($enum, new Match\Value($value)); }
php
public function when(Enum $enum, $value) { /** @noinspection PhpInternalEntityUsedInspection */ return $this->whenMatch($enum, new Match\Value($value)); }
[ "public", "function", "when", "(", "Enum", "$", "enum", ",", "$", "value", ")", "{", "/** @noinspection PhpInternalEntityUsedInspection */", "return", "$", "this", "->", "whenMatch", "(", "$", "enum", ",", "new", "Match", "\\", "Value", "(", "$", "value", ")", ")", ";", "}" ]
Maps an Enum instance to a value. <br/> If the subject of this map is equal to the given instance, `get()` will return this value. <br/> By chaining this method, a total case distinction can be expressed, for example: <br/> ``` $fruit ->when(Fruit::BANANA(), 'banana') ->when(Fruit::APPLE(), 'apple') ->get(); ``` <br/> will yield: <br/> `'banana'` if `$fruit = Fruit::BANANA()` or <br/> `'apple'` if `$fruit = Fruit::APPLE()` @param Enum $enum The Enum instance, must be an instance of the subject of this map. @param mixed $value The value to map the given instance to. @return Matcher @throws InvalidArgumentException If the given Enum is not an instance of the subject of this map, or if the given instance has already been mapped.
[ "Maps", "an", "Enum", "instance", "to", "a", "value", "." ]
train
https://github.com/vcn/enum/blob/ced38687b6140858956778140915d5d5a6397f23/src/Enum/Matcher.php#L117-L121
vcn/enum
src/Enum/Matcher.php
Matcher.whenDo
public function whenDo(Enum $enum, $callable) { if (!is_callable($callable)) { $type = is_object($callable) ? get_class($callable) : gettype($callable); throw new InvalidArgumentException( "Expected input argument to be callable, {$type} given. " . "If you want to match a plain value, use Matcher::when() instead." ); } return $this->whenMatch($enum, new Match\Callback($callable)); }
php
public function whenDo(Enum $enum, $callable) { if (!is_callable($callable)) { $type = is_object($callable) ? get_class($callable) : gettype($callable); throw new InvalidArgumentException( "Expected input argument to be callable, {$type} given. " . "If you want to match a plain value, use Matcher::when() instead." ); } return $this->whenMatch($enum, new Match\Callback($callable)); }
[ "public", "function", "whenDo", "(", "Enum", "$", "enum", ",", "$", "callable", ")", "{", "if", "(", "!", "is_callable", "(", "$", "callable", ")", ")", "{", "$", "type", "=", "is_object", "(", "$", "callable", ")", "?", "get_class", "(", "$", "callable", ")", ":", "gettype", "(", "$", "callable", ")", ";", "throw", "new", "InvalidArgumentException", "(", "\"Expected input argument to be callable, {$type} given. \"", ".", "\"If you want to match a plain value, use Matcher::when() instead.\"", ")", ";", "}", "return", "$", "this", "->", "whenMatch", "(", "$", "enum", ",", "new", "Match", "\\", "Callback", "(", "$", "callable", ")", ")", ";", "}" ]
Like `Matcher::when()`, but let a callback provide the value. <br/> Use this to lazily provide mapped values, or produce side effects when matched: ``` $fruit ->whenDo( Fruit::BANANA(), function () { return new LargeHadronCollider(); } ) ->whenDo( Fruit::APPLE(), function () use ($logger) { $logger->critical("I don't like apples!"); return null; } ) ->get(); ``` <br/> will yield: <br/> `LargeHadronCollider` if `$fruit = Fruit::BANANA()` or <br/> `null` if `$fruit = Fruit::APPLE()` <br/> It is <strong>discouraged</strong> to throw checked exceptions since PHPStorm can't infer the corresponding throws clauses on relevant methods. @param Enum $enum @param callable $callable @return Matcher @throws InvalidArgumentException If the given argument is not callable.
[ "Like", "Matcher", "::", "when", "()", "but", "let", "a", "callback", "provide", "the", "value", "." ]
train
https://github.com/vcn/enum/blob/ced38687b6140858956778140915d5d5a6397f23/src/Enum/Matcher.php#L172-L184
vcn/enum
src/Enum/Matcher.php
Matcher.orElseMatch
private function orElseMatch(Match $match) { return array_key_exists($this->subject->getName(), $this->matches) ? $this->matches[$this->subject->getName()]->get() : $match->get(); }
php
private function orElseMatch(Match $match) { return array_key_exists($this->subject->getName(), $this->matches) ? $this->matches[$this->subject->getName()]->get() : $match->get(); }
[ "private", "function", "orElseMatch", "(", "Match", "$", "match", ")", "{", "return", "array_key_exists", "(", "$", "this", "->", "subject", "->", "getName", "(", ")", ",", "$", "this", "->", "matches", ")", "?", "$", "this", "->", "matches", "[", "$", "this", "->", "subject", "->", "getName", "(", ")", "]", "->", "get", "(", ")", ":", "$", "match", "->", "get", "(", ")", ";", "}" ]
@param Match $match @return mixed
[ "@param", "Match", "$match" ]
train
https://github.com/vcn/enum/blob/ced38687b6140858956778140915d5d5a6397f23/src/Enum/Matcher.php#L191-L196
vcn/enum
src/Enum/Matcher.php
Matcher.orElseDo
public function orElseDo($callable) { if (!is_callable($callable)) { $type = is_object($callable) ? get_class($callable) : gettype($callable); throw new InvalidArgumentException( "Expected input argument to be callable, {$type} given. " . "If you want to provide a plain value as a surrogate, use Matcher::orElse() instead." ); } return $this->orElseMatch(new Match\Callback($callable)); }
php
public function orElseDo($callable) { if (!is_callable($callable)) { $type = is_object($callable) ? get_class($callable) : gettype($callable); throw new InvalidArgumentException( "Expected input argument to be callable, {$type} given. " . "If you want to provide a plain value as a surrogate, use Matcher::orElse() instead." ); } return $this->orElseMatch(new Match\Callback($callable)); }
[ "public", "function", "orElseDo", "(", "$", "callable", ")", "{", "if", "(", "!", "is_callable", "(", "$", "callable", ")", ")", "{", "$", "type", "=", "is_object", "(", "$", "callable", ")", "?", "get_class", "(", "$", "callable", ")", ":", "gettype", "(", "$", "callable", ")", ";", "throw", "new", "InvalidArgumentException", "(", "\"Expected input argument to be callable, {$type} given. \"", ".", "\"If you want to provide a plain value as a surrogate, use Matcher::orElse() instead.\"", ")", ";", "}", "return", "$", "this", "->", "orElseMatch", "(", "new", "Match", "\\", "Callback", "(", "$", "callable", ")", ")", ";", "}" ]
Like `Matcher::orElse()`, but let a callback provide the surrogate. <br/> Use this to lazily provide a surrogate, or produce side effects when no match is found: <br/> ``` $fruit ->when(Fruit::BANANA(), 'banana') ->when(Fruit::APPLE(), 'apple') ->orElseDo( function () { printf('Expected either a banana or apple.'); } ); ``` <br/> will yield: <br/> `'banana'` if `$fruit = Fruit::BANANA()` or <br/> `'apple'` if `$fruit = Fruit::APPLE()` or <br/> an invocation of the callback if `$fruit = Fruit::EGGPLANT()` <br/> It is <strong>discouraged</strong> to throw checked exceptions since PHPStorm can't infer the corresponding throws clause on this method. @param callable $callable @return mixed @throws InvalidArgumentException If the given argument is not callable.
[ "Like", "Matcher", "::", "orElse", "()", "but", "let", "a", "callback", "provide", "the", "surrogate", "." ]
train
https://github.com/vcn/enum/blob/ced38687b6140858956778140915d5d5a6397f23/src/Enum/Matcher.php#L286-L298
vcn/enum
src/Enum/Matcher.php
Matcher.get
public function get() { return array_key_exists($this->subject->getName(), $this->matches) ? $this->matches[$this->subject->getName()]->get() : $this->surrogate->get(); }
php
public function get() { return array_key_exists($this->subject->getName(), $this->matches) ? $this->matches[$this->subject->getName()]->get() : $this->surrogate->get(); }
[ "public", "function", "get", "(", ")", "{", "return", "array_key_exists", "(", "$", "this", "->", "subject", "->", "getName", "(", ")", ",", "$", "this", "->", "matches", ")", "?", "$", "this", "->", "matches", "[", "$", "this", "->", "subject", "->", "getName", "(", ")", "]", "->", "get", "(", ")", ":", "$", "this", "->", "surrogate", "->", "get", "(", ")", ";", "}" ]
Provides the value the instance of the mapped subject is mapped to, or throws a runtime exception if the instance has not been mapped to anything. <br/> For example: <br/> ``` $fruit ->when(Fruit::BANANA(), 'banana') ->when(Fruit::APPLE(), 'apple') ->get(); ``` <br/> will yield: <br/> `'banana'` if `$fruit = Fruit::BANANA()` or <br/> `'apple'` if `$fruit = Fruit::APPLE()` or <br/> a thrown exception if `$fruit = Fruit::EGGPLANT()` @return mixed @throws Enum\Matcher\Exception\MatchExhausted
[ "Provides", "the", "value", "the", "instance", "of", "the", "mapped", "subject", "is", "mapped", "to", "or", "throws", "a", "runtime", "exception", "if", "the", "instance", "has", "not", "been", "mapped", "to", "anything", "." ]
train
https://github.com/vcn/enum/blob/ced38687b6140858956778140915d5d5a6397f23/src/Enum/Matcher.php#L350-L355
withfatpanda/illuminate-wordpress
src/WordPress/Models/ProfileSection.php
ProfileSection.factory
static function factory(Plugin $plugin, $type) { $plugin->validator->extend('can_edit', function($attribute, $value, $parameters, $validator) { if (empty($value)) { return false; } $current_user = wp_get_current_user(); if (empty($current_user)) { return false; } if ($attribute === 'user_id') { $target_user = get_user_by('ID', $value); } else { $target_user = get_user_by($attribute, $value); } if ($current_user->ID === $target_user->ID) { return true; } else if ($current_user->can('administrator')) { return true; } else { return false; } }); if (empty($type)) { throw new \Exception("Missing required argument: type"); } $type = urldecode($type); if (class_exists($type)) { $implements = class_implements($type); if (!isset($implements['FatPanda\Illuminate\WordPress\Concerns\ProfileSectionContract'])) { throw new \Exception("Profile Section type {$type} does not implement ProfileSectionContract"); } $section = new $type(); $section->setPlugin($plugin); return $section; } else { return new SimpleProfileSection($type); } }
php
static function factory(Plugin $plugin, $type) { $plugin->validator->extend('can_edit', function($attribute, $value, $parameters, $validator) { if (empty($value)) { return false; } $current_user = wp_get_current_user(); if (empty($current_user)) { return false; } if ($attribute === 'user_id') { $target_user = get_user_by('ID', $value); } else { $target_user = get_user_by($attribute, $value); } if ($current_user->ID === $target_user->ID) { return true; } else if ($current_user->can('administrator')) { return true; } else { return false; } }); if (empty($type)) { throw new \Exception("Missing required argument: type"); } $type = urldecode($type); if (class_exists($type)) { $implements = class_implements($type); if (!isset($implements['FatPanda\Illuminate\WordPress\Concerns\ProfileSectionContract'])) { throw new \Exception("Profile Section type {$type} does not implement ProfileSectionContract"); } $section = new $type(); $section->setPlugin($plugin); return $section; } else { return new SimpleProfileSection($type); } }
[ "static", "function", "factory", "(", "Plugin", "$", "plugin", ",", "$", "type", ")", "{", "$", "plugin", "->", "validator", "->", "extend", "(", "'can_edit'", ",", "function", "(", "$", "attribute", ",", "$", "value", ",", "$", "parameters", ",", "$", "validator", ")", "{", "if", "(", "empty", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "$", "current_user", "=", "wp_get_current_user", "(", ")", ";", "if", "(", "empty", "(", "$", "current_user", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "attribute", "===", "'user_id'", ")", "{", "$", "target_user", "=", "get_user_by", "(", "'ID'", ",", "$", "value", ")", ";", "}", "else", "{", "$", "target_user", "=", "get_user_by", "(", "$", "attribute", ",", "$", "value", ")", ";", "}", "if", "(", "$", "current_user", "->", "ID", "===", "$", "target_user", "->", "ID", ")", "{", "return", "true", ";", "}", "else", "if", "(", "$", "current_user", "->", "can", "(", "'administrator'", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", ")", ";", "if", "(", "empty", "(", "$", "type", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Missing required argument: type\"", ")", ";", "}", "$", "type", "=", "urldecode", "(", "$", "type", ")", ";", "if", "(", "class_exists", "(", "$", "type", ")", ")", "{", "$", "implements", "=", "class_implements", "(", "$", "type", ")", ";", "if", "(", "!", "isset", "(", "$", "implements", "[", "'FatPanda\\Illuminate\\WordPress\\Concerns\\ProfileSectionContract'", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Profile Section type {$type} does not implement ProfileSectionContract\"", ")", ";", "}", "$", "section", "=", "new", "$", "type", "(", ")", ";", "$", "section", "->", "setPlugin", "(", "$", "plugin", ")", ";", "return", "$", "section", ";", "}", "else", "{", "return", "new", "SimpleProfileSection", "(", "$", "type", ")", ";", "}", "}" ]
Create a profile section of the given type, and associate it with the given Plugin @param Plugin @param String A classname of some class that implements ProfileSectionContract @return PluginSectionContract implementation @throws Exception If given class does not implement ProfileSectionContract
[ "Create", "a", "profile", "section", "of", "the", "given", "type", "and", "associate", "it", "with", "the", "given", "Plugin" ]
train
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Models/ProfileSection.php#L23-L69
link0/profiler
src/Link0/Profiler/PersistenceHandler/FilesystemHandler.php
FilesystemHandler.getList
public function getList() { $identifiers = array(); $fileList = $this->filesystem->listFiles($this->getPath()); foreach ($fileList as $file) { $identifiers[] = $file['filename']; } return $identifiers; }
php
public function getList() { $identifiers = array(); $fileList = $this->filesystem->listFiles($this->getPath()); foreach ($fileList as $file) { $identifiers[] = $file['filename']; } return $identifiers; }
[ "public", "function", "getList", "(", ")", "{", "$", "identifiers", "=", "array", "(", ")", ";", "$", "fileList", "=", "$", "this", "->", "filesystem", "->", "listFiles", "(", "$", "this", "->", "getPath", "(", ")", ")", ";", "foreach", "(", "$", "fileList", "as", "$", "file", ")", "{", "$", "identifiers", "[", "]", "=", "$", "file", "[", "'filename'", "]", ";", "}", "return", "$", "identifiers", ";", "}" ]
Returns a list of Identifier strings Unfortunately the list() method is reserved @return string[]
[ "Returns", "a", "list", "of", "Identifier", "strings", "Unfortunately", "the", "list", "()", "method", "is", "reserved" ]
train
https://github.com/link0/profiler/blob/0573073ff029743734de747619ab65ab2476052d/src/Link0/Profiler/PersistenceHandler/FilesystemHandler.php#L91-L101
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php
PermissionQuery.filterByName
public function filterByName($name = null, $comparison = null) { if (null === $comparison) { if (is_array($name)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $name)) { $name = str_replace('*', '%', $name); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(PermissionTableMap::COL_NAME, $name, $comparison); }
php
public function filterByName($name = null, $comparison = null) { if (null === $comparison) { if (is_array($name)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $name)) { $name = str_replace('*', '%', $name); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(PermissionTableMap::COL_NAME, $name, $comparison); }
[ "public", "function", "filterByName", "(", "$", "name", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "elseif", "(", "preg_match", "(", "'/[\\%\\*]/'", ",", "$", "name", ")", ")", "{", "$", "name", "=", "str_replace", "(", "'*'", ",", "'%'", ",", "$", "name", ")", ";", "$", "comparison", "=", "Criteria", "::", "LIKE", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "PermissionTableMap", "::", "COL_NAME", ",", "$", "name", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the name column Example usage: <code> $query->filterByName('fooValue'); // WHERE name = 'fooValue' $query->filterByName('%fooValue%'); // WHERE name LIKE '%fooValue%' </code> @param string $name The value to use as filter. Accepts wildcards (* and % trigger a LIKE) @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return $this|ChildPermissionQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "name", "column" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php#L311-L323
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php
PermissionQuery.filterByPermissionRelatedByParentId
public function filterByPermissionRelatedByParentId($permission, $comparison = null) { if ($permission instanceof \Alchemy\Component\Cerberus\Model\Permission) { return $this ->addUsingAlias(PermissionTableMap::COL_PARENT_ID, $permission->getId(), $comparison); } elseif ($permission instanceof ObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(PermissionTableMap::COL_PARENT_ID, $permission->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByPermissionRelatedByParentId() only accepts arguments of type \Alchemy\Component\Cerberus\Model\Permission or Collection'); } }
php
public function filterByPermissionRelatedByParentId($permission, $comparison = null) { if ($permission instanceof \Alchemy\Component\Cerberus\Model\Permission) { return $this ->addUsingAlias(PermissionTableMap::COL_PARENT_ID, $permission->getId(), $comparison); } elseif ($permission instanceof ObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(PermissionTableMap::COL_PARENT_ID, $permission->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByPermissionRelatedByParentId() only accepts arguments of type \Alchemy\Component\Cerberus\Model\Permission or Collection'); } }
[ "public", "function", "filterByPermissionRelatedByParentId", "(", "$", "permission", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "$", "permission", "instanceof", "\\", "Alchemy", "\\", "Component", "\\", "Cerberus", "\\", "Model", "\\", "Permission", ")", "{", "return", "$", "this", "->", "addUsingAlias", "(", "PermissionTableMap", "::", "COL_PARENT_ID", ",", "$", "permission", "->", "getId", "(", ")", ",", "$", "comparison", ")", ";", "}", "elseif", "(", "$", "permission", "instanceof", "ObjectCollection", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "return", "$", "this", "->", "addUsingAlias", "(", "PermissionTableMap", "::", "COL_PARENT_ID", ",", "$", "permission", "->", "toKeyValue", "(", "'PrimaryKey'", ",", "'Id'", ")", ",", "$", "comparison", ")", ";", "}", "else", "{", "throw", "new", "PropelException", "(", "'filterByPermissionRelatedByParentId() only accepts arguments of type \\Alchemy\\Component\\Cerberus\\Model\\Permission or Collection'", ")", ";", "}", "}" ]
Filter the query by a related \Alchemy\Component\Cerberus\Model\Permission object @param \Alchemy\Component\Cerberus\Model\Permission|ObjectCollection $permission The related object(s) to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return ChildPermissionQuery The current query, for fluid interface
[ "Filter", "the", "query", "by", "a", "related", "\\", "Alchemy", "\\", "Component", "\\", "Cerberus", "\\", "Model", "\\", "Permission", "object" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php#L520-L535
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php
PermissionQuery.usePermissionRelatedByParentIdQuery
public function usePermissionRelatedByParentIdQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) { return $this ->joinPermissionRelatedByParentId($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'PermissionRelatedByParentId', '\Alchemy\Component\Cerberus\Model\PermissionQuery'); }
php
public function usePermissionRelatedByParentIdQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) { return $this ->joinPermissionRelatedByParentId($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'PermissionRelatedByParentId', '\Alchemy\Component\Cerberus\Model\PermissionQuery'); }
[ "public", "function", "usePermissionRelatedByParentIdQuery", "(", "$", "relationAlias", "=", "null", ",", "$", "joinType", "=", "Criteria", "::", "LEFT_JOIN", ")", "{", "return", "$", "this", "->", "joinPermissionRelatedByParentId", "(", "$", "relationAlias", ",", "$", "joinType", ")", "->", "useQuery", "(", "$", "relationAlias", "?", "$", "relationAlias", ":", "'PermissionRelatedByParentId'", ",", "'\\Alchemy\\Component\\Cerberus\\Model\\PermissionQuery'", ")", ";", "}" ]
Use the PermissionRelatedByParentId relation Permission object @see useQuery() @param string $relationAlias optional alias for the relation, to be used as main alias in the secondary query @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' @return \Alchemy\Component\Cerberus\Model\PermissionQuery A secondary query class using the current class as primary query
[ "Use", "the", "PermissionRelatedByParentId", "relation", "Permission", "object" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php#L580-L585
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php
PermissionQuery.filterByPermissionRelatedById
public function filterByPermissionRelatedById($permission, $comparison = null) { if ($permission instanceof \Alchemy\Component\Cerberus\Model\Permission) { return $this ->addUsingAlias(PermissionTableMap::COL_ID, $permission->getParentId(), $comparison); } elseif ($permission instanceof ObjectCollection) { return $this ->usePermissionRelatedByIdQuery() ->filterByPrimaryKeys($permission->getPrimaryKeys()) ->endUse(); } else { throw new PropelException('filterByPermissionRelatedById() only accepts arguments of type \Alchemy\Component\Cerberus\Model\Permission or Collection'); } }
php
public function filterByPermissionRelatedById($permission, $comparison = null) { if ($permission instanceof \Alchemy\Component\Cerberus\Model\Permission) { return $this ->addUsingAlias(PermissionTableMap::COL_ID, $permission->getParentId(), $comparison); } elseif ($permission instanceof ObjectCollection) { return $this ->usePermissionRelatedByIdQuery() ->filterByPrimaryKeys($permission->getPrimaryKeys()) ->endUse(); } else { throw new PropelException('filterByPermissionRelatedById() only accepts arguments of type \Alchemy\Component\Cerberus\Model\Permission or Collection'); } }
[ "public", "function", "filterByPermissionRelatedById", "(", "$", "permission", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "$", "permission", "instanceof", "\\", "Alchemy", "\\", "Component", "\\", "Cerberus", "\\", "Model", "\\", "Permission", ")", "{", "return", "$", "this", "->", "addUsingAlias", "(", "PermissionTableMap", "::", "COL_ID", ",", "$", "permission", "->", "getParentId", "(", ")", ",", "$", "comparison", ")", ";", "}", "elseif", "(", "$", "permission", "instanceof", "ObjectCollection", ")", "{", "return", "$", "this", "->", "usePermissionRelatedByIdQuery", "(", ")", "->", "filterByPrimaryKeys", "(", "$", "permission", "->", "getPrimaryKeys", "(", ")", ")", "->", "endUse", "(", ")", ";", "}", "else", "{", "throw", "new", "PropelException", "(", "'filterByPermissionRelatedById() only accepts arguments of type \\Alchemy\\Component\\Cerberus\\Model\\Permission or Collection'", ")", ";", "}", "}" ]
Filter the query by a related \Alchemy\Component\Cerberus\Model\Permission object @param \Alchemy\Component\Cerberus\Model\Permission|ObjectCollection $permission the related object to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return ChildPermissionQuery The current query, for fluid interface
[ "Filter", "the", "query", "by", "a", "related", "\\", "Alchemy", "\\", "Component", "\\", "Cerberus", "\\", "Model", "\\", "Permission", "object" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php#L595-L608
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php
PermissionQuery.usePermissionRelatedByIdQuery
public function usePermissionRelatedByIdQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) { return $this ->joinPermissionRelatedById($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'PermissionRelatedById', '\Alchemy\Component\Cerberus\Model\PermissionQuery'); }
php
public function usePermissionRelatedByIdQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) { return $this ->joinPermissionRelatedById($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'PermissionRelatedById', '\Alchemy\Component\Cerberus\Model\PermissionQuery'); }
[ "public", "function", "usePermissionRelatedByIdQuery", "(", "$", "relationAlias", "=", "null", ",", "$", "joinType", "=", "Criteria", "::", "LEFT_JOIN", ")", "{", "return", "$", "this", "->", "joinPermissionRelatedById", "(", "$", "relationAlias", ",", "$", "joinType", ")", "->", "useQuery", "(", "$", "relationAlias", "?", "$", "relationAlias", ":", "'PermissionRelatedById'", ",", "'\\Alchemy\\Component\\Cerberus\\Model\\PermissionQuery'", ")", ";", "}" ]
Use the PermissionRelatedById relation Permission object @see useQuery() @param string $relationAlias optional alias for the relation, to be used as main alias in the secondary query @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' @return \Alchemy\Component\Cerberus\Model\PermissionQuery A secondary query class using the current class as primary query
[ "Use", "the", "PermissionRelatedById", "relation", "Permission", "object" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php#L653-L658
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php
PermissionQuery.filterByRolePermission
public function filterByRolePermission($rolePermission, $comparison = null) { if ($rolePermission instanceof \Alchemy\Component\Cerberus\Model\RolePermission) { return $this ->addUsingAlias(PermissionTableMap::COL_ID, $rolePermission->getPermissionId(), $comparison); } elseif ($rolePermission instanceof ObjectCollection) { return $this ->useRolePermissionQuery() ->filterByPrimaryKeys($rolePermission->getPrimaryKeys()) ->endUse(); } else { throw new PropelException('filterByRolePermission() only accepts arguments of type \Alchemy\Component\Cerberus\Model\RolePermission or Collection'); } }
php
public function filterByRolePermission($rolePermission, $comparison = null) { if ($rolePermission instanceof \Alchemy\Component\Cerberus\Model\RolePermission) { return $this ->addUsingAlias(PermissionTableMap::COL_ID, $rolePermission->getPermissionId(), $comparison); } elseif ($rolePermission instanceof ObjectCollection) { return $this ->useRolePermissionQuery() ->filterByPrimaryKeys($rolePermission->getPrimaryKeys()) ->endUse(); } else { throw new PropelException('filterByRolePermission() only accepts arguments of type \Alchemy\Component\Cerberus\Model\RolePermission or Collection'); } }
[ "public", "function", "filterByRolePermission", "(", "$", "rolePermission", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "$", "rolePermission", "instanceof", "\\", "Alchemy", "\\", "Component", "\\", "Cerberus", "\\", "Model", "\\", "RolePermission", ")", "{", "return", "$", "this", "->", "addUsingAlias", "(", "PermissionTableMap", "::", "COL_ID", ",", "$", "rolePermission", "->", "getPermissionId", "(", ")", ",", "$", "comparison", ")", ";", "}", "elseif", "(", "$", "rolePermission", "instanceof", "ObjectCollection", ")", "{", "return", "$", "this", "->", "useRolePermissionQuery", "(", ")", "->", "filterByPrimaryKeys", "(", "$", "rolePermission", "->", "getPrimaryKeys", "(", ")", ")", "->", "endUse", "(", ")", ";", "}", "else", "{", "throw", "new", "PropelException", "(", "'filterByRolePermission() only accepts arguments of type \\Alchemy\\Component\\Cerberus\\Model\\RolePermission or Collection'", ")", ";", "}", "}" ]
Filter the query by a related \Alchemy\Component\Cerberus\Model\RolePermission object @param \Alchemy\Component\Cerberus\Model\RolePermission|ObjectCollection $rolePermission the related object to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return ChildPermissionQuery The current query, for fluid interface
[ "Filter", "the", "query", "by", "a", "related", "\\", "Alchemy", "\\", "Component", "\\", "Cerberus", "\\", "Model", "\\", "RolePermission", "object" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php#L668-L681
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php
PermissionQuery.filterByRole
public function filterByRole($role, $comparison = Criteria::EQUAL) { return $this ->useRolePermissionQuery() ->filterByRole($role, $comparison) ->endUse(); }
php
public function filterByRole($role, $comparison = Criteria::EQUAL) { return $this ->useRolePermissionQuery() ->filterByRole($role, $comparison) ->endUse(); }
[ "public", "function", "filterByRole", "(", "$", "role", ",", "$", "comparison", "=", "Criteria", "::", "EQUAL", ")", "{", "return", "$", "this", "->", "useRolePermissionQuery", "(", ")", "->", "filterByRole", "(", "$", "role", ",", "$", "comparison", ")", "->", "endUse", "(", ")", ";", "}" ]
Filter the query by a related Role object using the role_permission table as cross reference @param Role $role the related object to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return ChildPermissionQuery The current query, for fluid interface
[ "Filter", "the", "query", "by", "a", "related", "Role", "object", "using", "the", "role_permission", "table", "as", "cross", "reference" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php#L742-L748
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php
PermissionQuery.prune
public function prune($permission = null) { if ($permission) { $this->addUsingAlias(PermissionTableMap::COL_ID, $permission->getId(), Criteria::NOT_EQUAL); } return $this; }
php
public function prune($permission = null) { if ($permission) { $this->addUsingAlias(PermissionTableMap::COL_ID, $permission->getId(), Criteria::NOT_EQUAL); } return $this; }
[ "public", "function", "prune", "(", "$", "permission", "=", "null", ")", "{", "if", "(", "$", "permission", ")", "{", "$", "this", "->", "addUsingAlias", "(", "PermissionTableMap", "::", "COL_ID", ",", "$", "permission", "->", "getId", "(", ")", ",", "Criteria", "::", "NOT_EQUAL", ")", ";", "}", "return", "$", "this", ";", "}" ]
Exclude object from result @param ChildPermission $permission Object to remove from the list of results @return $this|ChildPermissionQuery The current query, for fluid interface
[ "Exclude", "object", "from", "result" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/PermissionQuery.php#L757-L764
yosmanyga/resource
src/Yosmanyga/Resource/Cacher/Checker/SerializedDataChecker.php
SerializedDataChecker.add
public function add(Resource $resource) { $this->storer->add( serialize($resource->getMetadata('data')), $resource ); }
php
public function add(Resource $resource) { $this->storer->add( serialize($resource->getMetadata('data')), $resource ); }
[ "public", "function", "add", "(", "Resource", "$", "resource", ")", "{", "$", "this", "->", "storer", "->", "add", "(", "serialize", "(", "$", "resource", "->", "getMetadata", "(", "'data'", ")", ")", ",", "$", "resource", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yosmanyga/resource/blob/a8b505c355920a908917a0484f764ddfa63205fa/src/Yosmanyga/Resource/Cacher/Checker/SerializedDataChecker.php#L39-L45
yosmanyga/resource
src/Yosmanyga/Resource/Cacher/Checker/SerializedDataChecker.php
SerializedDataChecker.check
public function check(Resource $resource) { if (!$this->storer->has($resource)) { return false; } return $this->storer->get($resource) == serialize($resource->getMetadata('data')); }
php
public function check(Resource $resource) { if (!$this->storer->has($resource)) { return false; } return $this->storer->get($resource) == serialize($resource->getMetadata('data')); }
[ "public", "function", "check", "(", "Resource", "$", "resource", ")", "{", "if", "(", "!", "$", "this", "->", "storer", "->", "has", "(", "$", "resource", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "storer", "->", "get", "(", "$", "resource", ")", "==", "serialize", "(", "$", "resource", "->", "getMetadata", "(", "'data'", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yosmanyga/resource/blob/a8b505c355920a908917a0484f764ddfa63205fa/src/Yosmanyga/Resource/Cacher/Checker/SerializedDataChecker.php#L50-L57
movoin/one-swoole
src/Validation/Validators/EmailValidator.php
EmailValidator.validate
protected function validate(array $attributes, string $name, array $parameters): bool { if (isset($parameters['domain']) && ! Assert::email($attributes[$name], $parameters['domain'])) { $this->addError($name, $parameters, '%s 超出允许邮箱范围'); return false; } if (! Assert::email($attributes[$name])) { $this->addError($name, $parameters, '%s 必须为 Email'); return false; } return true; }
php
protected function validate(array $attributes, string $name, array $parameters): bool { if (isset($parameters['domain']) && ! Assert::email($attributes[$name], $parameters['domain'])) { $this->addError($name, $parameters, '%s 超出允许邮箱范围'); return false; } if (! Assert::email($attributes[$name])) { $this->addError($name, $parameters, '%s 必须为 Email'); return false; } return true; }
[ "protected", "function", "validate", "(", "array", "$", "attributes", ",", "string", "$", "name", ",", "array", "$", "parameters", ")", ":", "bool", "{", "if", "(", "isset", "(", "$", "parameters", "[", "'domain'", "]", ")", "&&", "!", "Assert", "::", "email", "(", "$", "attributes", "[", "$", "name", "]", ",", "$", "parameters", "[", "'domain'", "]", ")", ")", "{", "$", "this", "->", "addError", "(", "$", "name", ",", "$", "parameters", ",", "'%s 超出允许邮箱范围');", "", "", "return", "false", ";", "}", "if", "(", "!", "Assert", "::", "email", "(", "$", "attributes", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "addError", "(", "$", "name", ",", "$", "parameters", ",", "'%s 必须为 Email');", "", "", "return", "false", ";", "}", "return", "true", ";", "}" ]
校验规则 @param array $attributes @param string $name @param array $parameters @return bool
[ "校验规则" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Validation/Validators/EmailValidator.php#L28-L43
stubbles/stubbles-webapp-core
src/main/php/response/WebResponse.php
WebResponse.setStatusCode
public function setStatusCode(int $statusCode, string $reasonPhrase = null): Response { $this->status->setCode($statusCode, $reasonPhrase); return $this; }
php
public function setStatusCode(int $statusCode, string $reasonPhrase = null): Response { $this->status->setCode($statusCode, $reasonPhrase); return $this; }
[ "public", "function", "setStatusCode", "(", "int", "$", "statusCode", ",", "string", "$", "reasonPhrase", "=", "null", ")", ":", "Response", "{", "$", "this", "->", "status", "->", "setCode", "(", "$", "statusCode", ",", "$", "reasonPhrase", ")", ";", "return", "$", "this", ";", "}" ]
sets the status code to be send This needs only to be done if another status code then the default one 200 OK should be send. @param int $statusCode @param string $reasonPhrase optional @return \stubbles\webapp\Response
[ "sets", "the", "status", "code", "to", "be", "send" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/WebResponse.php#L136-L140
stubbles/stubbles-webapp-core
src/main/php/response/WebResponse.php
WebResponse.addHeader
public function addHeader(string $name, string $value): Response { $this->headers->add($name, $value); return $this; }
php
public function addHeader(string $name, string $value): Response { $this->headers->add($name, $value); return $this; }
[ "public", "function", "addHeader", "(", "string", "$", "name", ",", "string", "$", "value", ")", ":", "Response", "{", "$", "this", "->", "headers", "->", "add", "(", "$", "name", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
add a header to the response @param string $name the name of the header @param string $value the value of the header @return \stubbles\webapp\Response
[ "add", "a", "header", "to", "the", "response" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/WebResponse.php#L171-L175
stubbles/stubbles-webapp-core
src/main/php/response/WebResponse.php
WebResponse.containsHeader
public function containsHeader(string $name, string $value = null): bool { if ($this->headers->contain($name)) { if (null !== $value) { return $value === $this->headers[$name]; } return true; } return false; }
php
public function containsHeader(string $name, string $value = null): bool { if ($this->headers->contain($name)) { if (null !== $value) { return $value === $this->headers[$name]; } return true; } return false; }
[ "public", "function", "containsHeader", "(", "string", "$", "name", ",", "string", "$", "value", "=", "null", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "headers", "->", "contain", "(", "$", "name", ")", ")", "{", "if", "(", "null", "!==", "$", "value", ")", "{", "return", "$", "value", "===", "$", "this", "->", "headers", "[", "$", "name", "]", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
check if response contains a certain header @param string $name name of header to check @param string $value optional if given the value is checked as well @return bool @since 4.0.0
[ "check", "if", "response", "contains", "a", "certain", "header" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/WebResponse.php#L196-L207
stubbles/stubbles-webapp-core
src/main/php/response/WebResponse.php
WebResponse.addCookie
public function addCookie(Cookie $cookie): Response { $this->cookies[$cookie->name()] = $cookie; return $this; }
php
public function addCookie(Cookie $cookie): Response { $this->cookies[$cookie->name()] = $cookie; return $this; }
[ "public", "function", "addCookie", "(", "Cookie", "$", "cookie", ")", ":", "Response", "{", "$", "this", "->", "cookies", "[", "$", "cookie", "->", "name", "(", ")", "]", "=", "$", "cookie", ";", "return", "$", "this", ";", "}" ]
add a cookie to the response @param \stubbles\webapp\response\Cookie $cookie the cookie to set @return \stubbles\webapp\Response
[ "add", "a", "cookie", "to", "the", "response" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/WebResponse.php#L215-L219
stubbles/stubbles-webapp-core
src/main/php/response/WebResponse.php
WebResponse.removeCookie
public function removeCookie(string $name): Response { $this->addCookie( Cookie::create($name, 'remove')->expiringAt(time() - 86400) ); return $this; }
php
public function removeCookie(string $name): Response { $this->addCookie( Cookie::create($name, 'remove')->expiringAt(time() - 86400) ); return $this; }
[ "public", "function", "removeCookie", "(", "string", "$", "name", ")", ":", "Response", "{", "$", "this", "->", "addCookie", "(", "Cookie", "::", "create", "(", "$", "name", ",", "'remove'", ")", "->", "expiringAt", "(", "time", "(", ")", "-", "86400", ")", ")", ";", "return", "$", "this", ";", "}" ]
removes cookie with given name @param string $name @return \stubbles\webapp\Response @since 2.0.0
[ "removes", "cookie", "with", "given", "name" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/WebResponse.php#L228-L234
stubbles/stubbles-webapp-core
src/main/php/response/WebResponse.php
WebResponse.containsCookie
public function containsCookie(string $name, string $value = null): bool { if (isset($this->cookies[$name])) { if (null !== $value) { return $this->cookies[$name]->value() === $value; } return true; } return false; }
php
public function containsCookie(string $name, string $value = null): bool { if (isset($this->cookies[$name])) { if (null !== $value) { return $this->cookies[$name]->value() === $value; } return true; } return false; }
[ "public", "function", "containsCookie", "(", "string", "$", "name", ",", "string", "$", "value", "=", "null", ")", ":", "bool", "{", "if", "(", "isset", "(", "$", "this", "->", "cookies", "[", "$", "name", "]", ")", ")", "{", "if", "(", "null", "!==", "$", "value", ")", "{", "return", "$", "this", "->", "cookies", "[", "$", "name", "]", "->", "value", "(", ")", "===", "$", "value", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
checks if response contains a certain cookie @param string $name name of cookie to check @param string $value optional if given the value is checked as well @return bool @since 4.0.0
[ "checks", "if", "response", "contains", "a", "certain", "cookie" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/WebResponse.php#L244-L255
stubbles/stubbles-webapp-core
src/main/php/response/WebResponse.php
WebResponse.methodNotAllowed
public function methodNotAllowed(string $requestMethod, array $allowedMethods): Error { $this->status->methodNotAllowed($allowedMethods); return Error::methodNotAllowed($requestMethod, $allowedMethods); }
php
public function methodNotAllowed(string $requestMethod, array $allowedMethods): Error { $this->status->methodNotAllowed($allowedMethods); return Error::methodNotAllowed($requestMethod, $allowedMethods); }
[ "public", "function", "methodNotAllowed", "(", "string", "$", "requestMethod", ",", "array", "$", "allowedMethods", ")", ":", "Error", "{", "$", "this", "->", "status", "->", "methodNotAllowed", "(", "$", "allowedMethods", ")", ";", "return", "Error", "::", "methodNotAllowed", "(", "$", "requestMethod", ",", "$", "allowedMethods", ")", ";", "}" ]
creates a 405 Method Not Allowed message @param string $requestMethod @param string[] $allowedMethods @return \stubbles\webapp\response\Error @since 2.0.0
[ "creates", "a", "405", "Method", "Not", "Allowed", "message" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/WebResponse.php#L334-L338
stubbles/stubbles-webapp-core
src/main/php/response/WebResponse.php
WebResponse.send
public function send(OutputStream $out = null) { $this->sendHead(); if ($this->requestAllowsBody() && null != $this->resource) { $out = (null === $out ? new StandardOutputStream() : $out); $this->mimeType->serialize( $this->resource, $out ); } return $out; }
php
public function send(OutputStream $out = null) { $this->sendHead(); if ($this->requestAllowsBody() && null != $this->resource) { $out = (null === $out ? new StandardOutputStream() : $out); $this->mimeType->serialize( $this->resource, $out ); } return $out; }
[ "public", "function", "send", "(", "OutputStream", "$", "out", "=", "null", ")", "{", "$", "this", "->", "sendHead", "(", ")", ";", "if", "(", "$", "this", "->", "requestAllowsBody", "(", ")", "&&", "null", "!=", "$", "this", "->", "resource", ")", "{", "$", "out", "=", "(", "null", "===", "$", "out", "?", "new", "StandardOutputStream", "(", ")", ":", "$", "out", ")", ";", "$", "this", "->", "mimeType", "->", "serialize", "(", "$", "this", "->", "resource", ",", "$", "out", ")", ";", "}", "return", "$", "out", ";", "}" ]
sends response In case no output stream is passed it will create a stubbles\streams\StandardOutputStream where the response body will be written to. The output stream is returned. In case no output stream was passed and the request doesn't allow a response body or no resource for the response body was set the return value is null because no standard stream will be created in such a case. @param \stubbles\streams\OutputStream $out optional where to write response body to @return \stubbles\streams\OutputStream|null
[ "sends", "response" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/WebResponse.php#L391-L403
stubbles/stubbles-webapp-core
src/main/php/response/WebResponse.php
WebResponse.sendHead
private function sendHead(): Response { $this->header($this->status->line($this->version, $this->sapi)); foreach ($this->headers as $name => $value) { $this->header($name . ': ' . $value); } foreach ($this->cookies as $cookie) { $cookie->send(); } $this->header('Content-type: ' . $this->mimeType); if (!$this->headers->contain('X-Request-ID')) { $this->header('X-Request-ID: ' . $this->request->id()); } return $this; }
php
private function sendHead(): Response { $this->header($this->status->line($this->version, $this->sapi)); foreach ($this->headers as $name => $value) { $this->header($name . ': ' . $value); } foreach ($this->cookies as $cookie) { $cookie->send(); } $this->header('Content-type: ' . $this->mimeType); if (!$this->headers->contain('X-Request-ID')) { $this->header('X-Request-ID: ' . $this->request->id()); } return $this; }
[ "private", "function", "sendHead", "(", ")", ":", "Response", "{", "$", "this", "->", "header", "(", "$", "this", "->", "status", "->", "line", "(", "$", "this", "->", "version", ",", "$", "this", "->", "sapi", ")", ")", ";", "foreach", "(", "$", "this", "->", "headers", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "this", "->", "header", "(", "$", "name", ".", "': '", ".", "$", "value", ")", ";", "}", "foreach", "(", "$", "this", "->", "cookies", "as", "$", "cookie", ")", "{", "$", "cookie", "->", "send", "(", ")", ";", "}", "$", "this", "->", "header", "(", "'Content-type: '", ".", "$", "this", "->", "mimeType", ")", ";", "if", "(", "!", "$", "this", "->", "headers", "->", "contain", "(", "'X-Request-ID'", ")", ")", "{", "$", "this", "->", "header", "(", "'X-Request-ID: '", ".", "$", "this", "->", "request", "->", "id", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
sends head only @return \stubbles\webapp\Response
[ "sends", "head", "only" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/WebResponse.php#L421-L438
chippyash/Math-Type-Calculator
src/Chippyash/Math/Type/Comparator.php
Comparator.compare
public function compare(NumericTypeInterface $a, NumericTypeInterface $b) { return $this->compEngine->compare($a, $b); }
php
public function compare(NumericTypeInterface $a, NumericTypeInterface $b) { return $this->compEngine->compare($a, $b); }
[ "public", "function", "compare", "(", "NumericTypeInterface", "$", "a", ",", "NumericTypeInterface", "$", "b", ")", "{", "return", "$", "this", "->", "compEngine", "->", "compare", "(", "$", "a", ",", "$", "b", ")", ";", "}" ]
a == b = 0 a < b = -1 a > b = 1 @param NumericTypeInterface $a @param NumericTypeInterface $b @return int
[ "a", "==", "b", "=", "0", "a", "<", "b", "=", "-", "1", "a", ">", "b", "=", "1" ]
train
https://github.com/chippyash/Math-Type-Calculator/blob/2a2fae0ab4d052772d3dd45745efd5a91f88b9e3/src/Chippyash/Math/Type/Comparator.php#L77-L80
FrenchFrogs/framework
src/Panel/Renderer/Bootstrap.php
Bootstrap.panel
public function panel(Panel\Panel\Panel $panel) { $html = ''; //@todo Action render $actions = ''; foreach($panel->getActions() as $action) { $actions .= $action->render() . PHP_EOL; } $html .= html('div', ['class' => 'pull-right'], $actions); $title = '<h4>' . $panel->getTitle() . '</h4>'; $html .= html('div', ['class' => Style::PANEL_HEAD_CLASS_TITLE . ' clearfix'], $title); $html = html('div', ['class' => Style::PANEL_HEAD_CLASS], $html); //@todo footer render $html .= html('div', ['class' => Style::PANEL_BODY_CLASS], $panel->getBody()); $panel->addClass(Style::PANEL_CLASS); if ($panel->hasContext()) { $panel->addClass(constant( Style::class . '::' . $panel->getContext())); } return html('div', $panel->getAttributes(), $html); }
php
public function panel(Panel\Panel\Panel $panel) { $html = ''; //@todo Action render $actions = ''; foreach($panel->getActions() as $action) { $actions .= $action->render() . PHP_EOL; } $html .= html('div', ['class' => 'pull-right'], $actions); $title = '<h4>' . $panel->getTitle() . '</h4>'; $html .= html('div', ['class' => Style::PANEL_HEAD_CLASS_TITLE . ' clearfix'], $title); $html = html('div', ['class' => Style::PANEL_HEAD_CLASS], $html); //@todo footer render $html .= html('div', ['class' => Style::PANEL_BODY_CLASS], $panel->getBody()); $panel->addClass(Style::PANEL_CLASS); if ($panel->hasContext()) { $panel->addClass(constant( Style::class . '::' . $panel->getContext())); } return html('div', $panel->getAttributes(), $html); }
[ "public", "function", "panel", "(", "Panel", "\\", "Panel", "\\", "Panel", "$", "panel", ")", "{", "$", "html", "=", "''", ";", "//@todo Action render", "$", "actions", "=", "''", ";", "foreach", "(", "$", "panel", "->", "getActions", "(", ")", "as", "$", "action", ")", "{", "$", "actions", ".=", "$", "action", "->", "render", "(", ")", ".", "PHP_EOL", ";", "}", "$", "html", ".=", "html", "(", "'div'", ",", "[", "'class'", "=>", "'pull-right'", "]", ",", "$", "actions", ")", ";", "$", "title", "=", "'<h4>'", ".", "$", "panel", "->", "getTitle", "(", ")", ".", "'</h4>'", ";", "$", "html", ".=", "html", "(", "'div'", ",", "[", "'class'", "=>", "Style", "::", "PANEL_HEAD_CLASS_TITLE", ".", "' clearfix'", "]", ",", "$", "title", ")", ";", "$", "html", "=", "html", "(", "'div'", ",", "[", "'class'", "=>", "Style", "::", "PANEL_HEAD_CLASS", "]", ",", "$", "html", ")", ";", "//@todo footer render", "$", "html", ".=", "html", "(", "'div'", ",", "[", "'class'", "=>", "Style", "::", "PANEL_BODY_CLASS", "]", ",", "$", "panel", "->", "getBody", "(", ")", ")", ";", "$", "panel", "->", "addClass", "(", "Style", "::", "PANEL_CLASS", ")", ";", "if", "(", "$", "panel", "->", "hasContext", "(", ")", ")", "{", "$", "panel", "->", "addClass", "(", "constant", "(", "Style", "::", "class", ".", "'::'", ".", "$", "panel", "->", "getContext", "(", ")", ")", ")", ";", "}", "return", "html", "(", "'div'", ",", "$", "panel", "->", "getAttributes", "(", ")", ",", "$", "html", ")", ";", "}" ]
Main renderer @param \FrenchFrogs\Panel\Panel\Panel $panel
[ "Main", "renderer" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Panel/Renderer/Bootstrap.php#L28-L56
FrenchFrogs/framework
src/Panel/Renderer/Bootstrap.php
Bootstrap.selectremote
public function selectremote(Panel\Action\SelectRemote $action) { $element = $action->getElement(); $element->addAttribute('id', $element->getName()); $element->addClass('select2-remote input-callback'); $element->addAttribute('data-css', 'form-control input-large input-sm'); $element->addAttribute('data-remote', $element->getUrl()); $element->addAttribute('data-length', $element->getLength()); $element->addAttribute('data-action', $action->getUrl()); $element->addAttribute('data-method', 'post'); $element->addAttribute('placeholder', $element->getLabel()); $html = html('input', $element->getAttributes()); return $html; }
php
public function selectremote(Panel\Action\SelectRemote $action) { $element = $action->getElement(); $element->addAttribute('id', $element->getName()); $element->addClass('select2-remote input-callback'); $element->addAttribute('data-css', 'form-control input-large input-sm'); $element->addAttribute('data-remote', $element->getUrl()); $element->addAttribute('data-length', $element->getLength()); $element->addAttribute('data-action', $action->getUrl()); $element->addAttribute('data-method', 'post'); $element->addAttribute('placeholder', $element->getLabel()); $html = html('input', $element->getAttributes()); return $html; }
[ "public", "function", "selectremote", "(", "Panel", "\\", "Action", "\\", "SelectRemote", "$", "action", ")", "{", "$", "element", "=", "$", "action", "->", "getElement", "(", ")", ";", "$", "element", "->", "addAttribute", "(", "'id'", ",", "$", "element", "->", "getName", "(", ")", ")", ";", "$", "element", "->", "addClass", "(", "'select2-remote input-callback'", ")", ";", "$", "element", "->", "addAttribute", "(", "'data-css'", ",", "'form-control input-large input-sm'", ")", ";", "$", "element", "->", "addAttribute", "(", "'data-remote'", ",", "$", "element", "->", "getUrl", "(", ")", ")", ";", "$", "element", "->", "addAttribute", "(", "'data-length'", ",", "$", "element", "->", "getLength", "(", ")", ")", ";", "$", "element", "->", "addAttribute", "(", "'data-action'", ",", "$", "action", "->", "getUrl", "(", ")", ")", ";", "$", "element", "->", "addAttribute", "(", "'data-method'", ",", "'post'", ")", ";", "$", "element", "->", "addAttribute", "(", "'placeholder'", ",", "$", "element", "->", "getLabel", "(", ")", ")", ";", "$", "html", "=", "html", "(", "'input'", ",", "$", "element", "->", "getAttributes", "(", ")", ")", ";", "return", "$", "html", ";", "}" ]
Render a Select 2 @param \FrenchFrogs\Panel\Action\SelectRemote $action
[ "Render", "a", "Select", "2" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Panel/Renderer/Bootstrap.php#L109-L123
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.listSubscriptions
public static function listSubscriptions( $user, $page = 1, $per_page = 20, $order_by = self::ORDERBY_CREATED_AT, $order_dir = self::ORDERDIR_ASC, $include_finished = false, $hash_type = false, $hash = false ) { if ($page < 1) { throw new DataSift_Exception_InvalidData("The specified page number is invalid"); } if ($per_page < 1) { throw new DataSift_Exception_InvalidData("The specified per_page value is invalid"); } $params = array( 'page' => $page, 'per_page' => $per_page, 'order_by' => $order_by, 'order_dir' => $order_dir, ); if ($hash_type !== false && $hash !== false) { $params[$hash_type] = $hash; } if ($include_finished) { $params['include_finished'] = '1'; } $res = $user->post('push/get', $params); $retval = array('count' => $res['count'], 'subscriptions' => array()); foreach ($res['subscriptions'] as $sub) { $retval['subscriptions'][] = new self($user, $sub); } return $retval; }
php
public static function listSubscriptions( $user, $page = 1, $per_page = 20, $order_by = self::ORDERBY_CREATED_AT, $order_dir = self::ORDERDIR_ASC, $include_finished = false, $hash_type = false, $hash = false ) { if ($page < 1) { throw new DataSift_Exception_InvalidData("The specified page number is invalid"); } if ($per_page < 1) { throw new DataSift_Exception_InvalidData("The specified per_page value is invalid"); } $params = array( 'page' => $page, 'per_page' => $per_page, 'order_by' => $order_by, 'order_dir' => $order_dir, ); if ($hash_type !== false && $hash !== false) { $params[$hash_type] = $hash; } if ($include_finished) { $params['include_finished'] = '1'; } $res = $user->post('push/get', $params); $retval = array('count' => $res['count'], 'subscriptions' => array()); foreach ($res['subscriptions'] as $sub) { $retval['subscriptions'][] = new self($user, $sub); } return $retval; }
[ "public", "static", "function", "listSubscriptions", "(", "$", "user", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "20", ",", "$", "order_by", "=", "self", "::", "ORDERBY_CREATED_AT", ",", "$", "order_dir", "=", "self", "::", "ORDERDIR_ASC", ",", "$", "include_finished", "=", "false", ",", "$", "hash_type", "=", "false", ",", "$", "hash", "=", "false", ")", "{", "if", "(", "$", "page", "<", "1", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "\"The specified page number is invalid\"", ")", ";", "}", "if", "(", "$", "per_page", "<", "1", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "\"The specified per_page value is invalid\"", ")", ";", "}", "$", "params", "=", "array", "(", "'page'", "=>", "$", "page", ",", "'per_page'", "=>", "$", "per_page", ",", "'order_by'", "=>", "$", "order_by", ",", "'order_dir'", "=>", "$", "order_dir", ",", ")", ";", "if", "(", "$", "hash_type", "!==", "false", "&&", "$", "hash", "!==", "false", ")", "{", "$", "params", "[", "$", "hash_type", "]", "=", "$", "hash", ";", "}", "if", "(", "$", "include_finished", ")", "{", "$", "params", "[", "'include_finished'", "]", "=", "'1'", ";", "}", "$", "res", "=", "$", "user", "->", "post", "(", "'push/get'", ",", "$", "params", ")", ";", "$", "retval", "=", "array", "(", "'count'", "=>", "$", "res", "[", "'count'", "]", ",", "'subscriptions'", "=>", "array", "(", ")", ")", ";", "foreach", "(", "$", "res", "[", "'subscriptions'", "]", "as", "$", "sub", ")", "{", "$", "retval", "[", "'subscriptions'", "]", "[", "]", "=", "new", "self", "(", "$", "user", ",", "$", "sub", ")", ";", "}", "return", "$", "retval", ";", "}" ]
Get a page of push subscriptions in the given user's account, where each page contains up to per_page items. Results will be ordered according to the supplied ordering parameters. @param DataSift_User $user The user. @param int $page The page number to fetch. @param int $per_page The number of items per page. @param string $order_by The field on which to order the results. @param string $order_dir The direction of the ordering. @param boolean $include_finished True to include subscriptions against finished historic queries. @param string $hash_type Stream hash or Historics playback id. @param string $hash The stream hash or historics subscription id string. @return array Of DataSift_Push_Subscription objects. @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError @throws DataSift_Exception_AccessDenied
[ "Get", "a", "page", "of", "push", "subscriptions", "in", "the", "given", "user", "s", "account", "where", "each", "page", "contains", "up", "to", "per_page", "items", ".", "Results", "will", "be", "ordered", "according", "to", "the", "supplied", "ordering", "parameters", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L94-L135
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.listByPlaybackId
public static function listByPlaybackId( $user, $playback_id, $page = 1, $per_page = 20, $order_by = self::ORDERBY_CREATED_AT, $order_dir = self::ORDERDIR_ASC, $include_finished = false, $hash_type = false, $hash = false ) { return self::listSubscriptions( $user, $page, $per_page, $order_by, $order_dir, $include_finished, 'playback_id', $playback_id ); }
php
public static function listByPlaybackId( $user, $playback_id, $page = 1, $per_page = 20, $order_by = self::ORDERBY_CREATED_AT, $order_dir = self::ORDERDIR_ASC, $include_finished = false, $hash_type = false, $hash = false ) { return self::listSubscriptions( $user, $page, $per_page, $order_by, $order_dir, $include_finished, 'playback_id', $playback_id ); }
[ "public", "static", "function", "listByPlaybackId", "(", "$", "user", ",", "$", "playback_id", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "20", ",", "$", "order_by", "=", "self", "::", "ORDERBY_CREATED_AT", ",", "$", "order_dir", "=", "self", "::", "ORDERDIR_ASC", ",", "$", "include_finished", "=", "false", ",", "$", "hash_type", "=", "false", ",", "$", "hash", "=", "false", ")", "{", "return", "self", "::", "listSubscriptions", "(", "$", "user", ",", "$", "page", ",", "$", "per_page", ",", "$", "order_by", ",", "$", "order_dir", ",", "$", "include_finished", ",", "'playback_id'", ",", "$", "playback_id", ")", ";", "}" ]
Get a page of push subscriptions to the given stream playback_id, where each page contains up to per_page items. Results will be ordered according to the supplied ordering parameters. @param DataSift_User $user The user. @param string $playback_id The Historics playback ID. @param int $page The page number to fetch. @param int $per_page The number of items per page. @param string $order_by The field on which to order the results. @param string $order_dir The direction of the ordering. @param boolean $include_finished True to include subscriptions against @param string $hash_type Stream hash or Historics playback id. @param string $hash The stream hash. finished historic queries. @return array Of DataSift_Push_Subscription objects. @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError @throws DataSift_Exception_AccessDenied
[ "Get", "a", "page", "of", "push", "subscriptions", "to", "the", "given", "stream", "playback_id", "where", "each", "page", "contains", "up", "to", "per_page", "items", ".", "Results", "will", "be", "ordered", "according", "to", "the", "supplied", "ordering", "parameters", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L200-L221
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.getLogs
public static function getLogs( $user, $page = 1, $per_page = 20, $order_by = self::ORDERBY_REQUEST_TIME, $order_dir = self::ORDERDIR_ASC, $id = false ) { if ($page < 1) { throw new DataSift_Exception_InvalidData('The specified page number is invalid'); } if ($per_page < 1) { throw new DataSift_Exception_InvalidData('The specified per_page value is invalid'); } $params = array(); if ($id !== false && strlen($id) > 0) { $params['id'] = $id; } $params['page'] = $page; $params['per_page'] = $per_page; $params['order_by'] = $order_by; $params['order_dir'] = $order_dir; $res = $user->post('push/log', $params); $retval = array('count' => $res['count'], 'log_entries' => array()); foreach ($res['log_entries'] as $log) { $retval['log_entries'][] = new DataSift_Push_LogEntry($log); } return $retval; }
php
public static function getLogs( $user, $page = 1, $per_page = 20, $order_by = self::ORDERBY_REQUEST_TIME, $order_dir = self::ORDERDIR_ASC, $id = false ) { if ($page < 1) { throw new DataSift_Exception_InvalidData('The specified page number is invalid'); } if ($per_page < 1) { throw new DataSift_Exception_InvalidData('The specified per_page value is invalid'); } $params = array(); if ($id !== false && strlen($id) > 0) { $params['id'] = $id; } $params['page'] = $page; $params['per_page'] = $per_page; $params['order_by'] = $order_by; $params['order_dir'] = $order_dir; $res = $user->post('push/log', $params); $retval = array('count' => $res['count'], 'log_entries' => array()); foreach ($res['log_entries'] as $log) { $retval['log_entries'][] = new DataSift_Push_LogEntry($log); } return $retval; }
[ "public", "static", "function", "getLogs", "(", "$", "user", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "20", ",", "$", "order_by", "=", "self", "::", "ORDERBY_REQUEST_TIME", ",", "$", "order_dir", "=", "self", "::", "ORDERDIR_ASC", ",", "$", "id", "=", "false", ")", "{", "if", "(", "$", "page", "<", "1", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'The specified page number is invalid'", ")", ";", "}", "if", "(", "$", "per_page", "<", "1", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'The specified per_page value is invalid'", ")", ";", "}", "$", "params", "=", "array", "(", ")", ";", "if", "(", "$", "id", "!==", "false", "&&", "strlen", "(", "$", "id", ")", ">", "0", ")", "{", "$", "params", "[", "'id'", "]", "=", "$", "id", ";", "}", "$", "params", "[", "'page'", "]", "=", "$", "page", ";", "$", "params", "[", "'per_page'", "]", "=", "$", "per_page", ";", "$", "params", "[", "'order_by'", "]", "=", "$", "order_by", ";", "$", "params", "[", "'order_dir'", "]", "=", "$", "order_dir", ";", "$", "res", "=", "$", "user", "->", "post", "(", "'push/log'", ",", "$", "params", ")", ";", "$", "retval", "=", "array", "(", "'count'", "=>", "$", "res", "[", "'count'", "]", ",", "'log_entries'", "=>", "array", "(", ")", ")", ";", "foreach", "(", "$", "res", "[", "'log_entries'", "]", "as", "$", "log", ")", "{", "$", "retval", "[", "'log_entries'", "]", "[", "]", "=", "new", "DataSift_Push_LogEntry", "(", "$", "log", ")", ";", "}", "return", "$", "retval", ";", "}" ]
Page through recent push subscription log entries, specifying the sort order. @param DataSift_User $user The user making the request. @param int $page Which page to fetch. @param int $per_page Based on this page size. @param string $order_by Which field to sort by. @param string $order_dir In asc[ending] or desc[ending] order. @param string $id Push subscription ID. @return array Of LogEntry objects. @throws DataSift_Exception_APIError @throws DataSift_Exception_InvalidData @throws DataSift_Exception_AccessDenied
[ "Page", "through", "recent", "push", "subscription", "log", "entries", "specifying", "the", "sort", "order", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L239-L273
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.init
protected function init($data) { if (! isset($data['id'])) { throw new DataSift_Exception_InvalidData('No id found'); } $this->_id = $data['id']; if (! isset($data['name'])) { throw new DataSift_Exception_InvalidData('No name found'); } $this->_name = $data['name']; if (! isset($data['created_at'])) { throw new DataSift_Exception_InvalidData('No created_at found'); } $this->_created_at = $data['created_at']; if (! isset($data['status'])) { throw new DataSift_Exception_InvalidData('No status found'); } $this->_status = $data['status']; if (! isset($data['hash_type'], $data)) { throw new DataSift_Exception_InvalidData('No hash_type found'); } $this->_hash_type = $data['hash_type']; if (! isset($data['hash'])) { throw new DataSift_Exception_InvalidData('No hash found'); } $this->_hash = $data['hash']; if (! isset($data['last_request'])) { $this->_last_request = 0; } else { $this->_last_request = $data['last_request']; } if (! isset($data['last_success'])) { $this->_last_success = 0; } else { $this->_last_success = $data['last_success']; } if (! isset($data['output_type'])) { throw new DataSift_Exception_InvalidData('No output_type found'); } $this->_output_type = $data['output_type']; if (! isset($data['output_params'])) { throw new DataSift_Exception_InvalidData('No output_params found'); } $this->_output_params = $this->parseOutputParams($data['output_params']); }
php
protected function init($data) { if (! isset($data['id'])) { throw new DataSift_Exception_InvalidData('No id found'); } $this->_id = $data['id']; if (! isset($data['name'])) { throw new DataSift_Exception_InvalidData('No name found'); } $this->_name = $data['name']; if (! isset($data['created_at'])) { throw new DataSift_Exception_InvalidData('No created_at found'); } $this->_created_at = $data['created_at']; if (! isset($data['status'])) { throw new DataSift_Exception_InvalidData('No status found'); } $this->_status = $data['status']; if (! isset($data['hash_type'], $data)) { throw new DataSift_Exception_InvalidData('No hash_type found'); } $this->_hash_type = $data['hash_type']; if (! isset($data['hash'])) { throw new DataSift_Exception_InvalidData('No hash found'); } $this->_hash = $data['hash']; if (! isset($data['last_request'])) { $this->_last_request = 0; } else { $this->_last_request = $data['last_request']; } if (! isset($data['last_success'])) { $this->_last_success = 0; } else { $this->_last_success = $data['last_success']; } if (! isset($data['output_type'])) { throw new DataSift_Exception_InvalidData('No output_type found'); } $this->_output_type = $data['output_type']; if (! isset($data['output_params'])) { throw new DataSift_Exception_InvalidData('No output_params found'); } $this->_output_params = $this->parseOutputParams($data['output_params']); }
[ "protected", "function", "init", "(", "$", "data", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'id'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'No id found'", ")", ";", "}", "$", "this", "->", "_id", "=", "$", "data", "[", "'id'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'name'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'No name found'", ")", ";", "}", "$", "this", "->", "_name", "=", "$", "data", "[", "'name'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'created_at'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'No created_at found'", ")", ";", "}", "$", "this", "->", "_created_at", "=", "$", "data", "[", "'created_at'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'status'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'No status found'", ")", ";", "}", "$", "this", "->", "_status", "=", "$", "data", "[", "'status'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'hash_type'", "]", ",", "$", "data", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'No hash_type found'", ")", ";", "}", "$", "this", "->", "_hash_type", "=", "$", "data", "[", "'hash_type'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'hash'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'No hash found'", ")", ";", "}", "$", "this", "->", "_hash", "=", "$", "data", "[", "'hash'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'last_request'", "]", ")", ")", "{", "$", "this", "->", "_last_request", "=", "0", ";", "}", "else", "{", "$", "this", "->", "_last_request", "=", "$", "data", "[", "'last_request'", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "data", "[", "'last_success'", "]", ")", ")", "{", "$", "this", "->", "_last_success", "=", "0", ";", "}", "else", "{", "$", "this", "->", "_last_success", "=", "$", "data", "[", "'last_success'", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "data", "[", "'output_type'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'No output_type found'", ")", ";", "}", "$", "this", "->", "_output_type", "=", "$", "data", "[", "'output_type'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'output_params'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'No output_params found'", ")", ";", "}", "$", "this", "->", "_output_params", "=", "$", "this", "->", "parseOutputParams", "(", "$", "data", "[", "'output_params'", "]", ")", ";", "}" ]
Extract data from an array. @param array $data An array containing the subscription data. @throws DataSift_Exception_InvalidData
[ "Extract", "data", "from", "an", "array", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L342-L395
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.parseOutputParams
protected function parseOutputParams($params, $prefix = '') { $retval = array(); foreach ($params as $key => $val) { if (is_array($val)) { $retval = array_merge($retval, $this->parseOutputParams($val, $prefix . $key . '.')); } else { $retval[$prefix . $key] = $val; } } return $retval; }
php
protected function parseOutputParams($params, $prefix = '') { $retval = array(); foreach ($params as $key => $val) { if (is_array($val)) { $retval = array_merge($retval, $this->parseOutputParams($val, $prefix . $key . '.')); } else { $retval[$prefix . $key] = $val; } } return $retval; }
[ "protected", "function", "parseOutputParams", "(", "$", "params", ",", "$", "prefix", "=", "''", ")", "{", "$", "retval", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", ")", "{", "$", "retval", "=", "array_merge", "(", "$", "retval", ",", "$", "this", "->", "parseOutputParams", "(", "$", "val", ",", "$", "prefix", ".", "$", "key", ".", "'.'", ")", ")", ";", "}", "else", "{", "$", "retval", "[", "$", "prefix", ".", "$", "key", "]", "=", "$", "val", ";", "}", "}", "return", "$", "retval", ";", "}" ]
Recursive method to parse the output_params as received from the API into the flattened, dot-notation used by the client libraries. @param array $params The parameters to parse. @param string $prefix The current key prefix. @return array
[ "Recursive", "method", "to", "parse", "the", "output_params", "as", "received", "from", "the", "API", "into", "the", "flattened", "dot", "-", "notation", "used", "by", "the", "client", "libraries", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L406-L417
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.setOutputParam
public function setOutputParam($key, $val) { if ($this->isDeleted()) { throw new DataSift_Exception_InvalidData('Cannot modify a deleted subscription'); } parent::setOutputParam($key, $val); }
php
public function setOutputParam($key, $val) { if ($this->isDeleted()) { throw new DataSift_Exception_InvalidData('Cannot modify a deleted subscription'); } parent::setOutputParam($key, $val); }
[ "public", "function", "setOutputParam", "(", "$", "key", ",", "$", "val", ")", "{", "if", "(", "$", "this", "->", "isDeleted", "(", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot modify a deleted subscription'", ")", ";", "}", "parent", "::", "setOutputParam", "(", "$", "key", ",", "$", "val", ")", ";", "}" ]
Set an output parameter. Checks to see if the subscription has been deleted, and if not calls the base class to set the parameter. @param string $key The output parameter to set. @param string $val The value to which to set it. @throws DataSift_Exception_InvalidData
[ "Set", "an", "output", "parameter", ".", "Checks", "to", "see", "if", "the", "subscription", "has", "been", "deleted", "and", "if", "not", "calls", "the", "base", "class", "to", "set", "the", "parameter", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L460-L466
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.save
public function save() { // Can only update the name and output_params $params = array('id' => $this->getId(), 'name' => $this->getName()); foreach ($this->_output_params as $key => $val) { $params[DataSift_Push_Definition::OUTPUT_PARAMS_PREFIX . $key] = $val; } // Call the API and pass the returned object into init to update this object $this->init($this->_user->post('push/update', $params)); }
php
public function save() { // Can only update the name and output_params $params = array('id' => $this->getId(), 'name' => $this->getName()); foreach ($this->_output_params as $key => $val) { $params[DataSift_Push_Definition::OUTPUT_PARAMS_PREFIX . $key] = $val; } // Call the API and pass the returned object into init to update this object $this->init($this->_user->post('push/update', $params)); }
[ "public", "function", "save", "(", ")", "{", "// Can only update the name and output_params", "$", "params", "=", "array", "(", "'id'", "=>", "$", "this", "->", "getId", "(", ")", ",", "'name'", "=>", "$", "this", "->", "getName", "(", ")", ")", ";", "foreach", "(", "$", "this", "->", "_output_params", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "params", "[", "DataSift_Push_Definition", "::", "OUTPUT_PARAMS_PREFIX", ".", "$", "key", "]", "=", "$", "val", ";", "}", "// Call the API and pass the returned object into init to update this object", "$", "this", "->", "init", "(", "$", "this", "->", "_user", "->", "post", "(", "'push/update'", ",", "$", "params", ")", ")", ";", "}" ]
Save changes to the name and output_parameters of this subscription. @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError @throws DataSift_Exception_AccessDenied
[ "Save", "changes", "to", "the", "name", "and", "output_parameters", "of", "this", "subscription", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L557-L567
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.delete
public function delete() { $this->_user->post('push/delete', array('id' => $this->getId())); // The delete API call doesn't return the object, so set the status // manually $this->_status = self::STATUS_DELETED; }
php
public function delete() { $this->_user->post('push/delete', array('id' => $this->getId())); // The delete API call doesn't return the object, so set the status // manually $this->_status = self::STATUS_DELETED; }
[ "public", "function", "delete", "(", ")", "{", "$", "this", "->", "_user", "->", "post", "(", "'push/delete'", ",", "array", "(", "'id'", "=>", "$", "this", "->", "getId", "(", ")", ")", ")", ";", "// The delete API call doesn't return the object, so set the status", "// manually", "$", "this", "->", "_status", "=", "self", "::", "STATUS_DELETED", ";", "}" ]
Delete this subscription. @throws DataSift_Exception_APIError @throws DataSift_Exception_AccessDenied
[ "Delete", "this", "subscription", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L611-L617
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.pull
public function pull($size = 20971520, $cursor = false) { //Check that the output type of this subscription is a pull if (strtolower($this->_output_type) != 'pull') { throw new DataSift_Exception_InvalidData("Output type is not pull"); } $params = array('id' => $this->getId(), 'size' => $size); if ($cursor !== false) { $params['cursor'] = $cursor; } return $this->_user->get('pull', $params); }
php
public function pull($size = 20971520, $cursor = false) { //Check that the output type of this subscription is a pull if (strtolower($this->_output_type) != 'pull') { throw new DataSift_Exception_InvalidData("Output type is not pull"); } $params = array('id' => $this->getId(), 'size' => $size); if ($cursor !== false) { $params['cursor'] = $cursor; } return $this->_user->get('pull', $params); }
[ "public", "function", "pull", "(", "$", "size", "=", "20971520", ",", "$", "cursor", "=", "false", ")", "{", "//Check that the output type of this subscription is a pull", "if", "(", "strtolower", "(", "$", "this", "->", "_output_type", ")", "!=", "'pull'", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "\"Output type is not pull\"", ")", ";", "}", "$", "params", "=", "array", "(", "'id'", "=>", "$", "this", "->", "getId", "(", ")", ",", "'size'", "=>", "$", "size", ")", ";", "if", "(", "$", "cursor", "!==", "false", ")", "{", "$", "params", "[", "'cursor'", "]", "=", "$", "cursor", ";", "}", "return", "$", "this", "->", "_user", "->", "get", "(", "'pull'", ",", "$", "params", ")", ";", "}" ]
Pull data from this subscription. @param int $size The maximum amount of data that DataSift will send in a single batch. Can be any value from 1 byte through 20971520 bytes. @param string $cursor A pointer into the Push queue associated with the current Push subscription. @return array @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError @throws DataSift_Exception_AccessDenied
[ "Pull", "data", "from", "this", "subscription", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L631-L645
datasift/datasift-php
lib/DataSift/Push/Subscription.php
DataSift_Push_Subscription.getLog
public function getLog( $page = 1, $per_page = 20, $order_by = self::ORDERBY_REQUEST_TIME, $order_dir = self::ORDERDIR_DESC ) { return self::getLogs($this->_user, $page, $per_page, $order_by, $order_dir, $this->getId()); }
php
public function getLog( $page = 1, $per_page = 20, $order_by = self::ORDERBY_REQUEST_TIME, $order_dir = self::ORDERDIR_DESC ) { return self::getLogs($this->_user, $page, $per_page, $order_by, $order_dir, $this->getId()); }
[ "public", "function", "getLog", "(", "$", "page", "=", "1", ",", "$", "per_page", "=", "20", ",", "$", "order_by", "=", "self", "::", "ORDERBY_REQUEST_TIME", ",", "$", "order_dir", "=", "self", "::", "ORDERDIR_DESC", ")", "{", "return", "self", "::", "getLogs", "(", "$", "this", "->", "_user", ",", "$", "page", ",", "$", "per_page", ",", "$", "order_by", ",", "$", "order_dir", ",", "$", "this", "->", "getId", "(", ")", ")", ";", "}" ]
Get a page of the log for this subscription order as specified. @param int $page The page to get. @param int $per_page The number of entries per page. @param string $order_by By which field to order the entries. @param string $order_dir The direction of the sorting ("asc" or "desc"). @return array @throws DataSift_Exception_APIError @throws DataSift_Exception_InvalidData @throws DataSift_Exception_AccessDenied
[ "Get", "a", "page", "of", "the", "log", "for", "this", "subscription", "order", "as", "specified", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Push/Subscription.php#L660-L667
JoffreyPoreeCoding/MongoDB-ODM
src/Iterator/DocumentIterator.php
DocumentIterator.rewind
public function rewind() { if (!$this->rewindable && !$this->firstCross) { throw new \Exception('Unable to traverse not rewindable iterator multiple time'); } $this->firstCross = false; $this->position = 0; }
php
public function rewind() { if (!$this->rewindable && !$this->firstCross) { throw new \Exception('Unable to traverse not rewindable iterator multiple time'); } $this->firstCross = false; $this->position = 0; }
[ "public", "function", "rewind", "(", ")", "{", "if", "(", "!", "$", "this", "->", "rewindable", "&&", "!", "$", "this", "->", "firstCross", ")", "{", "throw", "new", "\\", "Exception", "(", "'Unable to traverse not rewindable iterator multiple time'", ")", ";", "}", "$", "this", "->", "firstCross", "=", "false", ";", "$", "this", "->", "position", "=", "0", ";", "}" ]
Rewinds the Iterator to the first element. @return void
[ "Rewinds", "the", "Iterator", "to", "the", "first", "element", "." ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Iterator/DocumentIterator.php#L154-L161
JoffreyPoreeCoding/MongoDB-ODM
src/Iterator/DocumentIterator.php
DocumentIterator.valid
public function valid() { if (isset($this->objects[$this->position])) { return true; } if ($this->currentData == null) { return false; } return $this->generator->valid(); }
php
public function valid() { if (isset($this->objects[$this->position])) { return true; } if ($this->currentData == null) { return false; } return $this->generator->valid(); }
[ "public", "function", "valid", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "objects", "[", "$", "this", "->", "position", "]", ")", ")", "{", "return", "true", ";", "}", "if", "(", "$", "this", "->", "currentData", "==", "null", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "generator", "->", "valid", "(", ")", ";", "}" ]
Checks if there is a current element after calls to rewind() or next(). @return bool
[ "Checks", "if", "there", "is", "a", "current", "element", "after", "calls", "to", "rewind", "()", "or", "next", "()", "." ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Iterator/DocumentIterator.php#L168-L179
JoffreyPoreeCoding/MongoDB-ODM
src/Iterator/DocumentIterator.php
DocumentIterator.current
public function current() { if ($this->valid() && !isset($this->objects[$this->position])) { $class = $this->objectClass; $object = new $class(); $this->hydrator->hydrate($object, $this->currentData); $this->classMetadata->getEventManager()->execute(EventManager::EVENT_POST_LOAD, $object); if (!$this->readOnly) { $this->repository->cacheObject($object); $this->documentManager->addObject($object, DocumentManager::OBJ_MANAGED, $this->repository); } if ($this->rewindable) { $this->objects[] = $object; } else { return $object; } } if (isset($this->objects[$this->position])) { return $this->objects[$this->position]; } else { return null; } }
php
public function current() { if ($this->valid() && !isset($this->objects[$this->position])) { $class = $this->objectClass; $object = new $class(); $this->hydrator->hydrate($object, $this->currentData); $this->classMetadata->getEventManager()->execute(EventManager::EVENT_POST_LOAD, $object); if (!$this->readOnly) { $this->repository->cacheObject($object); $this->documentManager->addObject($object, DocumentManager::OBJ_MANAGED, $this->repository); } if ($this->rewindable) { $this->objects[] = $object; } else { return $object; } } if (isset($this->objects[$this->position])) { return $this->objects[$this->position]; } else { return null; } }
[ "public", "function", "current", "(", ")", "{", "if", "(", "$", "this", "->", "valid", "(", ")", "&&", "!", "isset", "(", "$", "this", "->", "objects", "[", "$", "this", "->", "position", "]", ")", ")", "{", "$", "class", "=", "$", "this", "->", "objectClass", ";", "$", "object", "=", "new", "$", "class", "(", ")", ";", "$", "this", "->", "hydrator", "->", "hydrate", "(", "$", "object", ",", "$", "this", "->", "currentData", ")", ";", "$", "this", "->", "classMetadata", "->", "getEventManager", "(", ")", "->", "execute", "(", "EventManager", "::", "EVENT_POST_LOAD", ",", "$", "object", ")", ";", "if", "(", "!", "$", "this", "->", "readOnly", ")", "{", "$", "this", "->", "repository", "->", "cacheObject", "(", "$", "object", ")", ";", "$", "this", "->", "documentManager", "->", "addObject", "(", "$", "object", ",", "DocumentManager", "::", "OBJ_MANAGED", ",", "$", "this", "->", "repository", ")", ";", "}", "if", "(", "$", "this", "->", "rewindable", ")", "{", "$", "this", "->", "objects", "[", "]", "=", "$", "object", ";", "}", "else", "{", "return", "$", "object", ";", "}", "}", "if", "(", "isset", "(", "$", "this", "->", "objects", "[", "$", "this", "->", "position", "]", ")", ")", "{", "return", "$", "this", "->", "objects", "[", "$", "this", "->", "position", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the current element. @return mixed
[ "Returns", "the", "current", "element", "." ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Iterator/DocumentIterator.php#L196-L219
JoffreyPoreeCoding/MongoDB-ODM
src/Iterator/DocumentIterator.php
DocumentIterator.count
public function count() { if (!isset($this->count)) { $this->count = $this->repository->count($this->query); } return $this->count; }
php
public function count() { if (!isset($this->count)) { $this->count = $this->repository->count($this->query); } return $this->count; }
[ "public", "function", "count", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "count", ")", ")", "{", "$", "this", "->", "count", "=", "$", "this", "->", "repository", "->", "count", "(", "$", "this", "->", "query", ")", ";", "}", "return", "$", "this", "->", "count", ";", "}" ]
Count number of document from collection @return integer
[ "Count", "number", "of", "document", "from", "collection" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Iterator/DocumentIterator.php#L260-L266
belgattitude/soluble-metadata
src/Soluble/Metadata/Reader/PdoMysqlMetadataReader.php
PdoMysqlMetadataReader.readColumnsMetadata
protected function readColumnsMetadata(string $sql): ColumnsMetadata { $metadata = new ColumnsMetadata(); $fields = $this->readFields($sql); $type_map = PdoMysqlMapping::getDatatypeMapping(); foreach ($fields as $idx => $field) { $name = $field['name']; $tableName = $field['table']; $type = strtoupper($field['native_type']); if (!$type_map->offsetExists($type)) { $msg = "Cannot get type for field '$name'. Mapping for native type [$type] cannot be resolved into a valid type for driver: " . __CLASS__; throw new Exception\UnsupportedTypeException($msg); } $datatype = $type_map->offsetGet($type); $column = Column\Type::createColumnDefinition($datatype['type'], $name, $tableName, $schemaName = null); $alias = $field['name']; $column->setAlias($alias); $column->setTableAlias($field['table']); //$column->setCatalog($field->catalog); $column->setOrdinalPosition($idx + 1); $column->setDataType($datatype['type']); $column->setIsNullable(!in_array('not_null', $field['flags'], true)); $column->setIsPrimary(in_array('primary_key', $field['flags'], true)); //$column->setColumnDefault($field->def); $column->setNativeDataType($datatype['native']); /* if ($column instanceof Column\Definition\NumericColumnInterface) { $column->setNumericUnsigned(($field->flags & MYSQLI_UNSIGNED_FLAG) > 0); } */ if ($column instanceof Column\Definition\IntegerColumn) { // PDO does not support detection of autoincrement. // Always false $column->setIsAutoIncrement(false); } if ($column instanceof Column\Definition\DecimalColumn) { // salary DECIMAL(5,2) // In this example, 5 is the precision and 2 is the scale. // Standard SQL requires that DECIMAL(5,2) be able to store any value // with five digits and two decimals, so values that can be stored in // the salary column range from -999.99 to 999.99. $column->setNumericUnsigned(false); $column->setNumericPrecision($field['precision']); $column->setNumericScale((int) ($field['len'] - $field['precision'] + 1)); } if ($column instanceof Column\Definition\StringColumn) { $column->setCharacterMaximumLength($field['len']); } if ($column instanceof Column\Definition\BlobColumn) { $column->setCharacterOctetLength($field['len']); } if ($metadata->offsetExists($alias)) { $prev_column = $metadata->offsetGet($alias); $prev_def = $prev_column->toArray(); $curr_def = $column->toArray(); if ($prev_def['dataType'] !== $curr_def['dataType'] || $prev_def['nativeDataType'] !== $curr_def['nativeDataType']) { throw new Exception\AmbiguousColumnException("Cannot get column metadata, non unique column found '$alias' in query with different definitions."); } // If the the previous definition, was a prev_def /* if ($prev_def['isPrimary']) { $column = $prev_column; } */ } $metadata->offsetSet($alias, $column); } return $metadata; }
php
protected function readColumnsMetadata(string $sql): ColumnsMetadata { $metadata = new ColumnsMetadata(); $fields = $this->readFields($sql); $type_map = PdoMysqlMapping::getDatatypeMapping(); foreach ($fields as $idx => $field) { $name = $field['name']; $tableName = $field['table']; $type = strtoupper($field['native_type']); if (!$type_map->offsetExists($type)) { $msg = "Cannot get type for field '$name'. Mapping for native type [$type] cannot be resolved into a valid type for driver: " . __CLASS__; throw new Exception\UnsupportedTypeException($msg); } $datatype = $type_map->offsetGet($type); $column = Column\Type::createColumnDefinition($datatype['type'], $name, $tableName, $schemaName = null); $alias = $field['name']; $column->setAlias($alias); $column->setTableAlias($field['table']); //$column->setCatalog($field->catalog); $column->setOrdinalPosition($idx + 1); $column->setDataType($datatype['type']); $column->setIsNullable(!in_array('not_null', $field['flags'], true)); $column->setIsPrimary(in_array('primary_key', $field['flags'], true)); //$column->setColumnDefault($field->def); $column->setNativeDataType($datatype['native']); /* if ($column instanceof Column\Definition\NumericColumnInterface) { $column->setNumericUnsigned(($field->flags & MYSQLI_UNSIGNED_FLAG) > 0); } */ if ($column instanceof Column\Definition\IntegerColumn) { // PDO does not support detection of autoincrement. // Always false $column->setIsAutoIncrement(false); } if ($column instanceof Column\Definition\DecimalColumn) { // salary DECIMAL(5,2) // In this example, 5 is the precision and 2 is the scale. // Standard SQL requires that DECIMAL(5,2) be able to store any value // with five digits and two decimals, so values that can be stored in // the salary column range from -999.99 to 999.99. $column->setNumericUnsigned(false); $column->setNumericPrecision($field['precision']); $column->setNumericScale((int) ($field['len'] - $field['precision'] + 1)); } if ($column instanceof Column\Definition\StringColumn) { $column->setCharacterMaximumLength($field['len']); } if ($column instanceof Column\Definition\BlobColumn) { $column->setCharacterOctetLength($field['len']); } if ($metadata->offsetExists($alias)) { $prev_column = $metadata->offsetGet($alias); $prev_def = $prev_column->toArray(); $curr_def = $column->toArray(); if ($prev_def['dataType'] !== $curr_def['dataType'] || $prev_def['nativeDataType'] !== $curr_def['nativeDataType']) { throw new Exception\AmbiguousColumnException("Cannot get column metadata, non unique column found '$alias' in query with different definitions."); } // If the the previous definition, was a prev_def /* if ($prev_def['isPrimary']) { $column = $prev_column; } */ } $metadata->offsetSet($alias, $column); } return $metadata; }
[ "protected", "function", "readColumnsMetadata", "(", "string", "$", "sql", ")", ":", "ColumnsMetadata", "{", "$", "metadata", "=", "new", "ColumnsMetadata", "(", ")", ";", "$", "fields", "=", "$", "this", "->", "readFields", "(", "$", "sql", ")", ";", "$", "type_map", "=", "PdoMysqlMapping", "::", "getDatatypeMapping", "(", ")", ";", "foreach", "(", "$", "fields", "as", "$", "idx", "=>", "$", "field", ")", "{", "$", "name", "=", "$", "field", "[", "'name'", "]", ";", "$", "tableName", "=", "$", "field", "[", "'table'", "]", ";", "$", "type", "=", "strtoupper", "(", "$", "field", "[", "'native_type'", "]", ")", ";", "if", "(", "!", "$", "type_map", "->", "offsetExists", "(", "$", "type", ")", ")", "{", "$", "msg", "=", "\"Cannot get type for field '$name'. Mapping for native type [$type] cannot be resolved into a valid type for driver: \"", ".", "__CLASS__", ";", "throw", "new", "Exception", "\\", "UnsupportedTypeException", "(", "$", "msg", ")", ";", "}", "$", "datatype", "=", "$", "type_map", "->", "offsetGet", "(", "$", "type", ")", ";", "$", "column", "=", "Column", "\\", "Type", "::", "createColumnDefinition", "(", "$", "datatype", "[", "'type'", "]", ",", "$", "name", ",", "$", "tableName", ",", "$", "schemaName", "=", "null", ")", ";", "$", "alias", "=", "$", "field", "[", "'name'", "]", ";", "$", "column", "->", "setAlias", "(", "$", "alias", ")", ";", "$", "column", "->", "setTableAlias", "(", "$", "field", "[", "'table'", "]", ")", ";", "//$column->setCatalog($field->catalog);", "$", "column", "->", "setOrdinalPosition", "(", "$", "idx", "+", "1", ")", ";", "$", "column", "->", "setDataType", "(", "$", "datatype", "[", "'type'", "]", ")", ";", "$", "column", "->", "setIsNullable", "(", "!", "in_array", "(", "'not_null'", ",", "$", "field", "[", "'flags'", "]", ",", "true", ")", ")", ";", "$", "column", "->", "setIsPrimary", "(", "in_array", "(", "'primary_key'", ",", "$", "field", "[", "'flags'", "]", ",", "true", ")", ")", ";", "//$column->setColumnDefault($field->def);", "$", "column", "->", "setNativeDataType", "(", "$", "datatype", "[", "'native'", "]", ")", ";", "/*\n if ($column instanceof Column\\Definition\\NumericColumnInterface) {\n $column->setNumericUnsigned(($field->flags & MYSQLI_UNSIGNED_FLAG) > 0);\n }\n*/", "if", "(", "$", "column", "instanceof", "Column", "\\", "Definition", "\\", "IntegerColumn", ")", "{", "// PDO does not support detection of autoincrement.", "// Always false", "$", "column", "->", "setIsAutoIncrement", "(", "false", ")", ";", "}", "if", "(", "$", "column", "instanceof", "Column", "\\", "Definition", "\\", "DecimalColumn", ")", "{", "// salary DECIMAL(5,2)", "// In this example, 5 is the precision and 2 is the scale.", "// Standard SQL requires that DECIMAL(5,2) be able to store any value", "// with five digits and two decimals, so values that can be stored in", "// the salary column range from -999.99 to 999.99.", "$", "column", "->", "setNumericUnsigned", "(", "false", ")", ";", "$", "column", "->", "setNumericPrecision", "(", "$", "field", "[", "'precision'", "]", ")", ";", "$", "column", "->", "setNumericScale", "(", "(", "int", ")", "(", "$", "field", "[", "'len'", "]", "-", "$", "field", "[", "'precision'", "]", "+", "1", ")", ")", ";", "}", "if", "(", "$", "column", "instanceof", "Column", "\\", "Definition", "\\", "StringColumn", ")", "{", "$", "column", "->", "setCharacterMaximumLength", "(", "$", "field", "[", "'len'", "]", ")", ";", "}", "if", "(", "$", "column", "instanceof", "Column", "\\", "Definition", "\\", "BlobColumn", ")", "{", "$", "column", "->", "setCharacterOctetLength", "(", "$", "field", "[", "'len'", "]", ")", ";", "}", "if", "(", "$", "metadata", "->", "offsetExists", "(", "$", "alias", ")", ")", "{", "$", "prev_column", "=", "$", "metadata", "->", "offsetGet", "(", "$", "alias", ")", ";", "$", "prev_def", "=", "$", "prev_column", "->", "toArray", "(", ")", ";", "$", "curr_def", "=", "$", "column", "->", "toArray", "(", ")", ";", "if", "(", "$", "prev_def", "[", "'dataType'", "]", "!==", "$", "curr_def", "[", "'dataType'", "]", "||", "$", "prev_def", "[", "'nativeDataType'", "]", "!==", "$", "curr_def", "[", "'nativeDataType'", "]", ")", "{", "throw", "new", "Exception", "\\", "AmbiguousColumnException", "(", "\"Cannot get column metadata, non unique column found '$alias' in query with different definitions.\"", ")", ";", "}", "// If the the previous definition, was a prev_def", "/*\n if ($prev_def['isPrimary']) {\n $column = $prev_column;\n }\n */", "}", "$", "metadata", "->", "offsetSet", "(", "$", "alias", ",", "$", "column", ")", ";", "}", "return", "$", "metadata", ";", "}" ]
{@inheritdoc} @throws \Soluble\Metadata\Exception\ConnectionException @throws \Soluble\Metadata\Exception\EmptyQueryException @throws \Soluble\Metadata\Exception\InvalidQueryException
[ "{", "@inheritdoc", "}" ]
train
https://github.com/belgattitude/soluble-metadata/blob/6285461c40a619070f601184d58e6c772b769d5c/src/Soluble/Metadata/Reader/PdoMysqlMetadataReader.php#L64-L148
belgattitude/soluble-metadata
src/Soluble/Metadata/Reader/PdoMysqlMetadataReader.php
PdoMysqlMetadataReader.readFields
protected function readFields(string $sql): array { if (trim($sql) === '') { throw new Exception\EmptyQueryException('Cannot read fields for an empty query'); } $sql = $this->getEmptiedQuery($sql); $stmt = $this->pdo->prepare($sql); if ($stmt->execute() !== true) { throw new Exception\InvalidQueryException( sprintf('Invalid query: %s', $sql) ); } $column_count = $stmt->columnCount(); $metaFields = []; for ($i = 0; $i < $column_count; ++$i) { $meta = $stmt->getColumnMeta($i); $metaFields[$i] = $meta; } $stmt->closeCursor(); unset($stmt); return $metaFields; }
php
protected function readFields(string $sql): array { if (trim($sql) === '') { throw new Exception\EmptyQueryException('Cannot read fields for an empty query'); } $sql = $this->getEmptiedQuery($sql); $stmt = $this->pdo->prepare($sql); if ($stmt->execute() !== true) { throw new Exception\InvalidQueryException( sprintf('Invalid query: %s', $sql) ); } $column_count = $stmt->columnCount(); $metaFields = []; for ($i = 0; $i < $column_count; ++$i) { $meta = $stmt->getColumnMeta($i); $metaFields[$i] = $meta; } $stmt->closeCursor(); unset($stmt); return $metaFields; }
[ "protected", "function", "readFields", "(", "string", "$", "sql", ")", ":", "array", "{", "if", "(", "trim", "(", "$", "sql", ")", "===", "''", ")", "{", "throw", "new", "Exception", "\\", "EmptyQueryException", "(", "'Cannot read fields for an empty query'", ")", ";", "}", "$", "sql", "=", "$", "this", "->", "getEmptiedQuery", "(", "$", "sql", ")", ";", "$", "stmt", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "sql", ")", ";", "if", "(", "$", "stmt", "->", "execute", "(", ")", "!==", "true", ")", "{", "throw", "new", "Exception", "\\", "InvalidQueryException", "(", "sprintf", "(", "'Invalid query: %s'", ",", "$", "sql", ")", ")", ";", "}", "$", "column_count", "=", "$", "stmt", "->", "columnCount", "(", ")", ";", "$", "metaFields", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "column_count", ";", "++", "$", "i", ")", "{", "$", "meta", "=", "$", "stmt", "->", "getColumnMeta", "(", "$", "i", ")", ";", "$", "metaFields", "[", "$", "i", "]", "=", "$", "meta", ";", "}", "$", "stmt", "->", "closeCursor", "(", ")", ";", "unset", "(", "$", "stmt", ")", ";", "return", "$", "metaFields", ";", "}" ]
Read fields from pdo source. @return array<int, array> @throws Exception\ConnectionException @throws \Soluble\Metadata\Exception\EmptyQueryException @throws \Soluble\Metadata\Exception\InvalidQueryException
[ "Read", "fields", "from", "pdo", "source", "." ]
train
https://github.com/belgattitude/soluble-metadata/blob/6285461c40a619070f601184d58e6c772b769d5c/src/Soluble/Metadata/Reader/PdoMysqlMetadataReader.php#L159-L185
WellCommerce/OrderBundle
Calculator/SalesSummaryCalculator.php
SalesSummaryCalculator.filterCurrentItems
protected function filterCurrentItems(Collection $collection) { $endDate = new DateTime(); $format = $this->configuration->getGroupByDateFormat(); $identifier = $endDate->format($format); return $collection->filter(function (ReportRow $row) use ($identifier) { return $row->getIdentifier() === $identifier; }); }
php
protected function filterCurrentItems(Collection $collection) { $endDate = new DateTime(); $format = $this->configuration->getGroupByDateFormat(); $identifier = $endDate->format($format); return $collection->filter(function (ReportRow $row) use ($identifier) { return $row->getIdentifier() === $identifier; }); }
[ "protected", "function", "filterCurrentItems", "(", "Collection", "$", "collection", ")", "{", "$", "endDate", "=", "new", "DateTime", "(", ")", ";", "$", "format", "=", "$", "this", "->", "configuration", "->", "getGroupByDateFormat", "(", ")", ";", "$", "identifier", "=", "$", "endDate", "->", "format", "(", "$", "format", ")", ";", "return", "$", "collection", "->", "filter", "(", "function", "(", "ReportRow", "$", "row", ")", "use", "(", "$", "identifier", ")", "{", "return", "$", "row", "->", "getIdentifier", "(", ")", "===", "$", "identifier", ";", "}", ")", ";", "}" ]
Filters a collection to get only current items @param Collection $collection @return Collection
[ "Filters", "a", "collection", "to", "get", "only", "current", "items" ]
train
https://github.com/WellCommerce/OrderBundle/blob/d72cfb51eab7a1f66f186900d1e2d533a822c424/Calculator/SalesSummaryCalculator.php#L85-L94
php-ddd/command
src/Utils/ClassUtils.php
ClassUtils.shortName
public static function shortName($objectOrNamespace) { if (is_object($objectOrNamespace)) { $objectOrNamespace = get_class($objectOrNamespace); } elseif (!class_exists($objectOrNamespace)) { throw new InvalidArgumentException( sprintf( 'There is no class named %s', $objectOrNamespace ) ); } $classNameWithNamespace = explode('\\', $objectOrNamespace); return end($classNameWithNamespace); }
php
public static function shortName($objectOrNamespace) { if (is_object($objectOrNamespace)) { $objectOrNamespace = get_class($objectOrNamespace); } elseif (!class_exists($objectOrNamespace)) { throw new InvalidArgumentException( sprintf( 'There is no class named %s', $objectOrNamespace ) ); } $classNameWithNamespace = explode('\\', $objectOrNamespace); return end($classNameWithNamespace); }
[ "public", "static", "function", "shortName", "(", "$", "objectOrNamespace", ")", "{", "if", "(", "is_object", "(", "$", "objectOrNamespace", ")", ")", "{", "$", "objectOrNamespace", "=", "get_class", "(", "$", "objectOrNamespace", ")", ";", "}", "elseif", "(", "!", "class_exists", "(", "$", "objectOrNamespace", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'There is no class named %s'", ",", "$", "objectOrNamespace", ")", ")", ";", "}", "$", "classNameWithNamespace", "=", "explode", "(", "'\\\\'", ",", "$", "objectOrNamespace", ")", ";", "return", "end", "(", "$", "classNameWithNamespace", ")", ";", "}" ]
@param object|string $objectOrNamespace @return string
[ "@param", "object|string", "$objectOrNamespace" ]
train
https://github.com/php-ddd/command/blob/dbad1d35c8d740c29c3a28d34f4a787c2b14688a/src/Utils/ClassUtils.php#L16-L32
geosocio/http-serializer-bundle
src/DependencyInjection/Compiler/GroupResolverPass.php
GroupResolverPass.process
public function process(ContainerBuilder $container) : void { $this->addResolvers( $container, 'geosocio_http_serializer.request_group_resolver_manager', 'geosocio_http_serializer.request_group_resolver' ); $this->addResolvers( $container, 'geosocio_http_serializer.response_group_resolver_manager', 'geosocio_http_serializer.response_group_resolver' ); }
php
public function process(ContainerBuilder $container) : void { $this->addResolvers( $container, 'geosocio_http_serializer.request_group_resolver_manager', 'geosocio_http_serializer.request_group_resolver' ); $this->addResolvers( $container, 'geosocio_http_serializer.response_group_resolver_manager', 'geosocio_http_serializer.response_group_resolver' ); }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "this", "->", "addResolvers", "(", "$", "container", ",", "'geosocio_http_serializer.request_group_resolver_manager'", ",", "'geosocio_http_serializer.request_group_resolver'", ")", ";", "$", "this", "->", "addResolvers", "(", "$", "container", ",", "'geosocio_http_serializer.response_group_resolver_manager'", ",", "'geosocio_http_serializer.response_group_resolver'", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/geosocio/http-serializer-bundle/blob/2ceb24a148204b1f3b14083b202db7e5afff2099/src/DependencyInjection/Compiler/GroupResolverPass.php#L17-L29
geosocio/http-serializer-bundle
src/DependencyInjection/Compiler/GroupResolverPass.php
GroupResolverPass.addResolvers
protected function addResolvers(ContainerBuilder $container, string $service, string $tag) { if (!$container->has($service)) { return; } $definition = $container->getDefinition($service); $taggedServices = $container->findTaggedServiceIds($tag); foreach ($taggedServices as $id => $tags) { foreach ($tags as $attributes) { $definition->addMethodCall('addResolver', [ new Reference($id) ]); } } }
php
protected function addResolvers(ContainerBuilder $container, string $service, string $tag) { if (!$container->has($service)) { return; } $definition = $container->getDefinition($service); $taggedServices = $container->findTaggedServiceIds($tag); foreach ($taggedServices as $id => $tags) { foreach ($tags as $attributes) { $definition->addMethodCall('addResolver', [ new Reference($id) ]); } } }
[ "protected", "function", "addResolvers", "(", "ContainerBuilder", "$", "container", ",", "string", "$", "service", ",", "string", "$", "tag", ")", "{", "if", "(", "!", "$", "container", "->", "has", "(", "$", "service", ")", ")", "{", "return", ";", "}", "$", "definition", "=", "$", "container", "->", "getDefinition", "(", "$", "service", ")", ";", "$", "taggedServices", "=", "$", "container", "->", "findTaggedServiceIds", "(", "$", "tag", ")", ";", "foreach", "(", "$", "taggedServices", "as", "$", "id", "=>", "$", "tags", ")", "{", "foreach", "(", "$", "tags", "as", "$", "attributes", ")", "{", "$", "definition", "->", "addMethodCall", "(", "'addResolver'", ",", "[", "new", "Reference", "(", "$", "id", ")", "]", ")", ";", "}", "}", "}" ]
Add the Resolvers. @param ContainerBuilder $container @param string $service @param string $tag @return void
[ "Add", "the", "Resolvers", "." ]
train
https://github.com/geosocio/http-serializer-bundle/blob/2ceb24a148204b1f3b14083b202db7e5afff2099/src/DependencyInjection/Compiler/GroupResolverPass.php#L40-L56
jasny/router
src/Router/Runner/Callback.php
Callback.run
public function run(ServerRequestInterface $request, ResponseInterface $response) { $route = $request->getAttribute('route'); $callback = !empty($route->fn) ? $route->fn : null; if (!is_callable($callback)) { trigger_error("'fn' property of route shoud be a callable", E_USER_NOTICE); return $this->notFound($request, $response); } return $callback($request, $response); }
php
public function run(ServerRequestInterface $request, ResponseInterface $response) { $route = $request->getAttribute('route'); $callback = !empty($route->fn) ? $route->fn : null; if (!is_callable($callback)) { trigger_error("'fn' property of route shoud be a callable", E_USER_NOTICE); return $this->notFound($request, $response); } return $callback($request, $response); }
[ "public", "function", "run", "(", "ServerRequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "route", "=", "$", "request", "->", "getAttribute", "(", "'route'", ")", ";", "$", "callback", "=", "!", "empty", "(", "$", "route", "->", "fn", ")", "?", "$", "route", "->", "fn", ":", "null", ";", "if", "(", "!", "is_callable", "(", "$", "callback", ")", ")", "{", "trigger_error", "(", "\"'fn' property of route shoud be a callable\"", ",", "E_USER_NOTICE", ")", ";", "return", "$", "this", "->", "notFound", "(", "$", "request", ",", "$", "response", ")", ";", "}", "return", "$", "callback", "(", "$", "request", ",", "$", "response", ")", ";", "}" ]
Use function to handle request and response @param ServerRequestInterface $request @param ResponseInterface $response @return ResponseInterface|mixed
[ "Use", "function", "to", "handle", "request", "and", "response" ]
train
https://github.com/jasny/router/blob/4c776665ba343150b442c21893946e3d54190896/src/Router/Runner/Callback.php#L23-L34
stubbles/stubbles-webapp-core
src/main/php/response/Error.php
Error.methodNotAllowed
public static function methodNotAllowed(string $requestMethod, array $allowedMethods): self { return new self( 'The given request method ' . strtoupper($requestMethod) . ' is not valid. Please use one of ' . join(', ', $allowedMethods) . '.', 'Method Not Allowed' ); }
php
public static function methodNotAllowed(string $requestMethod, array $allowedMethods): self { return new self( 'The given request method ' . strtoupper($requestMethod) . ' is not valid. Please use one of ' . join(', ', $allowedMethods) . '.', 'Method Not Allowed' ); }
[ "public", "static", "function", "methodNotAllowed", "(", "string", "$", "requestMethod", ",", "array", "$", "allowedMethods", ")", ":", "self", "{", "return", "new", "self", "(", "'The given request method '", ".", "strtoupper", "(", "$", "requestMethod", ")", ".", "' is not valid. Please use one of '", ".", "join", "(", "', '", ",", "$", "allowedMethods", ")", ".", "'.'", ",", "'Method Not Allowed'", ")", ";", "}" ]
creates error when access to resource with request method is not allowed @param string $requestMethod actual request method @param string[] $allowedMethods list of allowed request methods @return \stubbles\webapp\response\Error
[ "creates", "error", "when", "access", "to", "resource", "with", "request", "method", "is", "not", "allowed" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/Error.php#L74-L83
stubbles/stubbles-webapp-core
src/main/php/response/Error.php
Error.inParams
public static function inParams(ParamErrors $errors, ParamErrorMessages $errorMessages): self { return new self(Sequence::of($errors)->map( function(array $errors, $paramName) use ($errorMessages): array { $resolved = ['field' => $paramName, 'errors' => []]; foreach ($errors as $id => $error) { $resolved['errors'][] = [ 'id' => $id, 'details' => $error->details(), 'message' => $errorMessages->messageFor($error)->message() ]; } return $resolved; } )); }
php
public static function inParams(ParamErrors $errors, ParamErrorMessages $errorMessages): self { return new self(Sequence::of($errors)->map( function(array $errors, $paramName) use ($errorMessages): array { $resolved = ['field' => $paramName, 'errors' => []]; foreach ($errors as $id => $error) { $resolved['errors'][] = [ 'id' => $id, 'details' => $error->details(), 'message' => $errorMessages->messageFor($error)->message() ]; } return $resolved; } )); }
[ "public", "static", "function", "inParams", "(", "ParamErrors", "$", "errors", ",", "ParamErrorMessages", "$", "errorMessages", ")", ":", "self", "{", "return", "new", "self", "(", "Sequence", "::", "of", "(", "$", "errors", ")", "->", "map", "(", "function", "(", "array", "$", "errors", ",", "$", "paramName", ")", "use", "(", "$", "errorMessages", ")", ":", "array", "{", "$", "resolved", "=", "[", "'field'", "=>", "$", "paramName", ",", "'errors'", "=>", "[", "]", "]", ";", "foreach", "(", "$", "errors", "as", "$", "id", "=>", "$", "error", ")", "{", "$", "resolved", "[", "'errors'", "]", "[", "]", "=", "[", "'id'", "=>", "$", "id", ",", "'details'", "=>", "$", "error", "->", "details", "(", ")", ",", "'message'", "=>", "$", "errorMessages", "->", "messageFor", "(", "$", "error", ")", "->", "message", "(", ")", "]", ";", "}", "return", "$", "resolved", ";", "}", ")", ")", ";", "}" ]
creates error with given list of param errors @param \stubbles\input\errors\ParamErrors $errors @param \stubbles\webapp\response\ParamErrorMessages $errorMessages @return self @since 6.2.0
[ "creates", "error", "with", "given", "list", "of", "param", "errors" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/Error.php#L141-L158
Wonail/wocenter
core/ServiceLocator.php
ServiceLocator.getService
public function getService($serviceName) { $service = $serviceName . 'Service'; if (!Yii::$app->has($service, true)) { /** @var Service $component */ $component = Yii::$app->get($service); if (!$component instanceof Service) { throw new InvalidConfigException("The required service component `{$service}` must return an object extends `\\wocenter\\core\\Service`."); } elseif ($component->getId() != $serviceName) { throw new InvalidConfigException("{$component->className()}::getId() method must return the '{$serviceName}' value."); } Yii::trace('Loading service: ' . $serviceName, __METHOD__); return $component; } else { return Yii::$app->get($service); } }
php
public function getService($serviceName) { $service = $serviceName . 'Service'; if (!Yii::$app->has($service, true)) { /** @var Service $component */ $component = Yii::$app->get($service); if (!$component instanceof Service) { throw new InvalidConfigException("The required service component `{$service}` must return an object extends `\\wocenter\\core\\Service`."); } elseif ($component->getId() != $serviceName) { throw new InvalidConfigException("{$component->className()}::getId() method must return the '{$serviceName}' value."); } Yii::trace('Loading service: ' . $serviceName, __METHOD__); return $component; } else { return Yii::$app->get($service); } }
[ "public", "function", "getService", "(", "$", "serviceName", ")", "{", "$", "service", "=", "$", "serviceName", ".", "'Service'", ";", "if", "(", "!", "Yii", "::", "$", "app", "->", "has", "(", "$", "service", ",", "true", ")", ")", "{", "/** @var Service $component */", "$", "component", "=", "Yii", "::", "$", "app", "->", "get", "(", "$", "service", ")", ";", "if", "(", "!", "$", "component", "instanceof", "Service", ")", "{", "throw", "new", "InvalidConfigException", "(", "\"The required service component `{$service}` must return an object\n extends `\\\\wocenter\\\\core\\\\Service`.\"", ")", ";", "}", "elseif", "(", "$", "component", "->", "getId", "(", ")", "!=", "$", "serviceName", ")", "{", "throw", "new", "InvalidConfigException", "(", "\"{$component->className()}::getId() method must return the '{$serviceName}' value.\"", ")", ";", "}", "Yii", "::", "trace", "(", "'Loading service: '", ".", "$", "serviceName", ",", "__METHOD__", ")", ";", "return", "$", "component", ";", "}", "else", "{", "return", "Yii", "::", "$", "app", "->", "get", "(", "$", "service", ")", ";", "}", "}" ]
获取系统顶级服务类 @param string $serviceName 服务名,不带后缀`Service`,如:`passport`、`log` @return Service|object|null @throws InvalidConfigException
[ "获取系统顶级服务类" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/core/ServiceLocator.php#L29-L48
phramework/validate
src/StringValidator.php
StringValidator.validate
public function validate($value) { $return = new ValidateResult($value, false); if (!is_string($value)) { //error $return->errorObject = new IncorrectParametersException([ [ 'type' => static::getType(), 'failure' => 'type' ] ]); } elseif (mb_strlen($value) < $this->minLength) { //error $return->errorObject = new IncorrectParametersException([ [ 'type' => static::getType(), 'failure' => 'minLength' ] ]); } elseif ($this->maxLength !== null && mb_strlen($value) > $this->maxLength ) { //error $return->errorObject = new IncorrectParametersException([ [ 'type' => static::getType(), 'failure' => 'maxLength' ] ]); } elseif ($this->pattern !== null && filter_var( $value, FILTER_VALIDATE_REGEXP, [ 'options' => ['regexp' => $this->pattern] ] ) === false ) { //error $return->errorObject = new IncorrectParametersException([ [ 'type' => static::getType(), 'failure' => 'pattern' ] ]); } else { $return->errorObject = null; //Set status to success $return->status = true; if ($this->raw) { //use raw $return->value = $value; } else { //or filter $return->value = strip_tags( filter_var($value, FILTER_SANITIZE_STRING) ); } } return $this->validateCommon($value, $return); }
php
public function validate($value) { $return = new ValidateResult($value, false); if (!is_string($value)) { //error $return->errorObject = new IncorrectParametersException([ [ 'type' => static::getType(), 'failure' => 'type' ] ]); } elseif (mb_strlen($value) < $this->minLength) { //error $return->errorObject = new IncorrectParametersException([ [ 'type' => static::getType(), 'failure' => 'minLength' ] ]); } elseif ($this->maxLength !== null && mb_strlen($value) > $this->maxLength ) { //error $return->errorObject = new IncorrectParametersException([ [ 'type' => static::getType(), 'failure' => 'maxLength' ] ]); } elseif ($this->pattern !== null && filter_var( $value, FILTER_VALIDATE_REGEXP, [ 'options' => ['regexp' => $this->pattern] ] ) === false ) { //error $return->errorObject = new IncorrectParametersException([ [ 'type' => static::getType(), 'failure' => 'pattern' ] ]); } else { $return->errorObject = null; //Set status to success $return->status = true; if ($this->raw) { //use raw $return->value = $value; } else { //or filter $return->value = strip_tags( filter_var($value, FILTER_SANITIZE_STRING) ); } } return $this->validateCommon($value, $return); }
[ "public", "function", "validate", "(", "$", "value", ")", "{", "$", "return", "=", "new", "ValidateResult", "(", "$", "value", ",", "false", ")", ";", "if", "(", "!", "is_string", "(", "$", "value", ")", ")", "{", "//error", "$", "return", "->", "errorObject", "=", "new", "IncorrectParametersException", "(", "[", "[", "'type'", "=>", "static", "::", "getType", "(", ")", ",", "'failure'", "=>", "'type'", "]", "]", ")", ";", "}", "elseif", "(", "mb_strlen", "(", "$", "value", ")", "<", "$", "this", "->", "minLength", ")", "{", "//error", "$", "return", "->", "errorObject", "=", "new", "IncorrectParametersException", "(", "[", "[", "'type'", "=>", "static", "::", "getType", "(", ")", ",", "'failure'", "=>", "'minLength'", "]", "]", ")", ";", "}", "elseif", "(", "$", "this", "->", "maxLength", "!==", "null", "&&", "mb_strlen", "(", "$", "value", ")", ">", "$", "this", "->", "maxLength", ")", "{", "//error", "$", "return", "->", "errorObject", "=", "new", "IncorrectParametersException", "(", "[", "[", "'type'", "=>", "static", "::", "getType", "(", ")", ",", "'failure'", "=>", "'maxLength'", "]", "]", ")", ";", "}", "elseif", "(", "$", "this", "->", "pattern", "!==", "null", "&&", "filter_var", "(", "$", "value", ",", "FILTER_VALIDATE_REGEXP", ",", "[", "'options'", "=>", "[", "'regexp'", "=>", "$", "this", "->", "pattern", "]", "]", ")", "===", "false", ")", "{", "//error", "$", "return", "->", "errorObject", "=", "new", "IncorrectParametersException", "(", "[", "[", "'type'", "=>", "static", "::", "getType", "(", ")", ",", "'failure'", "=>", "'pattern'", "]", "]", ")", ";", "}", "else", "{", "$", "return", "->", "errorObject", "=", "null", ";", "//Set status to success", "$", "return", "->", "status", "=", "true", ";", "if", "(", "$", "this", "->", "raw", ")", "{", "//use raw", "$", "return", "->", "value", "=", "$", "value", ";", "}", "else", "{", "//or filter", "$", "return", "->", "value", "=", "strip_tags", "(", "filter_var", "(", "$", "value", ",", "FILTER_SANITIZE_STRING", ")", ")", ";", "}", "}", "return", "$", "this", "->", "validateCommon", "(", "$", "value", ",", "$", "return", ")", ";", "}" ]
Validate value @see \Phramework\Validate\ValidateResult for ValidateResult object @param mixed $value Value to validate @return ValidateResult @uses https://secure.php.net/manual/en/function.is-string.php @uses filter_var with FILTER_VALIDATE_REGEXP for pattern
[ "Validate", "value" ]
train
https://github.com/phramework/validate/blob/22dd3c4e5f7a77a1a75d92f98444f3e4b7ce5cfc/src/StringValidator.php#L89-L152
activecollab/databasestructure
src/Association/HasManyViaAssociation.php
HasManyViaAssociation.buildGetFinderMethod
protected function buildGetFinderMethod(StructureInterface $structure, TypeInterface $source_type, TypeInterface $target_type, $namespace, array &$result) { $intermediary_type = $structure->getType($this->intermediary_type_name); $order_by = $this->getOrderBy() ? '->orderBy(' . var_export($this->getOrderBy(), true) . ')' : ''; $result[] = ''; $result[] = ' /**'; $result[] = ' * @var \\ActiveCollab\\DatabaseObject\\Finder'; $result[] = ' */'; $result[] = ' private $' . $this->getFinderPropertyName() . ';'; $result[] = ''; $result[] = ' /**'; $result[] = ' * Return ' . Inflector::singularize($source_type->getName()) . ' ' . $this->getName() . ' finder instance.'; $result[] = ' *'; $result[] = ' * @return \\ActiveCollab\\DatabaseObject\\Finder'; $result[] = ' */'; $result[] = ' protected function ' . $this->getFinderMethodName() . '()'; $result[] = ' {'; $result[] = ' if (empty($this->' . $this->getFinderPropertyName() . ')) {'; $result[] = ' $this->' . $this->getFinderPropertyName() . ' = $this->pool->find(' . var_export($this->getInstanceClassFrom($namespace, $target_type), true) . ')->join(' . var_export($this->getInstanceClassFrom($namespace, $intermediary_type), true) . ')->where(\'`' . $intermediary_type->getTableName() . '`.`' . $this->getFkFieldNameFrom($source_type) . '` = ?\', $this->getId())' . $order_by . ';'; $result[] = ' }'; $result[] = ''; $result[] = ' return $this->' . $this->getFinderPropertyName() . ';'; $result[] = ' }'; }
php
protected function buildGetFinderMethod(StructureInterface $structure, TypeInterface $source_type, TypeInterface $target_type, $namespace, array &$result) { $intermediary_type = $structure->getType($this->intermediary_type_name); $order_by = $this->getOrderBy() ? '->orderBy(' . var_export($this->getOrderBy(), true) . ')' : ''; $result[] = ''; $result[] = ' /**'; $result[] = ' * @var \\ActiveCollab\\DatabaseObject\\Finder'; $result[] = ' */'; $result[] = ' private $' . $this->getFinderPropertyName() . ';'; $result[] = ''; $result[] = ' /**'; $result[] = ' * Return ' . Inflector::singularize($source_type->getName()) . ' ' . $this->getName() . ' finder instance.'; $result[] = ' *'; $result[] = ' * @return \\ActiveCollab\\DatabaseObject\\Finder'; $result[] = ' */'; $result[] = ' protected function ' . $this->getFinderMethodName() . '()'; $result[] = ' {'; $result[] = ' if (empty($this->' . $this->getFinderPropertyName() . ')) {'; $result[] = ' $this->' . $this->getFinderPropertyName() . ' = $this->pool->find(' . var_export($this->getInstanceClassFrom($namespace, $target_type), true) . ')->join(' . var_export($this->getInstanceClassFrom($namespace, $intermediary_type), true) . ')->where(\'`' . $intermediary_type->getTableName() . '`.`' . $this->getFkFieldNameFrom($source_type) . '` = ?\', $this->getId())' . $order_by . ';'; $result[] = ' }'; $result[] = ''; $result[] = ' return $this->' . $this->getFinderPropertyName() . ';'; $result[] = ' }'; }
[ "protected", "function", "buildGetFinderMethod", "(", "StructureInterface", "$", "structure", ",", "TypeInterface", "$", "source_type", ",", "TypeInterface", "$", "target_type", ",", "$", "namespace", ",", "array", "&", "$", "result", ")", "{", "$", "intermediary_type", "=", "$", "structure", "->", "getType", "(", "$", "this", "->", "intermediary_type_name", ")", ";", "$", "order_by", "=", "$", "this", "->", "getOrderBy", "(", ")", "?", "'->orderBy('", ".", "var_export", "(", "$", "this", "->", "getOrderBy", "(", ")", ",", "true", ")", ".", "')'", ":", "''", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' /**'", ";", "$", "result", "[", "]", "=", "' * @var \\\\ActiveCollab\\\\DatabaseObject\\\\Finder'", ";", "$", "result", "[", "]", "=", "' */'", ";", "$", "result", "[", "]", "=", "' private $'", ".", "$", "this", "->", "getFinderPropertyName", "(", ")", ".", "';'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' /**'", ";", "$", "result", "[", "]", "=", "' * Return '", ".", "Inflector", "::", "singularize", "(", "$", "source_type", "->", "getName", "(", ")", ")", ".", "' '", ".", "$", "this", "->", "getName", "(", ")", ".", "' finder instance.'", ";", "$", "result", "[", "]", "=", "' *'", ";", "$", "result", "[", "]", "=", "' * @return \\\\ActiveCollab\\\\DatabaseObject\\\\Finder'", ";", "$", "result", "[", "]", "=", "' */'", ";", "$", "result", "[", "]", "=", "' protected function '", ".", "$", "this", "->", "getFinderMethodName", "(", ")", ".", "'()'", ";", "$", "result", "[", "]", "=", "' {'", ";", "$", "result", "[", "]", "=", "' if (empty($this->'", ".", "$", "this", "->", "getFinderPropertyName", "(", ")", ".", "')) {'", ";", "$", "result", "[", "]", "=", "' $this->'", ".", "$", "this", "->", "getFinderPropertyName", "(", ")", ".", "' = $this->pool->find('", ".", "var_export", "(", "$", "this", "->", "getInstanceClassFrom", "(", "$", "namespace", ",", "$", "target_type", ")", ",", "true", ")", ".", "')->join('", ".", "var_export", "(", "$", "this", "->", "getInstanceClassFrom", "(", "$", "namespace", ",", "$", "intermediary_type", ")", ",", "true", ")", ".", "')->where(\\'`'", ".", "$", "intermediary_type", "->", "getTableName", "(", ")", ".", "'`.`'", ".", "$", "this", "->", "getFkFieldNameFrom", "(", "$", "source_type", ")", ".", "'` = ?\\', $this->getId())'", ".", "$", "order_by", ".", "';'", ";", "$", "result", "[", "]", "=", "' }'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' return $this->'", ".", "$", "this", "->", "getFinderPropertyName", "(", ")", ".", "';'", ";", "$", "result", "[", "]", "=", "' }'", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Association/HasManyViaAssociation.php#L46-L71
activecollab/databasestructure
src/Association/HasManyViaAssociation.php
HasManyViaAssociation.buildAddRelatedObjectMethod
public function buildAddRelatedObjectMethod(StructureInterface $structure, TypeInterface $source_type, TypeInterface $target_type, $namespace, array &$result) { $intermediary_type = $structure->getType($this->intermediary_type_name); $target_instance_class = $this->getInstanceClassFrom($namespace, $target_type); $intermediary_instance_class = $this->getInstanceClassFrom($namespace, $intermediary_type); $longest_docs_param_type_name = max(strlen($target_instance_class), 'array|null', '$this'); $result[] = ''; $result[] = ' /**'; $result[] = ' * Create connection between this ' . Inflector::singularize($source_type->getName()) . ' and $object_to_add.'; $result[] = ' *'; $result[] = ' * @param ' . str_pad($target_instance_class, $longest_docs_param_type_name, ' ', STR_PAD_RIGHT) . ' $object_to_add'; $result[] = ' * @param ' . str_pad('array|null', $longest_docs_param_type_name, ' ', STR_PAD_RIGHT) . ' $attributes'; $result[] = ' * @return $this'; $result[] = ' */'; $result[] = ' public function &add' . $this->getClassifiedSingleAssociationName() . '(' . $this->getInstanceClassFrom($namespace, $target_type) . ' $object_to_add, array $attributes = null)'; $result[] = ' {'; $result[] = ' if ($this->isNew()) {'; $result[] = ' throw new \RuntimeException(\'' . ucfirst(Inflector::singularize($source_type->getName())) . ' needs to be saved first\');'; $result[] = ' }'; $result[] = ''; $result[] = ' if ($object_to_add->isNew()) {'; $result[] = ' throw new \RuntimeException(\'' . ucfirst(Inflector::singularize($target_type->getName())) . ' needs to be saved first\');'; $result[] = ' }'; $result[] = ''; $result[] = ' $produce_attributes = ['; $result[] = ' \'' . $this->getFkFieldNameFrom($source_type) . '\' => $this->getId(),'; $result[] = ' \'' . $this->getFkFieldNameFrom($target_type) . '\' => $object_to_add->getId(),'; $result[] = ' ];'; $result[] = ''; $result[] = ' if (!empty($attributes)) {'; $result[] = ' $produce_attributes = array_merge($produce_attributes, $attributes);'; $result[] = ' }'; $result[] = ''; $result[] = ' $this->pool->produce(' . var_export($intermediary_instance_class, true) . ', $produce_attributes);'; $result[] = ''; $result[] = ' return $this;'; $result[] = ' }'; }
php
public function buildAddRelatedObjectMethod(StructureInterface $structure, TypeInterface $source_type, TypeInterface $target_type, $namespace, array &$result) { $intermediary_type = $structure->getType($this->intermediary_type_name); $target_instance_class = $this->getInstanceClassFrom($namespace, $target_type); $intermediary_instance_class = $this->getInstanceClassFrom($namespace, $intermediary_type); $longest_docs_param_type_name = max(strlen($target_instance_class), 'array|null', '$this'); $result[] = ''; $result[] = ' /**'; $result[] = ' * Create connection between this ' . Inflector::singularize($source_type->getName()) . ' and $object_to_add.'; $result[] = ' *'; $result[] = ' * @param ' . str_pad($target_instance_class, $longest_docs_param_type_name, ' ', STR_PAD_RIGHT) . ' $object_to_add'; $result[] = ' * @param ' . str_pad('array|null', $longest_docs_param_type_name, ' ', STR_PAD_RIGHT) . ' $attributes'; $result[] = ' * @return $this'; $result[] = ' */'; $result[] = ' public function &add' . $this->getClassifiedSingleAssociationName() . '(' . $this->getInstanceClassFrom($namespace, $target_type) . ' $object_to_add, array $attributes = null)'; $result[] = ' {'; $result[] = ' if ($this->isNew()) {'; $result[] = ' throw new \RuntimeException(\'' . ucfirst(Inflector::singularize($source_type->getName())) . ' needs to be saved first\');'; $result[] = ' }'; $result[] = ''; $result[] = ' if ($object_to_add->isNew()) {'; $result[] = ' throw new \RuntimeException(\'' . ucfirst(Inflector::singularize($target_type->getName())) . ' needs to be saved first\');'; $result[] = ' }'; $result[] = ''; $result[] = ' $produce_attributes = ['; $result[] = ' \'' . $this->getFkFieldNameFrom($source_type) . '\' => $this->getId(),'; $result[] = ' \'' . $this->getFkFieldNameFrom($target_type) . '\' => $object_to_add->getId(),'; $result[] = ' ];'; $result[] = ''; $result[] = ' if (!empty($attributes)) {'; $result[] = ' $produce_attributes = array_merge($produce_attributes, $attributes);'; $result[] = ' }'; $result[] = ''; $result[] = ' $this->pool->produce(' . var_export($intermediary_instance_class, true) . ', $produce_attributes);'; $result[] = ''; $result[] = ' return $this;'; $result[] = ' }'; }
[ "public", "function", "buildAddRelatedObjectMethod", "(", "StructureInterface", "$", "structure", ",", "TypeInterface", "$", "source_type", ",", "TypeInterface", "$", "target_type", ",", "$", "namespace", ",", "array", "&", "$", "result", ")", "{", "$", "intermediary_type", "=", "$", "structure", "->", "getType", "(", "$", "this", "->", "intermediary_type_name", ")", ";", "$", "target_instance_class", "=", "$", "this", "->", "getInstanceClassFrom", "(", "$", "namespace", ",", "$", "target_type", ")", ";", "$", "intermediary_instance_class", "=", "$", "this", "->", "getInstanceClassFrom", "(", "$", "namespace", ",", "$", "intermediary_type", ")", ";", "$", "longest_docs_param_type_name", "=", "max", "(", "strlen", "(", "$", "target_instance_class", ")", ",", "'array|null'", ",", "'$this'", ")", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' /**'", ";", "$", "result", "[", "]", "=", "' * Create connection between this '", ".", "Inflector", "::", "singularize", "(", "$", "source_type", "->", "getName", "(", ")", ")", ".", "' and $object_to_add.'", ";", "$", "result", "[", "]", "=", "' *'", ";", "$", "result", "[", "]", "=", "' * @param '", ".", "str_pad", "(", "$", "target_instance_class", ",", "$", "longest_docs_param_type_name", ",", "' '", ",", "STR_PAD_RIGHT", ")", ".", "' $object_to_add'", ";", "$", "result", "[", "]", "=", "' * @param '", ".", "str_pad", "(", "'array|null'", ",", "$", "longest_docs_param_type_name", ",", "' '", ",", "STR_PAD_RIGHT", ")", ".", "' $attributes'", ";", "$", "result", "[", "]", "=", "' * @return $this'", ";", "$", "result", "[", "]", "=", "' */'", ";", "$", "result", "[", "]", "=", "' public function &add'", ".", "$", "this", "->", "getClassifiedSingleAssociationName", "(", ")", ".", "'('", ".", "$", "this", "->", "getInstanceClassFrom", "(", "$", "namespace", ",", "$", "target_type", ")", ".", "' $object_to_add, array $attributes = null)'", ";", "$", "result", "[", "]", "=", "' {'", ";", "$", "result", "[", "]", "=", "' if ($this->isNew()) {'", ";", "$", "result", "[", "]", "=", "' throw new \\RuntimeException(\\''", ".", "ucfirst", "(", "Inflector", "::", "singularize", "(", "$", "source_type", "->", "getName", "(", ")", ")", ")", ".", "' needs to be saved first\\');'", ";", "$", "result", "[", "]", "=", "' }'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' if ($object_to_add->isNew()) {'", ";", "$", "result", "[", "]", "=", "' throw new \\RuntimeException(\\''", ".", "ucfirst", "(", "Inflector", "::", "singularize", "(", "$", "target_type", "->", "getName", "(", ")", ")", ")", ".", "' needs to be saved first\\');'", ";", "$", "result", "[", "]", "=", "' }'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' $produce_attributes = ['", ";", "$", "result", "[", "]", "=", "' \\''", ".", "$", "this", "->", "getFkFieldNameFrom", "(", "$", "source_type", ")", ".", "'\\' => $this->getId(),'", ";", "$", "result", "[", "]", "=", "' \\''", ".", "$", "this", "->", "getFkFieldNameFrom", "(", "$", "target_type", ")", ".", "'\\' => $object_to_add->getId(),'", ";", "$", "result", "[", "]", "=", "' ];'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' if (!empty($attributes)) {'", ";", "$", "result", "[", "]", "=", "' $produce_attributes = array_merge($produce_attributes, $attributes);'", ";", "$", "result", "[", "]", "=", "' }'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' $this->pool->produce('", ".", "var_export", "(", "$", "intermediary_instance_class", ",", "true", ")", ".", "', $produce_attributes);'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' return $this;'", ";", "$", "result", "[", "]", "=", "' }'", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Association/HasManyViaAssociation.php#L76-L116
activecollab/databasestructure
src/Association/HasManyViaAssociation.php
HasManyViaAssociation.buildRemoveRelatedObjectMethod
public function buildRemoveRelatedObjectMethod(StructureInterface $structure, TypeInterface $source_type, TypeInterface $target_type, $namespace, array &$result) { $intermediary_type = $structure->getType($this->intermediary_type_name); $target_instance_class = $this->getInstanceClassFrom($namespace, $target_type); $intermediary_instance_class = $this->getInstanceClassFrom($namespace, $intermediary_type); $result[] = ''; $result[] = ' /**'; $result[] = ' * Drop connection between this ' . Inflector::singularize($source_type->getName()) . ' and $object_to_remove.'; $result[] = ' *'; $result[] = ' * @param ' . $target_instance_class . ' $object_to_remove'; $result[] = ' * @return $this'; $result[] = ' */'; $result[] = ' public function &remove' . $this->getClassifiedSingleAssociationName() . '(' . $this->getInstanceClassFrom($namespace, $target_type) . ' $object_to_remove)'; $result[] = ' {'; $result[] = ' if ($this->isNew()) {'; $result[] = ' throw new \RuntimeException(\'' . ucfirst(Inflector::singularize($source_type->getName())) . ' needs to be saved first\');'; $result[] = ' }'; $result[] = ''; $result[] = ' if ($object_to_remove->isNew()) {'; $result[] = ' throw new \RuntimeException(\'' . ucfirst(Inflector::singularize($target_type->getName())) . ' needs to be saved first\');'; $result[] = ' }'; $result[] = ''; $result[] = ' $intermediary_object = $this->pool->find(' . var_export($intermediary_instance_class, true) . ')->where(\'' . $this->getFkFieldNameFrom($source_type) . ' = ? AND ' . $this->getFkFieldNameFrom($target_type) . ' = ?\', $this->getId(), $object_to_remove->getId())->first();'; $result[] = ''; $result[] = ' if ($intermediary_object instanceof ' . $intermediary_instance_class . ') {'; $result[] = ' $this->pool->scrap($intermediary_object, true);'; $result[] = ' }'; $result[] = ''; $result[] = ' return $this;'; $result[] = ' }'; }
php
public function buildRemoveRelatedObjectMethod(StructureInterface $structure, TypeInterface $source_type, TypeInterface $target_type, $namespace, array &$result) { $intermediary_type = $structure->getType($this->intermediary_type_name); $target_instance_class = $this->getInstanceClassFrom($namespace, $target_type); $intermediary_instance_class = $this->getInstanceClassFrom($namespace, $intermediary_type); $result[] = ''; $result[] = ' /**'; $result[] = ' * Drop connection between this ' . Inflector::singularize($source_type->getName()) . ' and $object_to_remove.'; $result[] = ' *'; $result[] = ' * @param ' . $target_instance_class . ' $object_to_remove'; $result[] = ' * @return $this'; $result[] = ' */'; $result[] = ' public function &remove' . $this->getClassifiedSingleAssociationName() . '(' . $this->getInstanceClassFrom($namespace, $target_type) . ' $object_to_remove)'; $result[] = ' {'; $result[] = ' if ($this->isNew()) {'; $result[] = ' throw new \RuntimeException(\'' . ucfirst(Inflector::singularize($source_type->getName())) . ' needs to be saved first\');'; $result[] = ' }'; $result[] = ''; $result[] = ' if ($object_to_remove->isNew()) {'; $result[] = ' throw new \RuntimeException(\'' . ucfirst(Inflector::singularize($target_type->getName())) . ' needs to be saved first\');'; $result[] = ' }'; $result[] = ''; $result[] = ' $intermediary_object = $this->pool->find(' . var_export($intermediary_instance_class, true) . ')->where(\'' . $this->getFkFieldNameFrom($source_type) . ' = ? AND ' . $this->getFkFieldNameFrom($target_type) . ' = ?\', $this->getId(), $object_to_remove->getId())->first();'; $result[] = ''; $result[] = ' if ($intermediary_object instanceof ' . $intermediary_instance_class . ') {'; $result[] = ' $this->pool->scrap($intermediary_object, true);'; $result[] = ' }'; $result[] = ''; $result[] = ' return $this;'; $result[] = ' }'; }
[ "public", "function", "buildRemoveRelatedObjectMethod", "(", "StructureInterface", "$", "structure", ",", "TypeInterface", "$", "source_type", ",", "TypeInterface", "$", "target_type", ",", "$", "namespace", ",", "array", "&", "$", "result", ")", "{", "$", "intermediary_type", "=", "$", "structure", "->", "getType", "(", "$", "this", "->", "intermediary_type_name", ")", ";", "$", "target_instance_class", "=", "$", "this", "->", "getInstanceClassFrom", "(", "$", "namespace", ",", "$", "target_type", ")", ";", "$", "intermediary_instance_class", "=", "$", "this", "->", "getInstanceClassFrom", "(", "$", "namespace", ",", "$", "intermediary_type", ")", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' /**'", ";", "$", "result", "[", "]", "=", "' * Drop connection between this '", ".", "Inflector", "::", "singularize", "(", "$", "source_type", "->", "getName", "(", ")", ")", ".", "' and $object_to_remove.'", ";", "$", "result", "[", "]", "=", "' *'", ";", "$", "result", "[", "]", "=", "' * @param '", ".", "$", "target_instance_class", ".", "' $object_to_remove'", ";", "$", "result", "[", "]", "=", "' * @return $this'", ";", "$", "result", "[", "]", "=", "' */'", ";", "$", "result", "[", "]", "=", "' public function &remove'", ".", "$", "this", "->", "getClassifiedSingleAssociationName", "(", ")", ".", "'('", ".", "$", "this", "->", "getInstanceClassFrom", "(", "$", "namespace", ",", "$", "target_type", ")", ".", "' $object_to_remove)'", ";", "$", "result", "[", "]", "=", "' {'", ";", "$", "result", "[", "]", "=", "' if ($this->isNew()) {'", ";", "$", "result", "[", "]", "=", "' throw new \\RuntimeException(\\''", ".", "ucfirst", "(", "Inflector", "::", "singularize", "(", "$", "source_type", "->", "getName", "(", ")", ")", ")", ".", "' needs to be saved first\\');'", ";", "$", "result", "[", "]", "=", "' }'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' if ($object_to_remove->isNew()) {'", ";", "$", "result", "[", "]", "=", "' throw new \\RuntimeException(\\''", ".", "ucfirst", "(", "Inflector", "::", "singularize", "(", "$", "target_type", "->", "getName", "(", ")", ")", ")", ".", "' needs to be saved first\\');'", ";", "$", "result", "[", "]", "=", "' }'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' $intermediary_object = $this->pool->find('", ".", "var_export", "(", "$", "intermediary_instance_class", ",", "true", ")", ".", "')->where(\\''", ".", "$", "this", "->", "getFkFieldNameFrom", "(", "$", "source_type", ")", ".", "' = ? AND '", ".", "$", "this", "->", "getFkFieldNameFrom", "(", "$", "target_type", ")", ".", "' = ?\\', $this->getId(), $object_to_remove->getId())->first();'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' if ($intermediary_object instanceof '", ".", "$", "intermediary_instance_class", ".", "') {'", ";", "$", "result", "[", "]", "=", "' $this->pool->scrap($intermediary_object, true);'", ";", "$", "result", "[", "]", "=", "' }'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' return $this;'", ";", "$", "result", "[", "]", "=", "' }'", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Association/HasManyViaAssociation.php#L121-L153
activecollab/databasestructure
src/Association/HasManyViaAssociation.php
HasManyViaAssociation.buildClearRelatedObjectsMethod
public function buildClearRelatedObjectsMethod(StructureInterface $structure, TypeInterface $source_type, TypeInterface $target_type, $namespace, array &$result) { $intermediary_type = $structure->getType($this->intermediary_type_name); $intermediary_instance_class = $this->getInstanceClassFrom($namespace, $intermediary_type); $result[] = ''; $result[] = ' /**'; $result[] = ' * Drop all connections between ' . str_replace('_', ' ', $target_type->getName()) . ' and this ' . Inflector::singularize($source_type->getName()) . '.'; $result[] = ' *'; $result[] = ' * @return $this'; $result[] = ' */'; $result[] = " public function &clear{$this->getClassifiedAssociationName()}()"; $result[] = ' {'; $result[] = ' if ($objects = $this->get' . $this->getClassifiedAssociationName() . '()) {'; $result[] = ' $object_ids = [];'; $result[] = ''; $result[] = ' $this->connection->transact(function () use ($objects, &$object_ids) {'; $result[] = ' foreach ($objects as $object) {'; $result[] = ' $object_ids[] = $object->getId();'; $result[] = ' $object->delete(true);'; $result[] = ' }'; $result[] = ' });'; $result[] = ''; $result[] = ' $this->pool->forget(' . var_export($intermediary_instance_class, true) . ', $object_ids);'; $result[] = ' }'; $result[] = ''; $result[] = ' return $this;'; $result[] = ' }'; }
php
public function buildClearRelatedObjectsMethod(StructureInterface $structure, TypeInterface $source_type, TypeInterface $target_type, $namespace, array &$result) { $intermediary_type = $structure->getType($this->intermediary_type_name); $intermediary_instance_class = $this->getInstanceClassFrom($namespace, $intermediary_type); $result[] = ''; $result[] = ' /**'; $result[] = ' * Drop all connections between ' . str_replace('_', ' ', $target_type->getName()) . ' and this ' . Inflector::singularize($source_type->getName()) . '.'; $result[] = ' *'; $result[] = ' * @return $this'; $result[] = ' */'; $result[] = " public function &clear{$this->getClassifiedAssociationName()}()"; $result[] = ' {'; $result[] = ' if ($objects = $this->get' . $this->getClassifiedAssociationName() . '()) {'; $result[] = ' $object_ids = [];'; $result[] = ''; $result[] = ' $this->connection->transact(function () use ($objects, &$object_ids) {'; $result[] = ' foreach ($objects as $object) {'; $result[] = ' $object_ids[] = $object->getId();'; $result[] = ' $object->delete(true);'; $result[] = ' }'; $result[] = ' });'; $result[] = ''; $result[] = ' $this->pool->forget(' . var_export($intermediary_instance_class, true) . ', $object_ids);'; $result[] = ' }'; $result[] = ''; $result[] = ' return $this;'; $result[] = ' }'; }
[ "public", "function", "buildClearRelatedObjectsMethod", "(", "StructureInterface", "$", "structure", ",", "TypeInterface", "$", "source_type", ",", "TypeInterface", "$", "target_type", ",", "$", "namespace", ",", "array", "&", "$", "result", ")", "{", "$", "intermediary_type", "=", "$", "structure", "->", "getType", "(", "$", "this", "->", "intermediary_type_name", ")", ";", "$", "intermediary_instance_class", "=", "$", "this", "->", "getInstanceClassFrom", "(", "$", "namespace", ",", "$", "intermediary_type", ")", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' /**'", ";", "$", "result", "[", "]", "=", "' * Drop all connections between '", ".", "str_replace", "(", "'_'", ",", "' '", ",", "$", "target_type", "->", "getName", "(", ")", ")", ".", "' and this '", ".", "Inflector", "::", "singularize", "(", "$", "source_type", "->", "getName", "(", ")", ")", ".", "'.'", ";", "$", "result", "[", "]", "=", "' *'", ";", "$", "result", "[", "]", "=", "' * @return $this'", ";", "$", "result", "[", "]", "=", "' */'", ";", "$", "result", "[", "]", "=", "\" public function &clear{$this->getClassifiedAssociationName()}()\"", ";", "$", "result", "[", "]", "=", "' {'", ";", "$", "result", "[", "]", "=", "' if ($objects = $this->get'", ".", "$", "this", "->", "getClassifiedAssociationName", "(", ")", ".", "'()) {'", ";", "$", "result", "[", "]", "=", "' $object_ids = [];'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' $this->connection->transact(function () use ($objects, &$object_ids) {'", ";", "$", "result", "[", "]", "=", "' foreach ($objects as $object) {'", ";", "$", "result", "[", "]", "=", "' $object_ids[] = $object->getId();'", ";", "$", "result", "[", "]", "=", "' $object->delete(true);'", ";", "$", "result", "[", "]", "=", "' }'", ";", "$", "result", "[", "]", "=", "' });'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' $this->pool->forget('", ".", "var_export", "(", "$", "intermediary_instance_class", ",", "true", ")", ".", "', $object_ids);'", ";", "$", "result", "[", "]", "=", "' }'", ";", "$", "result", "[", "]", "=", "''", ";", "$", "result", "[", "]", "=", "' return $this;'", ";", "$", "result", "[", "]", "=", "' }'", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Association/HasManyViaAssociation.php#L158-L186
prooph/link-app-core
src/Model/ProcessingConfig.php
ProcessingConfig.initializeWithDefaultsIn
public static function initializeWithDefaultsIn(ConfigLocation $configLocation, ConfigWriter $configWriter) { $env = Environment::setUp(); $instance = new self(['processing' => array_merge( $env->getConfig()->toArray(), [ "connectors" => [], "js_ticker" => ['enabled' => false, 'interval' => 3], ] )], $configLocation); $configFilePath = $configLocation->toString() . DIRECTORY_SEPARATOR . self::$configFileName; if (file_exists($configFilePath)) { throw new \RuntimeException("Processing config already exists: " . $configFilePath); } $configWriter->writeNewConfigToDirectory($instance->toArray(), $configFilePath); $instance->recordThat(ProcessingConfigFileWasCreated::in($configLocation, self::$configFileName)); return $instance; }
php
public static function initializeWithDefaultsIn(ConfigLocation $configLocation, ConfigWriter $configWriter) { $env = Environment::setUp(); $instance = new self(['processing' => array_merge( $env->getConfig()->toArray(), [ "connectors" => [], "js_ticker" => ['enabled' => false, 'interval' => 3], ] )], $configLocation); $configFilePath = $configLocation->toString() . DIRECTORY_SEPARATOR . self::$configFileName; if (file_exists($configFilePath)) { throw new \RuntimeException("Processing config already exists: " . $configFilePath); } $configWriter->writeNewConfigToDirectory($instance->toArray(), $configFilePath); $instance->recordThat(ProcessingConfigFileWasCreated::in($configLocation, self::$configFileName)); return $instance; }
[ "public", "static", "function", "initializeWithDefaultsIn", "(", "ConfigLocation", "$", "configLocation", ",", "ConfigWriter", "$", "configWriter", ")", "{", "$", "env", "=", "Environment", "::", "setUp", "(", ")", ";", "$", "instance", "=", "new", "self", "(", "[", "'processing'", "=>", "array_merge", "(", "$", "env", "->", "getConfig", "(", ")", "->", "toArray", "(", ")", ",", "[", "\"connectors\"", "=>", "[", "]", ",", "\"js_ticker\"", "=>", "[", "'enabled'", "=>", "false", ",", "'interval'", "=>", "3", "]", ",", "]", ")", "]", ",", "$", "configLocation", ")", ";", "$", "configFilePath", "=", "$", "configLocation", "->", "toString", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "self", "::", "$", "configFileName", ";", "if", "(", "file_exists", "(", "$", "configFilePath", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Processing config already exists: \"", ".", "$", "configFilePath", ")", ";", "}", "$", "configWriter", "->", "writeNewConfigToDirectory", "(", "$", "instance", "->", "toArray", "(", ")", ",", "$", "configFilePath", ")", ";", "$", "instance", "->", "recordThat", "(", "ProcessingConfigFileWasCreated", "::", "in", "(", "$", "configLocation", ",", "self", "::", "$", "configFileName", ")", ")", ";", "return", "$", "instance", ";", "}" ]
Uses Prooph\Processing\Environment to initialize with its defaults
[ "Uses", "Prooph", "\\", "Processing", "\\", "Environment", "to", "initialize", "with", "its", "defaults" ]
train
https://github.com/prooph/link-app-core/blob/835a5945dfa7be7b2cebfa6e84e757ecfd783357/src/Model/ProcessingConfig.php#L80-L103
prooph/link-app-core
src/Model/ProcessingConfig.php
ProcessingConfig.configureJavascriptTicker
public function configureJavascriptTicker(array $jsTickerConfig, ConfigWriter $configWriter) { $this->assertJsTickerConfig($jsTickerConfig); $oldConfig = $this->config['processing']['js_ticker']; $this->config['processing']['js_ticker'] = $jsTickerConfig; $this->writeConfig($configWriter); $this->recordThat(JavascriptTickerWasConfigured::to($jsTickerConfig, $oldConfig)); }
php
public function configureJavascriptTicker(array $jsTickerConfig, ConfigWriter $configWriter) { $this->assertJsTickerConfig($jsTickerConfig); $oldConfig = $this->config['processing']['js_ticker']; $this->config['processing']['js_ticker'] = $jsTickerConfig; $this->writeConfig($configWriter); $this->recordThat(JavascriptTickerWasConfigured::to($jsTickerConfig, $oldConfig)); }
[ "public", "function", "configureJavascriptTicker", "(", "array", "$", "jsTickerConfig", ",", "ConfigWriter", "$", "configWriter", ")", "{", "$", "this", "->", "assertJsTickerConfig", "(", "$", "jsTickerConfig", ")", ";", "$", "oldConfig", "=", "$", "this", "->", "config", "[", "'processing'", "]", "[", "'js_ticker'", "]", ";", "$", "this", "->", "config", "[", "'processing'", "]", "[", "'js_ticker'", "]", "=", "$", "jsTickerConfig", ";", "$", "this", "->", "writeConfig", "(", "$", "configWriter", ")", ";", "$", "this", "->", "recordThat", "(", "JavascriptTickerWasConfigured", "::", "to", "(", "$", "jsTickerConfig", ",", "$", "oldConfig", ")", ")", ";", "}" ]
Configure the javascript ticker @param array $jsTickerConfig @param ConfigWriter $configWriter
[ "Configure", "the", "javascript", "ticker" ]
train
https://github.com/prooph/link-app-core/blob/835a5945dfa7be7b2cebfa6e84e757ecfd783357/src/Model/ProcessingConfig.php#L327-L336
prooph/link-app-core
src/Model/ProcessingConfig.php
ProcessingConfig.setConfig
private function setConfig(array $config) { if (! array_key_exists('processing', $config)) throw new \InvalidArgumentException('Missing the root key processing in configuration'); if (! array_key_exists('node_name', $config['processing'])) throw new \InvalidArgumentException('Missing key node_name in processing config'); if (! array_key_exists('plugins', $config['processing'])) throw new \InvalidArgumentException('Missing key plugins in processing config'); if (! is_array($config['processing']['plugins'])) throw new \InvalidArgumentException('Plugins must be an array in processing config'); if (! array_key_exists('connectors', $config['processing'])) throw new \InvalidArgumentException('Missing key connectors in processing config'); if (! is_array($config['processing']['connectors'])) throw new \InvalidArgumentException('Connectors must be an array in processing config'); if (! array_key_exists('channels', $config['processing'])) throw new \InvalidArgumentException('Missing key channels in processing config'); if (! is_array($config['processing']['channels'])) throw new \InvalidArgumentException('Channels must be an array in processing config'); if (! isset($config['processing']['channels']['local'])) throw new \InvalidArgumentException('Missing local channel config in processing.channels'); if (! array_key_exists('processes', $config['processing'])) throw new \InvalidArgumentException('Missing key processes in processing config'); if (! is_array($config['processing']['processes'])) throw new \InvalidArgumentException('Processes must be an array in processing config'); if (! array_key_exists('js_ticker', $config['processing'])) throw new \InvalidArgumentException('Missing key js_ticker in processing config'); if (! is_array($config['processing']['js_ticker'])) throw new \InvalidArgumentException('js_ticker must be an array in processing config'); $this->assertChannelConfig($config['processing']['channels']['local'], 'local'); $projection = new \Prooph\Link\Application\Projection\ProcessingConfig($config, $this->configLocation, true); foreach ($config['processing']['processes'] as $startMessage => $processConfig) { $this->assertMessageName($startMessage, $projection->getAllAvailableProcessingTypes()); $this->assertProcessConfig($startMessage, $processConfig); } foreach ($config['processing']['connectors'] as $connectorId => $connectorConfig) { if (! is_array($connectorConfig)) throw new \InvalidArgumentException(sprintf('Connector config for connector %s must be an array', $connectorId)); $this->assertConnectorConfig($connectorId, $connectorConfig, $projection, false); } $this->assertJsTickerConfig($config['processing']['js_ticker']); $this->config = $config; }
php
private function setConfig(array $config) { if (! array_key_exists('processing', $config)) throw new \InvalidArgumentException('Missing the root key processing in configuration'); if (! array_key_exists('node_name', $config['processing'])) throw new \InvalidArgumentException('Missing key node_name in processing config'); if (! array_key_exists('plugins', $config['processing'])) throw new \InvalidArgumentException('Missing key plugins in processing config'); if (! is_array($config['processing']['plugins'])) throw new \InvalidArgumentException('Plugins must be an array in processing config'); if (! array_key_exists('connectors', $config['processing'])) throw new \InvalidArgumentException('Missing key connectors in processing config'); if (! is_array($config['processing']['connectors'])) throw new \InvalidArgumentException('Connectors must be an array in processing config'); if (! array_key_exists('channels', $config['processing'])) throw new \InvalidArgumentException('Missing key channels in processing config'); if (! is_array($config['processing']['channels'])) throw new \InvalidArgumentException('Channels must be an array in processing config'); if (! isset($config['processing']['channels']['local'])) throw new \InvalidArgumentException('Missing local channel config in processing.channels'); if (! array_key_exists('processes', $config['processing'])) throw new \InvalidArgumentException('Missing key processes in processing config'); if (! is_array($config['processing']['processes'])) throw new \InvalidArgumentException('Processes must be an array in processing config'); if (! array_key_exists('js_ticker', $config['processing'])) throw new \InvalidArgumentException('Missing key js_ticker in processing config'); if (! is_array($config['processing']['js_ticker'])) throw new \InvalidArgumentException('js_ticker must be an array in processing config'); $this->assertChannelConfig($config['processing']['channels']['local'], 'local'); $projection = new \Prooph\Link\Application\Projection\ProcessingConfig($config, $this->configLocation, true); foreach ($config['processing']['processes'] as $startMessage => $processConfig) { $this->assertMessageName($startMessage, $projection->getAllAvailableProcessingTypes()); $this->assertProcessConfig($startMessage, $processConfig); } foreach ($config['processing']['connectors'] as $connectorId => $connectorConfig) { if (! is_array($connectorConfig)) throw new \InvalidArgumentException(sprintf('Connector config for connector %s must be an array', $connectorId)); $this->assertConnectorConfig($connectorId, $connectorConfig, $projection, false); } $this->assertJsTickerConfig($config['processing']['js_ticker']); $this->config = $config; }
[ "private", "function", "setConfig", "(", "array", "$", "config", ")", "{", "if", "(", "!", "array_key_exists", "(", "'processing'", ",", "$", "config", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Missing the root key processing in configuration'", ")", ";", "if", "(", "!", "array_key_exists", "(", "'node_name'", ",", "$", "config", "[", "'processing'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Missing key node_name in processing config'", ")", ";", "if", "(", "!", "array_key_exists", "(", "'plugins'", ",", "$", "config", "[", "'processing'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Missing key plugins in processing config'", ")", ";", "if", "(", "!", "is_array", "(", "$", "config", "[", "'processing'", "]", "[", "'plugins'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Plugins must be an array in processing config'", ")", ";", "if", "(", "!", "array_key_exists", "(", "'connectors'", ",", "$", "config", "[", "'processing'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Missing key connectors in processing config'", ")", ";", "if", "(", "!", "is_array", "(", "$", "config", "[", "'processing'", "]", "[", "'connectors'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Connectors must be an array in processing config'", ")", ";", "if", "(", "!", "array_key_exists", "(", "'channels'", ",", "$", "config", "[", "'processing'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Missing key channels in processing config'", ")", ";", "if", "(", "!", "is_array", "(", "$", "config", "[", "'processing'", "]", "[", "'channels'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Channels must be an array in processing config'", ")", ";", "if", "(", "!", "isset", "(", "$", "config", "[", "'processing'", "]", "[", "'channels'", "]", "[", "'local'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Missing local channel config in processing.channels'", ")", ";", "if", "(", "!", "array_key_exists", "(", "'processes'", ",", "$", "config", "[", "'processing'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Missing key processes in processing config'", ")", ";", "if", "(", "!", "is_array", "(", "$", "config", "[", "'processing'", "]", "[", "'processes'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Processes must be an array in processing config'", ")", ";", "if", "(", "!", "array_key_exists", "(", "'js_ticker'", ",", "$", "config", "[", "'processing'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Missing key js_ticker in processing config'", ")", ";", "if", "(", "!", "is_array", "(", "$", "config", "[", "'processing'", "]", "[", "'js_ticker'", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'js_ticker must be an array in processing config'", ")", ";", "$", "this", "->", "assertChannelConfig", "(", "$", "config", "[", "'processing'", "]", "[", "'channels'", "]", "[", "'local'", "]", ",", "'local'", ")", ";", "$", "projection", "=", "new", "\\", "Prooph", "\\", "Link", "\\", "Application", "\\", "Projection", "\\", "ProcessingConfig", "(", "$", "config", ",", "$", "this", "->", "configLocation", ",", "true", ")", ";", "foreach", "(", "$", "config", "[", "'processing'", "]", "[", "'processes'", "]", "as", "$", "startMessage", "=>", "$", "processConfig", ")", "{", "$", "this", "->", "assertMessageName", "(", "$", "startMessage", ",", "$", "projection", "->", "getAllAvailableProcessingTypes", "(", ")", ")", ";", "$", "this", "->", "assertProcessConfig", "(", "$", "startMessage", ",", "$", "processConfig", ")", ";", "}", "foreach", "(", "$", "config", "[", "'processing'", "]", "[", "'connectors'", "]", "as", "$", "connectorId", "=>", "$", "connectorConfig", ")", "{", "if", "(", "!", "is_array", "(", "$", "connectorConfig", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Connector config for connector %s must be an array'", ",", "$", "connectorId", ")", ")", ";", "$", "this", "->", "assertConnectorConfig", "(", "$", "connectorId", ",", "$", "connectorConfig", ",", "$", "projection", ",", "false", ")", ";", "}", "$", "this", "->", "assertJsTickerConfig", "(", "$", "config", "[", "'processing'", "]", "[", "'js_ticker'", "]", ")", ";", "$", "this", "->", "config", "=", "$", "config", ";", "}" ]
Assert and set config @param array $config @throws \InvalidArgumentException
[ "Assert", "and", "set", "config" ]
train
https://github.com/prooph/link-app-core/blob/835a5945dfa7be7b2cebfa6e84e757ecfd783357/src/Model/ProcessingConfig.php#L382-L416
prooph/link-app-core
src/Model/ProcessingConfig.php
ProcessingConfig.writeConfig
private function writeConfig(ConfigWriter $configWriter) { $configWriter->replaceConfigInDirectory( $this->toArray(), $this->configLocation->toString() . DIRECTORY_SEPARATOR . self::$configFileName ); }
php
private function writeConfig(ConfigWriter $configWriter) { $configWriter->replaceConfigInDirectory( $this->toArray(), $this->configLocation->toString() . DIRECTORY_SEPARATOR . self::$configFileName ); }
[ "private", "function", "writeConfig", "(", "ConfigWriter", "$", "configWriter", ")", "{", "$", "configWriter", "->", "replaceConfigInDirectory", "(", "$", "this", "->", "toArray", "(", ")", ",", "$", "this", "->", "configLocation", "->", "toString", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "self", "::", "$", "configFileName", ")", ";", "}" ]
Write config to file with the help of a config writer @param ConfigWriter $configWriter
[ "Write", "config", "to", "file", "with", "the", "help", "of", "a", "config", "writer" ]
train
https://github.com/prooph/link-app-core/blob/835a5945dfa7be7b2cebfa6e84e757ecfd783357/src/Model/ProcessingConfig.php#L585-L591
huasituo/hstcms
src/Libraries/Fields/File.php
File.output_data
public function output_data($data, $field = []) { if(!isset($data[$field['fieldname']])) { return $data; } $value = $data[$field['fieldname']]; $data['_'.$field['fieldname']] = $value; $data[$field['fieldname']] = AttachmentModel::getAttach($value); $data[$field['fieldname'].'_imgurl'] = $data[$field['fieldname']]['url']; return $data; }
php
public function output_data($data, $field = []) { if(!isset($data[$field['fieldname']])) { return $data; } $value = $data[$field['fieldname']]; $data['_'.$field['fieldname']] = $value; $data[$field['fieldname']] = AttachmentModel::getAttach($value); $data[$field['fieldname'].'_imgurl'] = $data[$field['fieldname']]['url']; return $data; }
[ "public", "function", "output_data", "(", "$", "data", ",", "$", "field", "=", "[", "]", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "$", "field", "[", "'fieldname'", "]", "]", ")", ")", "{", "return", "$", "data", ";", "}", "$", "value", "=", "$", "data", "[", "$", "field", "[", "'fieldname'", "]", "]", ";", "$", "data", "[", "'_'", ".", "$", "field", "[", "'fieldname'", "]", "]", "=", "$", "value", ";", "$", "data", "[", "$", "field", "[", "'fieldname'", "]", "]", "=", "AttachmentModel", "::", "getAttach", "(", "$", "value", ")", ";", "$", "data", "[", "$", "field", "[", "'fieldname'", "]", ".", "'_imgurl'", "]", "=", "$", "data", "[", "$", "field", "[", "'fieldname'", "]", "]", "[", "'url'", "]", ";", "return", "$", "data", ";", "}" ]
字段输出
[ "字段输出" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/Fields/File.php#L163-L173
sanpii/assetic
src/Assetic/Filter/UglifyCssFilter.php
UglifyCssFilter.filterDump
public function filterDump(AssetInterface $asset) { $commandline =$this->nodeBin ? array($this->nodeBin, $this->uglifycssBin) : array($this->uglifycssBin); if ($this->expandVars) { array_push($commandline, '--expand-vars'); } if ($this->uglyComments) { array_push($commandline, '--ugly-comments'); } if ($this->cuteComments) { array_push($commandline, '--cute-comments'); } // input and output files $input = FilesystemUtils::createTemporaryFile('uglifycss'); file_put_contents($input, $asset->getContent()); array_push($commandline, $input); $proc = new Process(implode(' ', $commandline)); $code = $proc->run(); unlink($input); if (127 === $code) { throw new \RuntimeException('Path to node executable could not be resolved.'); } if (0 !== $code) { throw FilterException::fromProcess($proc)->setInput($asset->getContent()); } $asset->setContent($proc->getOutput()); }
php
public function filterDump(AssetInterface $asset) { $commandline =$this->nodeBin ? array($this->nodeBin, $this->uglifycssBin) : array($this->uglifycssBin); if ($this->expandVars) { array_push($commandline, '--expand-vars'); } if ($this->uglyComments) { array_push($commandline, '--ugly-comments'); } if ($this->cuteComments) { array_push($commandline, '--cute-comments'); } // input and output files $input = FilesystemUtils::createTemporaryFile('uglifycss'); file_put_contents($input, $asset->getContent()); array_push($commandline, $input); $proc = new Process(implode(' ', $commandline)); $code = $proc->run(); unlink($input); if (127 === $code) { throw new \RuntimeException('Path to node executable could not be resolved.'); } if (0 !== $code) { throw FilterException::fromProcess($proc)->setInput($asset->getContent()); } $asset->setContent($proc->getOutput()); }
[ "public", "function", "filterDump", "(", "AssetInterface", "$", "asset", ")", "{", "$", "commandline", "=", "$", "this", "->", "nodeBin", "?", "array", "(", "$", "this", "->", "nodeBin", ",", "$", "this", "->", "uglifycssBin", ")", ":", "array", "(", "$", "this", "->", "uglifycssBin", ")", ";", "if", "(", "$", "this", "->", "expandVars", ")", "{", "array_push", "(", "$", "commandline", ",", "'--expand-vars'", ")", ";", "}", "if", "(", "$", "this", "->", "uglyComments", ")", "{", "array_push", "(", "$", "commandline", ",", "'--ugly-comments'", ")", ";", "}", "if", "(", "$", "this", "->", "cuteComments", ")", "{", "array_push", "(", "$", "commandline", ",", "'--cute-comments'", ")", ";", "}", "// input and output files", "$", "input", "=", "FilesystemUtils", "::", "createTemporaryFile", "(", "'uglifycss'", ")", ";", "file_put_contents", "(", "$", "input", ",", "$", "asset", "->", "getContent", "(", ")", ")", ";", "array_push", "(", "$", "commandline", ",", "$", "input", ")", ";", "$", "proc", "=", "new", "Process", "(", "implode", "(", "' '", ",", "$", "commandline", ")", ")", ";", "$", "code", "=", "$", "proc", "->", "run", "(", ")", ";", "unlink", "(", "$", "input", ")", ";", "if", "(", "127", "===", "$", "code", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Path to node executable could not be resolved.'", ")", ";", "}", "if", "(", "0", "!==", "$", "code", ")", "{", "throw", "FilterException", "::", "fromProcess", "(", "$", "proc", ")", "->", "setInput", "(", "$", "asset", "->", "getContent", "(", ")", ")", ";", "}", "$", "asset", "->", "setContent", "(", "$", "proc", "->", "getOutput", "(", ")", ")", ";", "}" ]
Run the asset through UglifyJs @see \Assetic\Filter\FilterInterface::filterDump()
[ "Run", "the", "asset", "through", "UglifyJs" ]
train
https://github.com/sanpii/assetic/blob/5c446eee54cc396cbbd6e252108f430e6e617c95/src/Assetic/Filter/UglifyCssFilter.php#L83-L120
syhol/mrcolor
src/SyHolloway/MrColor/Format/Hsl.php
Hsl.toHex
public function toHex() { $H = $this->values['hue'] / 360; $S = $this->values['saturation']; $L = $this->values['lightness']; if ($S == 0) { $r = $L * 255; $g = $L * 255; $b = $L * 255; } else { $var_2 = ($L < 0.5) ? $L * (1 + $S) : ($L + $S) - ($S * $L); $var_1 = 2 * $L - $var_2; $r = round(255 * $this->hueToRgb($var_1, $var_2, $H + (1 / 3))); $g = round(255 * $this->hueToRgb($var_1, $var_2, $H)); $b = round(255 * $this->hueToRgb($var_1, $var_2, $H - (1 / 3))); } $hex = array( dechex($r), dechex($g), dechex($b) ); //Make sure the hex is 6 digit foreach ($hex as $key => $value) { $hex[$key] = strlen($value) === 1 ? '0' . $value : $value ; } return implode('', $hex); }
php
public function toHex() { $H = $this->values['hue'] / 360; $S = $this->values['saturation']; $L = $this->values['lightness']; if ($S == 0) { $r = $L * 255; $g = $L * 255; $b = $L * 255; } else { $var_2 = ($L < 0.5) ? $L * (1 + $S) : ($L + $S) - ($S * $L); $var_1 = 2 * $L - $var_2; $r = round(255 * $this->hueToRgb($var_1, $var_2, $H + (1 / 3))); $g = round(255 * $this->hueToRgb($var_1, $var_2, $H)); $b = round(255 * $this->hueToRgb($var_1, $var_2, $H - (1 / 3))); } $hex = array( dechex($r), dechex($g), dechex($b) ); //Make sure the hex is 6 digit foreach ($hex as $key => $value) { $hex[$key] = strlen($value) === 1 ? '0' . $value : $value ; } return implode('', $hex); }
[ "public", "function", "toHex", "(", ")", "{", "$", "H", "=", "$", "this", "->", "values", "[", "'hue'", "]", "/", "360", ";", "$", "S", "=", "$", "this", "->", "values", "[", "'saturation'", "]", ";", "$", "L", "=", "$", "this", "->", "values", "[", "'lightness'", "]", ";", "if", "(", "$", "S", "==", "0", ")", "{", "$", "r", "=", "$", "L", "*", "255", ";", "$", "g", "=", "$", "L", "*", "255", ";", "$", "b", "=", "$", "L", "*", "255", ";", "}", "else", "{", "$", "var_2", "=", "(", "$", "L", "<", "0.5", ")", "?", "$", "L", "*", "(", "1", "+", "$", "S", ")", ":", "(", "$", "L", "+", "$", "S", ")", "-", "(", "$", "S", "*", "$", "L", ")", ";", "$", "var_1", "=", "2", "*", "$", "L", "-", "$", "var_2", ";", "$", "r", "=", "round", "(", "255", "*", "$", "this", "->", "hueToRgb", "(", "$", "var_1", ",", "$", "var_2", ",", "$", "H", "+", "(", "1", "/", "3", ")", ")", ")", ";", "$", "g", "=", "round", "(", "255", "*", "$", "this", "->", "hueToRgb", "(", "$", "var_1", ",", "$", "var_2", ",", "$", "H", ")", ")", ";", "$", "b", "=", "round", "(", "255", "*", "$", "this", "->", "hueToRgb", "(", "$", "var_1", ",", "$", "var_2", ",", "$", "H", "-", "(", "1", "/", "3", ")", ")", ")", ";", "}", "$", "hex", "=", "array", "(", "dechex", "(", "$", "r", ")", ",", "dechex", "(", "$", "g", ")", ",", "dechex", "(", "$", "b", ")", ")", ";", "//Make sure the hex is 6 digit", "foreach", "(", "$", "hex", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "hex", "[", "$", "key", "]", "=", "strlen", "(", "$", "value", ")", "===", "1", "?", "'0'", ".", "$", "value", ":", "$", "value", ";", "}", "return", "implode", "(", "''", ",", "$", "hex", ")", ";", "}" ]
Return the corresponding hex color value for the value in this format @return string (6 characters, hex color value, no hash)
[ "Return", "the", "corresponding", "hex", "color", "value", "for", "the", "value", "in", "this", "format" ]
train
https://github.com/syhol/mrcolor/blob/b0cfef8fa3dc52940ff6cb78d19a4fac9e02ef4d/src/SyHolloway/MrColor/Format/Hsl.php#L31-L63
syhol/mrcolor
src/SyHolloway/MrColor/Format/Hsl.php
Hsl.fromHex
public function fromHex($hex) { $R = hexdec($hex[0] . $hex[1]); $G = hexdec($hex[2] . $hex[3]); $B = hexdec($hex[4] . $hex[5]); $HSL = array(); $var_R = ($R / 255); $var_G = ($G / 255); $var_B = ($B / 255); $var_Min = min($var_R, $var_G, $var_B); $var_Max = max($var_R, $var_G, $var_B); $del_Max = $var_Max - $var_Min; $L = ($var_Max + $var_Min) / 2; if ($del_Max == 0) { $H = 0; $S = 0; } else { if ($L < 0.5) { $S = $del_Max / ($var_Max + $var_Min ); } else { $S = $del_Max / (2 - $var_Max - $var_Min ); } $del_R = ((($var_Max - $var_R ) / 6) + ($del_Max / 2)) / $del_Max; $del_G = ((($var_Max - $var_G ) / 6) + ($del_Max / 2)) / $del_Max; $del_B = ((($var_Max - $var_B ) / 6) + ($del_Max / 2)) / $del_Max; if ($var_R == $var_Max) { $H = $del_B - $del_G; } elseif ($var_G == $var_Max) { $H = (1 / 3) + $del_R - $del_B; } else if ($var_B == $var_Max) { $H = (2 / 3) + $del_G - $del_R; } if ($H < 0) { $H++; } if ($H > 1) { $H--; } } $this->values = array( 'hue' => ($H * 360), 'saturation' => floatval($S), 'lightness' => floatval($L) ); }
php
public function fromHex($hex) { $R = hexdec($hex[0] . $hex[1]); $G = hexdec($hex[2] . $hex[3]); $B = hexdec($hex[4] . $hex[5]); $HSL = array(); $var_R = ($R / 255); $var_G = ($G / 255); $var_B = ($B / 255); $var_Min = min($var_R, $var_G, $var_B); $var_Max = max($var_R, $var_G, $var_B); $del_Max = $var_Max - $var_Min; $L = ($var_Max + $var_Min) / 2; if ($del_Max == 0) { $H = 0; $S = 0; } else { if ($L < 0.5) { $S = $del_Max / ($var_Max + $var_Min ); } else { $S = $del_Max / (2 - $var_Max - $var_Min ); } $del_R = ((($var_Max - $var_R ) / 6) + ($del_Max / 2)) / $del_Max; $del_G = ((($var_Max - $var_G ) / 6) + ($del_Max / 2)) / $del_Max; $del_B = ((($var_Max - $var_B ) / 6) + ($del_Max / 2)) / $del_Max; if ($var_R == $var_Max) { $H = $del_B - $del_G; } elseif ($var_G == $var_Max) { $H = (1 / 3) + $del_R - $del_B; } else if ($var_B == $var_Max) { $H = (2 / 3) + $del_G - $del_R; } if ($H < 0) { $H++; } if ($H > 1) { $H--; } } $this->values = array( 'hue' => ($H * 360), 'saturation' => floatval($S), 'lightness' => floatval($L) ); }
[ "public", "function", "fromHex", "(", "$", "hex", ")", "{", "$", "R", "=", "hexdec", "(", "$", "hex", "[", "0", "]", ".", "$", "hex", "[", "1", "]", ")", ";", "$", "G", "=", "hexdec", "(", "$", "hex", "[", "2", "]", ".", "$", "hex", "[", "3", "]", ")", ";", "$", "B", "=", "hexdec", "(", "$", "hex", "[", "4", "]", ".", "$", "hex", "[", "5", "]", ")", ";", "$", "HSL", "=", "array", "(", ")", ";", "$", "var_R", "=", "(", "$", "R", "/", "255", ")", ";", "$", "var_G", "=", "(", "$", "G", "/", "255", ")", ";", "$", "var_B", "=", "(", "$", "B", "/", "255", ")", ";", "$", "var_Min", "=", "min", "(", "$", "var_R", ",", "$", "var_G", ",", "$", "var_B", ")", ";", "$", "var_Max", "=", "max", "(", "$", "var_R", ",", "$", "var_G", ",", "$", "var_B", ")", ";", "$", "del_Max", "=", "$", "var_Max", "-", "$", "var_Min", ";", "$", "L", "=", "(", "$", "var_Max", "+", "$", "var_Min", ")", "/", "2", ";", "if", "(", "$", "del_Max", "==", "0", ")", "{", "$", "H", "=", "0", ";", "$", "S", "=", "0", ";", "}", "else", "{", "if", "(", "$", "L", "<", "0.5", ")", "{", "$", "S", "=", "$", "del_Max", "/", "(", "$", "var_Max", "+", "$", "var_Min", ")", ";", "}", "else", "{", "$", "S", "=", "$", "del_Max", "/", "(", "2", "-", "$", "var_Max", "-", "$", "var_Min", ")", ";", "}", "$", "del_R", "=", "(", "(", "(", "$", "var_Max", "-", "$", "var_R", ")", "/", "6", ")", "+", "(", "$", "del_Max", "/", "2", ")", ")", "/", "$", "del_Max", ";", "$", "del_G", "=", "(", "(", "(", "$", "var_Max", "-", "$", "var_G", ")", "/", "6", ")", "+", "(", "$", "del_Max", "/", "2", ")", ")", "/", "$", "del_Max", ";", "$", "del_B", "=", "(", "(", "(", "$", "var_Max", "-", "$", "var_B", ")", "/", "6", ")", "+", "(", "$", "del_Max", "/", "2", ")", ")", "/", "$", "del_Max", ";", "if", "(", "$", "var_R", "==", "$", "var_Max", ")", "{", "$", "H", "=", "$", "del_B", "-", "$", "del_G", ";", "}", "elseif", "(", "$", "var_G", "==", "$", "var_Max", ")", "{", "$", "H", "=", "(", "1", "/", "3", ")", "+", "$", "del_R", "-", "$", "del_B", ";", "}", "else", "if", "(", "$", "var_B", "==", "$", "var_Max", ")", "{", "$", "H", "=", "(", "2", "/", "3", ")", "+", "$", "del_G", "-", "$", "del_R", ";", "}", "if", "(", "$", "H", "<", "0", ")", "{", "$", "H", "++", ";", "}", "if", "(", "$", "H", ">", "1", ")", "{", "$", "H", "--", ";", "}", "}", "$", "this", "->", "values", "=", "array", "(", "'hue'", "=>", "(", "$", "H", "*", "360", ")", ",", "'saturation'", "=>", "floatval", "(", "$", "S", ")", ",", "'lightness'", "=>", "floatval", "(", "$", "L", ")", ")", ";", "}" ]
Load the given hex color value into this format @param string (6 characters, hex color value, no hash)
[ "Load", "the", "given", "hex", "color", "value", "into", "this", "format" ]
train
https://github.com/syhol/mrcolor/blob/b0cfef8fa3dc52940ff6cb78d19a4fac9e02ef4d/src/SyHolloway/MrColor/Format/Hsl.php#L70-L124
syhol/mrcolor
src/SyHolloway/MrColor/Format/Hsl.php
Hsl.hueToRgb
private function hueToRgb($v1, $v2, $vH) { if ($vH < 0) { $vH += 1; } if ($vH > 1) { $vH -= 1; } if ((6 * $vH) < 1) { return ($v1 + ($v2 - $v1) * 6 * $vH); } if ((2 * $vH) < 1) { return $v2; } if ((3 * $vH) < 2) { return ($v1 + ($v2-$v1) * ( (2/3)-$vH ) * 6); } return $v1; }
php
private function hueToRgb($v1, $v2, $vH) { if ($vH < 0) { $vH += 1; } if ($vH > 1) { $vH -= 1; } if ((6 * $vH) < 1) { return ($v1 + ($v2 - $v1) * 6 * $vH); } if ((2 * $vH) < 1) { return $v2; } if ((3 * $vH) < 2) { return ($v1 + ($v2-$v1) * ( (2/3)-$vH ) * 6); } return $v1; }
[ "private", "function", "hueToRgb", "(", "$", "v1", ",", "$", "v2", ",", "$", "vH", ")", "{", "if", "(", "$", "vH", "<", "0", ")", "{", "$", "vH", "+=", "1", ";", "}", "if", "(", "$", "vH", ">", "1", ")", "{", "$", "vH", "-=", "1", ";", "}", "if", "(", "(", "6", "*", "$", "vH", ")", "<", "1", ")", "{", "return", "(", "$", "v1", "+", "(", "$", "v2", "-", "$", "v1", ")", "*", "6", "*", "$", "vH", ")", ";", "}", "if", "(", "(", "2", "*", "$", "vH", ")", "<", "1", ")", "{", "return", "$", "v2", ";", "}", "if", "(", "(", "3", "*", "$", "vH", ")", "<", "2", ")", "{", "return", "(", "$", "v1", "+", "(", "$", "v2", "-", "$", "v1", ")", "*", "(", "(", "2", "/", "3", ")", "-", "$", "vH", ")", "*", "6", ")", ";", "}", "return", "$", "v1", ";", "}" ]
Given a Hue, returns corresponding RGB value @param float $v1 @param float $v2 @param float $vH @return float
[ "Given", "a", "Hue", "returns", "corresponding", "RGB", "value" ]
train
https://github.com/syhol/mrcolor/blob/b0cfef8fa3dc52940ff6cb78d19a4fac9e02ef4d/src/SyHolloway/MrColor/Format/Hsl.php#L134-L157
EcomDev/magento-psr6-bridge
src/Model/CacheItemPool.php
CacheItemPool.getItem
public function getItem($key) { $cacheEntry = $this->cacheFrontend->load( $this->prepareKey($key) ); if ($cacheEntry !== false) { $cacheEntry = unserialize($cacheEntry); return $this->cacheItemFactory->create(['key' => $key, 'isHit' => true, 'value' => $cacheEntry]); } return $this->cacheItemFactory->create(['key' => $key, 'isHit' => false]); }
php
public function getItem($key) { $cacheEntry = $this->cacheFrontend->load( $this->prepareKey($key) ); if ($cacheEntry !== false) { $cacheEntry = unserialize($cacheEntry); return $this->cacheItemFactory->create(['key' => $key, 'isHit' => true, 'value' => $cacheEntry]); } return $this->cacheItemFactory->create(['key' => $key, 'isHit' => false]); }
[ "public", "function", "getItem", "(", "$", "key", ")", "{", "$", "cacheEntry", "=", "$", "this", "->", "cacheFrontend", "->", "load", "(", "$", "this", "->", "prepareKey", "(", "$", "key", ")", ")", ";", "if", "(", "$", "cacheEntry", "!==", "false", ")", "{", "$", "cacheEntry", "=", "unserialize", "(", "$", "cacheEntry", ")", ";", "return", "$", "this", "->", "cacheItemFactory", "->", "create", "(", "[", "'key'", "=>", "$", "key", ",", "'isHit'", "=>", "true", ",", "'value'", "=>", "$", "cacheEntry", "]", ")", ";", "}", "return", "$", "this", "->", "cacheItemFactory", "->", "create", "(", "[", "'key'", "=>", "$", "key", ",", "'isHit'", "=>", "false", "]", ")", ";", "}" ]
Returns a Cache Item representing the specified key. This method must always return a CacheItemInterface object, even in case of a cache miss. It MUST NOT return null. @param string $key The key for which to return the corresponding Cache Item. @throws InvalidArgumentException If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException MUST be thrown. @return CacheItemInterface The corresponding Cache Item.
[ "Returns", "a", "Cache", "Item", "representing", "the", "specified", "key", "." ]
train
https://github.com/EcomDev/magento-psr6-bridge/blob/405c5b455f239fe8dc1b710df5fe9438f09d4715/src/Model/CacheItemPool.php#L113-L125
EcomDev/magento-psr6-bridge
src/Model/CacheItemPool.php
CacheItemPool.hasItem
public function hasItem($key) { if ($this->cacheFrontend->load($this->prepareKey($key)) !== false) { return true; } return false; }
php
public function hasItem($key) { if ($this->cacheFrontend->load($this->prepareKey($key)) !== false) { return true; } return false; }
[ "public", "function", "hasItem", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "cacheFrontend", "->", "load", "(", "$", "this", "->", "prepareKey", "(", "$", "key", ")", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Confirms if the cache contains specified cache item. Note: This method MAY avoid retrieving the cached value for performance reasons. This could result in a race condition with CacheItemInterface::get(). To avoid such situation use CacheItemInterface::isHit() instead. @param string $key The key for which to check existence. @throws InvalidArgumentException If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException MUST be thrown. @return bool True if item exists in the cache, false otherwise.
[ "Confirms", "if", "the", "cache", "contains", "specified", "cache", "item", "." ]
train
https://github.com/EcomDev/magento-psr6-bridge/blob/405c5b455f239fe8dc1b710df5fe9438f09d4715/src/Model/CacheItemPool.php#L171-L178
EcomDev/magento-psr6-bridge
src/Model/CacheItemPool.php
CacheItemPool.clear
public function clear() { if (empty($this->tags)) { return false; } return $this->cacheFrontend->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, $this->tags); }
php
public function clear() { if (empty($this->tags)) { return false; } return $this->cacheFrontend->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, $this->tags); }
[ "public", "function", "clear", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "tags", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "cacheFrontend", "->", "clean", "(", "\\", "Zend_Cache", "::", "CLEANING_MODE_MATCHING_TAG", ",", "$", "this", "->", "tags", ")", ";", "}" ]
Deletes all items in the pool. @return bool True if the pool was successfully cleared. False if there was an error.
[ "Deletes", "all", "items", "in", "the", "pool", "." ]
train
https://github.com/EcomDev/magento-psr6-bridge/blob/405c5b455f239fe8dc1b710df5fe9438f09d4715/src/Model/CacheItemPool.php#L186-L193
EcomDev/magento-psr6-bridge
src/Model/CacheItemPool.php
CacheItemPool.save
public function save(CacheItemInterface $item) { $expirationTime = null; if ($item instanceof ExtractableCacheLifetimeInterface) { $expirationTime = $item->getCacheLifetime(); } return $this->cacheFrontend->save( serialize(( $item instanceof ExtractableCacheValueInterface ? $item->getCacheValue() : $item->get() )), $this->prepareKey($item->getKey()), $this->tags, $expirationTime ); }
php
public function save(CacheItemInterface $item) { $expirationTime = null; if ($item instanceof ExtractableCacheLifetimeInterface) { $expirationTime = $item->getCacheLifetime(); } return $this->cacheFrontend->save( serialize(( $item instanceof ExtractableCacheValueInterface ? $item->getCacheValue() : $item->get() )), $this->prepareKey($item->getKey()), $this->tags, $expirationTime ); }
[ "public", "function", "save", "(", "CacheItemInterface", "$", "item", ")", "{", "$", "expirationTime", "=", "null", ";", "if", "(", "$", "item", "instanceof", "ExtractableCacheLifetimeInterface", ")", "{", "$", "expirationTime", "=", "$", "item", "->", "getCacheLifetime", "(", ")", ";", "}", "return", "$", "this", "->", "cacheFrontend", "->", "save", "(", "serialize", "(", "(", "$", "item", "instanceof", "ExtractableCacheValueInterface", "?", "$", "item", "->", "getCacheValue", "(", ")", ":", "$", "item", "->", "get", "(", ")", ")", ")", ",", "$", "this", "->", "prepareKey", "(", "$", "item", "->", "getKey", "(", ")", ")", ",", "$", "this", "->", "tags", ",", "$", "expirationTime", ")", ";", "}" ]
Persists a cache item immediately. @param CacheItemInterface $item The cache item to save. @return bool True if the item was successfully persisted. False if there was an error. @throws InvalidArgumentException
[ "Persists", "a", "cache", "item", "immediately", "." ]
train
https://github.com/EcomDev/magento-psr6-bridge/blob/405c5b455f239fe8dc1b710df5fe9438f09d4715/src/Model/CacheItemPool.php#L250-L268
EcomDev/magento-psr6-bridge
src/Model/CacheItemPool.php
CacheItemPool.commit
public function commit() { foreach ($this->defferedItems as $item) { $this->save($item); } $this->defferedItems = []; return true; }
php
public function commit() { foreach ($this->defferedItems as $item) { $this->save($item); } $this->defferedItems = []; return true; }
[ "public", "function", "commit", "(", ")", "{", "foreach", "(", "$", "this", "->", "defferedItems", "as", "$", "item", ")", "{", "$", "this", "->", "save", "(", "$", "item", ")", ";", "}", "$", "this", "->", "defferedItems", "=", "[", "]", ";", "return", "true", ";", "}" ]
Persists any deferred cache items. @return bool True if all not-yet-saved items were successfully saved or there were none. False otherwise.
[ "Persists", "any", "deferred", "cache", "items", "." ]
train
https://github.com/EcomDev/magento-psr6-bridge/blob/405c5b455f239fe8dc1b710df5fe9438f09d4715/src/Model/CacheItemPool.php#L291-L299
EcomDev/magento-psr6-bridge
src/Model/CacheItemPool.php
CacheItemPool.prepareKey
private function prepareKey($key) { if (!preg_match('/^[a-zA-Z0-9_-]+$/', $key)) { throw new InvalidArgumentException($key); } return $this->keyPrefix . strtr($key, '-', '_'); }
php
private function prepareKey($key) { if (!preg_match('/^[a-zA-Z0-9_-]+$/', $key)) { throw new InvalidArgumentException($key); } return $this->keyPrefix . strtr($key, '-', '_'); }
[ "private", "function", "prepareKey", "(", "$", "key", ")", "{", "if", "(", "!", "preg_match", "(", "'/^[a-zA-Z0-9_-]+$/'", ",", "$", "key", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "$", "key", ")", ";", "}", "return", "$", "this", "->", "keyPrefix", ".", "strtr", "(", "$", "key", ",", "'-'", ",", "'_'", ")", ";", "}" ]
Prepares a key for cache storage @param string $key @return string @throws InvalidArgumentException
[ "Prepares", "a", "key", "for", "cache", "storage" ]
train
https://github.com/EcomDev/magento-psr6-bridge/blob/405c5b455f239fe8dc1b710df5fe9438f09d4715/src/Model/CacheItemPool.php#L310-L317
movoin/one-swoole
src/FileSystem/Manager.php
Manager.getFileSystem
public function getFileSystem(string $prefix): FileSystem { if (! isset($this->fs[$prefix])) { throw new InvalidArgumentException( sprintf('The filesystem was not found: "%s"', $prefix) ); } return $this->fs[$prefix]; }
php
public function getFileSystem(string $prefix): FileSystem { if (! isset($this->fs[$prefix])) { throw new InvalidArgumentException( sprintf('The filesystem was not found: "%s"', $prefix) ); } return $this->fs[$prefix]; }
[ "public", "function", "getFileSystem", "(", "string", "$", "prefix", ")", ":", "FileSystem", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "fs", "[", "$", "prefix", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'The filesystem was not found: \"%s\"'", ",", "$", "prefix", ")", ")", ";", "}", "return", "$", "this", "->", "fs", "[", "$", "prefix", "]", ";", "}" ]
获得指定文件系统实例 @param string $prefix @return \One\FileSystem\FileSystem @throws \InvalidArgumentException
[ "获得指定文件系统实例" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Manager.php#L48-L57
movoin/one-swoole
src/FileSystem/Manager.php
Manager.mountFileSystems
public function mountFileSystems(array $fileSystems = []): self { foreach ($fileSystems as $prefix => $fileSystem) { $this->mountFileSystem($prefix, $fileSystem); } return $this; }
php
public function mountFileSystems(array $fileSystems = []): self { foreach ($fileSystems as $prefix => $fileSystem) { $this->mountFileSystem($prefix, $fileSystem); } return $this; }
[ "public", "function", "mountFileSystems", "(", "array", "$", "fileSystems", "=", "[", "]", ")", ":", "self", "{", "foreach", "(", "$", "fileSystems", "as", "$", "prefix", "=>", "$", "fileSystem", ")", "{", "$", "this", "->", "mountFileSystem", "(", "$", "prefix", ",", "$", "fileSystem", ")", ";", "}", "return", "$", "this", ";", "}" ]
批量挂载文件系统 @param array $fileSystems @return self
[ "批量挂载文件系统" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Manager.php#L66-L73
movoin/one-swoole
src/FileSystem/Manager.php
Manager.mountFileSystem
public function mountFileSystem(string $prefix, FileSystem $fileSystem): self { if (! Assert::stringNotEmpty($prefix)) { throw new InvalidArgumentException( sprintf('"%s" parameter 1 must be string', __METHOD__) ); } $this->fs[$prefix] = $fileSystem; return $this; }
php
public function mountFileSystem(string $prefix, FileSystem $fileSystem): self { if (! Assert::stringNotEmpty($prefix)) { throw new InvalidArgumentException( sprintf('"%s" parameter 1 must be string', __METHOD__) ); } $this->fs[$prefix] = $fileSystem; return $this; }
[ "public", "function", "mountFileSystem", "(", "string", "$", "prefix", ",", "FileSystem", "$", "fileSystem", ")", ":", "self", "{", "if", "(", "!", "Assert", "::", "stringNotEmpty", "(", "$", "prefix", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'\"%s\" parameter 1 must be string'", ",", "__METHOD__", ")", ")", ";", "}", "$", "this", "->", "fs", "[", "$", "prefix", "]", "=", "$", "fileSystem", ";", "return", "$", "this", ";", "}" ]
挂载文件系统 @param string $prefix @param One\FileSystem\FileSystem $fileSystem @return self @throws \InvalidArgumentException
[ "挂载文件系统" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Manager.php#L84-L95
movoin/one-swoole
src/FileSystem/Manager.php
Manager.listContents
public function listContents(string $directory = '', bool $recursive = false): array { list($prefix, $directory) = $this->getPrefixAndPath($directory); $fs = $this->getFileSystem($prefix); $list = $fs->listContents($directory, $recursive); foreach ($list as &$file) { $file['filesystem'] = $prefix; } unset($prefix, $directory, $fs); return $list; }
php
public function listContents(string $directory = '', bool $recursive = false): array { list($prefix, $directory) = $this->getPrefixAndPath($directory); $fs = $this->getFileSystem($prefix); $list = $fs->listContents($directory, $recursive); foreach ($list as &$file) { $file['filesystem'] = $prefix; } unset($prefix, $directory, $fs); return $list; }
[ "public", "function", "listContents", "(", "string", "$", "directory", "=", "''", ",", "bool", "$", "recursive", "=", "false", ")", ":", "array", "{", "list", "(", "$", "prefix", ",", "$", "directory", ")", "=", "$", "this", "->", "getPrefixAndPath", "(", "$", "directory", ")", ";", "$", "fs", "=", "$", "this", "->", "getFileSystem", "(", "$", "prefix", ")", ";", "$", "list", "=", "$", "fs", "->", "listContents", "(", "$", "directory", ",", "$", "recursive", ")", ";", "foreach", "(", "$", "list", "as", "&", "$", "file", ")", "{", "$", "file", "[", "'filesystem'", "]", "=", "$", "prefix", ";", "}", "unset", "(", "$", "prefix", ",", "$", "directory", ",", "$", "fs", ")", ";", "return", "$", "list", ";", "}" ]
返回目录内容 @param string $directory @param bool $recursive @return array
[ "返回目录内容" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Manager.php#L105-L119