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
technote-space/wordpress-plugin-base
src/traits/hook.php
Hook.load_cache_settings
private function load_cache_settings() { if ( $this->app->isset_shared_object( 'is_valid_hook_cache' ) ) { return; } $this->app->set_shared_object( 'is_valid_hook_cache', ! empty( $this->app->get_config( 'config', 'cache_filter_result' ) ) ); $prevent_cache = $this->app->get_config( 'config', 'cache_filter_exclude_list', [] ); $prevent_cache = empty( $prevent_cache ) ? [] : array_combine( $prevent_cache, array_fill( 0, count( $prevent_cache ), true ) ); $this->app->set_shared_object( 'prevent_hook_cache', $prevent_cache ); $this->app->set_shared_object( 'hook_cache', [] ); }
php
private function load_cache_settings() { if ( $this->app->isset_shared_object( 'is_valid_hook_cache' ) ) { return; } $this->app->set_shared_object( 'is_valid_hook_cache', ! empty( $this->app->get_config( 'config', 'cache_filter_result' ) ) ); $prevent_cache = $this->app->get_config( 'config', 'cache_filter_exclude_list', [] ); $prevent_cache = empty( $prevent_cache ) ? [] : array_combine( $prevent_cache, array_fill( 0, count( $prevent_cache ), true ) ); $this->app->set_shared_object( 'prevent_hook_cache', $prevent_cache ); $this->app->set_shared_object( 'hook_cache', [] ); }
[ "private", "function", "load_cache_settings", "(", ")", "{", "if", "(", "$", "this", "->", "app", "->", "isset_shared_object", "(", "'is_valid_hook_cache'", ")", ")", "{", "return", ";", "}", "$", "this", "->", "app", "->", "set_shared_object", "(", "'is_val...
load cache settings
[ "load", "cache", "settings" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/hook.php#L30-L43
technote-space/wordpress-plugin-base
src/traits/hook.php
Hook.get_hook_cache
private function get_hook_cache( $key ) { $this->load_cache_settings(); $prevent_cache = $this->app->get_shared_object( 'prevent_hook_cache' ); $is_valid_cache = ! isset( $prevent_cache[ $key ] ) && $this->app->get_shared_object( 'is_valid_hook_cache' ); if ( ! $is_valid_cache ) { return [ false, null, $is_valid_cache ]; } $cache = $this->app->get_shared_object( 'hook_cache' ); if ( ! is_array( $cache ) || ! array_key_exists( $key, $cache ) ) { return [ false, null, $is_valid_cache ]; } return [ true, $cache[ $key ], $is_valid_cache ]; }
php
private function get_hook_cache( $key ) { $this->load_cache_settings(); $prevent_cache = $this->app->get_shared_object( 'prevent_hook_cache' ); $is_valid_cache = ! isset( $prevent_cache[ $key ] ) && $this->app->get_shared_object( 'is_valid_hook_cache' ); if ( ! $is_valid_cache ) { return [ false, null, $is_valid_cache ]; } $cache = $this->app->get_shared_object( 'hook_cache' ); if ( ! is_array( $cache ) || ! array_key_exists( $key, $cache ) ) { return [ false, null, $is_valid_cache ]; } return [ true, $cache[ $key ], $is_valid_cache ]; }
[ "private", "function", "get_hook_cache", "(", "$", "key", ")", "{", "$", "this", "->", "load_cache_settings", "(", ")", ";", "$", "prevent_cache", "=", "$", "this", "->", "app", "->", "get_shared_object", "(", "'prevent_hook_cache'", ")", ";", "$", "is_valid...
@param string $key @return array
[ "@param", "string", "$key" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/hook.php#L78-L92
technote-space/wordpress-plugin-base
src/traits/hook.php
Hook.get_bool_value
protected function get_bool_value( /** @noinspection PhpUnusedParameterInspection */ $value, $default, $setting ) { if ( is_bool( $value ) ) { return $value; } if ( 'true' === $value ) { return true; } if ( 'false' === $value ) { return false; } if ( isset( $value ) && (string) $value !== '' ) { return ! empty( $value ); } return ! empty( $default ); }
php
protected function get_bool_value( /** @noinspection PhpUnusedParameterInspection */ $value, $default, $setting ) { if ( is_bool( $value ) ) { return $value; } if ( 'true' === $value ) { return true; } if ( 'false' === $value ) { return false; } if ( isset( $value ) && (string) $value !== '' ) { return ! empty( $value ); } return ! empty( $default ); }
[ "protected", "function", "get_bool_value", "(", "/** @noinspection PhpUnusedParameterInspection */", "$", "value", ",", "$", "default", ",", "$", "setting", ")", "{", "if", "(", "is_bool", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "...
@param mixed $value @param mixed $default @param array $setting @return bool
[ "@param", "mixed", "$value", "@param", "mixed", "$default", "@param", "array", "$setting" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/hook.php#L152-L170
technote-space/wordpress-plugin-base
src/traits/hook.php
Hook.get_int_value
protected function get_int_value( $value, $default, $setting ) { $default = (int) $default; if ( is_numeric( $value ) ) { $value = (int) $value; if ( $value !== $default ) { if ( isset( $setting['min'] ) && $value < (int) $setting['min'] ) { $value = (int) $setting['min']; } if ( isset( $setting['max'] ) && $value > (int) $setting['max'] ) { $value = (int) $setting['max']; } } elseif ( isset( $setting['option'] ) ) { $default = isset( $setting['option_default'] ) ? (int) $setting['option_default'] : $default; $value = (int) $this->app->get_option( $setting['option'], $default ); } } else { $value = $default; } return $value; }
php
protected function get_int_value( $value, $default, $setting ) { $default = (int) $default; if ( is_numeric( $value ) ) { $value = (int) $value; if ( $value !== $default ) { if ( isset( $setting['min'] ) && $value < (int) $setting['min'] ) { $value = (int) $setting['min']; } if ( isset( $setting['max'] ) && $value > (int) $setting['max'] ) { $value = (int) $setting['max']; } } elseif ( isset( $setting['option'] ) ) { $default = isset( $setting['option_default'] ) ? (int) $setting['option_default'] : $default; $value = (int) $this->app->get_option( $setting['option'], $default ); } } else { $value = $default; } return $value; }
[ "protected", "function", "get_int_value", "(", "$", "value", ",", "$", "default", ",", "$", "setting", ")", "{", "$", "default", "=", "(", "int", ")", "$", "default", ";", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "{", "$", "value", "="...
@param mixed $value @param mixed $default @param array $setting @return int
[ "@param", "mixed", "$value", "@param", "mixed", "$default", "@param", "array", "$setting" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/hook.php#L179-L199
technote-space/wordpress-plugin-base
src/traits/hook.php
Hook.get_float_value
protected function get_float_value( $value, $default, $setting ) { $default = (float) $default; if ( is_numeric( $value ) ) { $value = (float) $value; if ( $value !== $default ) { if ( isset( $setting['min'] ) && $value < (float) $setting['min'] ) { $value = (float) $setting['min']; } if ( isset( $setting['max'] ) && $value > (float) $setting['max'] ) { $value = (float) $setting['max']; } } elseif ( isset( $setting['option'] ) ) { $default = isset( $setting['option_default'] ) ? (float) $setting['option_default'] : $default; $value = (float) $this->app->get_option( $setting['option'], $default ); } } else { $value = $default; } return $value; }
php
protected function get_float_value( $value, $default, $setting ) { $default = (float) $default; if ( is_numeric( $value ) ) { $value = (float) $value; if ( $value !== $default ) { if ( isset( $setting['min'] ) && $value < (float) $setting['min'] ) { $value = (float) $setting['min']; } if ( isset( $setting['max'] ) && $value > (float) $setting['max'] ) { $value = (float) $setting['max']; } } elseif ( isset( $setting['option'] ) ) { $default = isset( $setting['option_default'] ) ? (float) $setting['option_default'] : $default; $value = (float) $this->app->get_option( $setting['option'], $default ); } } else { $value = $default; } return $value; }
[ "protected", "function", "get_float_value", "(", "$", "value", ",", "$", "default", ",", "$", "setting", ")", "{", "$", "default", "=", "(", "float", ")", "$", "default", ";", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "{", "$", "value", ...
@param mixed $value @param mixed $default @param array $setting @return float
[ "@param", "mixed", "$value", "@param", "mixed", "$default", "@param", "array", "$setting" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/hook.php#L208-L228
mslib/resource-proxy
Msl/ResourceProxy/Source/SourceFactory.php
SourceFactory.getSourceInstance
public function getSourceInstance($type, $name, array $parameters, array $globalParameters = array()) { // The source object variable $sourceObj = null; // Getting SourceConfig object for an Imap Source object $sourceConfig = $this->getSourceConfig($name, $type, $parameters, $globalParameters); // Creating a Source object with the given source config object if ($sourceConfig instanceof SourceConfig ) { // Creating a Source object instance according to the given type switch ($type) { case SourceConfig::SOURCE_TYPE_IMAP: // Initializing an Imap Source object $sourceObj = new Imap(); break; case SourceConfig::SOURCE_TYPE_POP: // Initializing a Pop Source object $sourceObj = new Pop(); break; default: throw new Exception\BadSourceConfigConfigurationException( sprintf( "Unrecognized Parser Source type '%s'. Accepted values are: '%s'", $type, SourceConfig::SOURCE_TYPE_IMAP ) ); } // Setting the source config to the new source object if ($sourceObj instanceof SourceInterface) { $sourceObj->setConfig($sourceConfig); } else { throw new Exception\BadSourceConfigConfigurationException( sprintf( "Unexpected object type: expected 'Msl\ResourceProxy\Source\SourceInterface' for type '%s' but got '%s'.", $type, get_class($sourceObj) ) ); } } else { throw new Exception\BadSourceConfigConfigurationException( sprintf( "Unexpected object type: expected 'Msl\ResourceProxy\Source\SourceConfig' for type '%s' but got '%s'.", $type, get_class($sourceConfig) ) ); } // Returning result return $sourceObj; }
php
public function getSourceInstance($type, $name, array $parameters, array $globalParameters = array()) { // The source object variable $sourceObj = null; // Getting SourceConfig object for an Imap Source object $sourceConfig = $this->getSourceConfig($name, $type, $parameters, $globalParameters); // Creating a Source object with the given source config object if ($sourceConfig instanceof SourceConfig ) { // Creating a Source object instance according to the given type switch ($type) { case SourceConfig::SOURCE_TYPE_IMAP: // Initializing an Imap Source object $sourceObj = new Imap(); break; case SourceConfig::SOURCE_TYPE_POP: // Initializing a Pop Source object $sourceObj = new Pop(); break; default: throw new Exception\BadSourceConfigConfigurationException( sprintf( "Unrecognized Parser Source type '%s'. Accepted values are: '%s'", $type, SourceConfig::SOURCE_TYPE_IMAP ) ); } // Setting the source config to the new source object if ($sourceObj instanceof SourceInterface) { $sourceObj->setConfig($sourceConfig); } else { throw new Exception\BadSourceConfigConfigurationException( sprintf( "Unexpected object type: expected 'Msl\ResourceProxy\Source\SourceInterface' for type '%s' but got '%s'.", $type, get_class($sourceObj) ) ); } } else { throw new Exception\BadSourceConfigConfigurationException( sprintf( "Unexpected object type: expected 'Msl\ResourceProxy\Source\SourceConfig' for type '%s' but got '%s'.", $type, get_class($sourceConfig) ) ); } // Returning result return $sourceObj; }
[ "public", "function", "getSourceInstance", "(", "$", "type", ",", "$", "name", ",", "array", "$", "parameters", ",", "array", "$", "globalParameters", "=", "array", "(", ")", ")", "{", "// The source object variable", "$", "sourceObj", "=", "null", ";", "// ...
Gets a Source instance according to the type. @param string $type type of the required Source instance (e.g. 'imap') @param string $name name of the returned Source instance (e.g. 'imap.main.account') @param array $parameters configuration parameters to initialize a Source instance @param array $globalParameters Global configuration array: if required parameters are not specified in the parameters array, then we check if they are defined in this array @return \Msl\ResourceProxy\Source\SourceInterface @throws \Msl\ResourceProxy\Exception\BadSourceConfigConfigurationException
[ "Gets", "a", "Source", "instance", "according", "to", "the", "type", "." ]
train
https://github.com/mslib/resource-proxy/blob/be3f8589753f738f5114443a3465f5e84aecd156/Msl/ResourceProxy/Source/SourceFactory.php#L36-L90
mslib/resource-proxy
Msl/ResourceProxy/Source/SourceFactory.php
SourceFactory.getSourceConfig
protected function getSourceConfig($name, $type, array $parameters, array $globalParameters = array()) { // Initializing result object $sourceConfig = new SourceConfig(); // Checking connection parameters if (!isset($parameters['connection'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing parameters 'connection' for source configuration '$name'", $name) ); } else { // Checking host parameter if (!isset($parameters['connection']['host'])) { // We check the global configuration parameter if (!isset($globalParameters['host'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing global or local parameters 'host' for source configuration '$name.connection'", $name) ); } else { $host = $globalParameters['host']; } } else { $host = $parameters['connection']['host']; } // Checking port parameter if (!isset($parameters['connection']['port'])) { // We check the global configuration parameter if (!isset($globalParameters['port'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing global or local parameters 'port' for source configuration '$name.connection'", $name) ); } else { $port = $globalParameters['port']; } } else { $port = $parameters['connection']['port']; } // Checking ssl parameter if (!isset($parameters['connection']['ssl'])) { // We check the global configuration parameter if (!isset($globalParameters['ssl'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing global or local parameters 'ssl' for source configuration '$name.connection'", $name) ); } else { $ssl = $globalParameters['ssl']; } } else { $ssl = $parameters['connection']['ssl']; } // Checking username parameter if (!isset($parameters['connection']['username'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing parameters 'username' for source configuration '$name.username'", $name) ); } $username = $parameters['connection']['username']; // Checking password parameter if (!isset($parameters['connection']['password'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing parameters 'password' for source configuration '$name.password'", $name) ); } $password = $parameters['connection']['password']; // Populating SourceConfig object $sourceConfig->setName($name); $sourceConfig->setHost($host); $sourceConfig->setUsername($username); $sourceConfig->setPassword($password); $sourceConfig->setCryptProtocol($ssl); $sourceConfig->setPort($port); $sourceConfig->setType($type); if (isset($parameters['connection']['filter'])) { $sourceConfig->setFilter($parameters['connection']['filter']); } } // Returning SourceConfig object return $sourceConfig; }
php
protected function getSourceConfig($name, $type, array $parameters, array $globalParameters = array()) { // Initializing result object $sourceConfig = new SourceConfig(); // Checking connection parameters if (!isset($parameters['connection'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing parameters 'connection' for source configuration '$name'", $name) ); } else { // Checking host parameter if (!isset($parameters['connection']['host'])) { // We check the global configuration parameter if (!isset($globalParameters['host'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing global or local parameters 'host' for source configuration '$name.connection'", $name) ); } else { $host = $globalParameters['host']; } } else { $host = $parameters['connection']['host']; } // Checking port parameter if (!isset($parameters['connection']['port'])) { // We check the global configuration parameter if (!isset($globalParameters['port'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing global or local parameters 'port' for source configuration '$name.connection'", $name) ); } else { $port = $globalParameters['port']; } } else { $port = $parameters['connection']['port']; } // Checking ssl parameter if (!isset($parameters['connection']['ssl'])) { // We check the global configuration parameter if (!isset($globalParameters['ssl'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing global or local parameters 'ssl' for source configuration '$name.connection'", $name) ); } else { $ssl = $globalParameters['ssl']; } } else { $ssl = $parameters['connection']['ssl']; } // Checking username parameter if (!isset($parameters['connection']['username'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing parameters 'username' for source configuration '$name.username'", $name) ); } $username = $parameters['connection']['username']; // Checking password parameter if (!isset($parameters['connection']['password'])) { throw new Exception\BadSourceConfigConfigurationException( sprintf("Missing parameters 'password' for source configuration '$name.password'", $name) ); } $password = $parameters['connection']['password']; // Populating SourceConfig object $sourceConfig->setName($name); $sourceConfig->setHost($host); $sourceConfig->setUsername($username); $sourceConfig->setPassword($password); $sourceConfig->setCryptProtocol($ssl); $sourceConfig->setPort($port); $sourceConfig->setType($type); if (isset($parameters['connection']['filter'])) { $sourceConfig->setFilter($parameters['connection']['filter']); } } // Returning SourceConfig object return $sourceConfig; }
[ "protected", "function", "getSourceConfig", "(", "$", "name", ",", "$", "type", ",", "array", "$", "parameters", ",", "array", "$", "globalParameters", "=", "array", "(", ")", ")", "{", "// Initializing result object", "$", "sourceConfig", "=", "new", "SourceC...
Returns an instance of SourceConfig object to wrap all required configuration for any Source instance. @param string $name The Source name @param string $type The Source type (e.g. 'imap') @param array $parameters Required configuration array to create a Source instance @param array $globalParameters Global configuration array: if required parameters are not specified in the parameters array, then we check if they are defined in this array @throws \Msl\ResourceProxy\Exception\BadSourceConfigConfigurationException @return SourceConfig
[ "Returns", "an", "instance", "of", "SourceConfig", "object", "to", "wrap", "all", "required", "configuration", "for", "any", "Source", "instance", "." ]
train
https://github.com/mslib/resource-proxy/blob/be3f8589753f738f5114443a3465f5e84aecd156/Msl/ResourceProxy/Source/SourceFactory.php#L104-L188
shabbyrobe/amiss
src/Sql/Query/Select.php
Select.buildOrder
public function buildOrder($meta, $tableAlias=null) { // Careful! $meta might be null. $metaFields = $meta ? $meta->fields : null; $order = $this->order; if ($meta && $meta->defaultOrder && $order !== null) { $order = $meta->defaultOrder; } if ($order) { if (is_array($order)) { $oClauses = ''; foreach ($order as $field=>$dir) { if ($oClauses) { $oClauses .= ', '; } if (!is_string($field)) { $field = $dir; $dir = ''; } $name = (isset($metaFields[$field]) ? $metaFields[$field]['name'] : $field); $qname = $name[0] == '`' ? $name : '`'.$name.'`'; $qname = ($tableAlias ? $tableAlias.'.' : '').$qname; $oClauses .= $qname; if ($dir) { if ($dir === true) { $dir = 'asc'; } // strpos(strtolower($dir), 'desc') === 0; if (isset($dir[3]) && ($dir[0] == 'd' || $dir[0] == 'D') && ($dir[1] == 'e' || $dir[1] == 'E') && ($dir[2] == 's' || $dir[2] == 'S') && ($dir[3] == 'c' || $dir[3] == 'C')) { $oClauses .= ' desc'; } elseif (!isset($dir[2]) || !(($dir[0] == 'a' || $dir[0] == 'A') && ($dir[1] == 's' || $dir[1] == 'S') && ($dir[2] == 'c' || $dir[2] == 'C'))) { throw new \UnexpectedValueException("Order direction must be 'asc' or 'desc', found ".$dir); } } } $order = $oClauses; } else { if ($metaFields && strpos($order, '{') !== false) { $order = static::replaceFields($meta, $order, $tableAlias); } } } return $order; }
php
public function buildOrder($meta, $tableAlias=null) { // Careful! $meta might be null. $metaFields = $meta ? $meta->fields : null; $order = $this->order; if ($meta && $meta->defaultOrder && $order !== null) { $order = $meta->defaultOrder; } if ($order) { if (is_array($order)) { $oClauses = ''; foreach ($order as $field=>$dir) { if ($oClauses) { $oClauses .= ', '; } if (!is_string($field)) { $field = $dir; $dir = ''; } $name = (isset($metaFields[$field]) ? $metaFields[$field]['name'] : $field); $qname = $name[0] == '`' ? $name : '`'.$name.'`'; $qname = ($tableAlias ? $tableAlias.'.' : '').$qname; $oClauses .= $qname; if ($dir) { if ($dir === true) { $dir = 'asc'; } // strpos(strtolower($dir), 'desc') === 0; if (isset($dir[3]) && ($dir[0] == 'd' || $dir[0] == 'D') && ($dir[1] == 'e' || $dir[1] == 'E') && ($dir[2] == 's' || $dir[2] == 'S') && ($dir[3] == 'c' || $dir[3] == 'C')) { $oClauses .= ' desc'; } elseif (!isset($dir[2]) || !(($dir[0] == 'a' || $dir[0] == 'A') && ($dir[1] == 's' || $dir[1] == 'S') && ($dir[2] == 'c' || $dir[2] == 'C'))) { throw new \UnexpectedValueException("Order direction must be 'asc' or 'desc', found ".$dir); } } } $order = $oClauses; } else { if ($metaFields && strpos($order, '{') !== false) { $order = static::replaceFields($meta, $order, $tableAlias); } } } return $order; }
[ "public", "function", "buildOrder", "(", "$", "meta", ",", "$", "tableAlias", "=", "null", ")", "{", "// Careful! $meta might be null.", "$", "metaFields", "=", "$", "meta", "?", "$", "meta", "->", "fields", ":", "null", ";", "$", "order", "=", "$", "thi...
damn, this is pretty much identical to the above. FIXME, etc.
[ "damn", "this", "is", "pretty", "much", "identical", "to", "the", "above", ".", "FIXME", "etc", "." ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Sql/Query/Select.php#L94-L143
zhouyl/mellivora
Mellivora/Events/Dispatcher.php
Dispatcher.parseEventAndPayload
protected function parseEventAndPayload($event, $payload) { if (is_object($event)) { list($payload, $event) = [[$event], get_class($event)]; } return [$event, array_wrap($payload)]; }
php
protected function parseEventAndPayload($event, $payload) { if (is_object($event)) { list($payload, $event) = [[$event], get_class($event)]; } return [$event, array_wrap($payload)]; }
[ "protected", "function", "parseEventAndPayload", "(", "$", "event", ",", "$", "payload", ")", "{", "if", "(", "is_object", "(", "$", "event", ")", ")", "{", "list", "(", "$", "payload", ",", "$", "event", ")", "=", "[", "[", "$", "event", "]", ",",...
Parse the given event and payload and prepare them for dispatching. @param mixed $event @param mixed $payload @return array
[ "Parse", "the", "given", "event", "and", "payload", "and", "prepare", "them", "for", "dispatching", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Events/Dispatcher.php#L234-L241
zhouyl/mellivora
Mellivora/Events/Dispatcher.php
Dispatcher.getListeners
public function getListeners($eventName) { $listeners = isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : []; $listeners = array_merge( $listeners, $this->getWildcardListeners($eventName) ); return class_exists($eventName, false) ? $this->addInterfaceListeners($eventName, $listeners) : $listeners; }
php
public function getListeners($eventName) { $listeners = isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : []; $listeners = array_merge( $listeners, $this->getWildcardListeners($eventName) ); return class_exists($eventName, false) ? $this->addInterfaceListeners($eventName, $listeners) : $listeners; }
[ "public", "function", "getListeners", "(", "$", "eventName", ")", "{", "$", "listeners", "=", "isset", "(", "$", "this", "->", "listeners", "[", "$", "eventName", "]", ")", "?", "$", "this", "->", "listeners", "[", "$", "eventName", "]", ":", "[", "]...
Get all of the listeners for a given event name. @param string $eventName @return array
[ "Get", "all", "of", "the", "listeners", "for", "a", "given", "event", "name", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Events/Dispatcher.php#L250-L262
zhouyl/mellivora
Mellivora/Events/Dispatcher.php
Dispatcher.getWildcardListeners
protected function getWildcardListeners($eventName) { $wildcards = []; foreach ($this->wildcards as $key => $listeners) { if (Str::is($key, $eventName)) { $wildcards = array_merge($wildcards, $listeners); } } return $wildcards; }
php
protected function getWildcardListeners($eventName) { $wildcards = []; foreach ($this->wildcards as $key => $listeners) { if (Str::is($key, $eventName)) { $wildcards = array_merge($wildcards, $listeners); } } return $wildcards; }
[ "protected", "function", "getWildcardListeners", "(", "$", "eventName", ")", "{", "$", "wildcards", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "wildcards", "as", "$", "key", "=>", "$", "listeners", ")", "{", "if", "(", "Str", "::", "is", ...
Get the wildcard listeners for the event. @param string $eventName @return array
[ "Get", "the", "wildcard", "listeners", "for", "the", "event", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Events/Dispatcher.php#L271-L282
zhouyl/mellivora
Mellivora/Events/Dispatcher.php
Dispatcher.createClassCallable
protected function createClassCallable($listener) { list($class, $method) = $this->parseClassCallable($listener); if ($this->handlerShouldBeQueued($class)) { return $this->createQueuedHandlerCallable($class, $method); } return [$this->container->make($class), $method]; }
php
protected function createClassCallable($listener) { list($class, $method) = $this->parseClassCallable($listener); if ($this->handlerShouldBeQueued($class)) { return $this->createQueuedHandlerCallable($class, $method); } return [$this->container->make($class), $method]; }
[ "protected", "function", "createClassCallable", "(", "$", "listener", ")", "{", "list", "(", "$", "class", ",", "$", "method", ")", "=", "$", "this", "->", "parseClassCallable", "(", "$", "listener", ")", ";", "if", "(", "$", "this", "->", "handlerShould...
Create the class based event callable. @param string $listener @return callable
[ "Create", "the", "class", "based", "event", "callable", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Events/Dispatcher.php#L357-L366
zhouyl/mellivora
Mellivora/Events/Dispatcher.php
Dispatcher.createQueuedHandlerCallable
protected function createQueuedHandlerCallable($class, $method) { return function () use ($class, $method) { $arguments = array_map(function ($a) { return is_object($a) ? clone $a : $a; }, func_get_args()); if (method_exists($class, 'queue')) { $this->callQueueMethodOnHandler($class, $method, $arguments); } else { $this->queueHandler($class, $method, $arguments); } }; }
php
protected function createQueuedHandlerCallable($class, $method) { return function () use ($class, $method) { $arguments = array_map(function ($a) { return is_object($a) ? clone $a : $a; }, func_get_args()); if (method_exists($class, 'queue')) { $this->callQueueMethodOnHandler($class, $method, $arguments); } else { $this->queueHandler($class, $method, $arguments); } }; }
[ "protected", "function", "createQueuedHandlerCallable", "(", "$", "class", ",", "$", "method", ")", "{", "return", "function", "(", ")", "use", "(", "$", "class", ",", "$", "method", ")", "{", "$", "arguments", "=", "array_map", "(", "function", "(", "$"...
Create a callable for putting an event handler on the queue. @param string $class @param string $method @return \Closure
[ "Create", "a", "callable", "for", "putting", "an", "event", "handler", "on", "the", "queue", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Events/Dispatcher.php#L406-L419
zhouyl/mellivora
Mellivora/Events/Dispatcher.php
Dispatcher.queueHandler
protected function queueHandler($class, $method, $arguments) { list($listener, $job) = $this->createListenerAndJob($class, $method, $arguments); $connection = $this->resolveQueue()->connection( isset($listener->connection) ? $listener->connection : null ); $queue = isset($listener->queue) ? $listener->queue : null; isset($listener->delay) ? $connection->laterOn($queue, $listener->delay, $job) : $connection->pushOn($queue, $job); }
php
protected function queueHandler($class, $method, $arguments) { list($listener, $job) = $this->createListenerAndJob($class, $method, $arguments); $connection = $this->resolveQueue()->connection( isset($listener->connection) ? $listener->connection : null ); $queue = isset($listener->queue) ? $listener->queue : null; isset($listener->delay) ? $connection->laterOn($queue, $listener->delay, $job) : $connection->pushOn($queue, $job); }
[ "protected", "function", "queueHandler", "(", "$", "class", ",", "$", "method", ",", "$", "arguments", ")", "{", "list", "(", "$", "listener", ",", "$", "job", ")", "=", "$", "this", "->", "createListenerAndJob", "(", "$", "class", ",", "$", "method", ...
Queue the handler class. @param string $class @param string $method @param array $arguments @return void
[ "Queue", "the", "handler", "class", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Events/Dispatcher.php#L448-L461
zhouyl/mellivora
Mellivora/Events/Dispatcher.php
Dispatcher.createListenerAndJob
protected function createListenerAndJob($class, $method, $arguments) { $listener = (new ReflectionClass($class))->newInstanceWithoutConstructor(); return [$listener, $this->propogateListenerOptions( $listener, new CallQueuedListener($class, $method, $arguments) )]; }
php
protected function createListenerAndJob($class, $method, $arguments) { $listener = (new ReflectionClass($class))->newInstanceWithoutConstructor(); return [$listener, $this->propogateListenerOptions( $listener, new CallQueuedListener($class, $method, $arguments) )]; }
[ "protected", "function", "createListenerAndJob", "(", "$", "class", ",", "$", "method", ",", "$", "arguments", ")", "{", "$", "listener", "=", "(", "new", "ReflectionClass", "(", "$", "class", ")", ")", "->", "newInstanceWithoutConstructor", "(", ")", ";", ...
Create the listener and job for a queued listener. @param string $class @param string $method @param array $arguments @return array
[ "Create", "the", "listener", "and", "job", "for", "a", "queued", "listener", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Events/Dispatcher.php#L472-L480
zhouyl/mellivora
Mellivora/Events/Dispatcher.php
Dispatcher.propogateListenerOptions
protected function propogateListenerOptions($listener, $job) { return tap($job, function ($job) use ($listener) { $job->tries = isset($listener->tries) ? $listener->tries : null; $job->timeout = isset($listener->timeout) ? $listener->timeout : null; }); }
php
protected function propogateListenerOptions($listener, $job) { return tap($job, function ($job) use ($listener) { $job->tries = isset($listener->tries) ? $listener->tries : null; $job->timeout = isset($listener->timeout) ? $listener->timeout : null; }); }
[ "protected", "function", "propogateListenerOptions", "(", "$", "listener", ",", "$", "job", ")", "{", "return", "tap", "(", "$", "job", ",", "function", "(", "$", "job", ")", "use", "(", "$", "listener", ")", "{", "$", "job", "->", "tries", "=", "iss...
Propogate listener options to the job. @param mixed $listener @param mixed $job @return mixed
[ "Propogate", "listener", "options", "to", "the", "job", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Events/Dispatcher.php#L490-L496
ClementIV/yii-rest-rbac2.0
models/User.php
User.saveAllowance
public function saveAllowance($request, $action, $allowance, $timestamp) { $this->allowance = $allowance; $this->allowance_updated_at = $timestamp; $this->save(); }
php
public function saveAllowance($request, $action, $allowance, $timestamp) { $this->allowance = $allowance; $this->allowance_updated_at = $timestamp; $this->save(); }
[ "public", "function", "saveAllowance", "(", "$", "request", ",", "$", "action", ",", "$", "allowance", ",", "$", "timestamp", ")", "{", "$", "this", "->", "allowance", "=", "$", "allowance", ";", "$", "this", "->", "allowance_updated_at", "=", "$", "time...
保存请求时的UNIX时间戳。
[ "保存请求时的UNIX时间戳。" ]
train
https://github.com/ClementIV/yii-rest-rbac2.0/blob/435ffceca8d51b4d369182db3a06c20f336e9ac4/models/User.php#L74-L79
ClementIV/yii-rest-rbac2.0
models/User.php
User.isPasswordResetTokenValid
public static function isPasswordResetTokenValid($token) { if (empty($token)) { return false; } $timestamp = (int)substr($token, strrpos($token, '_') + 1); $expire = Yii::$app->params['passwordResetTokenExpire']; return $timestamp + $expire >= time(); }
php
public static function isPasswordResetTokenValid($token) { if (empty($token)) { return false; } $timestamp = (int)substr($token, strrpos($token, '_') + 1); $expire = Yii::$app->params['passwordResetTokenExpire']; return $timestamp + $expire >= time(); }
[ "public", "static", "function", "isPasswordResetTokenValid", "(", "$", "token", ")", "{", "if", "(", "empty", "(", "$", "token", ")", ")", "{", "return", "false", ";", "}", "$", "timestamp", "=", "(", "int", ")", "substr", "(", "$", "token", ",", "st...
Finds out if password reset token is valid. @param string $token password reset token @return boolean
[ "Finds", "out", "if", "password", "reset", "token", "is", "valid", "." ]
train
https://github.com/ClementIV/yii-rest-rbac2.0/blob/435ffceca8d51b4d369182db3a06c20f336e9ac4/models/User.php#L132-L142
ClementIV/yii-rest-rbac2.0
models/User.php
User.isAccessTokenValid
public static function isAccessTokenValid($token) { if (empty($token)) { return false; } $data = Yii::$app->jwt->getValidationData(); // It will use the current time to validate (iat, nbf and exp) $data->setIssuer(Yii::getAlias("@restIssuer")); $data->setAudience(Yii::getAlias("@restAudience")); $data->setId(Yii::getAlias("@restId")+strtotime(date('Y-m-d',time())), true); if (is_string($token)) $token = Yii::$app->jwt->getParser()->parse($token); return $token->validate($data); }
php
public static function isAccessTokenValid($token) { if (empty($token)) { return false; } $data = Yii::$app->jwt->getValidationData(); // It will use the current time to validate (iat, nbf and exp) $data->setIssuer(Yii::getAlias("@restIssuer")); $data->setAudience(Yii::getAlias("@restAudience")); $data->setId(Yii::getAlias("@restId")+strtotime(date('Y-m-d',time())), true); if (is_string($token)) $token = Yii::$app->jwt->getParser()->parse($token); return $token->validate($data); }
[ "public", "static", "function", "isAccessTokenValid", "(", "$", "token", ")", "{", "if", "(", "empty", "(", "$", "token", ")", ")", "{", "return", "false", ";", "}", "$", "data", "=", "Yii", "::", "$", "app", "->", "jwt", "->", "getValidationData", "...
Validates access_token. @param string $token token to validate @return bool if token provided is valid for current user
[ "Validates", "access_token", "." ]
train
https://github.com/ClementIV/yii-rest-rbac2.0/blob/435ffceca8d51b4d369182db3a06c20f336e9ac4/models/User.php#L151-L164
ClementIV/yii-rest-rbac2.0
models/User.php
User.generateAccessToken
public function generateAccessToken() { // $this->access_token = Yii::$app->security->generateRandomString() . '_' . time(); $signer = new Sha256(); $token = Yii::$app->jwt->getBuilder()->setIssuer(Yii::getAlias("@restIssuer"))// Configures the issuer (iss claim) ->setAudience(Yii::getAlias("@restAudience"))// Configures the audience (aud claim) ->setId(Yii::getAlias("@restId")+ strtotime(date('Y-m-d',time())), true) ->setExpiration(time() + Yii::$app->params['accessTokenExpire'])// Configures exp time ->setIssuedAt(time())// Configures the time that the token was issue (iat claim) ->sign($signer, Yii::$app->jwt->key) ->getToken(); // Retrieves the generated token //$this->auth_key=$this->id; $this->access_token = (string)$token; }
php
public function generateAccessToken() { // $this->access_token = Yii::$app->security->generateRandomString() . '_' . time(); $signer = new Sha256(); $token = Yii::$app->jwt->getBuilder()->setIssuer(Yii::getAlias("@restIssuer"))// Configures the issuer (iss claim) ->setAudience(Yii::getAlias("@restAudience"))// Configures the audience (aud claim) ->setId(Yii::getAlias("@restId")+ strtotime(date('Y-m-d',time())), true) ->setExpiration(time() + Yii::$app->params['accessTokenExpire'])// Configures exp time ->setIssuedAt(time())// Configures the time that the token was issue (iat claim) ->sign($signer, Yii::$app->jwt->key) ->getToken(); // Retrieves the generated token //$this->auth_key=$this->id; $this->access_token = (string)$token; }
[ "public", "function", "generateAccessToken", "(", ")", "{", "// $this->access_token = Yii::$app->security->generateRandomString() . '_' . time();", "$", "signer", "=", "new", "Sha256", "(", ")", ";", "$", "token", "=", "Yii", "::", "$", "app", "->", "jwt", "->", "ge...
Generates new api access token.
[ "Generates", "new", "api", "access", "token", "." ]
train
https://github.com/ClementIV/yii-rest-rbac2.0/blob/435ffceca8d51b4d369182db3a06c20f336e9ac4/models/User.php#L231-L246
zicht/z
src/Zicht/Tool/Script/Dumper.php
Dumper.getAst
public function getAst(Node\Node $b, $path = '') { $ret = array( 'type' => str_replace('Zicht\Tool\Script\Node\\', '', get_class($b)) ); if ($b instanceof Node\Branch) { if (count($b->nodes)) { $ret['nodes'] = array(); foreach ($b->nodes as $n) { if (null === $n) { $ret['nodes'][] = $n; } else { if (!$n instanceof Node\Node) { throw new \InvalidArgumentException("Invalid child node in " . Util::toPhp($path)); } $ret['nodes'][] = $this->getAst($n); } } } } return $ret; }
php
public function getAst(Node\Node $b, $path = '') { $ret = array( 'type' => str_replace('Zicht\Tool\Script\Node\\', '', get_class($b)) ); if ($b instanceof Node\Branch) { if (count($b->nodes)) { $ret['nodes'] = array(); foreach ($b->nodes as $n) { if (null === $n) { $ret['nodes'][] = $n; } else { if (!$n instanceof Node\Node) { throw new \InvalidArgumentException("Invalid child node in " . Util::toPhp($path)); } $ret['nodes'][] = $this->getAst($n); } } } } return $ret; }
[ "public", "function", "getAst", "(", "Node", "\\", "Node", "$", "b", ",", "$", "path", "=", "''", ")", "{", "$", "ret", "=", "array", "(", "'type'", "=>", "str_replace", "(", "'Zicht\\Tool\\Script\\Node\\\\'", ",", "''", ",", "get_class", "(", "$", "b"...
Returns the AST for a specified node as an array representation @param Node\Node $b @param string $path @return array
[ "Returns", "the", "AST", "for", "a", "specified", "node", "as", "an", "array", "representation" ]
train
https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Script/Dumper.php#L24-L47
Smile-SA/CronBundle
Cron/CronAbstract.php
CronAbstract.isDue
public function isDue() { $expression = $this->getExpression(); $cron = CronExpression::factory($expression); return $cron->isDue(); }
php
public function isDue() { $expression = $this->getExpression(); $cron = CronExpression::factory($expression); return $cron->isDue(); }
[ "public", "function", "isDue", "(", ")", "{", "$", "expression", "=", "$", "this", "->", "getExpression", "(", ")", ";", "$", "cron", "=", "CronExpression", "::", "factory", "(", "$", "expression", ")", ";", "return", "$", "cron", "->", "isDue", "(", ...
Check cron expression @return bool true if cron should be executed
[ "Check", "cron", "expression" ]
train
https://github.com/Smile-SA/CronBundle/blob/3e6d29112915fa957cc04386ba9c6d1fc134d31f/Cron/CronAbstract.php#L68-L73
Smile-SA/CronBundle
Cron/CronAbstract.php
CronAbstract.getExpression
public function getExpression() { $expression = array( $this->minute, $this->hour, $this->dayOfMonth, $this->month, $this->dayOfWeek ); return implode(' ', $expression); }
php
public function getExpression() { $expression = array( $this->minute, $this->hour, $this->dayOfMonth, $this->month, $this->dayOfWeek ); return implode(' ', $expression); }
[ "public", "function", "getExpression", "(", ")", "{", "$", "expression", "=", "array", "(", "$", "this", "->", "minute", ",", "$", "this", "->", "hour", ",", "$", "this", "->", "dayOfMonth", ",", "$", "this", "->", "month", ",", "$", "this", "->", ...
Return the cron expression @return string cron expression
[ "Return", "the", "cron", "expression" ]
train
https://github.com/Smile-SA/CronBundle/blob/3e6d29112915fa957cc04386ba9c6d1fc134d31f/Cron/CronAbstract.php#L80-L91
Smile-SA/CronBundle
Cron/CronAbstract.php
CronAbstract.getArgument
public function getArgument(InputInterface $input, $key) { if ($input->hasArgument($key)) { return $input->getArgument($key); } if (isset($this->arguments[$key])) { return $this->arguments[$key]; } return false; }
php
public function getArgument(InputInterface $input, $key) { if ($input->hasArgument($key)) { return $input->getArgument($key); } if (isset($this->arguments[$key])) { return $this->arguments[$key]; } return false; }
[ "public", "function", "getArgument", "(", "InputInterface", "$", "input", ",", "$", "key", ")", "{", "if", "(", "$", "input", "->", "hasArgument", "(", "$", "key", ")", ")", "{", "return", "$", "input", "->", "getArgument", "(", "$", "key", ")", ";",...
Get Cron arguments @param InputInterface $input Input interface @param string $key @return mixed return argument from input or tag settings
[ "Get", "Cron", "arguments" ]
train
https://github.com/Smile-SA/CronBundle/blob/3e6d29112915fa957cc04386ba9c6d1fc134d31f/Cron/CronAbstract.php#L143-L154
Innmind/Graphviz
src/Node/Node.php
Node.attributes
public function attributes(): MapInterface { $attributes = $this->attributes; if ($this->shape instanceof Shape) { $attributes = $this->shape->attributes()->merge($attributes); } return $attributes; }
php
public function attributes(): MapInterface { $attributes = $this->attributes; if ($this->shape instanceof Shape) { $attributes = $this->shape->attributes()->merge($attributes); } return $attributes; }
[ "public", "function", "attributes", "(", ")", ":", "MapInterface", "{", "$", "attributes", "=", "$", "this", "->", "attributes", ";", "if", "(", "$", "this", "->", "shape", "instanceof", "Shape", ")", "{", "$", "attributes", "=", "$", "this", "->", "sh...
{@inheritdoc}
[ "{" ]
train
https://github.com/Innmind/Graphviz/blob/6912f22a1482045e53e83477fcd04f29ad7cf85c/src/Node/Node.php#L99-L108
zicht/z
src/Zicht/Tool/Container/Executor.php
Executor.execute
public function execute($cmd, &$captureOutput = null) { $isInteractive = $this->container->get('INTERACTIVE'); $process = $this->createProcess($isInteractive); if ($isInteractive) { $process->setCommandLine(sprintf('/bin/bash -c \'%s\'', $cmd)); } else { $process->setInput($cmd); } if (null !== $captureOutput && false === $isInteractive) { $process->run(function ($type, $data) use(&$captureOutput) { $captureOutput .= $data; }); } else { $process->run(array($this, 'processCallback')); } $ret = $process->getExitCode(); if ($ret != 0) { if ((int)$ret == Container::ABORT_EXIT_CODE) { throw new ExecutionAbortedException("Command '$cmd' was aborted"); } else { throw new \UnexpectedValueException("Command '$cmd' failed with exit code {$ret}"); } } return $ret; }
php
public function execute($cmd, &$captureOutput = null) { $isInteractive = $this->container->get('INTERACTIVE'); $process = $this->createProcess($isInteractive); if ($isInteractive) { $process->setCommandLine(sprintf('/bin/bash -c \'%s\'', $cmd)); } else { $process->setInput($cmd); } if (null !== $captureOutput && false === $isInteractive) { $process->run(function ($type, $data) use(&$captureOutput) { $captureOutput .= $data; }); } else { $process->run(array($this, 'processCallback')); } $ret = $process->getExitCode(); if ($ret != 0) { if ((int)$ret == Container::ABORT_EXIT_CODE) { throw new ExecutionAbortedException("Command '$cmd' was aborted"); } else { throw new \UnexpectedValueException("Command '$cmd' failed with exit code {$ret}"); } } return $ret; }
[ "public", "function", "execute", "(", "$", "cmd", ",", "&", "$", "captureOutput", "=", "null", ")", "{", "$", "isInteractive", "=", "$", "this", "->", "container", "->", "get", "(", "'INTERACTIVE'", ")", ";", "$", "process", "=", "$", "this", "->", "...
Executes the passed command line in the shell. @param string $cmd @param null &$captureOutput @param string $captureOutput @return int @throws ExecutionAbortedException @throws \UnexpectedValueException
[ "Executes", "the", "passed", "command", "line", "in", "the", "shell", "." ]
train
https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Container/Executor.php#L38-L67
zicht/z
src/Zicht/Tool/Container/Executor.php
Executor.createProcess
protected function createProcess($interactive = false) { $process = new Process($this->container->resolve('SHELL'), null, null, null, null, []); if ($interactive) { $process->setTty(true); } else { if ($this->container->has('TIMEOUT') && $timeout = $this->container->get('TIMEOUT')) { $process->setTimeout($this->container->get('TIMEOUT')); } } return $process; }
php
protected function createProcess($interactive = false) { $process = new Process($this->container->resolve('SHELL'), null, null, null, null, []); if ($interactive) { $process->setTty(true); } else { if ($this->container->has('TIMEOUT') && $timeout = $this->container->get('TIMEOUT')) { $process->setTimeout($this->container->get('TIMEOUT')); } } return $process; }
[ "protected", "function", "createProcess", "(", "$", "interactive", "=", "false", ")", "{", "$", "process", "=", "new", "Process", "(", "$", "this", "->", "container", "->", "resolve", "(", "'SHELL'", ")", ",", "null", ",", "null", ",", "null", ",", "nu...
Create the process instance to use for non-interactive handling @var bool $interactive @return \Symfony\Component\Process\Process
[ "Create", "the", "process", "instance", "to", "use", "for", "non", "-", "interactive", "handling" ]
train
https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Container/Executor.php#L76-L89
zicht/z
src/Zicht/Tool/Container/Executor.php
Executor.processCallback
public function processCallback($mode, $data) { if (isset($this->container->output)) { $this->container->output->write($data); } }
php
public function processCallback($mode, $data) { if (isset($this->container->output)) { $this->container->output->write($data); } }
[ "public", "function", "processCallback", "(", "$", "mode", ",", "$", "data", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "container", "->", "output", ")", ")", "{", "$", "this", "->", "container", "->", "output", "->", "write", "(", "$", ...
The callback used for the process executed by Process @param mixed $mode @param string $data @return void
[ "The", "callback", "used", "for", "the", "process", "executed", "by", "Process" ]
train
https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Container/Executor.php#L99-L104
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Scrybe/ServiceProvider.php
ServiceProvider.register
public function register(Application $app) { $app[self::TEMPLATE_FOLDER] = realpath(__DIR__ . '/data/templates/'); $app[self::CONVERTERS] = array( '\phpDocumentor\Plugin\Scrybe\Converter\RestructuredText\ToHtml' => array(Format::RST, Format::HTML), ); $app[self::FORMATS] = $app->share( function () { return new Converter\Format\Collection(); } ); $app[self::CONVERTER_DEFINITION_FACTORY] = $app->share( function ($container) { return new Factory($container[ServiceProvider::FORMATS]); } ); $app[self::CONVERTER_FACTORY] = $app->share( function ($container) { return new Converter\Factory( $container['converters'], $container['converter_definition_factory'], $container['monolog'] ); } ); $app[self::TEMPLATE_FACTORY] = $app->share( function ($app) { return new Template\Factory( array('twig' => new Template\Twig($app[ServiceProvider::TEMPLATE_FOLDER])) ); } ); $this->addCommands($app); }
php
public function register(Application $app) { $app[self::TEMPLATE_FOLDER] = realpath(__DIR__ . '/data/templates/'); $app[self::CONVERTERS] = array( '\phpDocumentor\Plugin\Scrybe\Converter\RestructuredText\ToHtml' => array(Format::RST, Format::HTML), ); $app[self::FORMATS] = $app->share( function () { return new Converter\Format\Collection(); } ); $app[self::CONVERTER_DEFINITION_FACTORY] = $app->share( function ($container) { return new Factory($container[ServiceProvider::FORMATS]); } ); $app[self::CONVERTER_FACTORY] = $app->share( function ($container) { return new Converter\Factory( $container['converters'], $container['converter_definition_factory'], $container['monolog'] ); } ); $app[self::TEMPLATE_FACTORY] = $app->share( function ($app) { return new Template\Factory( array('twig' => new Template\Twig($app[ServiceProvider::TEMPLATE_FOLDER])) ); } ); $this->addCommands($app); }
[ "public", "function", "register", "(", "Application", "$", "app", ")", "{", "$", "app", "[", "self", "::", "TEMPLATE_FOLDER", "]", "=", "realpath", "(", "__DIR__", ".", "'/data/templates/'", ")", ";", "$", "app", "[", "self", "::", "CONVERTERS", "]", "="...
Registers services on the given app. @param Application $app An Application instance.
[ "Registers", "services", "on", "the", "given", "app", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Scrybe/ServiceProvider.php#L39-L74
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Scrybe/ServiceProvider.php
ServiceProvider.addCommands
protected function addCommands(Application $app) { $app->command( new Command\Manual\ToHtmlCommand(null, $app[self::TEMPLATE_FACTORY], $app[self::CONVERTER_FACTORY]) ); // FIXME: Disabled the ToLatex and ToPdf commands for now to prevent confusion of users. // $this->command(new \phpDocumentor\Plugin\Scrybe\Command\Manual\ToLatexCommand()); // $this->command(new \phpDocumentor\Plugin\Scrybe\Command\Manual\ToPdfCommand()); }
php
protected function addCommands(Application $app) { $app->command( new Command\Manual\ToHtmlCommand(null, $app[self::TEMPLATE_FACTORY], $app[self::CONVERTER_FACTORY]) ); // FIXME: Disabled the ToLatex and ToPdf commands for now to prevent confusion of users. // $this->command(new \phpDocumentor\Plugin\Scrybe\Command\Manual\ToLatexCommand()); // $this->command(new \phpDocumentor\Plugin\Scrybe\Command\Manual\ToPdfCommand()); }
[ "protected", "function", "addCommands", "(", "Application", "$", "app", ")", "{", "$", "app", "->", "command", "(", "new", "Command", "\\", "Manual", "\\", "ToHtmlCommand", "(", "null", ",", "$", "app", "[", "self", "::", "TEMPLATE_FACTORY", "]", ",", "$...
Method responsible for adding the commands for this application. @param Application $app @return void
[ "Method", "responsible", "for", "adding", "the", "commands", "for", "this", "application", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Scrybe/ServiceProvider.php#L83-L92
Eresus/EresusCMS
src/ext-3rd/editarea/eresus-connector.php
EditAreaConnector.forms_memo_syntax
public function forms_memo_syntax($form, $field) { // Проверяем, не были ли уже выполнены эти действия ранее if (!isset($form->options['editarea'])) { // Подключаем EditArea Eresus_Kernel::app()->getPage()->linkScripts($this->root . 'edit_area_full.js'); $form->options['editarea'] = true; } if (!$field['id']) { $field['id'] = $form->form['name'] . '_' . $field['name']; } Eresus_Kernel::app()->getPage()->addScripts(" editAreaLoader.init({ id : '{$field['id']}', syntax: '{$field['syntax']}', start_highlight: true, language: 'ru', toolbar: 'search,go_to_line,undo,redo,reset_highlight,highlight,word_wrap,help' }); "); return $field; }
php
public function forms_memo_syntax($form, $field) { // Проверяем, не были ли уже выполнены эти действия ранее if (!isset($form->options['editarea'])) { // Подключаем EditArea Eresus_Kernel::app()->getPage()->linkScripts($this->root . 'edit_area_full.js'); $form->options['editarea'] = true; } if (!$field['id']) { $field['id'] = $form->form['name'] . '_' . $field['name']; } Eresus_Kernel::app()->getPage()->addScripts(" editAreaLoader.init({ id : '{$field['id']}', syntax: '{$field['syntax']}', start_highlight: true, language: 'ru', toolbar: 'search,go_to_line,undo,redo,reset_highlight,highlight,word_wrap,help' }); "); return $field; }
[ "public", "function", "forms_memo_syntax", "(", "$", "form", ",", "$", "field", ")", "{", "// Проверяем, не были ли уже выполнены эти действия ранее", "if", "(", "!", "isset", "(", "$", "form", "->", "options", "[", "'editarea'", "]", ")", ")", "{", "// Подключа...
Обработка поля "syntax" для старых форм @param Form $form @param array $field @return array
[ "Обработка", "поля", "syntax", "для", "старых", "форм" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/ext-3rd/editarea/eresus-connector.php#L46-L73
brick/di
src/Definition.php
Definition.get
public function get(Container $container) { if ($this->scope === null) { $this->scope = $this->getDefaultScope(); } return $this->scope->get($this, $container); }
php
public function get(Container $container) { if ($this->scope === null) { $this->scope = $this->getDefaultScope(); } return $this->scope->get($this, $container); }
[ "public", "function", "get", "(", "Container", "$", "container", ")", "{", "if", "(", "$", "this", "->", "scope", "===", "null", ")", "{", "$", "this", "->", "scope", "=", "$", "this", "->", "getDefaultScope", "(", ")", ";", "}", "return", "$", "th...
Resolves the value of this definition, according to the current scope. This method is for internal use by the Container. @internal @param Container $container @return mixed
[ "Resolves", "the", "value", "of", "this", "definition", "according", "to", "the", "current", "scope", "." ]
train
https://github.com/brick/di/blob/6ced82ab3623b8f1470317d38cbd2de855e7aa3d/src/Definition.php#L42-L49
bpolaszek/simple-dbal
src/Model/Adapter/PDO/PDOAdapter.php
PDOAdapter.reconnect
private function reconnect() { if (0 === (int) $this->getOption(self::OPT_MAX_RECONNECT_ATTEMPTS)) { throw new MaxConnectAttempsException("Connection lost."); } elseif ($this->reconnectAttempts === (int) $this->getOption(self::OPT_MAX_RECONNECT_ATTEMPTS)) { throw new MaxConnectAttempsException("Max attempts to connect to database has been reached."); } if (null === $this->credentials) { throw new AccessDeniedException("Unable to reconnect: credentials not provided."); } try { if (0 !== $this->reconnectAttempts) { usleep((int) $this->getOption(self::OPT_USLEEP_AFTER_FIRST_ATTEMPT)); } $this->cnx = self::createLink($this->getCredentials(), $this->options); if ($this->isConnected()) { $this->reconnectAttempts = 0; } else { $this->reconnect(); } } catch (Throwable $e) { $this->reconnectAttempts++; } }
php
private function reconnect() { if (0 === (int) $this->getOption(self::OPT_MAX_RECONNECT_ATTEMPTS)) { throw new MaxConnectAttempsException("Connection lost."); } elseif ($this->reconnectAttempts === (int) $this->getOption(self::OPT_MAX_RECONNECT_ATTEMPTS)) { throw new MaxConnectAttempsException("Max attempts to connect to database has been reached."); } if (null === $this->credentials) { throw new AccessDeniedException("Unable to reconnect: credentials not provided."); } try { if (0 !== $this->reconnectAttempts) { usleep((int) $this->getOption(self::OPT_USLEEP_AFTER_FIRST_ATTEMPT)); } $this->cnx = self::createLink($this->getCredentials(), $this->options); if ($this->isConnected()) { $this->reconnectAttempts = 0; } else { $this->reconnect(); } } catch (Throwable $e) { $this->reconnectAttempts++; } }
[ "private", "function", "reconnect", "(", ")", "{", "if", "(", "0", "===", "(", "int", ")", "$", "this", "->", "getOption", "(", "self", "::", "OPT_MAX_RECONNECT_ATTEMPTS", ")", ")", "{", "throw", "new", "MaxConnectAttempsException", "(", "\"Connection lost.\""...
Tries to reconnect to database.
[ "Tries", "to", "reconnect", "to", "database", "." ]
train
https://github.com/bpolaszek/simple-dbal/blob/52cb50d326ba5854191814b470f5e84950ebb6e6/src/Model/Adapter/PDO/PDOAdapter.php#L101-L126
interactivesolutions/honeycomb-core
src/models/HCMultiLanguageModel.php
HCMultiLanguageModel.translations
public function translations() { if (is_null($this->translationsClass)) $this->translationsClass = get_class($this) . 'Translations'; return $this->hasMany($this->translationsClass, 'record_id', 'id'); }
php
public function translations() { if (is_null($this->translationsClass)) $this->translationsClass = get_class($this) . 'Translations'; return $this->hasMany($this->translationsClass, 'record_id', 'id'); }
[ "public", "function", "translations", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "translationsClass", ")", ")", "$", "this", "->", "translationsClass", "=", "get_class", "(", "$", "this", ")", ".", "'Translations'", ";", "return", "$", ...
Translations @return \Illuminate\Database\Eloquent\Relations\HasMany
[ "Translations" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/models/HCMultiLanguageModel.php#L19-L25
interactivesolutions/honeycomb-core
src/models/HCMultiLanguageModel.php
HCMultiLanguageModel.translation
public function translation() { if (is_null($this->translationsClass)) $this->translationsClass = get_class($this) . 'Translations'; return $this->hasOne($this->translationsClass, 'record_id', 'id')->where('language_code', app()->getLocale()); }
php
public function translation() { if (is_null($this->translationsClass)) $this->translationsClass = get_class($this) . 'Translations'; return $this->hasOne($this->translationsClass, 'record_id', 'id')->where('language_code', app()->getLocale()); }
[ "public", "function", "translation", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "translationsClass", ")", ")", "$", "this", "->", "translationsClass", "=", "get_class", "(", "$", "this", ")", ".", "'Translations'", ";", "return", "$", "...
Single translation only @return \Illuminate\Database\Eloquent\Relations\HasOne
[ "Single", "translation", "only" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/models/HCMultiLanguageModel.php#L32-L38
interactivesolutions/honeycomb-core
src/models/HCMultiLanguageModel.php
HCMultiLanguageModel.updateTranslation
public function updateTranslation(array $data) { $translations = $this->translations()->where([ 'record_id' => $this->id, 'language_code' => array_get($data, 'language_code'), ])->first(); if (is_null($translations)) $translations = $this->translations()->create($data); else $translations->update($data); return $translations; }
php
public function updateTranslation(array $data) { $translations = $this->translations()->where([ 'record_id' => $this->id, 'language_code' => array_get($data, 'language_code'), ])->first(); if (is_null($translations)) $translations = $this->translations()->create($data); else $translations->update($data); return $translations; }
[ "public", "function", "updateTranslation", "(", "array", "$", "data", ")", "{", "$", "translations", "=", "$", "this", "->", "translations", "(", ")", "->", "where", "(", "[", "'record_id'", "=>", "$", "this", "->", "id", ",", "'language_code'", "=>", "a...
Update translations @param array $data @return \Illuminate\Database\Eloquent\Model
[ "Update", "translations" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/models/HCMultiLanguageModel.php#L46-L59
interactivesolutions/honeycomb-core
src/models/HCMultiLanguageModel.php
HCMultiLanguageModel.translatedList
public static function translatedList(string $nameKey = "name") { return (new static())->with('translations')->get()->map(function ($item, $key) use ($nameKey) { return [ 'id' => $item->id, 'label' => get_translation_name( $nameKey, app()->getLocale(), array_get($item, 'translations') ), ]; }); }
php
public static function translatedList(string $nameKey = "name") { return (new static())->with('translations')->get()->map(function ($item, $key) use ($nameKey) { return [ 'id' => $item->id, 'label' => get_translation_name( $nameKey, app()->getLocale(), array_get($item, 'translations') ), ]; }); }
[ "public", "static", "function", "translatedList", "(", "string", "$", "nameKey", "=", "\"name\"", ")", "{", "return", "(", "new", "static", "(", ")", ")", "->", "with", "(", "'translations'", ")", "->", "get", "(", ")", "->", "map", "(", "function", "(...
Get translated id -> value names @param string $nameKey @return mixed
[ "Get", "translated", "id", "-", ">", "value", "names" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/models/HCMultiLanguageModel.php#L79-L89
VincentChalnot/SidusDataGridBundle
Renderer/DefaultColumnValueRenderer.php
DefaultColumnValueRenderer.renderValue
public function renderValue($value, array $options = []): string { $resolver = new OptionsResolver(); $this->configureOptions($resolver); $options = $resolver->resolve($options); if ($value instanceof \DateTimeInterface) { if (null !== $options['date_format']) { return (string) $value->format($options['date_format']); } if ($value->format('H:i') === '00:00') { $options['time_type'] = \IntlDateFormatter::NONE; } $dateFormatter = new \IntlDateFormatter( $this->translator->getLocale(), $options['date_type'], $options['time_type'] ); return (string) $dateFormatter->format($value); } if (\is_int($value)) { return (string) $value; } if (\is_float($value)) { if (null !== $options['decimals'] || null !== $options['dec_point'] || null !== $options['thousands_sep']) { return number_format( $value, $options['decimals'] ?: 2, $options['dec_point'] ?: '.', $options['thousands_sep'] ?: ',' ); } $numberFormatter = new \NumberFormatter($this->translator->getLocale(), $options['number_format']); return (string) $numberFormatter->format($value); } if (\is_iterable($value)) { $items = []; /** @noinspection ForeachSourceInspection */ foreach ($value as $key => $item) { $rendered = $this->renderValue($item, $options); if (!is_numeric($key)) { $rendered = $key.$options['key_value_separator'].$rendered; } $items[] = $rendered; } return implode($options['array_glue'], $items); } if (\is_bool($value)) { if ($options['bool_use_translator']) { return (string) $this->translator->trans( $value ? $options['bool_true'] : $options['bool_false'] ); } return $value ? $options['bool_true'] : $options['bool_false']; } return (string) $value; }
php
public function renderValue($value, array $options = []): string { $resolver = new OptionsResolver(); $this->configureOptions($resolver); $options = $resolver->resolve($options); if ($value instanceof \DateTimeInterface) { if (null !== $options['date_format']) { return (string) $value->format($options['date_format']); } if ($value->format('H:i') === '00:00') { $options['time_type'] = \IntlDateFormatter::NONE; } $dateFormatter = new \IntlDateFormatter( $this->translator->getLocale(), $options['date_type'], $options['time_type'] ); return (string) $dateFormatter->format($value); } if (\is_int($value)) { return (string) $value; } if (\is_float($value)) { if (null !== $options['decimals'] || null !== $options['dec_point'] || null !== $options['thousands_sep']) { return number_format( $value, $options['decimals'] ?: 2, $options['dec_point'] ?: '.', $options['thousands_sep'] ?: ',' ); } $numberFormatter = new \NumberFormatter($this->translator->getLocale(), $options['number_format']); return (string) $numberFormatter->format($value); } if (\is_iterable($value)) { $items = []; /** @noinspection ForeachSourceInspection */ foreach ($value as $key => $item) { $rendered = $this->renderValue($item, $options); if (!is_numeric($key)) { $rendered = $key.$options['key_value_separator'].$rendered; } $items[] = $rendered; } return implode($options['array_glue'], $items); } if (\is_bool($value)) { if ($options['bool_use_translator']) { return (string) $this->translator->trans( $value ? $options['bool_true'] : $options['bool_false'] ); } return $value ? $options['bool_true'] : $options['bool_false']; } return (string) $value; }
[ "public", "function", "renderValue", "(", "$", "value", ",", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "$", "resolver", "=", "new", "OptionsResolver", "(", ")", ";", "$", "this", "->", "configureOptions", "(", "$", "resolver", ")...
@param mixed $value @param array $options @throws \Exception @return string
[ "@param", "mixed", "$value", "@param", "array", "$options" ]
train
https://github.com/VincentChalnot/SidusDataGridBundle/blob/aa929113e2208ed335f514d2891affaf7fddf3f6/Renderer/DefaultColumnValueRenderer.php#L48-L109
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.findOne
public function findOne(string $from, $wheres = 1, $select = '*', array $options = []) { $options['select'] = $this->qns($select ?: '*'); $options['from'] = $this->qn($from); list($where, $bindings) = $this->handleWheres($wheres); $options['where'] = $where; $options['limit'] = 1; $statement = $this->compileSelect($options); if (isset($options['dumpSql'])) { return [$statement, $bindings]; } if ($class = $options['class'] ?? null) { return $this->fetchObject($statement, $bindings, $class); } $method = 'fetchAssoc'; if (isset($options['fetchType'])) { if ($options['fetchType'] === 'column') { $method = 'fetchColumn'; } elseif ($options['fetchType'] === 'value') { $method = 'fetchValue'; } } return $this->$method($statement, $bindings); }
php
public function findOne(string $from, $wheres = 1, $select = '*', array $options = []) { $options['select'] = $this->qns($select ?: '*'); $options['from'] = $this->qn($from); list($where, $bindings) = $this->handleWheres($wheres); $options['where'] = $where; $options['limit'] = 1; $statement = $this->compileSelect($options); if (isset($options['dumpSql'])) { return [$statement, $bindings]; } if ($class = $options['class'] ?? null) { return $this->fetchObject($statement, $bindings, $class); } $method = 'fetchAssoc'; if (isset($options['fetchType'])) { if ($options['fetchType'] === 'column') { $method = 'fetchColumn'; } elseif ($options['fetchType'] === 'value') { $method = 'fetchValue'; } } return $this->$method($statement, $bindings); }
[ "public", "function", "findOne", "(", "string", "$", "from", ",", "$", "wheres", "=", "1", ",", "$", "select", "=", "'*'", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "[", "'select'", "]", "=", "$", "this", "->", "qns",...
Run a select statement, fetch one @param string $from @param array|string|int $wheres @param string|array $select @param array $options @return array @throws \RuntimeException
[ "Run", "a", "select", "statement", "fetch", "one" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L289-L320
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.findAll
public function findAll(string $from, $wheres = 1, $select = '*', array $options = []) { $options['select'] = $this->qns($select ?: '*'); $options['from'] = $this->qn($from); list($where, $bindings) = $this->handleWheres($wheres); $options['where'] = $where; if (!isset($options['limit'])) { $options['limit'] = 1000; } $statement = $this->compileSelect($options); if (isset($options['dumpSql'])) { return [$statement, $bindings]; } $indexKey = $options['indexKey'] ?? null; if ($class = $options['class'] ?? null) { return $this->fetchObjects($statement, $bindings, $class, $indexKey); } $method = 'fetchAssocs'; if (isset($options['fetchType'])) { if ($options['fetchType'] === 'column') { // for get columns, indexKey is column number. $method = 'fetchColumns'; } elseif ($options['fetchType'] === 'value') { $method = 'fetchValues'; } } return $this->$method($statement, $bindings, $indexKey); }
php
public function findAll(string $from, $wheres = 1, $select = '*', array $options = []) { $options['select'] = $this->qns($select ?: '*'); $options['from'] = $this->qn($from); list($where, $bindings) = $this->handleWheres($wheres); $options['where'] = $where; if (!isset($options['limit'])) { $options['limit'] = 1000; } $statement = $this->compileSelect($options); if (isset($options['dumpSql'])) { return [$statement, $bindings]; } $indexKey = $options['indexKey'] ?? null; if ($class = $options['class'] ?? null) { return $this->fetchObjects($statement, $bindings, $class, $indexKey); } $method = 'fetchAssocs'; if (isset($options['fetchType'])) { if ($options['fetchType'] === 'column') { // for get columns, indexKey is column number. $method = 'fetchColumns'; } elseif ($options['fetchType'] === 'value') { $method = 'fetchValues'; } } return $this->$method($statement, $bindings, $indexKey); }
[ "public", "function", "findAll", "(", "string", "$", "from", ",", "$", "wheres", "=", "1", ",", "$", "select", "=", "'*'", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "[", "'select'", "]", "=", "$", "this", "->", "qns",...
Run a select statement, fetch all @param string $from @param array|string|int $wheres @param string|array $select @param array $options @return array @throws \RuntimeException
[ "Run", "a", "select", "statement", "fetch", "all" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L331-L368
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.insert
public function insert(string $from, array $data, array $options = []) { if (!$data) { throw new \RuntimeException('The data inserted into the database cannot be empty'); } list($statement, $bindings) = $this->compileInsert($from, $data); if (isset($options['dumpSql'])) { return [$statement, $bindings]; } $this->fetchAffected($statement, $bindings); // 'sequence' For special driver, like PgSQL return isset($options['sequence']) ? $this->lastInsertId($options['sequence']) : $this->lastInsertId(); }
php
public function insert(string $from, array $data, array $options = []) { if (!$data) { throw new \RuntimeException('The data inserted into the database cannot be empty'); } list($statement, $bindings) = $this->compileInsert($from, $data); if (isset($options['dumpSql'])) { return [$statement, $bindings]; } $this->fetchAffected($statement, $bindings); // 'sequence' For special driver, like PgSQL return isset($options['sequence']) ? $this->lastInsertId($options['sequence']) : $this->lastInsertId(); }
[ "public", "function", "insert", "(", "string", "$", "from", ",", "array", "$", "data", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "$", "data", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'The data inserted into...
Run a statement for insert a row @param string $from @param array $data <column => value> @param array $options @return int|array @throws \RuntimeException
[ "Run", "a", "statement", "for", "insert", "a", "row" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L378-L394
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.delete
public function delete(string $from, $wheres, array $options = []) { if (!$wheres) { throw new \RuntimeException('Safety considerations, where conditions can not be empty'); } list($where, $bindings) = $this->handleWheres($wheres); $options['from'] = $this->qn($from); $options['where'] = $where; $statement = $this->compileDelete($options); if (isset($options['dumpSql'])) { return [$statement, $bindings]; } return $this->fetchAffected($statement, $bindings); }
php
public function delete(string $from, $wheres, array $options = []) { if (!$wheres) { throw new \RuntimeException('Safety considerations, where conditions can not be empty'); } list($where, $bindings) = $this->handleWheres($wheres); $options['from'] = $this->qn($from); $options['where'] = $where; $statement = $this->compileDelete($options); if (isset($options['dumpSql'])) { return [$statement, $bindings]; } return $this->fetchAffected($statement, $bindings); }
[ "public", "function", "delete", "(", "string", "$", "from", ",", "$", "wheres", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "$", "wheres", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Safety considerations, where ...
Run a delete statement @param string $from @param array|string $wheres @param array $options @return int|array @throws \RuntimeException
[ "Run", "a", "delete", "statement" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L447-L465
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.count
public function count(string $table, $wheres) { list($where, $bindings) = $this->handleWheres($wheres); $sql = "SELECT COUNT(*) AS total FROM {$table} WHERE {$where}"; $result = $this->fetchObject($sql, $bindings); return $result ? (int)$result->total : 0; }
php
public function count(string $table, $wheres) { list($where, $bindings) = $this->handleWheres($wheres); $sql = "SELECT COUNT(*) AS total FROM {$table} WHERE {$where}"; $result = $this->fetchObject($sql, $bindings); return $result ? (int)$result->total : 0; }
[ "public", "function", "count", "(", "string", "$", "table", ",", "$", "wheres", ")", "{", "list", "(", "$", "where", ",", "$", "bindings", ")", "=", "$", "this", "->", "handleWheres", "(", "$", "wheres", ")", ";", "$", "sql", "=", "\"SELECT COUNT(*) ...
count ``` $db->count(); ``` @param string $table @param array|string $wheres @return int @throws \RuntimeException
[ "count", "$db", "-", ">", "count", "()", ";" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L477-L485
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.exists
public function exists($statement, array $bindings = []) { $sql = sprintf('SELECT EXISTS(%s) AS `exists`', $statement); $result = $this->fetchObject($sql, $bindings); return $result ? $result->exists : 0; }
php
public function exists($statement, array $bindings = []) { $sql = sprintf('SELECT EXISTS(%s) AS `exists`', $statement); $result = $this->fetchObject($sql, $bindings); return $result ? $result->exists : 0; }
[ "public", "function", "exists", "(", "$", "statement", ",", "array", "$", "bindings", "=", "[", "]", ")", "{", "$", "sql", "=", "sprintf", "(", "'SELECT EXISTS(%s) AS `exists`'", ",", "$", "statement", ")", ";", "$", "result", "=", "$", "this", "->", "...
exists ``` $db->exists(); // SQL: select exists(select * from `table` where (`phone` = 152xxx)) as `exists`; ``` @param $statement @param array $bindings @return int
[ "exists", "$db", "-", ">", "exists", "()", ";", "//", "SQL", ":", "select", "exists", "(", "select", "*", "from", "table", "where", "(", "phone", "=", "152xxx", "))", "as", "exists", ";" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L497-L504
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.fetchValues
public function fetchValues(string $statement, array $bindings = [], $indexKey = null) { $data = []; $sth = $this->execute($statement, $bindings); while ($row = $sth->fetch(PDO::FETCH_NUM)) { if ($indexKey) { $data[$row[$indexKey]] = $row; } else { $data[] = $row; } } $this->freeResource($sth); return $data; }
php
public function fetchValues(string $statement, array $bindings = [], $indexKey = null) { $data = []; $sth = $this->execute($statement, $bindings); while ($row = $sth->fetch(PDO::FETCH_NUM)) { if ($indexKey) { $data[$row[$indexKey]] = $row; } else { $data[] = $row; } } $this->freeResource($sth); return $data; }
[ "public", "function", "fetchValues", "(", "string", "$", "statement", ",", "array", "$", "bindings", "=", "[", "]", ",", "$", "indexKey", "=", "null", ")", "{", "$", "data", "=", "[", "]", ";", "$", "sth", "=", "$", "this", "->", "execute", "(", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L650-L666
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.fetchColumns
public function fetchColumns(string $statement, array $bindings = [], int $columnNum = 0) { $sth = $this->execute($statement, $bindings); $column = $sth->fetchAll(PDO::FETCH_COLUMN, $columnNum); $this->freeResource($sth); return $column; }
php
public function fetchColumns(string $statement, array $bindings = [], int $columnNum = 0) { $sth = $this->execute($statement, $bindings); $column = $sth->fetchAll(PDO::FETCH_COLUMN, $columnNum); $this->freeResource($sth); return $column; }
[ "public", "function", "fetchColumns", "(", "string", "$", "statement", ",", "array", "$", "bindings", "=", "[", "]", ",", "int", "$", "columnNum", "=", "0", ")", "{", "$", "sth", "=", "$", "this", "->", "execute", "(", "$", "statement", ",", "$", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L671-L679
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.fetchObjects
public function fetchObjects( string $statement, array $bindings = [], $class = 'stdClass', $indexKey = null, array $args = [] ) { $data = []; $sth = $this->execute($statement, $bindings); // if (!empty($args)) { // $result = $sth->fetchAll(PDO::FETCH_CLASS, $class, $args); // } else { // $result = $sth->fetchAll(PDO::FETCH_CLASS, $class); // } while ($row = $sth->fetchObject($class, $args)) { if ($indexKey) { $data[$row->$indexKey] = $row; } else { $data[] = $row; } } $this->freeResource($sth); return $data; }
php
public function fetchObjects( string $statement, array $bindings = [], $class = 'stdClass', $indexKey = null, array $args = [] ) { $data = []; $sth = $this->execute($statement, $bindings); // if (!empty($args)) { // $result = $sth->fetchAll(PDO::FETCH_CLASS, $class, $args); // } else { // $result = $sth->fetchAll(PDO::FETCH_CLASS, $class); // } while ($row = $sth->fetchObject($class, $args)) { if ($indexKey) { $data[$row->$indexKey] = $row; } else { $data[] = $row; } } $this->freeResource($sth); return $data; }
[ "public", "function", "fetchObjects", "(", "string", "$", "statement", ",", "array", "$", "bindings", "=", "[", "]", ",", "$", "class", "=", "'stdClass'", ",", "$", "indexKey", "=", "null", ",", "array", "$", "args", "=", "[", "]", ")", "{", "$", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L684-L711
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.ping
public function ping() { try { $this->connect(); $this->pdo->query('select 1')->fetchColumn(); } catch (\PDOException $e) { if (strpos($e->getMessage(), 'server has gone away') !== false) { return false; } } return true; }
php
public function ping() { try { $this->connect(); $this->pdo->query('select 1')->fetchColumn(); } catch (\PDOException $e) { if (strpos($e->getMessage(), 'server has gone away') !== false) { return false; } } return true; }
[ "public", "function", "ping", "(", ")", "{", "try", "{", "$", "this", "->", "connect", "(", ")", ";", "$", "this", "->", "pdo", "->", "query", "(", "'select 1'", ")", "->", "fetchColumn", "(", ")", ";", "}", "catch", "(", "\\", "PDOException", "$",...
Check whether the connection is available @return bool @throws \PDOException @throws \RuntimeException
[ "Check", "whether", "the", "connection", "is", "available" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L1025-L1037
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.handleWheres
public function handleWheres($wheres) { if (\is_object($wheres) && $wheres instanceof \Closure) { $wheres = $wheres($this); } if (!$wheres || $wheres === 1) { return [1, []]; } if (\is_string($wheres)) { return [$wheres, []]; } $nodes = $bindings = []; if (\is_array($wheres)) { foreach ($wheres as $key => $val) { if (\is_object($val) && $val instanceof \Closure) { $val = $val($this); } $key = trim($key); // string key: $key is column name, $val is column value if ($key && !is_numeric($key)) { $nodes[] = 'AND ' . $this->qn($key) . '= ?'; $bindings[] = $val; // array: [column, operator(e.g '=', '>=', 'IN'), value, option(Is optional, e.g 'AND', 'OR')] } elseif (\is_array($val)) { if (!isset($val[2])) { throw new \RuntimeException('Where condition data is incomplete, at least 3 elements'); } $bool = $val[3] ?? 'AND'; $nodes[] = strtoupper($bool) . ' ' . $this->qn($val[0]) . " {$val[1]} ?"; $bindings[] = $val[2]; } else { $val = trim((string)$val); $nodes[] = preg_match('/^and |or /i', $val) ? $val : 'AND ' . $val; } } } $where = implode(' ', $nodes); unset($nodes); return [$this->removeLeadingBoolean($where), $bindings]; }
php
public function handleWheres($wheres) { if (\is_object($wheres) && $wheres instanceof \Closure) { $wheres = $wheres($this); } if (!$wheres || $wheres === 1) { return [1, []]; } if (\is_string($wheres)) { return [$wheres, []]; } $nodes = $bindings = []; if (\is_array($wheres)) { foreach ($wheres as $key => $val) { if (\is_object($val) && $val instanceof \Closure) { $val = $val($this); } $key = trim($key); // string key: $key is column name, $val is column value if ($key && !is_numeric($key)) { $nodes[] = 'AND ' . $this->qn($key) . '= ?'; $bindings[] = $val; // array: [column, operator(e.g '=', '>=', 'IN'), value, option(Is optional, e.g 'AND', 'OR')] } elseif (\is_array($val)) { if (!isset($val[2])) { throw new \RuntimeException('Where condition data is incomplete, at least 3 elements'); } $bool = $val[3] ?? 'AND'; $nodes[] = strtoupper($bool) . ' ' . $this->qn($val[0]) . " {$val[1]} ?"; $bindings[] = $val[2]; } else { $val = trim((string)$val); $nodes[] = preg_match('/^and |or /i', $val) ? $val : 'AND ' . $val; } } } $where = implode(' ', $nodes); unset($nodes); return [$this->removeLeadingBoolean($where), $bindings]; }
[ "public", "function", "handleWheres", "(", "$", "wheres", ")", "{", "if", "(", "\\", "is_object", "(", "$", "wheres", ")", "&&", "$", "wheres", "instanceof", "\\", "Closure", ")", "{", "$", "wheres", "=", "$", "wheres", "(", "$", "this", ")", ";", ...
handle where condition @param array|string|\Closure $wheres @example ``` ... $result = $db->findAll('user', [ 'userId' => 23, // ==> 'AND `userId` = 23' 'title' => 'test', // value will auto add quote, equal to "AND title = 'test'" ['publishTime', '>', '0'], // ==> 'AND `publishTime` > 0' ['createdAt', '<=', 1345665427, 'OR'], // ==> 'OR `createdAt` <= 1345665427' ['id', 'IN' ,[4,5,56]], // ==> '`id` IN ('4','5','56')' ['id', 'NOT IN', [4,5,56]], // ==> '`id` NOT IN ('4','5','56')' // a closure function () { return 'a < 5 OR b > 6'; } ]); ``` @return array @throws \RuntimeException
[ "handle", "where", "condition", "@param", "array|string|", "\\", "Closure", "$wheres", "@example", "...", "$result", "=", "$db", "-", ">", "findAll", "(", "user", "[", "userId", "=", ">", "23", "//", "==", ">", "AND", "userId", "=", "23", "title", "=", ...
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L1062-L1111
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.initQuoteNameChar
protected function initQuoteNameChar($driver) { switch ($driver) { case 'mysql': $this->quoteNamePrefix = '`'; $this->quoteNameSuffix = '`'; $this->quoteNameEscapeChar = '`'; $this->quoteNameEscapeReplace = '``'; return; case 'sqlsrv': $this->quoteNamePrefix = '['; $this->quoteNameSuffix = ']'; $this->quoteNameEscapeChar = ']'; $this->quoteNameEscapeReplace = ']['; return; default: $this->quoteNamePrefix = '"'; $this->quoteNameSuffix = '"'; $this->quoteNameEscapeChar = '"'; $this->quoteNameEscapeReplace = '""'; return; } }
php
protected function initQuoteNameChar($driver) { switch ($driver) { case 'mysql': $this->quoteNamePrefix = '`'; $this->quoteNameSuffix = '`'; $this->quoteNameEscapeChar = '`'; $this->quoteNameEscapeReplace = '``'; return; case 'sqlsrv': $this->quoteNamePrefix = '['; $this->quoteNameSuffix = ']'; $this->quoteNameEscapeChar = ']'; $this->quoteNameEscapeReplace = ']['; return; default: $this->quoteNamePrefix = '"'; $this->quoteNameSuffix = '"'; $this->quoteNameEscapeChar = '"'; $this->quoteNameEscapeReplace = '""'; return; } }
[ "protected", "function", "initQuoteNameChar", "(", "$", "driver", ")", "{", "switch", "(", "$", "driver", ")", "{", "case", "'mysql'", ":", "$", "this", "->", "quoteNamePrefix", "=", "'`'", ";", "$", "this", "->", "quoteNameSuffix", "=", "'`'", ";", "$",...
{@inheritdoc}
[ "{" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L1321-L1346
inhere/php-librarys
src/Components/DatabaseClient.php
DatabaseClient.query
public function query($statement, ...$fetch) { $this->connect(); // trigger before event $this->fire(self::BEFORE_EXECUTE, [$statement, 'query']); $sth = $this->pdo->query($this->replaceTablePrefix($statement), ...$fetch); // trigger after event $this->fire(self::AFTER_EXECUTE, [$statement, 'query']); return $sth; }
php
public function query($statement, ...$fetch) { $this->connect(); // trigger before event $this->fire(self::BEFORE_EXECUTE, [$statement, 'query']); $sth = $this->pdo->query($this->replaceTablePrefix($statement), ...$fetch); // trigger after event $this->fire(self::AFTER_EXECUTE, [$statement, 'query']); return $sth; }
[ "public", "function", "query", "(", "$", "statement", ",", "...", "$", "fetch", ")", "{", "$", "this", "->", "connect", "(", ")", ";", "// trigger before event", "$", "this", "->", "fire", "(", "self", "::", "BEFORE_EXECUTE", ",", "[", "$", "statement", ...
{@inheritDoc} @return PDOStatement @throws \PDOException @throws \RuntimeException
[ "{" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/DatabaseClient.php#L1407-L1420
php-lug/lug
src/Bundle/GridBundle/Form/Type/Filter/BooleanFilterType.php
BooleanFilterType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->addModelTransformer($this->booleanFilterTransformer) ->addEventSubscriber($this->booleanFilterSubscriber); }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->addModelTransformer($this->booleanFilterTransformer) ->addEventSubscriber($this->booleanFilterSubscriber); }
[ "public", "function", "buildForm", "(", "FormBuilderInterface", "$", "builder", ",", "array", "$", "options", ")", "{", "$", "builder", "->", "addModelTransformer", "(", "$", "this", "->", "booleanFilterTransformer", ")", "->", "addEventSubscriber", "(", "$", "t...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Form/Type/Filter/BooleanFilterType.php#L51-L56
php-lug/lug
src/Bundle/GridBundle/Form/Type/Filter/BooleanFilterType.php
BooleanFilterType.configureOptions
public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setDefaults([ 'choices' => function (Options $options) { return array_combine( array_map(function ($choice) use ($options) { return $options['label_prefix'].'.'.$choice; }, $choices = ['true', 'false']), $choices ); }, 'choices_as_values' => true, 'placeholder' => '', ]); }
php
public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setDefaults([ 'choices' => function (Options $options) { return array_combine( array_map(function ($choice) use ($options) { return $options['label_prefix'].'.'.$choice; }, $choices = ['true', 'false']), $choices ); }, 'choices_as_values' => true, 'placeholder' => '', ]); }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", "{", "parent", "::", "configureOptions", "(", "$", "resolver", ")", ";", "$", "resolver", "->", "setDefaults", "(", "[", "'choices'", "=>", "function", "(", "Options", "$",...
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Form/Type/Filter/BooleanFilterType.php#L61-L77
gordalina/mangopay-php
src/Gordalina/Mangopay/Model/User.php
User.setPersonType
public function setPersonType($PersonType) { switch ($PersonType) { case static::NATURAL_PERSON: case static::LEGAL_PERSONALITY: $this->PersonType = $PersonType; break; default: throw new \InvalidArgumentException(sprintf('Invalid person type: %s', $PersonType)); } return $this; }
php
public function setPersonType($PersonType) { switch ($PersonType) { case static::NATURAL_PERSON: case static::LEGAL_PERSONALITY: $this->PersonType = $PersonType; break; default: throw new \InvalidArgumentException(sprintf('Invalid person type: %s', $PersonType)); } return $this; }
[ "public", "function", "setPersonType", "(", "$", "PersonType", ")", "{", "switch", "(", "$", "PersonType", ")", "{", "case", "static", "::", "NATURAL_PERSON", ":", "case", "static", "::", "LEGAL_PERSONALITY", ":", "$", "this", "->", "PersonType", "=", "$", ...
Immutable field @param string $PersonType @return User
[ "Immutable", "field" ]
train
https://github.com/gordalina/mangopay-php/blob/6807992416d964e25670d961b66dbccd7a46ef62/src/Gordalina/Mangopay/Model/User.php#L316-L329
gordalina/mangopay-php
src/Gordalina/Mangopay/Model/User.php
User.setPersonalWalletAmount
public function setPersonalWalletAmount($PersonalWalletAmount) { if ($PersonalWalletAmount < 0) { throw new \InvalidArgumentException(sprintf('Wallet amount cannot be negative: %d', $PersonalWalletAmount)); } $this->PersonalWalletAmount = (integer) $PersonalWalletAmount; return $this; }
php
public function setPersonalWalletAmount($PersonalWalletAmount) { if ($PersonalWalletAmount < 0) { throw new \InvalidArgumentException(sprintf('Wallet amount cannot be negative: %d', $PersonalWalletAmount)); } $this->PersonalWalletAmount = (integer) $PersonalWalletAmount; return $this; }
[ "public", "function", "setPersonalWalletAmount", "(", "$", "PersonalWalletAmount", ")", "{", "if", "(", "$", "PersonalWalletAmount", "<", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Wallet amount cannot be negative: %d'", ",...
Immutable field @param integer $PersonalWalletAmount @return User
[ "Immutable", "field" ]
train
https://github.com/gordalina/mangopay-php/blob/6807992416d964e25670d961b66dbccd7a46ef62/src/Gordalina/Mangopay/Model/User.php#L337-L346
songshenzong/log
src/ServiceProvider.php
ServiceProvider.register
public function register() { $this->app->alias( 'Songshenzong\Log\DataFormatter\DataFormatter', 'Songshenzong\Log\DataFormatter\DataFormatterInterface' ); $this->app->singleton('songshenzongLog', function ($app) { $debugbar = new LaravelDebugbar($app); if ($app->bound(SessionManager::class)) { $sessionManager = $app->make(SessionManager::class); $httpDriver = new SymfonyHttpDriver($sessionManager); $debugbar->setHttpDriver($httpDriver); } return $debugbar; }); $this->app->alias('songshenzongLog', 'Songshenzong\Log\LaravelDebugbar'); }
php
public function register() { $this->app->alias( 'Songshenzong\Log\DataFormatter\DataFormatter', 'Songshenzong\Log\DataFormatter\DataFormatterInterface' ); $this->app->singleton('songshenzongLog', function ($app) { $debugbar = new LaravelDebugbar($app); if ($app->bound(SessionManager::class)) { $sessionManager = $app->make(SessionManager::class); $httpDriver = new SymfonyHttpDriver($sessionManager); $debugbar->setHttpDriver($httpDriver); } return $debugbar; }); $this->app->alias('songshenzongLog', 'Songshenzong\Log\LaravelDebugbar'); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "app", "->", "alias", "(", "'Songshenzong\\Log\\DataFormatter\\DataFormatter'", ",", "'Songshenzong\\Log\\DataFormatter\\DataFormatterInterface'", ")", ";", "$", "this", "->", "app", "->", "singleton", ...
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/songshenzong/log/blob/b1e01f7994da47737866eabf82367490eab17c46/src/ServiceProvider.php#L34-L54
songshenzong/log
src/ServiceProvider.php
ServiceProvider.isEnabled
public function isEnabled() { if ($this->enabled === null) { $environments = config('songshenzong-log.env', ['dev', 'local', 'production']); $this->enabled = in_array(env('APP_ENV'), $environments, true); } return $this->enabled; }
php
public function isEnabled() { if ($this->enabled === null) { $environments = config('songshenzong-log.env', ['dev', 'local', 'production']); $this->enabled = in_array(env('APP_ENV'), $environments, true); } return $this->enabled; }
[ "public", "function", "isEnabled", "(", ")", "{", "if", "(", "$", "this", "->", "enabled", "===", "null", ")", "{", "$", "environments", "=", "config", "(", "'songshenzong-log.env'", ",", "[", "'dev'", ",", "'local'", ",", "'production'", "]", ")", ";", ...
Check if is enabled @return boolean
[ "Check", "if", "is", "enabled" ]
train
https://github.com/songshenzong/log/blob/b1e01f7994da47737866eabf82367490eab17c46/src/ServiceProvider.php#L62-L70
songshenzong/log
src/ServiceProvider.php
ServiceProvider.boot
public function boot() { $this->publishes([ __DIR__ . '/../config/songshenzong-log.php' => config_path('songshenzong-log.php') ], 'config'); if (!$this->isEnabled()) { return; } $kernel = $this->app->make(Kernel::class); $kernel->prependMiddleware(Middleware::class); $routeConfig = [ 'namespace' => 'Songshenzong\Log\Controllers', 'prefix' => config('songshenzong-log.route_prefix', 'songshenzong/log'), ]; app('router')->group($routeConfig, function ($router) { $router->get('', 'WebController@index'); $router->get('login', 'WebController@login'); $router->get('api/login', 'ApiController@login'); $router->group(['middleware' => 'Songshenzong\Log\TokenMiddleware'], function ($router) { $router->get('logs', 'ApiController@getList'); $router->get('logs/{id}', 'ApiController@getItem')->where('id', '[0-9\.]+'); $router->get('destroy', 'ApiController@destroy'); $router->get('create', 'ApiController@createTable'); $router->get('collect/status', 'ApiController@getOrSetCollectStatus'); $router->get('table/status', 'ApiController@getTableStatus'); }); }); if (app()->runningInConsole() || app()->environment('testing')) { return; } app('songshenzongLog')->enable(); app('songshenzongLog')->boot(); }
php
public function boot() { $this->publishes([ __DIR__ . '/../config/songshenzong-log.php' => config_path('songshenzong-log.php') ], 'config'); if (!$this->isEnabled()) { return; } $kernel = $this->app->make(Kernel::class); $kernel->prependMiddleware(Middleware::class); $routeConfig = [ 'namespace' => 'Songshenzong\Log\Controllers', 'prefix' => config('songshenzong-log.route_prefix', 'songshenzong/log'), ]; app('router')->group($routeConfig, function ($router) { $router->get('', 'WebController@index'); $router->get('login', 'WebController@login'); $router->get('api/login', 'ApiController@login'); $router->group(['middleware' => 'Songshenzong\Log\TokenMiddleware'], function ($router) { $router->get('logs', 'ApiController@getList'); $router->get('logs/{id}', 'ApiController@getItem')->where('id', '[0-9\.]+'); $router->get('destroy', 'ApiController@destroy'); $router->get('create', 'ApiController@createTable'); $router->get('collect/status', 'ApiController@getOrSetCollectStatus'); $router->get('table/status', 'ApiController@getTableStatus'); }); }); if (app()->runningInConsole() || app()->environment('testing')) { return; } app('songshenzongLog')->enable(); app('songshenzongLog')->boot(); }
[ "public", "function", "boot", "(", ")", "{", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../config/songshenzong-log.php'", "=>", "config_path", "(", "'songshenzong-log.php'", ")", "]", ",", "'config'", ")", ";", "if", "(", "!", "$", "this", ...
Bootstrap the application events. @return void
[ "Bootstrap", "the", "application", "events", "." ]
train
https://github.com/songshenzong/log/blob/b1e01f7994da47737866eabf82367490eab17c46/src/ServiceProvider.php#L78-L120
petrica/php-statsd-system
Gauge/ProcessesGauge.php
ProcessesGauge.getCollection
public function getCollection() { $processes = $this->getProcesses(); $cpu = $this->aggregateCpu($processes); $cpu = $this->filterAbove($cpu, $this->cpuAbove); $memory = $this->aggregateMemory($processes); $memory = $this->filterAbove($memory, $this->memoryAbove); // Get previous values saved $collection = $this->retrieveCollection(); $this->resetValues($collection); foreach ($cpu as $name => $value) { $collection->add($name . '.cpu.value', $value); } foreach ($memory as $name => $value) { $collection->add($name . '.memory.value', $value); } // Persist collection to a temporary storage $copyCollection = new ValuesCollection($collection->getValues()); $this->removeEmpty($copyCollection); $this->persistCollection($copyCollection); return $collection; }
php
public function getCollection() { $processes = $this->getProcesses(); $cpu = $this->aggregateCpu($processes); $cpu = $this->filterAbove($cpu, $this->cpuAbove); $memory = $this->aggregateMemory($processes); $memory = $this->filterAbove($memory, $this->memoryAbove); // Get previous values saved $collection = $this->retrieveCollection(); $this->resetValues($collection); foreach ($cpu as $name => $value) { $collection->add($name . '.cpu.value', $value); } foreach ($memory as $name => $value) { $collection->add($name . '.memory.value', $value); } // Persist collection to a temporary storage $copyCollection = new ValuesCollection($collection->getValues()); $this->removeEmpty($copyCollection); $this->persistCollection($copyCollection); return $collection; }
[ "public", "function", "getCollection", "(", ")", "{", "$", "processes", "=", "$", "this", "->", "getProcesses", "(", ")", ";", "$", "cpu", "=", "$", "this", "->", "aggregateCpu", "(", "$", "processes", ")", ";", "$", "cpu", "=", "$", "this", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/ProcessesGauge.php#L63-L91
petrica/php-statsd-system
Gauge/ProcessesGauge.php
ProcessesGauge.getProcesses
protected function getProcesses() { $data = $this->getCommand()->run(); $parser = new TopProcessParser($data); $parser->parse(); return $parser->getProcesses(); }
php
protected function getProcesses() { $data = $this->getCommand()->run(); $parser = new TopProcessParser($data); $parser->parse(); return $parser->getProcesses(); }
[ "protected", "function", "getProcesses", "(", ")", "{", "$", "data", "=", "$", "this", "->", "getCommand", "(", ")", "->", "run", "(", ")", ";", "$", "parser", "=", "new", "TopProcessParser", "(", "$", "data", ")", ";", "$", "parser", "->", "parse", ...
Return parsed data for processes
[ "Return", "parsed", "data", "for", "processes" ]
train
https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/ProcessesGauge.php#L96-L104
petrica/php-statsd-system
Gauge/ProcessesGauge.php
ProcessesGauge.aggregateCpu
protected function aggregateCpu($processes) { $cpus = array(); foreach ($processes as $process) { if (isset($cpus[$process->getName()])) { $cpus[$process->getName()] += $process->getCpu(); } else { $cpus[$process->getName()] = $process->getCpu(); } } return $cpus; }
php
protected function aggregateCpu($processes) { $cpus = array(); foreach ($processes as $process) { if (isset($cpus[$process->getName()])) { $cpus[$process->getName()] += $process->getCpu(); } else { $cpus[$process->getName()] = $process->getCpu(); } } return $cpus; }
[ "protected", "function", "aggregateCpu", "(", "$", "processes", ")", "{", "$", "cpus", "=", "array", "(", ")", ";", "foreach", "(", "$", "processes", "as", "$", "process", ")", "{", "if", "(", "isset", "(", "$", "cpus", "[", "$", "process", "->", "...
Aggregate CPU for processes with the same name @param $processes Process[]
[ "Aggregate", "CPU", "for", "processes", "with", "the", "same", "name" ]
train
https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/ProcessesGauge.php#L124-L138
petrica/php-statsd-system
Gauge/ProcessesGauge.php
ProcessesGauge.aggregateMemory
protected function aggregateMemory($processes) { $memory = array(); foreach ($processes as $process) { if (isset($memory[$process->getName()])) { $memory[$process->getName()] += $process->getMemory(); } else { $memory[$process->getName()] = $process->getMemory(); } } return $memory; }
php
protected function aggregateMemory($processes) { $memory = array(); foreach ($processes as $process) { if (isset($memory[$process->getName()])) { $memory[$process->getName()] += $process->getMemory(); } else { $memory[$process->getName()] = $process->getMemory(); } } return $memory; }
[ "protected", "function", "aggregateMemory", "(", "$", "processes", ")", "{", "$", "memory", "=", "array", "(", ")", ";", "foreach", "(", "$", "processes", "as", "$", "process", ")", "{", "if", "(", "isset", "(", "$", "memory", "[", "$", "process", "-...
Aggregate memory for processes with the same name @param $processes Process[] @return array
[ "Aggregate", "memory", "for", "processes", "with", "the", "same", "name" ]
train
https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/ProcessesGauge.php#L146-L160
petrica/php-statsd-system
Gauge/ProcessesGauge.php
ProcessesGauge.persistCollection
protected function persistCollection($collection) { $cache = new FilesystemAdapter($this->namespace); $item = $cache->getItem('collection'); $item->set($collection); $cache->save($item); }
php
protected function persistCollection($collection) { $cache = new FilesystemAdapter($this->namespace); $item = $cache->getItem('collection'); $item->set($collection); $cache->save($item); }
[ "protected", "function", "persistCollection", "(", "$", "collection", ")", "{", "$", "cache", "=", "new", "FilesystemAdapter", "(", "$", "this", "->", "namespace", ")", ";", "$", "item", "=", "$", "cache", "->", "getItem", "(", "'collection'", ")", ";", ...
Persist collection values to a temporary storage key is the command string value @param $collection
[ "Persist", "collection", "values", "to", "a", "temporary", "storage", "key", "is", "the", "command", "string", "value" ]
train
https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/ProcessesGauge.php#L178-L184
petrica/php-statsd-system
Gauge/ProcessesGauge.php
ProcessesGauge.retrieveCollection
protected function retrieveCollection() { $cache = new FilesystemAdapter($this->namespace); $item = $cache->getItem('collection'); $collection = null; if ($item->isHit()) { $collection = $item->get('collection'); } if (empty($collection) || !$collection instanceof ValuesCollection) { $collection = new ValuesCollection(); } return $collection; }
php
protected function retrieveCollection() { $cache = new FilesystemAdapter($this->namespace); $item = $cache->getItem('collection'); $collection = null; if ($item->isHit()) { $collection = $item->get('collection'); } if (empty($collection) || !$collection instanceof ValuesCollection) { $collection = new ValuesCollection(); } return $collection; }
[ "protected", "function", "retrieveCollection", "(", ")", "{", "$", "cache", "=", "new", "FilesystemAdapter", "(", "$", "this", "->", "namespace", ")", ";", "$", "item", "=", "$", "cache", "->", "getItem", "(", "'collection'", ")", ";", "$", "collection", ...
\ Retrieve a new collection of a previous collection @return mixed|ValuesCollection
[ "\\", "Retrieve", "a", "new", "collection", "of", "a", "previous", "collection" ]
train
https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/ProcessesGauge.php#L191-L206
petrica/php-statsd-system
Gauge/ProcessesGauge.php
ProcessesGauge.removeEmpty
protected function removeEmpty($collection) { foreach ($collection as $key => $value) { if (empty($value)) { unset($collection[$key]); } } return $collection; }
php
protected function removeEmpty($collection) { foreach ($collection as $key => $value) { if (empty($value)) { unset($collection[$key]); } } return $collection; }
[ "protected", "function", "removeEmpty", "(", "$", "collection", ")", "{", "foreach", "(", "$", "collection", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "empty", "(", "$", "value", ")", ")", "{", "unset", "(", "$", "collection", "[", ...
Remove empty values from collection @param $collection
[ "Remove", "empty", "values", "from", "collection" ]
train
https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/ProcessesGauge.php#L228-L236
raideer/twitch-api
src/Resources/Teams.php
Teams.getTeams
public function getTeams($params = []) { $defaults = [ 'limit' => 25, 'offset' => 0, ]; return $this->wrapper->request('GET', 'teams', ['query' => $this->resolveOptions($params, $defaults)]); }
php
public function getTeams($params = []) { $defaults = [ 'limit' => 25, 'offset' => 0, ]; return $this->wrapper->request('GET', 'teams', ['query' => $this->resolveOptions($params, $defaults)]); }
[ "public", "function", "getTeams", "(", "$", "params", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'limit'", "=>", "25", ",", "'offset'", "=>", "0", ",", "]", ";", "return", "$", "this", "->", "wrapper", "->", "request", "(", "'GET'", ",", ...
Returns a list of active teams. Learn more: https://github.com/justintv/Twitch-API/blob/master/v3_resources/teams.md#get-teams @param array $params Optiona params @return array
[ "Returns", "a", "list", "of", "active", "teams", "." ]
train
https://github.com/raideer/twitch-api/blob/27ebf1dcb0315206300d507600b6a82ebe33d57e/src/Resources/Teams.php#L30-L38
moneymaxim/TrustpilotAuthenticator
src/Authenticator.php
Authenticator.getAccessToken
public function getAccessToken($apiKey, $apiSecret, $username, $password) { $response = $this->guzzle->request('POST', self::ENDPOINT, [ 'auth' => [$apiKey, $apiSecret], 'form_params' => [ 'grant_type' => 'password', 'username' => $username, 'password' => $password, ], ]); $data = json_decode((string) $response->getBody(), true); $token = $data['access_token']; $expiry = new \DateTime('@' . (time() + $data['expires_in'])); return new AccessToken($token, $expiry); }
php
public function getAccessToken($apiKey, $apiSecret, $username, $password) { $response = $this->guzzle->request('POST', self::ENDPOINT, [ 'auth' => [$apiKey, $apiSecret], 'form_params' => [ 'grant_type' => 'password', 'username' => $username, 'password' => $password, ], ]); $data = json_decode((string) $response->getBody(), true); $token = $data['access_token']; $expiry = new \DateTime('@' . (time() + $data['expires_in'])); return new AccessToken($token, $expiry); }
[ "public", "function", "getAccessToken", "(", "$", "apiKey", ",", "$", "apiSecret", ",", "$", "username", ",", "$", "password", ")", "{", "$", "response", "=", "$", "this", "->", "guzzle", "->", "request", "(", "'POST'", ",", "self", "::", "ENDPOINT", "...
@param string $apiKey @param string $apiSecret @param string $username @param string $password @return AccessToken
[ "@param", "string", "$apiKey", "@param", "string", "$apiSecret", "@param", "string", "$username", "@param", "string", "$password" ]
train
https://github.com/moneymaxim/TrustpilotAuthenticator/blob/701b60040542c5d32f6ef2eb55e66b57d66021d1/src/Authenticator.php#L33-L50
hametuha/wpametu
src/WPametu/UI/Field/Text.php
Text.build_input
protected function build_input($data, array $fields = [] ){ return parent::build_input($data, $fields).$this->length_helper($data); }
php
protected function build_input($data, array $fields = [] ){ return parent::build_input($data, $fields).$this->length_helper($data); }
[ "protected", "function", "build_input", "(", "$", "data", ",", "array", "$", "fields", "=", "[", "]", ")", "{", "return", "parent", "::", "build_input", "(", "$", "data", ",", "$", "fields", ")", ".", "$", "this", "->", "length_helper", "(", "$", "da...
Return input field @param mixed $data @param array $fields @return string
[ "Return", "input", "field" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Text.php#L46-L48
hametuha/wpametu
src/WPametu/UI/Field/Text.php
Text.length_helper
protected function length_helper($data){ if ( ($this->min || $this->max) && $this->length_helper ){ $notice = []; $class_name = 'ok'; if( $this->min ){ $notice[] = sprintf($this->__('%s chars or more'), number_format($this->min)); if( $this->min > mb_strlen($data, 'utf-8') ){ $class_name = 'ng'; } } if( $this->max ){ $notice[] = sprintf($this->__('%s chars or less'), number_format($this->max)); if( $this->max < mb_strlen($data, 'utf-8') ){ $class_name = 'ng'; } } return sprintf('<p class="char-counter %s"><i class="dashicons"></i> <strong>%s</strong><span> %s</span><small>%s</small></p>', $class_name, mb_strlen($data, 'utf-8'), $this->__('Letters'), implode(', ', $notice)); }else{ return ''; } }
php
protected function length_helper($data){ if ( ($this->min || $this->max) && $this->length_helper ){ $notice = []; $class_name = 'ok'; if( $this->min ){ $notice[] = sprintf($this->__('%s chars or more'), number_format($this->min)); if( $this->min > mb_strlen($data, 'utf-8') ){ $class_name = 'ng'; } } if( $this->max ){ $notice[] = sprintf($this->__('%s chars or less'), number_format($this->max)); if( $this->max < mb_strlen($data, 'utf-8') ){ $class_name = 'ng'; } } return sprintf('<p class="char-counter %s"><i class="dashicons"></i> <strong>%s</strong><span> %s</span><small>%s</small></p>', $class_name, mb_strlen($data, 'utf-8'), $this->__('Letters'), implode(', ', $notice)); }else{ return ''; } }
[ "protected", "function", "length_helper", "(", "$", "data", ")", "{", "if", "(", "(", "$", "this", "->", "min", "||", "$", "this", "->", "max", ")", "&&", "$", "this", "->", "length_helper", ")", "{", "$", "notice", "=", "[", "]", ";", "$", "clas...
Returns length helper @param string $data @return string
[ "Returns", "length", "helper" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Text.php#L56-L78
hametuha/wpametu
src/WPametu/UI/Field/Text.php
Text.validate
protected function validate($value){ if( parent::validate($value) ){ $length = mb_strlen($value, 'utf-8'); if( $this->min && $this->min > $length ){ throw new ValidateException(sprintf($this->__('Fields %s must be %d digits and more.'), $this->label, $this->min)); } if( $this->max && $this->max < $length ){ throw new ValidateException(sprintf($this->__('Fields %s must be %d digits and fewer.'), $this->label, $this->max)); } } return true; }
php
protected function validate($value){ if( parent::validate($value) ){ $length = mb_strlen($value, 'utf-8'); if( $this->min && $this->min > $length ){ throw new ValidateException(sprintf($this->__('Fields %s must be %d digits and more.'), $this->label, $this->min)); } if( $this->max && $this->max < $length ){ throw new ValidateException(sprintf($this->__('Fields %s must be %d digits and fewer.'), $this->label, $this->max)); } } return true; }
[ "protected", "function", "validate", "(", "$", "value", ")", "{", "if", "(", "parent", "::", "validate", "(", "$", "value", ")", ")", "{", "$", "length", "=", "mb_strlen", "(", "$", "value", ",", "'utf-8'", ")", ";", "if", "(", "$", "this", "->", ...
Validator @param mixed $value @return bool @throws \WPametu\Exception\ValidateException
[ "Validator" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Text.php#L106-L117
highday/glitter
src/Audit/Listeners/Member/LogSuccessfulLogout.php
LogSuccessfulLogout.handle
public function handle(Logout $event) { $model = snake_case(class_basename($event->user)); $data = [ 'ip' => request()->ip(), 'ua' => request()->header('User-Agent'), ]; $event->user->log("{$model}.logout", $data); }
php
public function handle(Logout $event) { $model = snake_case(class_basename($event->user)); $data = [ 'ip' => request()->ip(), 'ua' => request()->header('User-Agent'), ]; $event->user->log("{$model}.logout", $data); }
[ "public", "function", "handle", "(", "Logout", "$", "event", ")", "{", "$", "model", "=", "snake_case", "(", "class_basename", "(", "$", "event", "->", "user", ")", ")", ";", "$", "data", "=", "[", "'ip'", "=>", "request", "(", ")", "->", "ip", "("...
Handle the event. @param Logout $event @return void
[ "Handle", "the", "event", "." ]
train
https://github.com/highday/glitter/blob/d1c7a227fd2343806bd3ec0314e621ced57dfe66/src/Audit/Listeners/Member/LogSuccessfulLogout.php#L26-L34
InactiveProjects/limoncello-illuminate
app/Api/Crud.php
Crud.readOnIndex
protected function readOnIndex(Builder $builder, EncodingParametersInterface $parameters = null) { return $this->paginateBuilder($builder, $parameters); }
php
protected function readOnIndex(Builder $builder, EncodingParametersInterface $parameters = null) { return $this->paginateBuilder($builder, $parameters); }
[ "protected", "function", "readOnIndex", "(", "Builder", "$", "builder", ",", "EncodingParametersInterface", "$", "parameters", "=", "null", ")", "{", "return", "$", "this", "->", "paginateBuilder", "(", "$", "builder", ",", "$", "parameters", ")", ";", "}" ]
@noinspection PhpMissingParentCallCommonInspection @inheritdoc @return PagedDataInterface
[ "@noinspection", "PhpMissingParentCallCommonInspection", "@inheritdoc" ]
train
https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Api/Crud.php#L136-L139
InactiveProjects/limoncello-illuminate
app/Api/Crud.php
Crud.indexRelationship
public function indexRelationship($resourceId, $relationshipName, EncodingParametersInterface $parameters) { $resource = $this->read($resourceId); /** @var Relation $relation */ $relation = $resource->{$relationshipName}(); $result = $this->paginateBuilder($relation->getQuery(), $parameters); $this->applyIndexPolicy($result->getData()); return $result; }
php
public function indexRelationship($resourceId, $relationshipName, EncodingParametersInterface $parameters) { $resource = $this->read($resourceId); /** @var Relation $relation */ $relation = $resource->{$relationshipName}(); $result = $this->paginateBuilder($relation->getQuery(), $parameters); $this->applyIndexPolicy($result->getData()); return $result; }
[ "public", "function", "indexRelationship", "(", "$", "resourceId", ",", "$", "relationshipName", ",", "EncodingParametersInterface", "$", "parameters", ")", "{", "$", "resource", "=", "$", "this", "->", "read", "(", "$", "resourceId", ")", ";", "/** @var Relatio...
@param int|string $resourceId @param string $relationshipName @param EncodingParametersInterface $parameters @return PagedDataInterface
[ "@param", "int|string", "$resourceId", "@param", "string", "$relationshipName", "@param", "EncodingParametersInterface", "$parameters" ]
train
https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Api/Crud.php#L148-L160
InactiveProjects/limoncello-illuminate
app/Api/Crud.php
Crud.paginateBuilder
protected function paginateBuilder(Builder $builder, EncodingParametersInterface $parameters) { $pageSize = $this->getPageSize($parameters); $pageNumber = $this->getPageNumber($parameters); $paginator = $builder->paginate($pageSize, ['*'], 'page', $pageNumber); /** @var IlluminateRequest $request */ $request = $this->getContainer()->make(IlluminateRequest::class); $url = $request->url(); $query = $request->query(); $pagedData = $this->getFactory()->createPagingStrategy()->createPagedData($paginator, $url, true, $query); return $pagedData; }
php
protected function paginateBuilder(Builder $builder, EncodingParametersInterface $parameters) { $pageSize = $this->getPageSize($parameters); $pageNumber = $this->getPageNumber($parameters); $paginator = $builder->paginate($pageSize, ['*'], 'page', $pageNumber); /** @var IlluminateRequest $request */ $request = $this->getContainer()->make(IlluminateRequest::class); $url = $request->url(); $query = $request->query(); $pagedData = $this->getFactory()->createPagingStrategy()->createPagedData($paginator, $url, true, $query); return $pagedData; }
[ "protected", "function", "paginateBuilder", "(", "Builder", "$", "builder", ",", "EncodingParametersInterface", "$", "parameters", ")", "{", "$", "pageSize", "=", "$", "this", "->", "getPageSize", "(", "$", "parameters", ")", ";", "$", "pageNumber", "=", "$", ...
@param Builder $builder @param EncodingParametersInterface $parameters @return PagedDataInterface
[ "@param", "Builder", "$builder", "@param", "EncodingParametersInterface", "$parameters" ]
train
https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Api/Crud.php#L168-L182
InactiveProjects/limoncello-illuminate
app/Api/Crud.php
Crud.getPageSize
protected function getPageSize(EncodingParametersInterface $parameters = null) { return $this->getPagingParameter(Request::PARAM_PAGING_SIZE, static::MAX_PAGE_SIZE, $parameters); }
php
protected function getPageSize(EncodingParametersInterface $parameters = null) { return $this->getPagingParameter(Request::PARAM_PAGING_SIZE, static::MAX_PAGE_SIZE, $parameters); }
[ "protected", "function", "getPageSize", "(", "EncodingParametersInterface", "$", "parameters", "=", "null", ")", "{", "return", "$", "this", "->", "getPagingParameter", "(", "Request", "::", "PARAM_PAGING_SIZE", ",", "static", "::", "MAX_PAGE_SIZE", ",", "$", "par...
@param EncodingParametersInterface|null $parameters @return int
[ "@param", "EncodingParametersInterface|null", "$parameters" ]
train
https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Api/Crud.php#L189-L192
InactiveProjects/limoncello-illuminate
app/Api/Crud.php
Crud.getPageNumber
protected function getPageNumber(EncodingParametersInterface $parameters = null) { return $this->getPagingParameter(Request::PARAM_PAGING_NUMBER, null, $parameters); }
php
protected function getPageNumber(EncodingParametersInterface $parameters = null) { return $this->getPagingParameter(Request::PARAM_PAGING_NUMBER, null, $parameters); }
[ "protected", "function", "getPageNumber", "(", "EncodingParametersInterface", "$", "parameters", "=", "null", ")", "{", "return", "$", "this", "->", "getPagingParameter", "(", "Request", "::", "PARAM_PAGING_NUMBER", ",", "null", ",", "$", "parameters", ")", ";", ...
@param EncodingParametersInterface|null $parameters @return int|null
[ "@param", "EncodingParametersInterface|null", "$parameters" ]
train
https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Api/Crud.php#L199-L202
InactiveProjects/limoncello-illuminate
app/Api/Crud.php
Crud.getPagingParameter
protected function getPagingParameter($key, $default, EncodingParametersInterface $parameters = null) { $value = $default; if ($parameters !== null) { $paging = $parameters->getPaginationParameters(); if (empty($paging) === false && array_key_exists($key, $paging) === true) { $tmp = (int)$paging[$key]; $value = $tmp < 0 || $tmp > static::MAX_PAGE_SIZE ? static::MAX_PAGE_SIZE : $tmp; } } return $value; }
php
protected function getPagingParameter($key, $default, EncodingParametersInterface $parameters = null) { $value = $default; if ($parameters !== null) { $paging = $parameters->getPaginationParameters(); if (empty($paging) === false && array_key_exists($key, $paging) === true) { $tmp = (int)$paging[$key]; $value = $tmp < 0 || $tmp > static::MAX_PAGE_SIZE ? static::MAX_PAGE_SIZE : $tmp; } } return $value; }
[ "protected", "function", "getPagingParameter", "(", "$", "key", ",", "$", "default", ",", "EncodingParametersInterface", "$", "parameters", "=", "null", ")", "{", "$", "value", "=", "$", "default", ";", "if", "(", "$", "parameters", "!==", "null", ")", "{"...
@param string $key @param mixed $default @param EncodingParametersInterface|null $parameters @return mixed
[ "@param", "string", "$key", "@param", "mixed", "$default", "@param", "EncodingParametersInterface|null", "$parameters" ]
train
https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Api/Crud.php#L211-L223
InactiveProjects/limoncello-illuminate
app/Api/Crud.php
Crud.createValidator
protected function createValidator(array $data, array $rules) { /** @var Factory $factory */ $factory = app('validator'); $validator = $factory->make($data, $rules); return $validator; }
php
protected function createValidator(array $data, array $rules) { /** @var Factory $factory */ $factory = app('validator'); $validator = $factory->make($data, $rules); return $validator; }
[ "protected", "function", "createValidator", "(", "array", "$", "data", ",", "array", "$", "rules", ")", "{", "/** @var Factory $factory */", "$", "factory", "=", "app", "(", "'validator'", ")", ";", "$", "validator", "=", "$", "factory", "->", "make", "(", ...
@param array $data @param array $rules @return Validator
[ "@param", "array", "$data", "@param", "array", "$rules" ]
train
https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Api/Crud.php#L265-L272
mr-luke/configuration
src/Host.php
Host.get
public function get(string $key, $default = null) { $result = $this->iterateConfig($key); return is_null($result) ? $default : $result; }
php
public function get(string $key, $default = null) { $result = $this->iterateConfig($key); return is_null($result) ? $default : $result; }
[ "public", "function", "get", "(", "string", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "result", "=", "$", "this", "->", "iterateConfig", "(", "$", "key", ")", ";", "return", "is_null", "(", "$", "result", ")", "?", "$", "default"...
Return given key from array. @param string $key @param mixed $default @return mixed
[ "Return", "given", "key", "from", "array", "." ]
train
https://github.com/mr-luke/configuration/blob/487c90011dc15556787785ed60c60ea92655beac/src/Host.php#L43-L48
mr-luke/configuration
src/Host.php
Host.has
public function has(string $key): bool { $result = $this->iterateConfig($key); return !($result === null); }
php
public function has(string $key): bool { $result = $this->iterateConfig($key); return !($result === null); }
[ "public", "function", "has", "(", "string", "$", "key", ")", ":", "bool", "{", "$", "result", "=", "$", "this", "->", "iterateConfig", "(", "$", "key", ")", ";", "return", "!", "(", "$", "result", "===", "null", ")", ";", "}" ]
Return of givent key is present. @param string $key @return boolean
[ "Return", "of", "givent", "key", "is", "present", "." ]
train
https://github.com/mr-luke/configuration/blob/487c90011dc15556787785ed60c60ea92655beac/src/Host.php#L56-L61
mr-luke/configuration
src/Host.php
Host.iterateConfig
protected function iterateConfig(string $key) { $result = $this->config; foreach (explode('.', $key) as $p) { if (!isset($result[$p])) { return null; } $result = $result[$p]; } return $result; }
php
protected function iterateConfig(string $key) { $result = $this->config; foreach (explode('.', $key) as $p) { if (!isset($result[$p])) { return null; } $result = $result[$p]; } return $result; }
[ "protected", "function", "iterateConfig", "(", "string", "$", "key", ")", "{", "$", "result", "=", "$", "this", "->", "config", ";", "foreach", "(", "explode", "(", "'.'", ",", "$", "key", ")", "as", "$", "p", ")", "{", "if", "(", "!", "isset", "...
Iterate through configuration. @param string $key @return mixed
[ "Iterate", "through", "configuration", "." ]
train
https://github.com/mr-luke/configuration/blob/487c90011dc15556787785ed60c60ea92655beac/src/Host.php#L90-L103
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.addMeta
public function addMeta(array $data):SuccessResponseBuilder { $this->meta = array_merge($this->meta, $data); return $this; }
php
public function addMeta(array $data):SuccessResponseBuilder { $this->meta = array_merge($this->meta, $data); return $this; }
[ "public", "function", "addMeta", "(", "array", "$", "data", ")", ":", "SuccessResponseBuilder", "{", "$", "this", "->", "meta", "=", "array_merge", "(", "$", "this", "->", "meta", ",", "$", "data", ")", ";", "return", "$", "this", ";", "}" ]
Add data to the meta data appended to the response data. @param array $data @return self
[ "Add", "data", "to", "the", "meta", "data", "appended", "to", "the", "response", "data", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L92-L97
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.include
public function include($relations):SuccessResponseBuilder { if (is_string($relations)) { $relations = explode(',', $relations); } $this->relations = array_merge($this->relations, (array) $relations); return $this; }
php
public function include($relations):SuccessResponseBuilder { if (is_string($relations)) { $relations = explode(',', $relations); } $this->relations = array_merge($this->relations, (array) $relations); return $this; }
[ "public", "function", "include", "(", "$", "relations", ")", ":", "SuccessResponseBuilder", "{", "if", "(", "is_string", "(", "$", "relations", ")", ")", "{", "$", "relations", "=", "explode", "(", "','", ",", "$", "relations", ")", ";", "}", "$", "thi...
Set the serializer used to serialize the resource data. @param array|string $relations @return self
[ "Set", "the", "serializer", "used", "to", "serialize", "the", "resource", "data", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L105-L114
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.serializer
public function serializer($serializer):SuccessResponseBuilder { $this->manager->setSerializer($this->resolveSerializer($serializer)); return $this; }
php
public function serializer($serializer):SuccessResponseBuilder { $this->manager->setSerializer($this->resolveSerializer($serializer)); return $this; }
[ "public", "function", "serializer", "(", "$", "serializer", ")", ":", "SuccessResponseBuilder", "{", "$", "this", "->", "manager", "->", "setSerializer", "(", "$", "this", "->", "resolveSerializer", "(", "$", "serializer", ")", ")", ";", "return", "$", "this...
Set the serializer used to serialize the resource data. @param \League\Fractal\Serializer\SerializerAbstract|string $serializer @return self
[ "Set", "the", "serializer", "used", "to", "serialize", "the", "resource", "data", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L122-L127
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.transform
public function transform($data = null, $transformer = null, string $resourceKey = null):SuccessResponseBuilder { $resource = $this->resourceFactory->make($data); if (! is_null($resource->getData())) { $model = $this->resolveModel($resource->getData()); $transformer = $this->resolveTransformer($model, $transformer); $resourceKey = $this->resolveResourceKey($model, $resourceKey); } if ($transformer instanceof Transformer) { $this->include($relations = $this->resolveNestedRelations($resource->getData())); if ($transformer->allRelationsAllowed()) { $transformer->setRelations($relations); } } $this->resource = $resource->setTransformer($transformer)->setResourceKey($resourceKey); return $this; }
php
public function transform($data = null, $transformer = null, string $resourceKey = null):SuccessResponseBuilder { $resource = $this->resourceFactory->make($data); if (! is_null($resource->getData())) { $model = $this->resolveModel($resource->getData()); $transformer = $this->resolveTransformer($model, $transformer); $resourceKey = $this->resolveResourceKey($model, $resourceKey); } if ($transformer instanceof Transformer) { $this->include($relations = $this->resolveNestedRelations($resource->getData())); if ($transformer->allRelationsAllowed()) { $transformer->setRelations($relations); } } $this->resource = $resource->setTransformer($transformer)->setResourceKey($resourceKey); return $this; }
[ "public", "function", "transform", "(", "$", "data", "=", "null", ",", "$", "transformer", "=", "null", ",", "string", "$", "resourceKey", "=", "null", ")", ":", "SuccessResponseBuilder", "{", "$", "resource", "=", "$", "this", "->", "resourceFactory", "->...
Set the transformation data. This will set a new resource instance on the response builder depending on what type of data is provided. @param mixed|null $data @param callable|string|null $transformer @param string|null $resourceKey @return self
[ "Set", "the", "transformation", "data", ".", "This", "will", "set", "a", "new", "resource", "instance", "on", "the", "response", "builder", "depending", "on", "what", "type", "of", "data", "is", "provided", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L164-L185
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.getResource
public function getResource():ResourceInterface { $this->manager->parseIncludes($this->relations); $transformer = $this->resource->getTransformer(); if ($transformer instanceof Transformer && $transformer->allRelationsAllowed()) { $this->resource->setTransformer($transformer->setRelations($this->manager->getRequestedIncludes())); } return $this->resource->setMeta($this->meta); }
php
public function getResource():ResourceInterface { $this->manager->parseIncludes($this->relations); $transformer = $this->resource->getTransformer(); if ($transformer instanceof Transformer && $transformer->allRelationsAllowed()) { $this->resource->setTransformer($transformer->setRelations($this->manager->getRequestedIncludes())); } return $this->resource->setMeta($this->meta); }
[ "public", "function", "getResource", "(", ")", ":", "ResourceInterface", "{", "$", "this", "->", "manager", "->", "parseIncludes", "(", "$", "this", "->", "relations", ")", ";", "$", "transformer", "=", "$", "this", "->", "resource", "->", "getTransformer", ...
Get the Fractal resource instance. @return \League\Fractal\Resource\ResourceInterface
[ "Get", "the", "Fractal", "resource", "instance", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L202-L212
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.resolveSerializer
protected function resolveSerializer($serializer):SerializerAbstract { if (is_string($serializer)) { $serializer = new $serializer; } if (! $serializer instanceof SerializerAbstract) { throw new InvalidSerializerException(); } return $serializer; }
php
protected function resolveSerializer($serializer):SerializerAbstract { if (is_string($serializer)) { $serializer = new $serializer; } if (! $serializer instanceof SerializerAbstract) { throw new InvalidSerializerException(); } return $serializer; }
[ "protected", "function", "resolveSerializer", "(", "$", "serializer", ")", ":", "SerializerAbstract", "{", "if", "(", "is_string", "(", "$", "serializer", ")", ")", "{", "$", "serializer", "=", "new", "$", "serializer", ";", "}", "if", "(", "!", "$", "se...
Resolve a serializer instance from the value. @param \League\Fractal\Serializer\SerializerAbstract|string $serializer @return \League\Fractal\Serializer\SerializerAbstract @throws \Flugg\Responder\Exceptions\InvalidSerializerException
[ "Resolve", "a", "serializer", "instance", "from", "the", "value", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L231-L242
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.resolveModel
protected function resolveModel($data):Model { if ($data instanceof Model) { return $data; } $model = array_values($data)[0]; if (! $model instanceof Model) { throw new InvalidArgumentException('You can only transform data containing Eloquent models.'); } return $model; }
php
protected function resolveModel($data):Model { if ($data instanceof Model) { return $data; } $model = array_values($data)[0]; if (! $model instanceof Model) { throw new InvalidArgumentException('You can only transform data containing Eloquent models.'); } return $model; }
[ "protected", "function", "resolveModel", "(", "$", "data", ")", ":", "Model", "{", "if", "(", "$", "data", "instanceof", "Model", ")", "{", "return", "$", "data", ";", "}", "$", "model", "=", "array_values", "(", "$", "data", ")", "[", "0", "]", ";...
Resolve a model instance from the data. @param \Illuminate\Database\Eloquent\Model|array $data @return \Illuminate\Database\Eloquent\Model @throws \InvalidArgumentException
[ "Resolve", "a", "model", "instance", "from", "the", "data", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L251-L263
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.resolveTransformer
protected function resolveTransformer(Model $model, $transformer = null) { $transformer = $transformer ?: $this->resolveTransformerFromModel($model); if (is_string($transformer)) { $transformer = new $transformer; } return $this->parseTransformer($transformer, $model); }
php
protected function resolveTransformer(Model $model, $transformer = null) { $transformer = $transformer ?: $this->resolveTransformerFromModel($model); if (is_string($transformer)) { $transformer = new $transformer; } return $this->parseTransformer($transformer, $model); }
[ "protected", "function", "resolveTransformer", "(", "Model", "$", "model", ",", "$", "transformer", "=", "null", ")", "{", "$", "transformer", "=", "$", "transformer", "?", ":", "$", "this", "->", "resolveTransformerFromModel", "(", "$", "model", ")", ";", ...
Resolve a transformer. @param \Illuminate\Database\ELoquent\Model $model @param \Flugg\Responder\Transformer|callable|null $transformer @return \Flugg\Responder\Transformer|callable
[ "Resolve", "a", "transformer", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L272-L281
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.resolveTransformerFromModel
protected function resolveTransformerFromModel(Model $model) { if (! $model instanceof Transformable) { return function ($model) { return $model->toArray(); }; } return $model::transformer(); }
php
protected function resolveTransformerFromModel(Model $model) { if (! $model instanceof Transformable) { return function ($model) { return $model->toArray(); }; } return $model::transformer(); }
[ "protected", "function", "resolveTransformerFromModel", "(", "Model", "$", "model", ")", "{", "if", "(", "!", "$", "model", "instanceof", "Transformable", ")", "{", "return", "function", "(", "$", "model", ")", "{", "return", "$", "model", "->", "toArray", ...
Resolve a transformer from the model. If the model is not transformable, a closure based transformer will be created instead, from the model's fillable attributes. @param \Illuminate\Database\ELoquent\Model $model @return \Flugg\Responder\Transformer|callable
[ "Resolve", "a", "transformer", "from", "the", "model", ".", "If", "the", "model", "is", "not", "transformable", "a", "closure", "based", "transformer", "will", "be", "created", "instead", "from", "the", "model", "s", "fillable", "attributes", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L290-L299
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.parseTransformer
protected function parseTransformer($transformer, Model $model) { if ($transformer instanceof Transformer) { $relations = $transformer->allRelationsAllowed() ? $this->resolveRelations($model) : $transformer->getRelations(); $transformer = $transformer->setRelations($relations); } elseif (! is_callable($transformer)) { throw new InvalidTransformerException($model); } return $transformer; }
php
protected function parseTransformer($transformer, Model $model) { if ($transformer instanceof Transformer) { $relations = $transformer->allRelationsAllowed() ? $this->resolveRelations($model) : $transformer->getRelations(); $transformer = $transformer->setRelations($relations); } elseif (! is_callable($transformer)) { throw new InvalidTransformerException($model); } return $transformer; }
[ "protected", "function", "parseTransformer", "(", "$", "transformer", ",", "Model", "$", "model", ")", "{", "if", "(", "$", "transformer", "instanceof", "Transformer", ")", "{", "$", "relations", "=", "$", "transformer", "->", "allRelationsAllowed", "(", ")", ...
Parse a transformer class and set relations. @param \Flugg\Responder\Transformer|callable $transformer @param \Illuminate\Database\ELoquent\Model $model @return \Flugg\Responder\Transformer|callable @throws \InvalidTransformerException
[ "Parse", "a", "transformer", "class", "and", "set", "relations", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L309-L320
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.resolveNestedRelations
protected function resolveNestedRelations($data):array { if (is_null($data)) { return []; } $data = $data instanceof Model ? [$data] : $data; return collect($data)->flatMap(function ($model) { $relations = collect($model->getRelations()); return $relations->keys()->merge($relations->flatMap(function ($relation, $key) { return collect($this->resolveNestedRelations($relation))->map(function ($nestedRelation) use ($key) { return $key . '.' . $nestedRelation; }); })); })->unique()->toArray(); }
php
protected function resolveNestedRelations($data):array { if (is_null($data)) { return []; } $data = $data instanceof Model ? [$data] : $data; return collect($data)->flatMap(function ($model) { $relations = collect($model->getRelations()); return $relations->keys()->merge($relations->flatMap(function ($relation, $key) { return collect($this->resolveNestedRelations($relation))->map(function ($nestedRelation) use ($key) { return $key . '.' . $nestedRelation; }); })); })->unique()->toArray(); }
[ "protected", "function", "resolveNestedRelations", "(", "$", "data", ")", ":", "array", "{", "if", "(", "is_null", "(", "$", "data", ")", ")", "{", "return", "[", "]", ";", "}", "$", "data", "=", "$", "data", "instanceof", "Model", "?", "[", "$", "...
Resolve eager loaded relations from the model including any nested relations. @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model $data @return array
[ "Resolve", "eager", "loaded", "relations", "from", "the", "model", "including", "any", "nested", "relations", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L339-L356
tttptd/laravel-responder
src/Http/SuccessResponseBuilder.php
SuccessResponseBuilder.resolveResourceKey
protected function resolveResourceKey(Model $model, string $resourceKey = null):string { if (! is_null($resourceKey)) { return $resourceKey; } if (method_exists($model, 'getResourceKey')) { return $model->getResourceKey(); } return $model->getTable(); }
php
protected function resolveResourceKey(Model $model, string $resourceKey = null):string { if (! is_null($resourceKey)) { return $resourceKey; } if (method_exists($model, 'getResourceKey')) { return $model->getResourceKey(); } return $model->getTable(); }
[ "protected", "function", "resolveResourceKey", "(", "Model", "$", "model", ",", "string", "$", "resourceKey", "=", "null", ")", ":", "string", "{", "if", "(", "!", "is_null", "(", "$", "resourceKey", ")", ")", "{", "return", "$", "resourceKey", ";", "}",...
Resolve the resource key from the model. @param \Illuminate\Database\Eloquent\Model $model @param string|null $resourceKey @return string
[ "Resolve", "the", "resource", "key", "from", "the", "model", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Http/SuccessResponseBuilder.php#L365-L376
grozzzny/catalog
controllers/AController.php
AController.actionCreate
public function actionCreate($slug, $category_id = null) { $model = $slug == Category::SLUG ? $this->getCategoryModel() : $this->getItemModel($category_id); $modelCategory = $this->getCategoryModel(); $currentCategory = empty($category_id) ? null : $modelCategory::findOne(['id' => $category_id]); $this->scenarios($model); if ($model->load(Yii::$app->request->post())) { if(Yii::$app->request->isAjax){ Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ActiveForm::validate($model); } else{ if(isset($_FILES)){ $this->saveFiles($model); } if($model->save()){ $this->trigger(self::EVENT_AFTER_SAVE, new EventController(['model' => $model])); $this->flash('success', Yii::t('gr', 'Post created')); return $this->redirect(Url::previous()); } else{ $this->flash('error', Yii::t('gr', 'Error')); return $this->refresh(); } } } else { if($slug == Category::SLUG){ $title = empty($currentCategory) ? Yii::t('gr', 'Create subcategory in the top-level category') : Yii::t('gr', 'Create Subcategory in Category <b>«{0}»</b>', [$currentCategory->title]); }else{ $title = empty($currentCategory) ? Yii::t('gr', 'Create an item in the top-level category') : Yii::t('gr', 'Create Item in Category <b>«{0}»</b>', [$currentCategory->title]); } return $this->render('create', [ 'model' => $model, 'currentCategory' => $currentCategory, 'title' => $title ]); } }
php
public function actionCreate($slug, $category_id = null) { $model = $slug == Category::SLUG ? $this->getCategoryModel() : $this->getItemModel($category_id); $modelCategory = $this->getCategoryModel(); $currentCategory = empty($category_id) ? null : $modelCategory::findOne(['id' => $category_id]); $this->scenarios($model); if ($model->load(Yii::$app->request->post())) { if(Yii::$app->request->isAjax){ Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ActiveForm::validate($model); } else{ if(isset($_FILES)){ $this->saveFiles($model); } if($model->save()){ $this->trigger(self::EVENT_AFTER_SAVE, new EventController(['model' => $model])); $this->flash('success', Yii::t('gr', 'Post created')); return $this->redirect(Url::previous()); } else{ $this->flash('error', Yii::t('gr', 'Error')); return $this->refresh(); } } } else { if($slug == Category::SLUG){ $title = empty($currentCategory) ? Yii::t('gr', 'Create subcategory in the top-level category') : Yii::t('gr', 'Create Subcategory in Category <b>«{0}»</b>', [$currentCategory->title]); }else{ $title = empty($currentCategory) ? Yii::t('gr', 'Create an item in the top-level category') : Yii::t('gr', 'Create Item in Category <b>«{0}»</b>', [$currentCategory->title]); } return $this->render('create', [ 'model' => $model, 'currentCategory' => $currentCategory, 'title' => $title ]); } }
[ "public", "function", "actionCreate", "(", "$", "slug", ",", "$", "category_id", "=", "null", ")", "{", "$", "model", "=", "$", "slug", "==", "Category", "::", "SLUG", "?", "$", "this", "->", "getCategoryModel", "(", ")", ":", "$", "this", "->", "get...
Создать @param $slug @return array|string|\yii\web\Response
[ "Создать" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/controllers/AController.php#L96-L137
grozzzny/catalog
controllers/AController.php
AController.changeStatus
public function changeStatus($slug, $id, $status) { $current_model = Base::getModel($slug); if($current_model = $current_model::findOne($id)){ $current_model->status = $status; $current_model->save(); }else{ $this->error = Yii::t('easyii2', 'Not found'); } return $this->formatResponse(Yii::t('easyii2', 'Status successfully changed')); }
php
public function changeStatus($slug, $id, $status) { $current_model = Base::getModel($slug); if($current_model = $current_model::findOne($id)){ $current_model->status = $status; $current_model->save(); }else{ $this->error = Yii::t('easyii2', 'Not found'); } return $this->formatResponse(Yii::t('easyii2', 'Status successfully changed')); }
[ "public", "function", "changeStatus", "(", "$", "slug", ",", "$", "id", ",", "$", "status", ")", "{", "$", "current_model", "=", "Base", "::", "getModel", "(", "$", "slug", ")", ";", "if", "(", "$", "current_model", "=", "$", "current_model", "::", "...
Изменить статус @param $slug @param $id @param $status @return mixed
[ "Изменить", "статус" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/controllers/AController.php#L351-L363
nabab/bbn
src/bbn/mvc.php
mvc.add_view
private static function add_view($path, $mode, mvc\view $view) { if ( !isset(self::$loaded_views[$mode][$path]) ){ self::$loaded_views[$mode][$path] = $view; } return self::$loaded_views[$mode][$path]; }
php
private static function add_view($path, $mode, mvc\view $view) { if ( !isset(self::$loaded_views[$mode][$path]) ){ self::$loaded_views[$mode][$path] = $view; } return self::$loaded_views[$mode][$path]; }
[ "private", "static", "function", "add_view", "(", "$", "path", ",", "$", "mode", ",", "mvc", "\\", "view", "$", "view", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "loaded_views", "[", "$", "mode", "]", "[", "$", "path", "]", ")", ...
This function gets the content of a view file and adds it to the loaded_views array. @param string $p The full path to the view file @return string The content of the view
[ "This", "function", "gets", "the", "content", "of", "a", "view", "file", "and", "adds", "it", "to", "the", "loaded_views", "array", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc.php#L226-L232
nabab/bbn
src/bbn/mvc.php
mvc.get_route
public function get_route($path, $mode, $root = null){ return $this->router->route($path, $mode, $root); }
php
public function get_route($path, $mode, $root = null){ return $this->router->route($path, $mode, $root); }
[ "public", "function", "get_route", "(", "$", "path", ",", "$", "mode", ",", "$", "root", "=", "null", ")", "{", "return", "$", "this", "->", "router", "->", "route", "(", "$", "path", ",", "$", "mode", ",", "$", "root", ")", ";", "}" ]
/*public function add_routes(array $routes){ $this->routes = x::merge_arrays($this->routes, $routes); return $this; }
[ "/", "*", "public", "function", "add_routes", "(", "array", "$routes", ")", "{", "$this", "-", ">", "routes", "=", "x", "::", "merge_arrays", "(", "$this", "-", ">", "routes", "$routes", ")", ";", "return", "$this", ";", "}" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc.php#L366-L368
nabab/bbn
src/bbn/mvc.php
mvc.reroute
public function reroute($path='', $post = false, $arguments = false){ $this->env->simulate($path, $post, $arguments); $this->is_routed = false; $this->is_controlled = null; $this->info = null; $this->router->reset(); $this->route(); $this->info['args'] = $arguments; $this->controller->reset($this->info); return $this; }
php
public function reroute($path='', $post = false, $arguments = false){ $this->env->simulate($path, $post, $arguments); $this->is_routed = false; $this->is_controlled = null; $this->info = null; $this->router->reset(); $this->route(); $this->info['args'] = $arguments; $this->controller->reset($this->info); return $this; }
[ "public", "function", "reroute", "(", "$", "path", "=", "''", ",", "$", "post", "=", "false", ",", "$", "arguments", "=", "false", ")", "{", "$", "this", "->", "env", "->", "simulate", "(", "$", "path", ",", "$", "post", ",", "$", "arguments", ")...
This will reroute a controller to another one seemlessly. Chainable @param string $path The request path <em>(e.g books/466565 or xml/books/48465)</em> @return void
[ "This", "will", "reroute", "a", "controller", "to", "another", "one", "seemlessly", ".", "Chainable" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc.php#L412-L422
nabab/bbn
src/bbn/mvc.php
mvc.get_view
public function get_view(string $path, string $mode = 'html', array $data=null){ if ( !router::is_mode($mode) ){ die("Incorrect mode $path $mode"); } $view = null; if ( $this->has_view($path, $mode) ){ $view = self::$loaded_views[$mode][$path]; } else if ( $info = $this->router->route($path, $mode) ){ $view = new mvc\view($info); $this->add_to_views($path, $mode, $view); } if ( \is_object($view) && $view->check() ){ return \is_array($data) ? $view->get($data) : $view->get(); } return ''; }
php
public function get_view(string $path, string $mode = 'html', array $data=null){ if ( !router::is_mode($mode) ){ die("Incorrect mode $path $mode"); } $view = null; if ( $this->has_view($path, $mode) ){ $view = self::$loaded_views[$mode][$path]; } else if ( $info = $this->router->route($path, $mode) ){ $view = new mvc\view($info); $this->add_to_views($path, $mode, $view); } if ( \is_object($view) && $view->check() ){ return \is_array($data) ? $view->get($data) : $view->get(); } return ''; }
[ "public", "function", "get_view", "(", "string", "$", "path", ",", "string", "$", "mode", "=", "'html'", ",", "array", "$", "data", "=", "null", ")", "{", "if", "(", "!", "router", "::", "is_mode", "(", "$", "mode", ")", ")", "{", "die", "(", "\"...
This will get a view. @param string $path @param string $mode @param array $data @return string|false
[ "This", "will", "get", "a", "view", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc.php#L456-L472
nabab/bbn
src/bbn/mvc.php
mvc.get_external_view
public function get_external_view(string $full_path, string $mode = 'html', array $data=null){ if ( !router::is_mode($mode) ){ die("Incorrect mode $full_path $mode"); } if ( ($this->get_mode() === 'dom') && (!defined('BBN_DEFAULT_MODE') || (BBN_DEFAULT_MODE !== 'dom')) ){ $full_path .= ($full_path === '' ? '' : '/').'index'; } $view = null; if ( $this->has_view($full_path, $mode) ){ $view = self::$loaded_views[$mode][$full_path]; } else if ( $info = $this->router->route(basename($full_path), 'free-'.$mode, \dirname($full_path)) ){ $view = new mvc\view($info); $this->add_to_views($full_path, $mode, $view); } if ( \is_object($view) && $view->check() ){ return \is_array($data) ? $view->get($data) : $view->get(); } return ''; }
php
public function get_external_view(string $full_path, string $mode = 'html', array $data=null){ if ( !router::is_mode($mode) ){ die("Incorrect mode $full_path $mode"); } if ( ($this->get_mode() === 'dom') && (!defined('BBN_DEFAULT_MODE') || (BBN_DEFAULT_MODE !== 'dom')) ){ $full_path .= ($full_path === '' ? '' : '/').'index'; } $view = null; if ( $this->has_view($full_path, $mode) ){ $view = self::$loaded_views[$mode][$full_path]; } else if ( $info = $this->router->route(basename($full_path), 'free-'.$mode, \dirname($full_path)) ){ $view = new mvc\view($info); $this->add_to_views($full_path, $mode, $view); } if ( \is_object($view) && $view->check() ){ return \is_array($data) ? $view->get($data) : $view->get(); } return ''; }
[ "public", "function", "get_external_view", "(", "string", "$", "full_path", ",", "string", "$", "mode", "=", "'html'", ",", "array", "$", "data", "=", "null", ")", "{", "if", "(", "!", "router", "::", "is_mode", "(", "$", "mode", ")", ")", "{", "die"...
This will get a view from a different root. @param string $full_path @param string $mode @param array $data @return string|false
[ "This", "will", "get", "a", "view", "from", "a", "different", "root", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc.php#L482-L501