repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.loadShortCodes
protected function loadShortCodes() { if ($config = $this->loadConfigFile('shortcodes.php')) { $renderer = $this->renderer; $app = $this->app; foreach ($config as $shortcode => $provider) { add_shortcode($shortcode, function ($attrs, $content) use ($app, $provider, $renderer) { if (is_string($provider) && is_subclass_of($provider, 'Tev\Plugin\Shortcode\AbstractProvider')) { $sp = new $provider($app, $renderer); return $sp->shortcode($attrs, $content); } elseif ($provider instanceof Closure) { return $provider($attrs, $content, $renderer); } }); } } return $this; }
php
protected function loadShortCodes() { if ($config = $this->loadConfigFile('shortcodes.php')) { $renderer = $this->renderer; $app = $this->app; foreach ($config as $shortcode => $provider) { add_shortcode($shortcode, function ($attrs, $content) use ($app, $provider, $renderer) { if (is_string($provider) && is_subclass_of($provider, 'Tev\Plugin\Shortcode\AbstractProvider')) { $sp = new $provider($app, $renderer); return $sp->shortcode($attrs, $content); } elseif ($provider instanceof Closure) { return $provider($attrs, $content, $renderer); } }); } } return $this; }
[ "protected", "function", "loadShortCodes", "(", ")", "{", "if", "(", "$", "config", "=", "$", "this", "->", "loadConfigFile", "(", "'shortcodes.php'", ")", ")", "{", "$", "renderer", "=", "$", "this", "->", "renderer", ";", "$", "app", "=", "$", "this", "->", "app", ";", "foreach", "(", "$", "config", "as", "$", "shortcode", "=>", "$", "provider", ")", "{", "add_shortcode", "(", "$", "shortcode", ",", "function", "(", "$", "attrs", ",", "$", "content", ")", "use", "(", "$", "app", ",", "$", "provider", ",", "$", "renderer", ")", "{", "if", "(", "is_string", "(", "$", "provider", ")", "&&", "is_subclass_of", "(", "$", "provider", ",", "'Tev\\Plugin\\Shortcode\\AbstractProvider'", ")", ")", "{", "$", "sp", "=", "new", "$", "provider", "(", "$", "app", ",", "$", "renderer", ")", ";", "return", "$", "sp", "->", "shortcode", "(", "$", "attrs", ",", "$", "content", ")", ";", "}", "elseif", "(", "$", "provider", "instanceof", "Closure", ")", "{", "return", "$", "provider", "(", "$", "attrs", ",", "$", "content", ",", "$", "renderer", ")", ";", "}", "}", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Load shortcodes from configuration files. @return \Tev\Plugin\Loader This, for chaining
[ "Load", "shortcodes", "from", "configuration", "files", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L249-L269
train
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.loadOptionScreens
protected function loadOptionScreens() { if (function_exists('acf_add_options_page') && ($config = $this->loadConfigFile('option_screens.php'))) { foreach ($config as $optionScreenConfig) { acf_add_options_page($optionScreenConfig); } } return $this; }
php
protected function loadOptionScreens() { if (function_exists('acf_add_options_page') && ($config = $this->loadConfigFile('option_screens.php'))) { foreach ($config as $optionScreenConfig) { acf_add_options_page($optionScreenConfig); } } return $this; }
[ "protected", "function", "loadOptionScreens", "(", ")", "{", "if", "(", "function_exists", "(", "'acf_add_options_page'", ")", "&&", "(", "$", "config", "=", "$", "this", "->", "loadConfigFile", "(", "'option_screens.php'", ")", ")", ")", "{", "foreach", "(", "$", "config", "as", "$", "optionScreenConfig", ")", "{", "acf_add_options_page", "(", "$", "optionScreenConfig", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Load custom option screens from configuration files. @return \Tev\Plugin\Loader This, for chaining
[ "Load", "custom", "option", "screens", "from", "configuration", "files", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L276-L285
train
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.loadCliCommands
protected function loadCliCommands() { if (defined('WP_CLI') && WP_CLI && ($config = $this->loadConfigFile('commands.php'))) { foreach ($config as $command => $className) { \WP_CLI::add_command($command, $className); } } return $this; }
php
protected function loadCliCommands() { if (defined('WP_CLI') && WP_CLI && ($config = $this->loadConfigFile('commands.php'))) { foreach ($config as $command => $className) { \WP_CLI::add_command($command, $className); } } return $this; }
[ "protected", "function", "loadCliCommands", "(", ")", "{", "if", "(", "defined", "(", "'WP_CLI'", ")", "&&", "WP_CLI", "&&", "(", "$", "config", "=", "$", "this", "->", "loadConfigFile", "(", "'commands.php'", ")", ")", ")", "{", "foreach", "(", "$", "config", "as", "$", "command", "=>", "$", "className", ")", "{", "\\", "WP_CLI", "::", "add_command", "(", "$", "command", ",", "$", "className", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Load custom WP CLI commands from configuration files. @return \Tev\Plugin\Loader This, for chaining
[ "Load", "custom", "WP", "CLI", "commands", "from", "configuration", "files", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L292-L301
train
3ev/wordpress-core
src/Tev/Plugin/Loader.php
Loader.loadConfigFile
protected function loadConfigFile($file) { $path = $this->getConfigPath() . '/' . $file; if (file_exists($path)) { $config = include $path; return is_array($config) ? $config : null; } return null; }
php
protected function loadConfigFile($file) { $path = $this->getConfigPath() . '/' . $file; if (file_exists($path)) { $config = include $path; return is_array($config) ? $config : null; } return null; }
[ "protected", "function", "loadConfigFile", "(", "$", "file", ")", "{", "$", "path", "=", "$", "this", "->", "getConfigPath", "(", ")", ".", "'/'", ".", "$", "file", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "$", "config", "=", "include", "$", "path", ";", "return", "is_array", "(", "$", "config", ")", "?", "$", "config", ":", "null", ";", "}", "return", "null", ";", "}" ]
Load a config file from the config directory. @param string $file Filename @return array|null Array config or null if not found
[ "Load", "a", "config", "file", "from", "the", "config", "directory", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L349-L359
train
AntonyThorpe/consumer
src/Consumer.php
Consumer.isTimestamp
public static function isTimestamp($string) { if (substr($string, 0, 5) == "/Date") { return true; } try { new DateTime('@' . $string); } catch (Exception $e) { return false; } return true; }
php
public static function isTimestamp($string) { if (substr($string, 0, 5) == "/Date") { return true; } try { new DateTime('@' . $string); } catch (Exception $e) { return false; } return true; }
[ "public", "static", "function", "isTimestamp", "(", "$", "string", ")", "{", "if", "(", "substr", "(", "$", "string", ",", "0", ",", "5", ")", "==", "\"/Date\"", ")", "{", "return", "true", ";", "}", "try", "{", "new", "DateTime", "(", "'@'", ".", "$", "string", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determine if the string is a Unix Timestamp @link(Stack Overflow, http://stackoverflow.com/questions/2524680/check-whether-the-string-is-a-unix-timestamp) @param string $string @return boolean
[ "Determine", "if", "the", "string", "is", "a", "Unix", "Timestamp" ]
c9f464b901c09ab0bfbb62c94589637363af7bf0
https://github.com/AntonyThorpe/consumer/blob/c9f464b901c09ab0bfbb62c94589637363af7bf0/src/Consumer.php#L49-L61
train
AntonyThorpe/consumer
src/Consumer.php
Consumer.setMaxExternalLastEdited
public function setMaxExternalLastEdited(array $apidata) { $external_last_edited_key = $this->ExternalLastEditedKey; // Validation if (!$external_last_edited_key) { user_error( _t('Consumer.ExternalLastEditedKeyNeeded', 'Property ExternalLastEditedKey needs to be set before calling setMaxExternalLastEdited method'), E_USER_WARNING ); } $dates = array_map(function ($item) use ($external_last_edited_key) { return $item[$external_last_edited_key]; }, $apidata); $max_date = max($dates); if (self::isTimestamp($max_date)) { $max_date = self::convertUnix2UTC($max_date); } $this->ExternalLastEdited = $max_date; return $this; }
php
public function setMaxExternalLastEdited(array $apidata) { $external_last_edited_key = $this->ExternalLastEditedKey; // Validation if (!$external_last_edited_key) { user_error( _t('Consumer.ExternalLastEditedKeyNeeded', 'Property ExternalLastEditedKey needs to be set before calling setMaxExternalLastEdited method'), E_USER_WARNING ); } $dates = array_map(function ($item) use ($external_last_edited_key) { return $item[$external_last_edited_key]; }, $apidata); $max_date = max($dates); if (self::isTimestamp($max_date)) { $max_date = self::convertUnix2UTC($max_date); } $this->ExternalLastEdited = $max_date; return $this; }
[ "public", "function", "setMaxExternalLastEdited", "(", "array", "$", "apidata", ")", "{", "$", "external_last_edited_key", "=", "$", "this", "->", "ExternalLastEditedKey", ";", "// Validation", "if", "(", "!", "$", "external_last_edited_key", ")", "{", "user_error", "(", "_t", "(", "'Consumer.ExternalLastEditedKeyNeeded'", ",", "'Property ExternalLastEditedKey needs to be set before calling setMaxExternalLastEdited method'", ")", ",", "E_USER_WARNING", ")", ";", "}", "$", "dates", "=", "array_map", "(", "function", "(", "$", "item", ")", "use", "(", "$", "external_last_edited_key", ")", "{", "return", "$", "item", "[", "$", "external_last_edited_key", "]", ";", "}", ",", "$", "apidata", ")", ";", "$", "max_date", "=", "max", "(", "$", "dates", ")", ";", "if", "(", "self", "::", "isTimestamp", "(", "$", "max_date", ")", ")", "{", "$", "max_date", "=", "self", "::", "convertUnix2UTC", "(", "$", "max_date", ")", ";", "}", "$", "this", "->", "ExternalLastEdited", "=", "$", "max_date", ";", "return", "$", "this", ";", "}" ]
Set the ExternalLastEdited to the maximum last edited date @param array $apidata @return $this
[ "Set", "the", "ExternalLastEdited", "to", "the", "maximum", "last", "edited", "date" ]
c9f464b901c09ab0bfbb62c94589637363af7bf0
https://github.com/AntonyThorpe/consumer/blob/c9f464b901c09ab0bfbb62c94589637363af7bf0/src/Consumer.php#L68-L91
train
acacha/forge-publish
src/Console/Commands/PublishAssignmentUsers.php
PublishAssignmentUsers.assignUsersToAssignment
protected function assignUsersToAssignment() { $assignment = fp_env('ACACHA_FORGE_ASSIGNMENT'); foreach ( $this->users as $user) { $uri = str_replace('{assignment}', $assignment, config('forge-publish.assign_user_to_assignment_uri')); $uri = str_replace('{user}', $user, $uri); $url = config('forge-publish.url') . $uri; try { $response = $this->http->post($url, [ 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest', 'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN') ] ]); } catch (\Exception $e) { if ($e->getResponse()->getStatusCode() == 422) { $this->error('The user is already assigned'); return; } $this->error('And error occurs connecting to the api url: ' . $url); $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase()); return; } } }
php
protected function assignUsersToAssignment() { $assignment = fp_env('ACACHA_FORGE_ASSIGNMENT'); foreach ( $this->users as $user) { $uri = str_replace('{assignment}', $assignment, config('forge-publish.assign_user_to_assignment_uri')); $uri = str_replace('{user}', $user, $uri); $url = config('forge-publish.url') . $uri; try { $response = $this->http->post($url, [ 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest', 'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN') ] ]); } catch (\Exception $e) { if ($e->getResponse()->getStatusCode() == 422) { $this->error('The user is already assigned'); return; } $this->error('And error occurs connecting to the api url: ' . $url); $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase()); return; } } }
[ "protected", "function", "assignUsersToAssignment", "(", ")", "{", "$", "assignment", "=", "fp_env", "(", "'ACACHA_FORGE_ASSIGNMENT'", ")", ";", "foreach", "(", "$", "this", "->", "users", "as", "$", "user", ")", "{", "$", "uri", "=", "str_replace", "(", "'{assignment}'", ",", "$", "assignment", ",", "config", "(", "'forge-publish.assign_user_to_assignment_uri'", ")", ")", ";", "$", "uri", "=", "str_replace", "(", "'{user}'", ",", "$", "user", ",", "$", "uri", ")", ";", "$", "url", "=", "config", "(", "'forge-publish.url'", ")", ".", "$", "uri", ";", "try", "{", "$", "response", "=", "$", "this", "->", "http", "->", "post", "(", "$", "url", ",", "[", "'headers'", "=>", "[", "'X-Requested-With'", "=>", "'XMLHttpRequest'", ",", "'Authorization'", "=>", "'Bearer '", ".", "fp_env", "(", "'ACACHA_FORGE_ACCESS_TOKEN'", ")", "]", "]", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "$", "e", "->", "getResponse", "(", ")", "->", "getStatusCode", "(", ")", "==", "422", ")", "{", "$", "this", "->", "error", "(", "'The user is already assigned'", ")", ";", "return", ";", "}", "$", "this", "->", "error", "(", "'And error occurs connecting to the api url: '", ".", "$", "url", ")", ";", "$", "this", "->", "error", "(", "'Status code: '", ".", "$", "e", "->", "getResponse", "(", ")", "->", "getStatusCode", "(", ")", ".", "' | Reason : '", ".", "$", "e", "->", "getResponse", "(", ")", "->", "getReasonPhrase", "(", ")", ")", ";", "return", ";", "}", "}", "}" ]
Assign users to assignment @return array|mixed
[ "Assign", "users", "to", "assignment" ]
010779e3d2297c763b82dc3fbde992edffb3a6c6
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishAssignmentUsers.php#L83-L107
train
acacha/forge-publish
src/Console/Commands/PublishAssignmentUsers.php
PublishAssignmentUsers.askForUsers
protected function askForUsers() { $default = 0; $users = $this->users(); $user_names = array_merge( ['Skip'], collect($users)->pluck('name')->toArray() ); $selected_user_names = $this->choice('Users?', $user_names ,$default, null, true); if ($selected_user_names == 0) return null; $users = collect($users)->filter(function ($user) use ($selected_user_names) { return in_array($user->name,$selected_user_names); }); return $users->pluck('id'); }
php
protected function askForUsers() { $default = 0; $users = $this->users(); $user_names = array_merge( ['Skip'], collect($users)->pluck('name')->toArray() ); $selected_user_names = $this->choice('Users?', $user_names ,$default, null, true); if ($selected_user_names == 0) return null; $users = collect($users)->filter(function ($user) use ($selected_user_names) { return in_array($user->name,$selected_user_names); }); return $users->pluck('id'); }
[ "protected", "function", "askForUsers", "(", ")", "{", "$", "default", "=", "0", ";", "$", "users", "=", "$", "this", "->", "users", "(", ")", ";", "$", "user_names", "=", "array_merge", "(", "[", "'Skip'", "]", ",", "collect", "(", "$", "users", ")", "->", "pluck", "(", "'name'", ")", "->", "toArray", "(", ")", ")", ";", "$", "selected_user_names", "=", "$", "this", "->", "choice", "(", "'Users?'", ",", "$", "user_names", ",", "$", "default", ",", "null", ",", "true", ")", ";", "if", "(", "$", "selected_user_names", "==", "0", ")", "return", "null", ";", "$", "users", "=", "collect", "(", "$", "users", ")", "->", "filter", "(", "function", "(", "$", "user", ")", "use", "(", "$", "selected_user_names", ")", "{", "return", "in_array", "(", "$", "user", "->", "name", ",", "$", "selected_user_names", ")", ";", "}", ")", ";", "return", "$", "users", "->", "pluck", "(", "'id'", ")", ";", "}" ]
Ask for users. @return string
[ "Ask", "for", "users", "." ]
010779e3d2297c763b82dc3fbde992edffb3a6c6
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishAssignmentUsers.php#L135-L152
train
schpill/thin
src/Paypal.php
Paypal.ipn
public static function ipn() { // only accept post data if (!count($_POST)) { return false; } // if production mode... if (Config::get('paypal.production_mode')) { // use production endpoint $endpoint = 'https://www.paypal.com/cgi-bin/webscr'; } else { // use sandbox endpoint $endpoint = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; } // build response $fields = http_build_query(array('cmd' => '_notify-validate') + Input::all()); // curl request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // if errors... if (curl_errno($ch)) { #$errors = curl_error($ch); curl_close($ch); // return false return false; } else { // close connection curl_close($ch); // if success... if ($code === 200 and $response === 'VERIFIED') { return true; } else { return false; } } }
php
public static function ipn() { // only accept post data if (!count($_POST)) { return false; } // if production mode... if (Config::get('paypal.production_mode')) { // use production endpoint $endpoint = 'https://www.paypal.com/cgi-bin/webscr'; } else { // use sandbox endpoint $endpoint = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; } // build response $fields = http_build_query(array('cmd' => '_notify-validate') + Input::all()); // curl request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // if errors... if (curl_errno($ch)) { #$errors = curl_error($ch); curl_close($ch); // return false return false; } else { // close connection curl_close($ch); // if success... if ($code === 200 and $response === 'VERIFIED') { return true; } else { return false; } } }
[ "public", "static", "function", "ipn", "(", ")", "{", "// only accept post data", "if", "(", "!", "count", "(", "$", "_POST", ")", ")", "{", "return", "false", ";", "}", "// if production mode...", "if", "(", "Config", "::", "get", "(", "'paypal.production_mode'", ")", ")", "{", "// use production endpoint", "$", "endpoint", "=", "'https://www.paypal.com/cgi-bin/webscr'", ";", "}", "else", "{", "// use sandbox endpoint", "$", "endpoint", "=", "'https://www.sandbox.paypal.com/cgi-bin/webscr'", ";", "}", "// build response", "$", "fields", "=", "http_build_query", "(", "array", "(", "'cmd'", "=>", "'_notify-validate'", ")", "+", "Input", "::", "all", "(", ")", ")", ";", "// curl request", "$", "ch", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "endpoint", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_TIMEOUT", ",", "30", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYHOST", ",", "2", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "fields", ")", ";", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "$", "code", "=", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_HTTP_CODE", ")", ";", "// if errors...", "if", "(", "curl_errno", "(", "$", "ch", ")", ")", "{", "#$errors = curl_error($ch);", "curl_close", "(", "$", "ch", ")", ";", "// return false", "return", "false", ";", "}", "else", "{", "// close connection", "curl_close", "(", "$", "ch", ")", ";", "// if success...", "if", "(", "$", "code", "===", "200", "and", "$", "response", "===", "'VERIFIED'", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}" ]
Automatically verify Paypal IPN communications. @return boolean
[ "Automatically", "verify", "Paypal", "IPN", "communications", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Paypal.php#L79-L128
train
ajaxtown/eaglehorn_framework
src/Eaglehorn/worker/Profiler/Profiler.php
Profiler.profile
public function profile($classname, $methodname, $methodargs, $invocations = 1) { if (class_exists($classname) != TRUE) { throw new Exception("{$classname} doesn't exist"); } $method = new ReflectionMethod($classname, $methodname); $instance = NULL; if (!$method->isStatic()) { $class = new ReflectionClass($classname); $instance = $class->newInstance(); } $durations = array(); for ($i = 0; $i < $invocations; $i++) { $start = microtime(true); $method->invokeArgs($instance, $methodargs); $durations[] = microtime(true) - $start; } $durations['worst'] = round(max($durations), 5); $durations['total'] = round(array_sum($durations), 5); $durations['average'] = round($durations['total'] / count($durations), 5); $this->details = array('class' => $classname, 'method' => $methodname, 'arguments' => $methodargs, 'duration' => $durations, 'invocations' => $invocations); return $durations['average']; }
php
public function profile($classname, $methodname, $methodargs, $invocations = 1) { if (class_exists($classname) != TRUE) { throw new Exception("{$classname} doesn't exist"); } $method = new ReflectionMethod($classname, $methodname); $instance = NULL; if (!$method->isStatic()) { $class = new ReflectionClass($classname); $instance = $class->newInstance(); } $durations = array(); for ($i = 0; $i < $invocations; $i++) { $start = microtime(true); $method->invokeArgs($instance, $methodargs); $durations[] = microtime(true) - $start; } $durations['worst'] = round(max($durations), 5); $durations['total'] = round(array_sum($durations), 5); $durations['average'] = round($durations['total'] / count($durations), 5); $this->details = array('class' => $classname, 'method' => $methodname, 'arguments' => $methodargs, 'duration' => $durations, 'invocations' => $invocations); return $durations['average']; }
[ "public", "function", "profile", "(", "$", "classname", ",", "$", "methodname", ",", "$", "methodargs", ",", "$", "invocations", "=", "1", ")", "{", "if", "(", "class_exists", "(", "$", "classname", ")", "!=", "TRUE", ")", "{", "throw", "new", "Exception", "(", "\"{$classname} doesn't exist\"", ")", ";", "}", "$", "method", "=", "new", "ReflectionMethod", "(", "$", "classname", ",", "$", "methodname", ")", ";", "$", "instance", "=", "NULL", ";", "if", "(", "!", "$", "method", "->", "isStatic", "(", ")", ")", "{", "$", "class", "=", "new", "ReflectionClass", "(", "$", "classname", ")", ";", "$", "instance", "=", "$", "class", "->", "newInstance", "(", ")", ";", "}", "$", "durations", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "invocations", ";", "$", "i", "++", ")", "{", "$", "start", "=", "microtime", "(", "true", ")", ";", "$", "method", "->", "invokeArgs", "(", "$", "instance", ",", "$", "methodargs", ")", ";", "$", "durations", "[", "]", "=", "microtime", "(", "true", ")", "-", "$", "start", ";", "}", "$", "durations", "[", "'worst'", "]", "=", "round", "(", "max", "(", "$", "durations", ")", ",", "5", ")", ";", "$", "durations", "[", "'total'", "]", "=", "round", "(", "array_sum", "(", "$", "durations", ")", ",", "5", ")", ";", "$", "durations", "[", "'average'", "]", "=", "round", "(", "$", "durations", "[", "'total'", "]", "/", "count", "(", "$", "durations", ")", ",", "5", ")", ";", "$", "this", "->", "details", "=", "array", "(", "'class'", "=>", "$", "classname", ",", "'method'", "=>", "$", "methodname", ",", "'arguments'", "=>", "$", "methodargs", ",", "'duration'", "=>", "$", "durations", ",", "'invocations'", "=>", "$", "invocations", ")", ";", "return", "$", "durations", "[", "'average'", "]", ";", "}" ]
Runs a method with the provided arguments, and returns details about how long it took. Works with instance methods and static methods. @param string $classname @param string $methodname @param array $methodargs @param int $invocations @throws Exception @internal param string $classname @internal param string $methodname @internal param array $methodargs @internal param int $invocations The number of times to call the method @return float average invocation duration in seconds
[ "Runs", "a", "method", "with", "the", "provided", "arguments", "and", "returns", "details", "about", "how", "long", "it", "took", ".", "Works", "with", "instance", "methods", "and", "static", "methods", "." ]
5e2a1456ff6c65b3925f1219f115d8a919930f52
https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/worker/Profiler/Profiler.php#L53-L85
train
phavour/phavour
Phavour/Cache/AdapterMemcache.php
AdapterMemcache.flush
public function flush() { if (!$this->hasConnection()) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } try { return $this->memcache->flush(); // @codeCoverageIgnoreStart } catch (\Exception $e) { } return false; // @codeCoverageIgnoreEnd }
php
public function flush() { if (!$this->hasConnection()) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } try { return $this->memcache->flush(); // @codeCoverageIgnoreStart } catch (\Exception $e) { } return false; // @codeCoverageIgnoreEnd }
[ "public", "function", "flush", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasConnection", "(", ")", ")", "{", "// @codeCoverageIgnoreStart", "return", "false", ";", "// @codeCoverageIgnoreEnd", "}", "try", "{", "return", "$", "this", "->", "memcache", "->", "flush", "(", ")", ";", "// @codeCoverageIgnoreStart", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "return", "false", ";", "// @codeCoverageIgnoreEnd", "}" ]
Flush all existing Cache @return boolean
[ "Flush", "all", "existing", "Cache" ]
2246f78203312eb2e23fdb0f776f790e81b4d20f
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Cache/AdapterMemcache.php#L217-L233
train
stonedz/pff2
src/Abs/AController.php
AController.beforeFilter
public function beforeFilter() { if(!isset($this->_beforeFilters[$this->_action])) { return false; } foreach($this->_beforeFilters[$this->_action] as $method) { call_user_func($method); } }
php
public function beforeFilter() { if(!isset($this->_beforeFilters[$this->_action])) { return false; } foreach($this->_beforeFilters[$this->_action] as $method) { call_user_func($method); } }
[ "public", "function", "beforeFilter", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_beforeFilters", "[", "$", "this", "->", "_action", "]", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "this", "->", "_beforeFilters", "[", "$", "this", "->", "_action", "]", "as", "$", "method", ")", "{", "call_user_func", "(", "$", "method", ")", ";", "}", "}" ]
Executes all the registered beforeFilters for the current action
[ "Executes", "all", "the", "registered", "beforeFilters", "for", "the", "current", "action" ]
ec3b087d4d4732816f61ac487f0cb25511e0da88
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Abs/AController.php#L314-L322
train
stonedz/pff2
src/Abs/AController.php
AController.afterFilter
public function afterFilter() { if(!isset($this->_afterFilters[$this->_action])) { return false; } foreach($this->_afterFilters[$this->_action] as $method) { call_user_func($method); } }
php
public function afterFilter() { if(!isset($this->_afterFilters[$this->_action])) { return false; } foreach($this->_afterFilters[$this->_action] as $method) { call_user_func($method); } }
[ "public", "function", "afterFilter", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_afterFilters", "[", "$", "this", "->", "_action", "]", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "this", "->", "_afterFilters", "[", "$", "this", "->", "_action", "]", "as", "$", "method", ")", "{", "call_user_func", "(", "$", "method", ")", ";", "}", "}" ]
Execute all the registered afterFilters for the current action
[ "Execute", "all", "the", "registered", "afterFilters", "for", "the", "current", "action" ]
ec3b087d4d4732816f61ac487f0cb25511e0da88
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Abs/AController.php#L327-L335
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.getView
public final function getView($id, $view, & $properties_cache = null, & $view_cache = null, & $persistent_view_cache = null) { // Check cache if (isset($view_cache[$view])) { return $view_cache[$view]; } switch ($view) { case 'url': // Get URL of this state machine return $this->urlFormat($id, $this->url_fmt, $properties_cache); case 'parent_url': // Get URL of parent state machine or collection or whatever it is if ($this->parent_url_fmt !== null) { return $this->urlFormat($id, $this->parent_url_fmt, $properties_cache); } else { return null; } case 'post_action_url': // Get URL of redirect-after-post return $this->urlFormat($id, $this->post_action_url_fmt !== null ? $this->post_action_url_fmt : $this->url_fmt, $properties_cache); default: // Check references if (isset($this->references[$view])) { // Populate properties cache if empty if ($properties_cache === null) { $properties_cache = $this->getProperties($id); } // Create reference & cache it return ($view_cache[$view] = $this->resolveMachineReference($view, $properties_cache)); } else { return ($view_cache[$view] = $this->calculateViewValue($id, $view, $properties_cache, $view_cache, $persistent_view_cache)); } } }
php
public final function getView($id, $view, & $properties_cache = null, & $view_cache = null, & $persistent_view_cache = null) { // Check cache if (isset($view_cache[$view])) { return $view_cache[$view]; } switch ($view) { case 'url': // Get URL of this state machine return $this->urlFormat($id, $this->url_fmt, $properties_cache); case 'parent_url': // Get URL of parent state machine or collection or whatever it is if ($this->parent_url_fmt !== null) { return $this->urlFormat($id, $this->parent_url_fmt, $properties_cache); } else { return null; } case 'post_action_url': // Get URL of redirect-after-post return $this->urlFormat($id, $this->post_action_url_fmt !== null ? $this->post_action_url_fmt : $this->url_fmt, $properties_cache); default: // Check references if (isset($this->references[$view])) { // Populate properties cache if empty if ($properties_cache === null) { $properties_cache = $this->getProperties($id); } // Create reference & cache it return ($view_cache[$view] = $this->resolveMachineReference($view, $properties_cache)); } else { return ($view_cache[$view] = $this->calculateViewValue($id, $view, $properties_cache, $view_cache, $persistent_view_cache)); } } }
[ "public", "final", "function", "getView", "(", "$", "id", ",", "$", "view", ",", "&", "$", "properties_cache", "=", "null", ",", "&", "$", "view_cache", "=", "null", ",", "&", "$", "persistent_view_cache", "=", "null", ")", "{", "// Check cache", "if", "(", "isset", "(", "$", "view_cache", "[", "$", "view", "]", ")", ")", "{", "return", "$", "view_cache", "[", "$", "view", "]", ";", "}", "switch", "(", "$", "view", ")", "{", "case", "'url'", ":", "// Get URL of this state machine", "return", "$", "this", "->", "urlFormat", "(", "$", "id", ",", "$", "this", "->", "url_fmt", ",", "$", "properties_cache", ")", ";", "case", "'parent_url'", ":", "// Get URL of parent state machine or collection or whatever it is", "if", "(", "$", "this", "->", "parent_url_fmt", "!==", "null", ")", "{", "return", "$", "this", "->", "urlFormat", "(", "$", "id", ",", "$", "this", "->", "parent_url_fmt", ",", "$", "properties_cache", ")", ";", "}", "else", "{", "return", "null", ";", "}", "case", "'post_action_url'", ":", "// Get URL of redirect-after-post", "return", "$", "this", "->", "urlFormat", "(", "$", "id", ",", "$", "this", "->", "post_action_url_fmt", "!==", "null", "?", "$", "this", "->", "post_action_url_fmt", ":", "$", "this", "->", "url_fmt", ",", "$", "properties_cache", ")", ";", "default", ":", "// Check references", "if", "(", "isset", "(", "$", "this", "->", "references", "[", "$", "view", "]", ")", ")", "{", "// Populate properties cache if empty", "if", "(", "$", "properties_cache", "===", "null", ")", "{", "$", "properties_cache", "=", "$", "this", "->", "getProperties", "(", "$", "id", ")", ";", "}", "// Create reference & cache it", "return", "(", "$", "view_cache", "[", "$", "view", "]", "=", "$", "this", "->", "resolveMachineReference", "(", "$", "view", ",", "$", "properties_cache", ")", ")", ";", "}", "else", "{", "return", "(", "$", "view_cache", "[", "$", "view", "]", "=", "$", "this", "->", "calculateViewValue", "(", "$", "id", ",", "$", "view", ",", "$", "properties_cache", ",", "$", "view_cache", ",", "$", "persistent_view_cache", ")", ")", ";", "}", "}", "}" ]
Get properties in given view. Just like SQL view, the property view is transformed set of properties. These views are useful when some properties require heavy calculations. Keep in mind, that view name must not interfere with Reference properties, otherwise the view is inaccessible directly. Array $properties_cache is supplied by Reference class to make some calculations faster and without duplicate database queries. Make sure these cached properties are up to date or null. Array $view_cache is writable cache inside the Reference class, flushed together with $properties_cache. If cache is empty, but available, an empty array is supplied. Array $persistent_view_cache is kept untouched for entire Reference lifetime. If cache is empty, but available, an empty array is supplied. @see AbstractMachine::calculateViewValue()
[ "Get", "properties", "in", "given", "view", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L469-L504
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.urlFormat
protected function urlFormat($id, $url_fmt, $properties_cache): string { if (isset($url_fmt)) { if ($properties_cache === null) { // URL contains ID only, so there is no need to load properties. return Utils::filename_format($url_fmt, array_combine($this->describeId(), (array) $id)); } else { // However, if properties are in cache, it is better to use them. return Utils::filename_format($url_fmt, $properties_cache); } } else { // Default fallback to something reasonable. It might not work, but meh. return '/'.$this->machine_type.'/'.(is_array($id) ? join('/', $id) : $id); } }
php
protected function urlFormat($id, $url_fmt, $properties_cache): string { if (isset($url_fmt)) { if ($properties_cache === null) { // URL contains ID only, so there is no need to load properties. return Utils::filename_format($url_fmt, array_combine($this->describeId(), (array) $id)); } else { // However, if properties are in cache, it is better to use them. return Utils::filename_format($url_fmt, $properties_cache); } } else { // Default fallback to something reasonable. It might not work, but meh. return '/'.$this->machine_type.'/'.(is_array($id) ? join('/', $id) : $id); } }
[ "protected", "function", "urlFormat", "(", "$", "id", ",", "$", "url_fmt", ",", "$", "properties_cache", ")", ":", "string", "{", "if", "(", "isset", "(", "$", "url_fmt", ")", ")", "{", "if", "(", "$", "properties_cache", "===", "null", ")", "{", "// URL contains ID only, so there is no need to load properties.", "return", "Utils", "::", "filename_format", "(", "$", "url_fmt", ",", "array_combine", "(", "$", "this", "->", "describeId", "(", ")", ",", "(", "array", ")", "$", "id", ")", ")", ";", "}", "else", "{", "// However, if properties are in cache, it is better to use them.", "return", "Utils", "::", "filename_format", "(", "$", "url_fmt", ",", "$", "properties_cache", ")", ";", "}", "}", "else", "{", "// Default fallback to something reasonable. It might not work, but meh.", "return", "'/'", ".", "$", "this", "->", "machine_type", ".", "'/'", ".", "(", "is_array", "(", "$", "id", ")", "?", "join", "(", "'/'", ",", "$", "id", ")", ":", "$", "id", ")", ";", "}", "}" ]
Create URL using properties and given format.
[ "Create", "URL", "using", "properties", "and", "given", "format", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L523-L537
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.resolveMachineReference
protected function resolveMachineReference(string $reference_name, array $properties_cache): Reference { if (!isset($this->references[$reference_name])) { throw new \InvalidArgumentException('Unknown reference: '.$reference_name); } // Get reference configuration $r = $this->references[$reference_name]; // Get referenced machine id $ref_machine_id = array(); foreach ($r['machine_id'] as $mid_prop) { $ref_machine_id[] = $properties_cache[$mid_prop]; } // Get referenced machine type $ref_machine_type = $r['machine_type']; return $this->smalldb->getMachine($ref_machine_type)->ref($ref_machine_id); }
php
protected function resolveMachineReference(string $reference_name, array $properties_cache): Reference { if (!isset($this->references[$reference_name])) { throw new \InvalidArgumentException('Unknown reference: '.$reference_name); } // Get reference configuration $r = $this->references[$reference_name]; // Get referenced machine id $ref_machine_id = array(); foreach ($r['machine_id'] as $mid_prop) { $ref_machine_id[] = $properties_cache[$mid_prop]; } // Get referenced machine type $ref_machine_type = $r['machine_type']; return $this->smalldb->getMachine($ref_machine_type)->ref($ref_machine_id); }
[ "protected", "function", "resolveMachineReference", "(", "string", "$", "reference_name", ",", "array", "$", "properties_cache", ")", ":", "Reference", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "references", "[", "$", "reference_name", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unknown reference: '", ".", "$", "reference_name", ")", ";", "}", "// Get reference configuration", "$", "r", "=", "$", "this", "->", "references", "[", "$", "reference_name", "]", ";", "// Get referenced machine id", "$", "ref_machine_id", "=", "array", "(", ")", ";", "foreach", "(", "$", "r", "[", "'machine_id'", "]", "as", "$", "mid_prop", ")", "{", "$", "ref_machine_id", "[", "]", "=", "$", "properties_cache", "[", "$", "mid_prop", "]", ";", "}", "// Get referenced machine type", "$", "ref_machine_type", "=", "$", "r", "[", "'machine_type'", "]", ";", "return", "$", "this", "->", "smalldb", "->", "getMachine", "(", "$", "ref_machine_type", ")", "->", "ref", "(", "$", "ref_machine_id", ")", ";", "}" ]
Helper function to resolve reference to another machine. @param string $reference_name Name of the reference in AbstractMachine::references. @param array $properties_cache Properties of referencing machine. @return Reference to referred machine.
[ "Helper", "function", "to", "resolve", "reference", "to", "another", "machine", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L547-L566
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.isTransitionAllowed
public function isTransitionAllowed(Reference $ref, $transition_name, $state = null, & $access_policy = null) { if ($state === null) { $state = $ref->state; } if ($transition_name == '') { // Read access $access_policy = $this->read_access_policy; return $this->checkAccessPolicy($this->read_access_policy, $ref); } else if (isset($this->actions[$transition_name]['transitions'][$state])) { $tr = $this->actions[$transition_name]['transitions'][$state]; if (isset($tr['access_policy'])) { // Transition-specific policy $access_policy = $tr['access_policy']; } else if (isset($this->actions[$transition_name]['access_policy'])) { // Action-specific policy (for all transitions of this name) $access_policy = $this->actions[$transition_name]['access_policy']; } else { // No policy, use default $access_policy = $this->default_access_policy; } return $this->checkAccessPolicy($access_policy, $ref); } else { // Not a valid transition return false; } }
php
public function isTransitionAllowed(Reference $ref, $transition_name, $state = null, & $access_policy = null) { if ($state === null) { $state = $ref->state; } if ($transition_name == '') { // Read access $access_policy = $this->read_access_policy; return $this->checkAccessPolicy($this->read_access_policy, $ref); } else if (isset($this->actions[$transition_name]['transitions'][$state])) { $tr = $this->actions[$transition_name]['transitions'][$state]; if (isset($tr['access_policy'])) { // Transition-specific policy $access_policy = $tr['access_policy']; } else if (isset($this->actions[$transition_name]['access_policy'])) { // Action-specific policy (for all transitions of this name) $access_policy = $this->actions[$transition_name]['access_policy']; } else { // No policy, use default $access_policy = $this->default_access_policy; } return $this->checkAccessPolicy($access_policy, $ref); } else { // Not a valid transition return false; } }
[ "public", "function", "isTransitionAllowed", "(", "Reference", "$", "ref", ",", "$", "transition_name", ",", "$", "state", "=", "null", ",", "&", "$", "access_policy", "=", "null", ")", "{", "if", "(", "$", "state", "===", "null", ")", "{", "$", "state", "=", "$", "ref", "->", "state", ";", "}", "if", "(", "$", "transition_name", "==", "''", ")", "{", "// Read access", "$", "access_policy", "=", "$", "this", "->", "read_access_policy", ";", "return", "$", "this", "->", "checkAccessPolicy", "(", "$", "this", "->", "read_access_policy", ",", "$", "ref", ")", ";", "}", "else", "if", "(", "isset", "(", "$", "this", "->", "actions", "[", "$", "transition_name", "]", "[", "'transitions'", "]", "[", "$", "state", "]", ")", ")", "{", "$", "tr", "=", "$", "this", "->", "actions", "[", "$", "transition_name", "]", "[", "'transitions'", "]", "[", "$", "state", "]", ";", "if", "(", "isset", "(", "$", "tr", "[", "'access_policy'", "]", ")", ")", "{", "// Transition-specific policy", "$", "access_policy", "=", "$", "tr", "[", "'access_policy'", "]", ";", "}", "else", "if", "(", "isset", "(", "$", "this", "->", "actions", "[", "$", "transition_name", "]", "[", "'access_policy'", "]", ")", ")", "{", "// Action-specific policy (for all transitions of this name)", "$", "access_policy", "=", "$", "this", "->", "actions", "[", "$", "transition_name", "]", "[", "'access_policy'", "]", ";", "}", "else", "{", "// No policy, use default", "$", "access_policy", "=", "$", "this", "->", "default_access_policy", ";", "}", "return", "$", "this", "->", "checkAccessPolicy", "(", "$", "access_policy", ",", "$", "ref", ")", ";", "}", "else", "{", "// Not a valid transition", "return", "false", ";", "}", "}" ]
Returns true if transition can be invoked right now. TODO: Transition should not have full definition of the policy, only its name. Definitions should be in common place.
[ "Returns", "true", "if", "transition", "can", "be", "invoked", "right", "now", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L575-L602
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.ref
public function ref($id): Reference { $ref = new $this->reference_class($this->smalldb, $this, $id); if ($this->debug_logger) { $this->debug_logger->afterReferenceCreated(null, $ref); } return $ref; }
php
public function ref($id): Reference { $ref = new $this->reference_class($this->smalldb, $this, $id); if ($this->debug_logger) { $this->debug_logger->afterReferenceCreated(null, $ref); } return $ref; }
[ "public", "function", "ref", "(", "$", "id", ")", ":", "Reference", "{", "$", "ref", "=", "new", "$", "this", "->", "reference_class", "(", "$", "this", "->", "smalldb", ",", "$", "this", ",", "$", "id", ")", ";", "if", "(", "$", "this", "->", "debug_logger", ")", "{", "$", "this", "->", "debug_logger", "->", "afterReferenceCreated", "(", "null", ",", "$", "ref", ")", ";", "}", "return", "$", "ref", ";", "}" ]
Helper to create Reference to this machine. @see AbstractBackend::ref
[ "Helper", "to", "create", "Reference", "to", "this", "machine", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L758-L765
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.hotRef
public function hotRef($properties): Reference { $ref = $this->reference_class::createPreheatedReference($this->smalldb, $this, $properties); if ($this->debug_logger) { $this->debug_logger->afterReferenceCreated(null, $ref, $properties); } return $ref; }
php
public function hotRef($properties): Reference { $ref = $this->reference_class::createPreheatedReference($this->smalldb, $this, $properties); if ($this->debug_logger) { $this->debug_logger->afterReferenceCreated(null, $ref, $properties); } return $ref; }
[ "public", "function", "hotRef", "(", "$", "properties", ")", ":", "Reference", "{", "$", "ref", "=", "$", "this", "->", "reference_class", "::", "createPreheatedReference", "(", "$", "this", "->", "smalldb", ",", "$", "this", ",", "$", "properties", ")", ";", "if", "(", "$", "this", "->", "debug_logger", ")", "{", "$", "this", "->", "debug_logger", "->", "afterReferenceCreated", "(", "null", ",", "$", "ref", ",", "$", "properties", ")", ";", "}", "return", "$", "ref", ";", "}" ]
Create pre-heated reference using properties loaded from elsewhere. @warning This may break things a lot. Be careful.
[ "Create", "pre", "-", "heated", "reference", "using", "properties", "loaded", "from", "elsewhere", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L788-L795
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.performSelfCheck
public function performSelfCheck() { $results = []; $results['id'] = $this->describeId(); $results['class'] = get_class($this); $results['missing_methods'] = []; $results['errors'] = $this->errors; foreach ($this->describeAllMachineActions() as $a => $action) { foreach ($action['transitions'] as $t => $transition) { $transition = array_merge($action, $transition); $method = isset($transition['method']) ? $transition['method'] : $a; if (!is_callable([$this, $method])) { $results['missing_methods'][] = $method; } } sort($results['missing_methods']); $results['missing_methods'] = array_unique($results['missing_methods']); } $results['unreachable_states'] = $this->findUnreachableStates(); return $results; }
php
public function performSelfCheck() { $results = []; $results['id'] = $this->describeId(); $results['class'] = get_class($this); $results['missing_methods'] = []; $results['errors'] = $this->errors; foreach ($this->describeAllMachineActions() as $a => $action) { foreach ($action['transitions'] as $t => $transition) { $transition = array_merge($action, $transition); $method = isset($transition['method']) ? $transition['method'] : $a; if (!is_callable([$this, $method])) { $results['missing_methods'][] = $method; } } sort($results['missing_methods']); $results['missing_methods'] = array_unique($results['missing_methods']); } $results['unreachable_states'] = $this->findUnreachableStates(); return $results; }
[ "public", "function", "performSelfCheck", "(", ")", "{", "$", "results", "=", "[", "]", ";", "$", "results", "[", "'id'", "]", "=", "$", "this", "->", "describeId", "(", ")", ";", "$", "results", "[", "'class'", "]", "=", "get_class", "(", "$", "this", ")", ";", "$", "results", "[", "'missing_methods'", "]", "=", "[", "]", ";", "$", "results", "[", "'errors'", "]", "=", "$", "this", "->", "errors", ";", "foreach", "(", "$", "this", "->", "describeAllMachineActions", "(", ")", "as", "$", "a", "=>", "$", "action", ")", "{", "foreach", "(", "$", "action", "[", "'transitions'", "]", "as", "$", "t", "=>", "$", "transition", ")", "{", "$", "transition", "=", "array_merge", "(", "$", "action", ",", "$", "transition", ")", ";", "$", "method", "=", "isset", "(", "$", "transition", "[", "'method'", "]", ")", "?", "$", "transition", "[", "'method'", "]", ":", "$", "a", ";", "if", "(", "!", "is_callable", "(", "[", "$", "this", ",", "$", "method", "]", ")", ")", "{", "$", "results", "[", "'missing_methods'", "]", "[", "]", "=", "$", "method", ";", "}", "}", "sort", "(", "$", "results", "[", "'missing_methods'", "]", ")", ";", "$", "results", "[", "'missing_methods'", "]", "=", "array_unique", "(", "$", "results", "[", "'missing_methods'", "]", ")", ";", "}", "$", "results", "[", "'unreachable_states'", "]", "=", "$", "this", "->", "findUnreachableStates", "(", ")", ";", "return", "$", "results", ";", "}" ]
Perform self-check. TODO: Extend this method with more checks. @see AbstractBackend::performSelfCheck()
[ "Perform", "self", "-", "check", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L805-L829
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.findUnreachableStates
public function findUnreachableStates(): array { $g = new Graph(); $g->indexNodeAttr('unreachable'); $g->createNode('', ['unreachable' => false]); foreach ($this->states as $s => $state) { if ($s !== '') { $g->createNode($s, ['unreachable' => true]); } } foreach ($this->actions as $a => $action) { foreach ($action['transitions'] ?? [] as $source => $transition) { foreach ($transition['targets'] ?? [] as $target) { $g->createEdge(null, $g->getNode($source), $g->getNode($target), []); } } } GraphSearch::DFS($g) ->onNode(function (Node $node) use ($g) { $node->setAttr('unreachable', false); return true; }) ->start([$g->getNode('')]); return array_map(function(Node $n) { return $n->getId(); }, $g->getNodesByAttr('unreachable', true)); }
php
public function findUnreachableStates(): array { $g = new Graph(); $g->indexNodeAttr('unreachable'); $g->createNode('', ['unreachable' => false]); foreach ($this->states as $s => $state) { if ($s !== '') { $g->createNode($s, ['unreachable' => true]); } } foreach ($this->actions as $a => $action) { foreach ($action['transitions'] ?? [] as $source => $transition) { foreach ($transition['targets'] ?? [] as $target) { $g->createEdge(null, $g->getNode($source), $g->getNode($target), []); } } } GraphSearch::DFS($g) ->onNode(function (Node $node) use ($g) { $node->setAttr('unreachable', false); return true; }) ->start([$g->getNode('')]); return array_map(function(Node $n) { return $n->getId(); }, $g->getNodesByAttr('unreachable', true)); }
[ "public", "function", "findUnreachableStates", "(", ")", ":", "array", "{", "$", "g", "=", "new", "Graph", "(", ")", ";", "$", "g", "->", "indexNodeAttr", "(", "'unreachable'", ")", ";", "$", "g", "->", "createNode", "(", "''", ",", "[", "'unreachable'", "=>", "false", "]", ")", ";", "foreach", "(", "$", "this", "->", "states", "as", "$", "s", "=>", "$", "state", ")", "{", "if", "(", "$", "s", "!==", "''", ")", "{", "$", "g", "->", "createNode", "(", "$", "s", ",", "[", "'unreachable'", "=>", "true", "]", ")", ";", "}", "}", "foreach", "(", "$", "this", "->", "actions", "as", "$", "a", "=>", "$", "action", ")", "{", "foreach", "(", "$", "action", "[", "'transitions'", "]", "??", "[", "]", "as", "$", "source", "=>", "$", "transition", ")", "{", "foreach", "(", "$", "transition", "[", "'targets'", "]", "??", "[", "]", "as", "$", "target", ")", "{", "$", "g", "->", "createEdge", "(", "null", ",", "$", "g", "->", "getNode", "(", "$", "source", ")", ",", "$", "g", "->", "getNode", "(", "$", "target", ")", ",", "[", "]", ")", ";", "}", "}", "}", "GraphSearch", "::", "DFS", "(", "$", "g", ")", "->", "onNode", "(", "function", "(", "Node", "$", "node", ")", "use", "(", "$", "g", ")", "{", "$", "node", "->", "setAttr", "(", "'unreachable'", ",", "false", ")", ";", "return", "true", ";", "}", ")", "->", "start", "(", "[", "$", "g", "->", "getNode", "(", "''", ")", "]", ")", ";", "return", "array_map", "(", "function", "(", "Node", "$", "n", ")", "{", "return", "$", "n", "->", "getId", "(", ")", ";", "}", ",", "$", "g", "->", "getNodesByAttr", "(", "'unreachable'", ",", "true", ")", ")", ";", "}" ]
Run DFS from not-exists state and return list of unreachable states.
[ "Run", "DFS", "from", "not", "-", "exists", "state", "and", "return", "list", "of", "unreachable", "states", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L835-L863
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.exportDotRenderGroups
private function exportDotRenderGroups($groups, $group_content, $indent = "\t") { foreach ($groups as $g => $group) { echo $indent, "subgraph ", $this->exportDotIdentifier($g, 'cluster_'), " {\n"; if (isset($group['label'])) { echo $indent, "\t", "label = \"", addcslashes($group['label'], '"'), "\";\n"; } if (!empty($group['color'])) { echo $indent, "\t", "color=\"", addcslashes($group['color'], '"'), "\";\n"; echo $indent, "\t", "fontcolor=\"", addcslashes($group['color'], '"'), "\";\n"; } else { // This cannot be defined globally, since nested groups inherit the settings. echo $indent, "\t", "color=\"#666666\";\n"; echo $indent, "\t", "fontcolor=\"#666666\";\n"; } foreach ($group_content[$g] as $s) { echo $indent, "\t", $this->exportDotIdentifier($s), ";\n"; } if (isset($group['groups'])) { $this->exportDotRenderGroups($group['groups'], $group_content, "\t".$indent); } echo $indent, "}\n"; } }
php
private function exportDotRenderGroups($groups, $group_content, $indent = "\t") { foreach ($groups as $g => $group) { echo $indent, "subgraph ", $this->exportDotIdentifier($g, 'cluster_'), " {\n"; if (isset($group['label'])) { echo $indent, "\t", "label = \"", addcslashes($group['label'], '"'), "\";\n"; } if (!empty($group['color'])) { echo $indent, "\t", "color=\"", addcslashes($group['color'], '"'), "\";\n"; echo $indent, "\t", "fontcolor=\"", addcslashes($group['color'], '"'), "\";\n"; } else { // This cannot be defined globally, since nested groups inherit the settings. echo $indent, "\t", "color=\"#666666\";\n"; echo $indent, "\t", "fontcolor=\"#666666\";\n"; } foreach ($group_content[$g] as $s) { echo $indent, "\t", $this->exportDotIdentifier($s), ";\n"; } if (isset($group['groups'])) { $this->exportDotRenderGroups($group['groups'], $group_content, "\t".$indent); } echo $indent, "}\n"; } }
[ "private", "function", "exportDotRenderGroups", "(", "$", "groups", ",", "$", "group_content", ",", "$", "indent", "=", "\"\\t\"", ")", "{", "foreach", "(", "$", "groups", "as", "$", "g", "=>", "$", "group", ")", "{", "echo", "$", "indent", ",", "\"subgraph \"", ",", "$", "this", "->", "exportDotIdentifier", "(", "$", "g", ",", "'cluster_'", ")", ",", "\" {\\n\"", ";", "if", "(", "isset", "(", "$", "group", "[", "'label'", "]", ")", ")", "{", "echo", "$", "indent", ",", "\"\\t\"", ",", "\"label = \\\"\"", ",", "addcslashes", "(", "$", "group", "[", "'label'", "]", ",", "'\"'", ")", ",", "\"\\\";\\n\"", ";", "}", "if", "(", "!", "empty", "(", "$", "group", "[", "'color'", "]", ")", ")", "{", "echo", "$", "indent", ",", "\"\\t\"", ",", "\"color=\\\"\"", ",", "addcslashes", "(", "$", "group", "[", "'color'", "]", ",", "'\"'", ")", ",", "\"\\\";\\n\"", ";", "echo", "$", "indent", ",", "\"\\t\"", ",", "\"fontcolor=\\\"\"", ",", "addcslashes", "(", "$", "group", "[", "'color'", "]", ",", "'\"'", ")", ",", "\"\\\";\\n\"", ";", "}", "else", "{", "// This cannot be defined globally, since nested groups inherit the settings.", "echo", "$", "indent", ",", "\"\\t\"", ",", "\"color=\\\"#666666\\\";\\n\"", ";", "echo", "$", "indent", ",", "\"\\t\"", ",", "\"fontcolor=\\\"#666666\\\";\\n\"", ";", "}", "foreach", "(", "$", "group_content", "[", "$", "g", "]", "as", "$", "s", ")", "{", "echo", "$", "indent", ",", "\"\\t\"", ",", "$", "this", "->", "exportDotIdentifier", "(", "$", "s", ")", ",", "\";\\n\"", ";", "}", "if", "(", "isset", "(", "$", "group", "[", "'groups'", "]", ")", ")", "{", "$", "this", "->", "exportDotRenderGroups", "(", "$", "group", "[", "'groups'", "]", ",", "$", "group_content", ",", "\"\\t\"", ".", "$", "indent", ")", ";", "}", "echo", "$", "indent", ",", "\"}\\n\"", ";", "}", "}" ]
Recursively render groups in state machine diagram.
[ "Recursively", "render", "groups", "in", "state", "machine", "diagram", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1480-L1502
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.exportDotRenderExtras
protected function exportDotRenderExtras($debug_opts) { if (!empty($this->state_diagram_extras)) { echo "\tsubgraph cluster_extras {\n", "\t\tgraph [ margin = 10; ];\n", "\t\tcolor=transparent;\n\n"; foreach($this->state_diagram_extras as $i => $e) { echo "\n\t# Extras ", str_replace("\n", " ", $i), "\n"; echo $e, "\n"; } echo "\t}\n"; } }
php
protected function exportDotRenderExtras($debug_opts) { if (!empty($this->state_diagram_extras)) { echo "\tsubgraph cluster_extras {\n", "\t\tgraph [ margin = 10; ];\n", "\t\tcolor=transparent;\n\n"; foreach($this->state_diagram_extras as $i => $e) { echo "\n\t# Extras ", str_replace("\n", " ", $i), "\n"; echo $e, "\n"; } echo "\t}\n"; } }
[ "protected", "function", "exportDotRenderExtras", "(", "$", "debug_opts", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "state_diagram_extras", ")", ")", "{", "echo", "\"\\tsubgraph cluster_extras {\\n\"", ",", "\"\\t\\tgraph [ margin = 10; ];\\n\"", ",", "\"\\t\\tcolor=transparent;\\n\\n\"", ";", "foreach", "(", "$", "this", "->", "state_diagram_extras", "as", "$", "i", "=>", "$", "e", ")", "{", "echo", "\"\\n\\t# Extras \"", ",", "str_replace", "(", "\"\\n\"", ",", "\" \"", ",", "$", "i", ")", ",", "\"\\n\"", ";", "echo", "$", "e", ",", "\"\\n\"", ";", "}", "echo", "\"\\t}\\n\"", ";", "}", "}" ]
Render extra diagram features. Writes Graphviz dot syntax to stdout (echo), output is placed just before digraph's closing bracket. @param mixed $debug_opts Machine-specific Options to configure visible debug data.
[ "Render", "extra", "diagram", "features", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1514-L1526
train
smalldb/libSmalldb
class/AbstractMachine.php
AbstractMachine.exportJsonAddExtras
protected function exportJsonAddExtras($debug_opts, array $machine_graph): array { if (!empty($this->state_diagram_extras_json)) { $graph = $this->state_diagram_extras_json; if (!isset($graph['layout'])) { $graph['layout'] = 'row'; $graph['layoutOptions'] = [ 'align' => 'top', ]; } if (!isset($graph['nodes'])) { $graph['nodes'] = []; } if (!isset($graph['edges'])) { $graph['edges'] = []; } array_unshift($graph['nodes'], [ 'id' => 'smalldb', 'label' => $this->machine_type, 'graph' => $machine_graph, 'color' => '#aaa', 'x' => 0, 'y' => 0, ]); return $graph; } else { return $machine_graph; } }
php
protected function exportJsonAddExtras($debug_opts, array $machine_graph): array { if (!empty($this->state_diagram_extras_json)) { $graph = $this->state_diagram_extras_json; if (!isset($graph['layout'])) { $graph['layout'] = 'row'; $graph['layoutOptions'] = [ 'align' => 'top', ]; } if (!isset($graph['nodes'])) { $graph['nodes'] = []; } if (!isset($graph['edges'])) { $graph['edges'] = []; } array_unshift($graph['nodes'], [ 'id' => 'smalldb', 'label' => $this->machine_type, 'graph' => $machine_graph, 'color' => '#aaa', 'x' => 0, 'y' => 0, ]); return $graph; } else { return $machine_graph; } }
[ "protected", "function", "exportJsonAddExtras", "(", "$", "debug_opts", ",", "array", "$", "machine_graph", ")", ":", "array", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "state_diagram_extras_json", ")", ")", "{", "$", "graph", "=", "$", "this", "->", "state_diagram_extras_json", ";", "if", "(", "!", "isset", "(", "$", "graph", "[", "'layout'", "]", ")", ")", "{", "$", "graph", "[", "'layout'", "]", "=", "'row'", ";", "$", "graph", "[", "'layoutOptions'", "]", "=", "[", "'align'", "=>", "'top'", ",", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "graph", "[", "'nodes'", "]", ")", ")", "{", "$", "graph", "[", "'nodes'", "]", "=", "[", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "graph", "[", "'edges'", "]", ")", ")", "{", "$", "graph", "[", "'edges'", "]", "=", "[", "]", ";", "}", "array_unshift", "(", "$", "graph", "[", "'nodes'", "]", ",", "[", "'id'", "=>", "'smalldb'", ",", "'label'", "=>", "$", "this", "->", "machine_type", ",", "'graph'", "=>", "$", "machine_graph", ",", "'color'", "=>", "'#aaa'", ",", "'x'", "=>", "0", ",", "'y'", "=>", "0", ",", "]", ")", ";", "return", "$", "graph", ";", "}", "else", "{", "return", "$", "machine_graph", ";", "}", "}" ]
Add extra diagram features into the diagram. Extend this method to add debugging visualizations. @see AbstractMachine::exportJson(). @see https://grafovatko.smalldb.org/ @param mixed $debug_opts Machine-specific Options to configure visible debug data. @param array $machine_graph Smalldb state chart wrapped in a 'smalldb' node.
[ "Add", "extra", "diagram", "features", "into", "the", "diagram", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1541-L1569
train
wigedev/farm
src/DataAccess/MsSQL.php
MsSQL.disconnect
public function disconnect() : void { if ($this->dbconn->inTransaction()) { $this->dbconn->rollBack(); } $this->dbconn = null; $this->is_connected = false; }
php
public function disconnect() : void { if ($this->dbconn->inTransaction()) { $this->dbconn->rollBack(); } $this->dbconn = null; $this->is_connected = false; }
[ "public", "function", "disconnect", "(", ")", ":", "void", "{", "if", "(", "$", "this", "->", "dbconn", "->", "inTransaction", "(", ")", ")", "{", "$", "this", "->", "dbconn", "->", "rollBack", "(", ")", ";", "}", "$", "this", "->", "dbconn", "=", "null", ";", "$", "this", "->", "is_connected", "=", "false", ";", "}" ]
Close the connection if it has been established.
[ "Close", "the", "connection", "if", "it", "has", "been", "established", "." ]
7a1729ec78628b7e5435e4a42e42d547a07af851
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataAccess/MsSQL.php#L92-L99
train
wigedev/farm
src/DataAccess/MsSQL.php
MsSQL.beginTransaction
public function beginTransaction() : bool { if ($this->dbconn->inTransaction()) { throw new TransactionErrorException("A transaction has already been started."); } try { return $this->dbconn->beginTransaction(); } catch (\PDOException $exception) { throw new TransactionsNotSupportedException("Transactions are not supported in this database."); } }
php
public function beginTransaction() : bool { if ($this->dbconn->inTransaction()) { throw new TransactionErrorException("A transaction has already been started."); } try { return $this->dbconn->beginTransaction(); } catch (\PDOException $exception) { throw new TransactionsNotSupportedException("Transactions are not supported in this database."); } }
[ "public", "function", "beginTransaction", "(", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "dbconn", "->", "inTransaction", "(", ")", ")", "{", "throw", "new", "TransactionErrorException", "(", "\"A transaction has already been started.\"", ")", ";", "}", "try", "{", "return", "$", "this", "->", "dbconn", "->", "beginTransaction", "(", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "exception", ")", "{", "throw", "new", "TransactionsNotSupportedException", "(", "\"Transactions are not supported in this database.\"", ")", ";", "}", "}" ]
Start a transaction. @return bool @throws TransactionErrorException if a transaction is already started @throws TransactionsNotSupportedException if transactions are not supported
[ "Start", "a", "transaction", "." ]
7a1729ec78628b7e5435e4a42e42d547a07af851
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataAccess/MsSQL.php#L108-L118
train
wigedev/farm
src/DataAccess/MsSQL.php
MsSQL.toArray
public function toArray() : ?array { if (null === $this->stmt || false === $this->stmt) { return null; } return $this->stmt->toArray(); }
php
public function toArray() : ?array { if (null === $this->stmt || false === $this->stmt) { return null; } return $this->stmt->toArray(); }
[ "public", "function", "toArray", "(", ")", ":", "?", "array", "{", "if", "(", "null", "===", "$", "this", "->", "stmt", "||", "false", "===", "$", "this", "->", "stmt", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "stmt", "->", "toArray", "(", ")", ";", "}" ]
Gets the results and a multidimensional array. @return array|null The results as an array or null if this was not a select or if there was an error.
[ "Gets", "the", "results", "and", "a", "multidimensional", "array", "." ]
7a1729ec78628b7e5435e4a42e42d547a07af851
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataAccess/MsSQL.php#L223-L229
train
amarcinkowski/hospitalplugin
src/utils/ExcelExport.php
ExcelExport.clearName
private static function clearName($string, $removeWords) { $string = str_replace ( ' ', '-', $string ); $string = preg_replace ( '/[^A-Za-z0-9\-]/', '', $string ); foreach ( $removeWords as $word ) { $string = str_replace ( $word, '', $string ); } $string = substr ( $string, 0, 29 ); return $string; }
php
private static function clearName($string, $removeWords) { $string = str_replace ( ' ', '-', $string ); $string = preg_replace ( '/[^A-Za-z0-9\-]/', '', $string ); foreach ( $removeWords as $word ) { $string = str_replace ( $word, '', $string ); } $string = substr ( $string, 0, 29 ); return $string; }
[ "private", "static", "function", "clearName", "(", "$", "string", ",", "$", "removeWords", ")", "{", "$", "string", "=", "str_replace", "(", "' '", ",", "'-'", ",", "$", "string", ")", ";", "$", "string", "=", "preg_replace", "(", "'/[^A-Za-z0-9\\-]/'", ",", "''", ",", "$", "string", ")", ";", "foreach", "(", "$", "removeWords", "as", "$", "word", ")", "{", "$", "string", "=", "str_replace", "(", "$", "word", ",", "''", ",", "$", "string", ")", ";", "}", "$", "string", "=", "substr", "(", "$", "string", ",", "0", ",", "29", ")", ";", "return", "$", "string", ";", "}" ]
remove special chars and words from string @param unknown $string
[ "remove", "special", "chars", "and", "words", "from", "string" ]
acdc2be5157abfbdcafb4dcf6c6ba505e291263f
https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/utils/ExcelExport.php#L94-L102
train
chilimatic/chilimatic-framework
lib/file/Upload.php
Upload.upload
public function upload($file = null) { if (empty($file) || !is_array($file)) return false; $this->u_tmp_name = $file['tmp_name']; $this->u_name = $file['name']; $this->u_size = $file['size']; $this->u_mime_type = $file['type']; $this->u_error = isset($file['error']) ? $file['error'] : null; if ($this->u_error) { throw new FileException("File couldn't be uploaded reason " . FileException::$upload_errors[$this->u_error], Config::get('file_error'), Config::get('error_lvl_low'), __FILE__, __LINE__); } $this->_get_file_extension(); return true; }
php
public function upload($file = null) { if (empty($file) || !is_array($file)) return false; $this->u_tmp_name = $file['tmp_name']; $this->u_name = $file['name']; $this->u_size = $file['size']; $this->u_mime_type = $file['type']; $this->u_error = isset($file['error']) ? $file['error'] : null; if ($this->u_error) { throw new FileException("File couldn't be uploaded reason " . FileException::$upload_errors[$this->u_error], Config::get('file_error'), Config::get('error_lvl_low'), __FILE__, __LINE__); } $this->_get_file_extension(); return true; }
[ "public", "function", "upload", "(", "$", "file", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "file", ")", "||", "!", "is_array", "(", "$", "file", ")", ")", "return", "false", ";", "$", "this", "->", "u_tmp_name", "=", "$", "file", "[", "'tmp_name'", "]", ";", "$", "this", "->", "u_name", "=", "$", "file", "[", "'name'", "]", ";", "$", "this", "->", "u_size", "=", "$", "file", "[", "'size'", "]", ";", "$", "this", "->", "u_mime_type", "=", "$", "file", "[", "'type'", "]", ";", "$", "this", "->", "u_error", "=", "isset", "(", "$", "file", "[", "'error'", "]", ")", "?", "$", "file", "[", "'error'", "]", ":", "null", ";", "if", "(", "$", "this", "->", "u_error", ")", "{", "throw", "new", "FileException", "(", "\"File couldn't be uploaded reason \"", ".", "FileException", "::", "$", "upload_errors", "[", "$", "this", "->", "u_error", "]", ",", "Config", "::", "get", "(", "'file_error'", ")", ",", "Config", "::", "get", "(", "'error_lvl_low'", ")", ",", "__FILE__", ",", "__LINE__", ")", ";", "}", "$", "this", "->", "_get_file_extension", "(", ")", ";", "return", "true", ";", "}" ]
current upload process @param $file array @return bool @throws FileException
[ "current", "upload", "process" ]
8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Upload.php#L80-L98
train
chilimatic/chilimatic-framework
lib/file/Upload.php
Upload._get_file_extension
private function _get_file_extension() { if (empty($this->u_mime_type)) return false; $tmp = explode('/', $this->u_mime_type); $this->file_extension = array_pop($tmp); unset($tmp); return true; }
php
private function _get_file_extension() { if (empty($this->u_mime_type)) return false; $tmp = explode('/', $this->u_mime_type); $this->file_extension = array_pop($tmp); unset($tmp); return true; }
[ "private", "function", "_get_file_extension", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "u_mime_type", ")", ")", "return", "false", ";", "$", "tmp", "=", "explode", "(", "'/'", ",", "$", "this", "->", "u_mime_type", ")", ";", "$", "this", "->", "file_extension", "=", "array_pop", "(", "$", "tmp", ")", ";", "unset", "(", "$", "tmp", ")", ";", "return", "true", ";", "}" ]
gets the suffix for the file that has been uploaded @return bool
[ "gets", "the", "suffix", "for", "the", "file", "that", "has", "been", "uploaded" ]
8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Upload.php#L106-L117
train
smalldb/libSmalldb
class/Graph/ElementAttrIndex.php
ElementAttrIndex.rebuildAttrIndex
private function rebuildAttrIndex(string $key) { $this->index[$key] = []; foreach ($this->elements as $id => $element) { if ($element instanceof $this->elementClassName) { $value = $element->getAttr($key); $this->index[$key][$value][$id] = $element; } else { throw new \InvalidArgumentException("Indexed element must be instance of " . $this->elementClassName); } } }
php
private function rebuildAttrIndex(string $key) { $this->index[$key] = []; foreach ($this->elements as $id => $element) { if ($element instanceof $this->elementClassName) { $value = $element->getAttr($key); $this->index[$key][$value][$id] = $element; } else { throw new \InvalidArgumentException("Indexed element must be instance of " . $this->elementClassName); } } }
[ "private", "function", "rebuildAttrIndex", "(", "string", "$", "key", ")", "{", "$", "this", "->", "index", "[", "$", "key", "]", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "elements", "as", "$", "id", "=>", "$", "element", ")", "{", "if", "(", "$", "element", "instanceof", "$", "this", "->", "elementClassName", ")", "{", "$", "value", "=", "$", "element", "->", "getAttr", "(", "$", "key", ")", ";", "$", "this", "->", "index", "[", "$", "key", "]", "[", "$", "value", "]", "[", "$", "id", "]", "=", "$", "element", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Indexed element must be instance of \"", ".", "$", "this", "->", "elementClassName", ")", ";", "}", "}", "}" ]
Rebuild the entire index from provided elements.
[ "Rebuild", "the", "entire", "index", "from", "provided", "elements", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/ElementAttrIndex.php#L85-L97
train
smalldb/libSmalldb
class/Graph/ElementAttrIndex.php
ElementAttrIndex.removeElement
public function removeElement(AbstractElement $element) { $id = $element->getId(); if (!isset($this->elements[$id])) { throw new MissingElementException("Element \"$id\" is not indexed."); } unset($this->elements[$id]); $indexedAttrs = array_intersect_key($element->getAttributes(), $this->index); foreach ($indexedAttrs as $key => $oldValue) { unset($this->index[$key][$oldValue][$id]); } }
php
public function removeElement(AbstractElement $element) { $id = $element->getId(); if (!isset($this->elements[$id])) { throw new MissingElementException("Element \"$id\" is not indexed."); } unset($this->elements[$id]); $indexedAttrs = array_intersect_key($element->getAttributes(), $this->index); foreach ($indexedAttrs as $key => $oldValue) { unset($this->index[$key][$oldValue][$id]); } }
[ "public", "function", "removeElement", "(", "AbstractElement", "$", "element", ")", "{", "$", "id", "=", "$", "element", "->", "getId", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "elements", "[", "$", "id", "]", ")", ")", "{", "throw", "new", "MissingElementException", "(", "\"Element \\\"$id\\\" is not indexed.\"", ")", ";", "}", "unset", "(", "$", "this", "->", "elements", "[", "$", "id", "]", ")", ";", "$", "indexedAttrs", "=", "array_intersect_key", "(", "$", "element", "->", "getAttributes", "(", ")", ",", "$", "this", "->", "index", ")", ";", "foreach", "(", "$", "indexedAttrs", "as", "$", "key", "=>", "$", "oldValue", ")", "{", "unset", "(", "$", "this", "->", "index", "[", "$", "key", "]", "[", "$", "oldValue", "]", "[", "$", "id", "]", ")", ";", "}", "}" ]
Remove element from index
[ "Remove", "element", "from", "index" ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/ElementAttrIndex.php#L127-L141
train
smalldb/libSmalldb
class/Graph/ElementAttrIndex.php
ElementAttrIndex.update
public function update(string $key, $oldValue, $newValue, AbstractElement $element) { if (!isset($this->index[$key])) { throw new MissingAttrIndexException("Attribute index \"$key\" is not defined."); } $id = $element->getId(); if (isset($this->index[$key][$oldValue][$id])) { unset($this->index[$key][$oldValue][$id]); } else { throw new MissingElementException("Old value of \"$id\" is not indexed."); } $this->index[$key][$newValue][$id] = $element; }
php
public function update(string $key, $oldValue, $newValue, AbstractElement $element) { if (!isset($this->index[$key])) { throw new MissingAttrIndexException("Attribute index \"$key\" is not defined."); } $id = $element->getId(); if (isset($this->index[$key][$oldValue][$id])) { unset($this->index[$key][$oldValue][$id]); } else { throw new MissingElementException("Old value of \"$id\" is not indexed."); } $this->index[$key][$newValue][$id] = $element; }
[ "public", "function", "update", "(", "string", "$", "key", ",", "$", "oldValue", ",", "$", "newValue", ",", "AbstractElement", "$", "element", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "index", "[", "$", "key", "]", ")", ")", "{", "throw", "new", "MissingAttrIndexException", "(", "\"Attribute index \\\"$key\\\" is not defined.\"", ")", ";", "}", "$", "id", "=", "$", "element", "->", "getId", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "index", "[", "$", "key", "]", "[", "$", "oldValue", "]", "[", "$", "id", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "index", "[", "$", "key", "]", "[", "$", "oldValue", "]", "[", "$", "id", "]", ")", ";", "}", "else", "{", "throw", "new", "MissingElementException", "(", "\"Old value of \\\"$id\\\" is not indexed.\"", ")", ";", "}", "$", "this", "->", "index", "[", "$", "key", "]", "[", "$", "newValue", "]", "[", "$", "id", "]", "=", "$", "element", ";", "}" ]
Update indices to match the changed attribute of the element
[ "Update", "indices", "to", "match", "the", "changed", "attribute", "of", "the", "element" ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/ElementAttrIndex.php#L147-L162
train
smalldb/libSmalldb
class/Graph/ElementAttrIndex.php
ElementAttrIndex.getElements
public function getElements(string $key, $value): array { if (!isset($this->index[$key])) { throw new MissingAttrIndexException("Attribute index \"$key\" is not defined."); } return $this->index[$key][$value] ?? []; }
php
public function getElements(string $key, $value): array { if (!isset($this->index[$key])) { throw new MissingAttrIndexException("Attribute index \"$key\" is not defined."); } return $this->index[$key][$value] ?? []; }
[ "public", "function", "getElements", "(", "string", "$", "key", ",", "$", "value", ")", ":", "array", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "index", "[", "$", "key", "]", ")", ")", "{", "throw", "new", "MissingAttrIndexException", "(", "\"Attribute index \\\"$key\\\" is not defined.\"", ")", ";", "}", "return", "$", "this", "->", "index", "[", "$", "key", "]", "[", "$", "value", "]", "??", "[", "]", ";", "}" ]
Get elements by the value of the attribute
[ "Get", "elements", "by", "the", "value", "of", "the", "attribute" ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/ElementAttrIndex.php#L179-L186
train
luoxiaojun1992/lb_framework
components/helpers/HtmlHelper.php
HtmlHelper.image
public static function image($src, $alt = '', $options = []) { $image_tag_tpl = '<img src="%s" alt="%s"%s />'; $cdnHost = Lb::app()->getCdnHost(); if ($cdnHost) { if (!ValidationHelper::isUrl($src)) { $src = $cdnHost . $src; } else { $src = preg_replace('/^(http|https):\/\/.+?\//i', $cdnHost . '/', $src); } } return sprintf($image_tag_tpl, $src, $alt, self::assembleTagOptions($options)); }
php
public static function image($src, $alt = '', $options = []) { $image_tag_tpl = '<img src="%s" alt="%s"%s />'; $cdnHost = Lb::app()->getCdnHost(); if ($cdnHost) { if (!ValidationHelper::isUrl($src)) { $src = $cdnHost . $src; } else { $src = preg_replace('/^(http|https):\/\/.+?\//i', $cdnHost . '/', $src); } } return sprintf($image_tag_tpl, $src, $alt, self::assembleTagOptions($options)); }
[ "public", "static", "function", "image", "(", "$", "src", ",", "$", "alt", "=", "''", ",", "$", "options", "=", "[", "]", ")", "{", "$", "image_tag_tpl", "=", "'<img src=\"%s\" alt=\"%s\"%s />'", ";", "$", "cdnHost", "=", "Lb", "::", "app", "(", ")", "->", "getCdnHost", "(", ")", ";", "if", "(", "$", "cdnHost", ")", "{", "if", "(", "!", "ValidationHelper", "::", "isUrl", "(", "$", "src", ")", ")", "{", "$", "src", "=", "$", "cdnHost", ".", "$", "src", ";", "}", "else", "{", "$", "src", "=", "preg_replace", "(", "'/^(http|https):\\/\\/.+?\\//i'", ",", "$", "cdnHost", ".", "'/'", ",", "$", "src", ")", ";", "}", "}", "return", "sprintf", "(", "$", "image_tag_tpl", ",", "$", "src", ",", "$", "alt", ",", "self", "::", "assembleTagOptions", "(", "$", "options", ")", ")", ";", "}" ]
Generate image tag @param $src @param string $alt @param array $options @return string
[ "Generate", "image", "tag" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/HtmlHelper.php#L84-L96
train
luoxiaojun1992/lb_framework
components/helpers/HtmlHelper.php
HtmlHelper.purify
public static function purify($dirtyHtml) { if (self::$htmlPurifier && self::$htmlPurifier instanceof \HTMLPurifier) { $purifier = self::$htmlPurifier; } else { $purifier = (self::$htmlPurifier = new \HTMLPurifier(\HTMLPurifier_Config::createDefault())); } return $purifier->purify($dirtyHtml); }
php
public static function purify($dirtyHtml) { if (self::$htmlPurifier && self::$htmlPurifier instanceof \HTMLPurifier) { $purifier = self::$htmlPurifier; } else { $purifier = (self::$htmlPurifier = new \HTMLPurifier(\HTMLPurifier_Config::createDefault())); } return $purifier->purify($dirtyHtml); }
[ "public", "static", "function", "purify", "(", "$", "dirtyHtml", ")", "{", "if", "(", "self", "::", "$", "htmlPurifier", "&&", "self", "::", "$", "htmlPurifier", "instanceof", "\\", "HTMLPurifier", ")", "{", "$", "purifier", "=", "self", "::", "$", "htmlPurifier", ";", "}", "else", "{", "$", "purifier", "=", "(", "self", "::", "$", "htmlPurifier", "=", "new", "\\", "HTMLPurifier", "(", "\\", "HTMLPurifier_Config", "::", "createDefault", "(", ")", ")", ")", ";", "}", "return", "$", "purifier", "->", "purify", "(", "$", "dirtyHtml", ")", ";", "}" ]
Purify dirty html @param $dirtyHtml @return mixed
[ "Purify", "dirty", "html" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/HtmlHelper.php#L120-L128
train
krupni/yii-eoauth
src/EOAuthUtils.php
EOAuthUtils.GetRequestToken
public static function GetRequestToken(OAuthConsumer $consumer, $scope, $endpoint, $applicationName, $callbackUrl) { $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1(); // Set parameters. $params = array(); $params['scope'] = $scope; if (isset($applicationName)) { $params['xoauth_displayname'] = $applicationName; } if (isset($callbackUrl)) { $params['oauth_callback'] = $callbackUrl; } // Create and sign request. $request = OAuthRequest::from_consumer_and_token($consumer, NULL, 'GET', $endpoint, $params); $request->sign_request($signatureMethod, $consumer, NULL); // Get token. return self::GetTokenFromUrl($request->to_url()); }
php
public static function GetRequestToken(OAuthConsumer $consumer, $scope, $endpoint, $applicationName, $callbackUrl) { $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1(); // Set parameters. $params = array(); $params['scope'] = $scope; if (isset($applicationName)) { $params['xoauth_displayname'] = $applicationName; } if (isset($callbackUrl)) { $params['oauth_callback'] = $callbackUrl; } // Create and sign request. $request = OAuthRequest::from_consumer_and_token($consumer, NULL, 'GET', $endpoint, $params); $request->sign_request($signatureMethod, $consumer, NULL); // Get token. return self::GetTokenFromUrl($request->to_url()); }
[ "public", "static", "function", "GetRequestToken", "(", "OAuthConsumer", "$", "consumer", ",", "$", "scope", ",", "$", "endpoint", ",", "$", "applicationName", ",", "$", "callbackUrl", ")", "{", "$", "signatureMethod", "=", "new", "OAuthSignatureMethod_HMAC_SHA1", "(", ")", ";", "// Set parameters.", "$", "params", "=", "array", "(", ")", ";", "$", "params", "[", "'scope'", "]", "=", "$", "scope", ";", "if", "(", "isset", "(", "$", "applicationName", ")", ")", "{", "$", "params", "[", "'xoauth_displayname'", "]", "=", "$", "applicationName", ";", "}", "if", "(", "isset", "(", "$", "callbackUrl", ")", ")", "{", "$", "params", "[", "'oauth_callback'", "]", "=", "$", "callbackUrl", ";", "}", "// Create and sign request.", "$", "request", "=", "OAuthRequest", "::", "from_consumer_and_token", "(", "$", "consumer", ",", "NULL", ",", "'GET'", ",", "$", "endpoint", ",", "$", "params", ")", ";", "$", "request", "->", "sign_request", "(", "$", "signatureMethod", ",", "$", "consumer", ",", "NULL", ")", ";", "// Get token.", "return", "self", "::", "GetTokenFromUrl", "(", "$", "request", "->", "to_url", "(", ")", ")", ";", "}" ]
Using the consumer and scope provided, a request is made to the endpoint to generate an OAuth request token. @param OAuthConsumer $consumer the consumer @param string $scope the scope of the application to authorize @param string $endpoint the OAuth endpoint to make the request against @param string $applicationName optional name of the application to display on the authorization redirect page @param string $callbackUrl optional callback URL @return OAuthToken a request token @see http://code.google.com/apis/accounts/docs/OAuth_ref.html#RequestToken
[ "Using", "the", "consumer", "and", "scope", "provided", "a", "request", "is", "made", "to", "the", "endpoint", "to", "generate", "an", "OAuth", "request", "token", "." ]
182bcaaea73c87d90635c2201213273f40cfab26
https://github.com/krupni/yii-eoauth/blob/182bcaaea73c87d90635c2201213273f40cfab26/src/EOAuthUtils.php#L35-L56
train
krupni/yii-eoauth
src/EOAuthUtils.php
EOAuthUtils.GetAccessToken
public static function GetAccessToken(OAuthConsumer $consumer, OAuthToken $token, $verifier, $endpoint) { $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1(); // Set parameters. $params = array(); $params['oauth_verifier'] = $verifier; // Create and sign request. $request = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $endpoint, $params); $request->sign_request($signatureMethod, $consumer, $token); // Get token. return self::GetTokenFromUrl($request->to_url()); }
php
public static function GetAccessToken(OAuthConsumer $consumer, OAuthToken $token, $verifier, $endpoint) { $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1(); // Set parameters. $params = array(); $params['oauth_verifier'] = $verifier; // Create and sign request. $request = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $endpoint, $params); $request->sign_request($signatureMethod, $consumer, $token); // Get token. return self::GetTokenFromUrl($request->to_url()); }
[ "public", "static", "function", "GetAccessToken", "(", "OAuthConsumer", "$", "consumer", ",", "OAuthToken", "$", "token", ",", "$", "verifier", ",", "$", "endpoint", ")", "{", "$", "signatureMethod", "=", "new", "OAuthSignatureMethod_HMAC_SHA1", "(", ")", ";", "// Set parameters.", "$", "params", "=", "array", "(", ")", ";", "$", "params", "[", "'oauth_verifier'", "]", "=", "$", "verifier", ";", "// Create and sign request.", "$", "request", "=", "OAuthRequest", "::", "from_consumer_and_token", "(", "$", "consumer", ",", "$", "token", ",", "'GET'", ",", "$", "endpoint", ",", "$", "params", ")", ";", "$", "request", "->", "sign_request", "(", "$", "signatureMethod", ",", "$", "consumer", ",", "$", "token", ")", ";", "// Get token.", "return", "self", "::", "GetTokenFromUrl", "(", "$", "request", "->", "to_url", "(", ")", ")", ";", "}" ]
Using the provided consumer and authorized request token, a request is made to the endpoint to generate an OAuth access token. @param OAuthConsumer $consumer the consumer @param OAuthToken $token the authorized request token @param string $verifier the OAuth verifier code returned with the callback @param string $endpoint the OAuth endpoint to make the request against @return OAuthToken an access token @see http://code.google.com/apis/accounts/docs/OAuth_ref.html#AccessToken
[ "Using", "the", "provided", "consumer", "and", "authorized", "request", "token", "a", "request", "is", "made", "to", "the", "endpoint", "to", "generate", "an", "OAuth", "access", "token", "." ]
182bcaaea73c87d90635c2201213273f40cfab26
https://github.com/krupni/yii-eoauth/blob/182bcaaea73c87d90635c2201213273f40cfab26/src/EOAuthUtils.php#L80-L95
train
krupni/yii-eoauth
src/EOAuthUtils.php
EOAuthUtils.GetTokenFromUrl
private static function GetTokenFromUrl($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); $headers = curl_getinfo($ch); curl_close($ch); if ($headers['http_code'] != 200) { throw new OAuthException($response); } return self::GetTokenFromQueryString($response); }
php
private static function GetTokenFromUrl($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); $headers = curl_getinfo($ch); curl_close($ch); if ($headers['http_code'] != 200) { throw new OAuthException($response); } return self::GetTokenFromQueryString($response); }
[ "private", "static", "function", "GetTokenFromUrl", "(", "$", "url", ")", "{", "$", "ch", "=", "curl_init", "(", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_FOLLOWLOCATION", ",", "1", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADER", ",", "0", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "1", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "0", ")", ";", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "$", "headers", "=", "curl_getinfo", "(", "$", "ch", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "if", "(", "$", "headers", "[", "'http_code'", "]", "!=", "200", ")", "{", "throw", "new", "OAuthException", "(", "$", "response", ")", ";", "}", "return", "self", "::", "GetTokenFromQueryString", "(", "$", "response", ")", ";", "}" ]
Makes an HTTP request to the given URL and extracts the returned OAuth token. @param string $url the URL to make the request to @return OAuthToken the returned token
[ "Makes", "an", "HTTP", "request", "to", "the", "given", "URL", "and", "extracts", "the", "returned", "OAuth", "token", "." ]
182bcaaea73c87d90635c2201213273f40cfab26
https://github.com/krupni/yii-eoauth/blob/182bcaaea73c87d90635c2201213273f40cfab26/src/EOAuthUtils.php#L103-L118
train
chilimatic/chilimatic-framework
lib/database/sql/mysql/MySQLClone.php
MySQLClone.init
public function init($main_db, $clone_db, $table_list = null) { try { if (empty($main_db) && empty($clone_db)) return false; if (!$this->select_db((string)$main_db)) { throw new DatabaseException('Could not select Main Database ' . $main_db); } $this->clone_dbname = $clone_db; $this->main_dbname = $main_db; $sql = "SHOW DATABASES"; if (($this->database_list = $this->fetch_simple_list($this->query((string)$sql))) == false) { throw new DatabaseException('No Databases on the Main Server'); } $this->clone_exists = (!in_array($clone_db, $this->database_list)) ? false : true; if (empty($table_list)) { $sql = "SHOW TABLES"; $this->table_list = $this->fetch_simple_list($this->query($sql)); } elseif (!is_array($table_list)) { $this->table_list = array( $table_list ); } else { $this->table_list = $table_list; } if ($this->clone_exists === false && !$this->clone_database($main_db, $clone_db)) { throw new DatabaseException('Couldnt replicate database'); } foreach ($this->table_list as $table_name) { if ($this->clone_exists) { $sql = ($this->force_rebuild) ? "DROP TABLE `{$clone_db}`.`{$table_name}`" : "TRUNCATE `{$clone_db}`.`{$table_name}`"; $this->query($sql); } $sql = "CREATE TABLE `{$clone_db}`.`{$table_name}` LIKE `{$main_db}`.`{$table_name}`"; if (!$this->query($sql)) continue; $sql = "INSERT INTO `{$clone_db}`.`{$table_name}` SELECT * FROM `{$main_db}`.`{$table_name}`"; if (!$this->query($sql)) continue; } } catch (DatabaseException $e) { throw $e; } return true; }
php
public function init($main_db, $clone_db, $table_list = null) { try { if (empty($main_db) && empty($clone_db)) return false; if (!$this->select_db((string)$main_db)) { throw new DatabaseException('Could not select Main Database ' . $main_db); } $this->clone_dbname = $clone_db; $this->main_dbname = $main_db; $sql = "SHOW DATABASES"; if (($this->database_list = $this->fetch_simple_list($this->query((string)$sql))) == false) { throw new DatabaseException('No Databases on the Main Server'); } $this->clone_exists = (!in_array($clone_db, $this->database_list)) ? false : true; if (empty($table_list)) { $sql = "SHOW TABLES"; $this->table_list = $this->fetch_simple_list($this->query($sql)); } elseif (!is_array($table_list)) { $this->table_list = array( $table_list ); } else { $this->table_list = $table_list; } if ($this->clone_exists === false && !$this->clone_database($main_db, $clone_db)) { throw new DatabaseException('Couldnt replicate database'); } foreach ($this->table_list as $table_name) { if ($this->clone_exists) { $sql = ($this->force_rebuild) ? "DROP TABLE `{$clone_db}`.`{$table_name}`" : "TRUNCATE `{$clone_db}`.`{$table_name}`"; $this->query($sql); } $sql = "CREATE TABLE `{$clone_db}`.`{$table_name}` LIKE `{$main_db}`.`{$table_name}`"; if (!$this->query($sql)) continue; $sql = "INSERT INTO `{$clone_db}`.`{$table_name}` SELECT * FROM `{$main_db}`.`{$table_name}`"; if (!$this->query($sql)) continue; } } catch (DatabaseException $e) { throw $e; } return true; }
[ "public", "function", "init", "(", "$", "main_db", ",", "$", "clone_db", ",", "$", "table_list", "=", "null", ")", "{", "try", "{", "if", "(", "empty", "(", "$", "main_db", ")", "&&", "empty", "(", "$", "clone_db", ")", ")", "return", "false", ";", "if", "(", "!", "$", "this", "->", "select_db", "(", "(", "string", ")", "$", "main_db", ")", ")", "{", "throw", "new", "DatabaseException", "(", "'Could not select Main Database '", ".", "$", "main_db", ")", ";", "}", "$", "this", "->", "clone_dbname", "=", "$", "clone_db", ";", "$", "this", "->", "main_dbname", "=", "$", "main_db", ";", "$", "sql", "=", "\"SHOW DATABASES\"", ";", "if", "(", "(", "$", "this", "->", "database_list", "=", "$", "this", "->", "fetch_simple_list", "(", "$", "this", "->", "query", "(", "(", "string", ")", "$", "sql", ")", ")", ")", "==", "false", ")", "{", "throw", "new", "DatabaseException", "(", "'No Databases on the Main Server'", ")", ";", "}", "$", "this", "->", "clone_exists", "=", "(", "!", "in_array", "(", "$", "clone_db", ",", "$", "this", "->", "database_list", ")", ")", "?", "false", ":", "true", ";", "if", "(", "empty", "(", "$", "table_list", ")", ")", "{", "$", "sql", "=", "\"SHOW TABLES\"", ";", "$", "this", "->", "table_list", "=", "$", "this", "->", "fetch_simple_list", "(", "$", "this", "->", "query", "(", "$", "sql", ")", ")", ";", "}", "elseif", "(", "!", "is_array", "(", "$", "table_list", ")", ")", "{", "$", "this", "->", "table_list", "=", "array", "(", "$", "table_list", ")", ";", "}", "else", "{", "$", "this", "->", "table_list", "=", "$", "table_list", ";", "}", "if", "(", "$", "this", "->", "clone_exists", "===", "false", "&&", "!", "$", "this", "->", "clone_database", "(", "$", "main_db", ",", "$", "clone_db", ")", ")", "{", "throw", "new", "DatabaseException", "(", "'Couldnt replicate database'", ")", ";", "}", "foreach", "(", "$", "this", "->", "table_list", "as", "$", "table_name", ")", "{", "if", "(", "$", "this", "->", "clone_exists", ")", "{", "$", "sql", "=", "(", "$", "this", "->", "force_rebuild", ")", "?", "\"DROP TABLE `{$clone_db}`.`{$table_name}`\"", ":", "\"TRUNCATE `{$clone_db}`.`{$table_name}`\"", ";", "$", "this", "->", "query", "(", "$", "sql", ")", ";", "}", "$", "sql", "=", "\"CREATE TABLE `{$clone_db}`.`{$table_name}` LIKE `{$main_db}`.`{$table_name}`\"", ";", "if", "(", "!", "$", "this", "->", "query", "(", "$", "sql", ")", ")", "continue", ";", "$", "sql", "=", "\"INSERT INTO `{$clone_db}`.`{$table_name}` SELECT * FROM `{$main_db}`.`{$table_name}`\"", ";", "if", "(", "!", "$", "this", "->", "query", "(", "$", "sql", ")", ")", "continue", ";", "}", "}", "catch", "(", "DatabaseException", "$", "e", ")", "{", "throw", "$", "e", ";", "}", "return", "true", ";", "}" ]
starts the cloning process @param $main_db string @param $clone_db string @param $table_list array|string @throws \chilimatic\exception\DatabaseException @throws \Exception @return boolean
[ "starts", "the", "cloning", "process" ]
8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/MySQLClone.php#L77-L129
train
chilimatic/chilimatic-framework
lib/database/sql/mysql/MySQLClone.php
MySQLClone.clone_database
public function clone_database($main_db = null, $clone_db = null) { if (empty($this->db)) { throw new DatabaseException('Clone or Main database not connected'); } if (empty($main_db) || empty($clone_db)) { throw new DatabaseException('clone names havent been set'); } $sql = "SHOW CREATE DATABASE `$main_db`"; $result = $this->fetch_assoc($this->query($sql)); $create_sql = str_replace($main_db, $clone_db, $result['Create Database']); if (empty($create_sql)) { throw new DatabaseException('Create database statement is empty!'); } return $this->query($create_sql); }
php
public function clone_database($main_db = null, $clone_db = null) { if (empty($this->db)) { throw new DatabaseException('Clone or Main database not connected'); } if (empty($main_db) || empty($clone_db)) { throw new DatabaseException('clone names havent been set'); } $sql = "SHOW CREATE DATABASE `$main_db`"; $result = $this->fetch_assoc($this->query($sql)); $create_sql = str_replace($main_db, $clone_db, $result['Create Database']); if (empty($create_sql)) { throw new DatabaseException('Create database statement is empty!'); } return $this->query($create_sql); }
[ "public", "function", "clone_database", "(", "$", "main_db", "=", "null", ",", "$", "clone_db", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "db", ")", ")", "{", "throw", "new", "DatabaseException", "(", "'Clone or Main database not connected'", ")", ";", "}", "if", "(", "empty", "(", "$", "main_db", ")", "||", "empty", "(", "$", "clone_db", ")", ")", "{", "throw", "new", "DatabaseException", "(", "'clone names havent been set'", ")", ";", "}", "$", "sql", "=", "\"SHOW CREATE DATABASE `$main_db`\"", ";", "$", "result", "=", "$", "this", "->", "fetch_assoc", "(", "$", "this", "->", "query", "(", "$", "sql", ")", ")", ";", "$", "create_sql", "=", "str_replace", "(", "$", "main_db", ",", "$", "clone_db", ",", "$", "result", "[", "'Create Database'", "]", ")", ";", "if", "(", "empty", "(", "$", "create_sql", ")", ")", "{", "throw", "new", "DatabaseException", "(", "'Create database statement is empty!'", ")", ";", "}", "return", "$", "this", "->", "query", "(", "$", "create_sql", ")", ";", "}" ]
clones the specific database @param $main_db string @param $clone_db string @return bool @throws DatabaseException @throws \Exception
[ "clones", "the", "specific", "database" ]
8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/MySQLClone.php#L142-L163
train
ben-gibson/foursquare-venue-client
src/Factory/Photo/PhotoGroupFactory.php
PhotoGroupFactory.getPhotos
private function getPhotos(Description $description) { return array_map( function (\stdClass $photoDescription) { return $this->photoFactory->create(new Description($photoDescription)); }, $description->getOptionalProperty('items', []) ); }
php
private function getPhotos(Description $description) { return array_map( function (\stdClass $photoDescription) { return $this->photoFactory->create(new Description($photoDescription)); }, $description->getOptionalProperty('items', []) ); }
[ "private", "function", "getPhotos", "(", "Description", "$", "description", ")", "{", "return", "array_map", "(", "function", "(", "\\", "stdClass", "$", "photoDescription", ")", "{", "return", "$", "this", "->", "photoFactory", "->", "create", "(", "new", "Description", "(", "$", "photoDescription", ")", ")", ";", "}", ",", "$", "description", "->", "getOptionalProperty", "(", "'items'", ",", "[", "]", ")", ")", ";", "}" ]
Get the venue photos. @param Description $description The photo group description. @return Photo[]
[ "Get", "the", "venue", "photos", "." ]
ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969
https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/Photo/PhotoGroupFactory.php#L49-L57
train
andyburton/Sonic-Framework
src/Message.php
Message.getString
public static function getString ($status = FALSE, $tagStart = NULL, $tagEnd = "\n") { // Get messages $arr = self::get ($status); // Set message string $str = ''; foreach ($arr as $msg) { $str .= $tagStart . $msg . $tagEnd; } // Return message return $str; }
php
public static function getString ($status = FALSE, $tagStart = NULL, $tagEnd = "\n") { // Get messages $arr = self::get ($status); // Set message string $str = ''; foreach ($arr as $msg) { $str .= $tagStart . $msg . $tagEnd; } // Return message return $str; }
[ "public", "static", "function", "getString", "(", "$", "status", "=", "FALSE", ",", "$", "tagStart", "=", "NULL", ",", "$", "tagEnd", "=", "\"\\n\"", ")", "{", "// Get messages", "$", "arr", "=", "self", "::", "get", "(", "$", "status", ")", ";", "// Set message string", "$", "str", "=", "''", ";", "foreach", "(", "$", "arr", "as", "$", "msg", ")", "{", "$", "str", ".=", "$", "tagStart", ".", "$", "msg", ".", "$", "tagEnd", ";", "}", "// Return message", "return", "$", "str", ";", "}" ]
Return messages as a string @param mixed $status Message status to return @param string $tagStart Opening tag for each message @param string $tagEnd Closing tag for each message @return string
[ "Return", "messages", "as", "a", "string" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Message.php#L71-L91
train
andyburton/Sonic-Framework
src/Message.php
Message.count
public static function count ($status = FALSE) { // If no status return all messages if ($status === FALSE) { return count (self::$messages); } // Return messages for a specific status if (isset (self::$messages[$status])) { return count (self::$messages[$status]); } else { return 0; } }
php
public static function count ($status = FALSE) { // If no status return all messages if ($status === FALSE) { return count (self::$messages); } // Return messages for a specific status if (isset (self::$messages[$status])) { return count (self::$messages[$status]); } else { return 0; } }
[ "public", "static", "function", "count", "(", "$", "status", "=", "FALSE", ")", "{", "// If no status return all messages", "if", "(", "$", "status", "===", "FALSE", ")", "{", "return", "count", "(", "self", "::", "$", "messages", ")", ";", "}", "// Return messages for a specific status", "if", "(", "isset", "(", "self", "::", "$", "messages", "[", "$", "status", "]", ")", ")", "{", "return", "count", "(", "self", "::", "$", "messages", "[", "$", "status", "]", ")", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Return number of messages @param mixed $status Message status to count @return integer
[ "Return", "number", "of", "messages" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Message.php#L126-L147
train
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.getBasicDefinition
public function getBasicDefinition($class) { if (!class_exists($class)) { throw new \InvalidArgumentException("$class is not a valid class name"); } $definition = new Definition($class, []); $traits = $this->classUsesDeep($class); foreach ($traits as $trait) { switch ($trait) { case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEvaluator': $definition->addMethodCall('setEvaluator', [new Reference('smartesb.util.evaluator')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesSerializer': $definition->addMethodCall('setSerializer', [new Reference('jms_serializer')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesValidator': $definition->addMethodCall('setValidator', [new Reference('validator')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEventDispatcher': $definition->addMethodCall('setEventDispatcher', [new Reference('event_dispatcher')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEndpointFactory': $definition->addMethodCall('setEndpointFactory', [new Reference('smartesb.endpoint_factory')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEndpointRouter': $definition->addMethodCall('setEndpointsRouter', [new Reference('smartesb.router.endpoints')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\MessageFactoryAware': $definition->addMethodCall('setMessageFactory', [new Reference('smartesb.message_factory')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesCacheService': $definition->addMethodCall('setCacheService', [new Reference('smartcore.cache_service')]); break; case 'Symfony\Component\DependencyInjection\ContainerAwareTrait': $definition->addMethodCall('setContainer', [new Reference('service_container')]); break; } } return $definition; }
php
public function getBasicDefinition($class) { if (!class_exists($class)) { throw new \InvalidArgumentException("$class is not a valid class name"); } $definition = new Definition($class, []); $traits = $this->classUsesDeep($class); foreach ($traits as $trait) { switch ($trait) { case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEvaluator': $definition->addMethodCall('setEvaluator', [new Reference('smartesb.util.evaluator')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesSerializer': $definition->addMethodCall('setSerializer', [new Reference('jms_serializer')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesValidator': $definition->addMethodCall('setValidator', [new Reference('validator')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEventDispatcher': $definition->addMethodCall('setEventDispatcher', [new Reference('event_dispatcher')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEndpointFactory': $definition->addMethodCall('setEndpointFactory', [new Reference('smartesb.endpoint_factory')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEndpointRouter': $definition->addMethodCall('setEndpointsRouter', [new Reference('smartesb.router.endpoints')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\MessageFactoryAware': $definition->addMethodCall('setMessageFactory', [new Reference('smartesb.message_factory')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesCacheService': $definition->addMethodCall('setCacheService', [new Reference('smartcore.cache_service')]); break; case 'Symfony\Component\DependencyInjection\ContainerAwareTrait': $definition->addMethodCall('setContainer', [new Reference('service_container')]); break; } } return $definition; }
[ "public", "function", "getBasicDefinition", "(", "$", "class", ")", "{", "if", "(", "!", "class_exists", "(", "$", "class", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"$class is not a valid class name\"", ")", ";", "}", "$", "definition", "=", "new", "Definition", "(", "$", "class", ",", "[", "]", ")", ";", "$", "traits", "=", "$", "this", "->", "classUsesDeep", "(", "$", "class", ")", ";", "foreach", "(", "$", "traits", "as", "$", "trait", ")", "{", "switch", "(", "$", "trait", ")", "{", "case", "'Smartbox\\Integration\\FrameworkBundle\\DependencyInjection\\Traits\\UsesEvaluator'", ":", "$", "definition", "->", "addMethodCall", "(", "'setEvaluator'", ",", "[", "new", "Reference", "(", "'smartesb.util.evaluator'", ")", "]", ")", ";", "break", ";", "case", "'Smartbox\\Integration\\FrameworkBundle\\DependencyInjection\\Traits\\UsesSerializer'", ":", "$", "definition", "->", "addMethodCall", "(", "'setSerializer'", ",", "[", "new", "Reference", "(", "'jms_serializer'", ")", "]", ")", ";", "break", ";", "case", "'Smartbox\\Integration\\FrameworkBundle\\DependencyInjection\\Traits\\UsesValidator'", ":", "$", "definition", "->", "addMethodCall", "(", "'setValidator'", ",", "[", "new", "Reference", "(", "'validator'", ")", "]", ")", ";", "break", ";", "case", "'Smartbox\\Integration\\FrameworkBundle\\DependencyInjection\\Traits\\UsesEventDispatcher'", ":", "$", "definition", "->", "addMethodCall", "(", "'setEventDispatcher'", ",", "[", "new", "Reference", "(", "'event_dispatcher'", ")", "]", ")", ";", "break", ";", "case", "'Smartbox\\Integration\\FrameworkBundle\\DependencyInjection\\Traits\\UsesEndpointFactory'", ":", "$", "definition", "->", "addMethodCall", "(", "'setEndpointFactory'", ",", "[", "new", "Reference", "(", "'smartesb.endpoint_factory'", ")", "]", ")", ";", "break", ";", "case", "'Smartbox\\Integration\\FrameworkBundle\\DependencyInjection\\Traits\\UsesEndpointRouter'", ":", "$", "definition", "->", "addMethodCall", "(", "'setEndpointsRouter'", ",", "[", "new", "Reference", "(", "'smartesb.router.endpoints'", ")", "]", ")", ";", "break", ";", "case", "'Smartbox\\Integration\\FrameworkBundle\\DependencyInjection\\Traits\\MessageFactoryAware'", ":", "$", "definition", "->", "addMethodCall", "(", "'setMessageFactory'", ",", "[", "new", "Reference", "(", "'smartesb.message_factory'", ")", "]", ")", ";", "break", ";", "case", "'Smartbox\\Integration\\FrameworkBundle\\DependencyInjection\\Traits\\UsesCacheService'", ":", "$", "definition", "->", "addMethodCall", "(", "'setCacheService'", ",", "[", "new", "Reference", "(", "'smartcore.cache_service'", ")", "]", ")", ";", "break", ";", "case", "'Symfony\\Component\\DependencyInjection\\ContainerAwareTrait'", ":", "$", "definition", "->", "addMethodCall", "(", "'setContainer'", ",", "[", "new", "Reference", "(", "'service_container'", ")", "]", ")", ";", "break", ";", "}", "}", "return", "$", "definition", ";", "}" ]
Creates a basic service definition for the given class, injecting the typical dependencies according with the traits the class uses. @return Definition
[ "Creates", "a", "basic", "service", "definition", "for", "the", "given", "class", "injecting", "the", "typical", "dependencies", "according", "with", "the", "traits", "the", "class", "uses", "." ]
f38505c50a446707b8e8f79ecaa1addd0a6cca11
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L123-L173
train
phPoirot/Stream
Filter/aFilterStreamCustom.php
aFilterStreamCustom.getLabel
function getLabel() { if ($this->filtername) return $this->filtername; $className = explode('\\', get_class($this)); $className = $className[count($className)-1]; return $className.'.*'; }
php
function getLabel() { if ($this->filtername) return $this->filtername; $className = explode('\\', get_class($this)); $className = $className[count($className)-1]; return $className.'.*'; }
[ "function", "getLabel", "(", ")", "{", "if", "(", "$", "this", "->", "filtername", ")", "return", "$", "this", "->", "filtername", ";", "$", "className", "=", "explode", "(", "'\\\\'", ",", "get_class", "(", "$", "this", ")", ")", ";", "$", "className", "=", "$", "className", "[", "count", "(", "$", "className", ")", "-", "1", "]", ";", "return", "$", "className", ".", "'.*'", ";", "}" ]
Label Used To Register Our Filter @return string
[ "Label", "Used", "To", "Register", "Our", "Filter" ]
db448ee0528c2a5b07c594b8a30e2543fbc15f57
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Filter/aFilterStreamCustom.php#L72-L81
train
phPoirot/Stream
Filter/aFilterStreamCustom.php
aFilterStreamCustom._getDataFromBucket
protected function _getDataFromBucket($in, &$consumed) { $data = ''; while ($bucket = stream_bucket_make_writeable($in)) { $data .= $bucket->data; $consumed += $bucket->datalen; } return $data; }
php
protected function _getDataFromBucket($in, &$consumed) { $data = ''; while ($bucket = stream_bucket_make_writeable($in)) { $data .= $bucket->data; $consumed += $bucket->datalen; } return $data; }
[ "protected", "function", "_getDataFromBucket", "(", "$", "in", ",", "&", "$", "consumed", ")", "{", "$", "data", "=", "''", ";", "while", "(", "$", "bucket", "=", "stream_bucket_make_writeable", "(", "$", "in", ")", ")", "{", "$", "data", ".=", "$", "bucket", "->", "data", ";", "$", "consumed", "+=", "$", "bucket", "->", "datalen", ";", "}", "return", "$", "data", ";", "}" ]
Read Data From Bucket @param resource $in userfilter.bucket brigade @param int $consumed @return string
[ "Read", "Data", "From", "Bucket" ]
db448ee0528c2a5b07c594b8a30e2543fbc15f57
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Filter/aFilterStreamCustom.php#L156-L165
train
phPoirot/Stream
Filter/aFilterStreamCustom.php
aFilterStreamCustom._writeBackDataOut
protected function _writeBackDataOut($out, $data) { $buck = stream_bucket_new($this->bufferHandle, ''); if (false === $buck) // trigger filter error return PSFS_ERR_FATAL; $buck->data = $data; stream_bucket_append($out, $buck); // data was processed successfully return PSFS_PASS_ON; }
php
protected function _writeBackDataOut($out, $data) { $buck = stream_bucket_new($this->bufferHandle, ''); if (false === $buck) // trigger filter error return PSFS_ERR_FATAL; $buck->data = $data; stream_bucket_append($out, $buck); // data was processed successfully return PSFS_PASS_ON; }
[ "protected", "function", "_writeBackDataOut", "(", "$", "out", ",", "$", "data", ")", "{", "$", "buck", "=", "stream_bucket_new", "(", "$", "this", "->", "bufferHandle", ",", "''", ")", ";", "if", "(", "false", "===", "$", "buck", ")", "// trigger filter error", "return", "PSFS_ERR_FATAL", ";", "$", "buck", "->", "data", "=", "$", "data", ";", "stream_bucket_append", "(", "$", "out", ",", "$", "buck", ")", ";", "// data was processed successfully", "return", "PSFS_PASS_ON", ";", "}" ]
Write Back Filtered Data On Out Bucket @param resource $out userfilter.bucket brigade @param string $data @return int PSFS_ERR_FATAL|PSFS_PASS_ON
[ "Write", "Back", "Filtered", "Data", "On", "Out", "Bucket" ]
db448ee0528c2a5b07c594b8a30e2543fbc15f57
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Filter/aFilterStreamCustom.php#L175-L187
train
zikula/FileSystem
Facade/SftpFacade.php
SftpFacade.authPubkey
public function authPubkey($session, $username, $pubkey, $privkey, $passphrase) { return ssh2_auth_pubkey_file($session, $username, $pubkey, $privkey, $passphrase); }
php
public function authPubkey($session, $username, $pubkey, $privkey, $passphrase) { return ssh2_auth_pubkey_file($session, $username, $pubkey, $privkey, $passphrase); }
[ "public", "function", "authPubkey", "(", "$", "session", ",", "$", "username", ",", "$", "pubkey", ",", "$", "privkey", ",", "$", "passphrase", ")", "{", "return", "ssh2_auth_pubkey_file", "(", "$", "session", ",", "$", "username", ",", "$", "pubkey", ",", "$", "privkey", ",", "$", "passphrase", ")", ";", "}" ]
Facade for ssh2_auth_pubkey_file. @param resource $session The resource to login to. @param string $username The username to login with. @param string $pubkey The path to the public key to use. @param string $privkey The path to the private key. @param string $passphrase The passphrase for the key. @return boolean True if logged in.
[ "Facade", "for", "ssh2_auth_pubkey_file", "." ]
8e12d6839aa50a7590f5ad22cc2d33c8f88ff726
https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Facade/SftpFacade.php#L68-L71
train
zikula/FileSystem
Facade/SftpFacade.php
SftpFacade.scpSend
public function scpSend($session, $local_file, $remote_file, $create_mode = 0644) { return ssh2_scp_send($session, $local_file, $remote_file, $create_mode); }
php
public function scpSend($session, $local_file, $remote_file, $create_mode = 0644) { return ssh2_scp_send($session, $local_file, $remote_file, $create_mode); }
[ "public", "function", "scpSend", "(", "$", "session", ",", "$", "local_file", ",", "$", "remote_file", ",", "$", "create_mode", "=", "0644", ")", "{", "return", "ssh2_scp_send", "(", "$", "session", ",", "$", "local_file", ",", "$", "remote_file", ",", "$", "create_mode", ")", ";", "}" ]
Facade for ssh2_scp_send. @param resource $session The sftp resource to use. @param string $local_file The local file to send. @param string $remote_file The remote path to write to. @param int $create_mode The permission of the remote file. @return boolean True on success.
[ "Facade", "for", "ssh2_scp_send", "." ]
8e12d6839aa50a7590f5ad22cc2d33c8f88ff726
https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Facade/SftpFacade.php#L110-L113
train
keeko/framework
src/foundation/ModuleManager.php
ModuleManager.load
public function load($packageName) { if ($this->loadedModules->has($packageName)) { return $this->loadedModules->get($packageName); } // check existence if (!$this->installedModules->has($packageName)) { throw new ModuleException(sprintf('Module (%s) does not exist.', $packageName), 500); } // check activation if (!$this->activatedModules->has($packageName)) { throw new ModuleException(sprintf('Module (%s) not activated', $packageName), 501); } $model = $this->activatedModules->get($packageName); if ($model->getInstalledVersion() > $model->getActivatedVersion()) { throw new ModuleException(sprintf('Module Version Mismatch (%s). Module needs to be updated by the Administrator', $packageName), 500); } // load $className = $model->getClassName(); /* @var $module AbstractModule */ $module = new $className($model, $this->service); $this->loadedModules->set($packageName, $module); // load locale $localeService = $this->getServiceContainer()->getLocaleService(); $file = sprintf('/%s/locales/{locale}/translations.json', $packageName); $localeService->loadLocaleFile($file, $module->getCanonicalName()); return $module; }
php
public function load($packageName) { if ($this->loadedModules->has($packageName)) { return $this->loadedModules->get($packageName); } // check existence if (!$this->installedModules->has($packageName)) { throw new ModuleException(sprintf('Module (%s) does not exist.', $packageName), 500); } // check activation if (!$this->activatedModules->has($packageName)) { throw new ModuleException(sprintf('Module (%s) not activated', $packageName), 501); } $model = $this->activatedModules->get($packageName); if ($model->getInstalledVersion() > $model->getActivatedVersion()) { throw new ModuleException(sprintf('Module Version Mismatch (%s). Module needs to be updated by the Administrator', $packageName), 500); } // load $className = $model->getClassName(); /* @var $module AbstractModule */ $module = new $className($model, $this->service); $this->loadedModules->set($packageName, $module); // load locale $localeService = $this->getServiceContainer()->getLocaleService(); $file = sprintf('/%s/locales/{locale}/translations.json', $packageName); $localeService->loadLocaleFile($file, $module->getCanonicalName()); return $module; }
[ "public", "function", "load", "(", "$", "packageName", ")", "{", "if", "(", "$", "this", "->", "loadedModules", "->", "has", "(", "$", "packageName", ")", ")", "{", "return", "$", "this", "->", "loadedModules", "->", "get", "(", "$", "packageName", ")", ";", "}", "// check existence", "if", "(", "!", "$", "this", "->", "installedModules", "->", "has", "(", "$", "packageName", ")", ")", "{", "throw", "new", "ModuleException", "(", "sprintf", "(", "'Module (%s) does not exist.'", ",", "$", "packageName", ")", ",", "500", ")", ";", "}", "// check activation", "if", "(", "!", "$", "this", "->", "activatedModules", "->", "has", "(", "$", "packageName", ")", ")", "{", "throw", "new", "ModuleException", "(", "sprintf", "(", "'Module (%s) not activated'", ",", "$", "packageName", ")", ",", "501", ")", ";", "}", "$", "model", "=", "$", "this", "->", "activatedModules", "->", "get", "(", "$", "packageName", ")", ";", "if", "(", "$", "model", "->", "getInstalledVersion", "(", ")", ">", "$", "model", "->", "getActivatedVersion", "(", ")", ")", "{", "throw", "new", "ModuleException", "(", "sprintf", "(", "'Module Version Mismatch (%s). Module needs to be updated by the Administrator'", ",", "$", "packageName", ")", ",", "500", ")", ";", "}", "// load", "$", "className", "=", "$", "model", "->", "getClassName", "(", ")", ";", "/* @var $module AbstractModule */", "$", "module", "=", "new", "$", "className", "(", "$", "model", ",", "$", "this", "->", "service", ")", ";", "$", "this", "->", "loadedModules", "->", "set", "(", "$", "packageName", ",", "$", "module", ")", ";", "// load locale", "$", "localeService", "=", "$", "this", "->", "getServiceContainer", "(", ")", "->", "getLocaleService", "(", ")", ";", "$", "file", "=", "sprintf", "(", "'/%s/locales/{locale}/translations.json'", ",", "$", "packageName", ")", ";", "$", "localeService", "->", "loadLocaleFile", "(", "$", "file", ",", "$", "module", "->", "getCanonicalName", "(", ")", ")", ";", "return", "$", "module", ";", "}" ]
Loads a module and returns the associated class or returns if already loaded @param String $packageName @throws ModuleException @return AbstractModule
[ "Loads", "a", "module", "and", "returns", "the", "associated", "class", "or", "returns", "if", "already", "loaded" ]
a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/foundation/ModuleManager.php#L126-L160
train
prooph/processing
library/Type/String.php
String.buildDescription
public static function buildDescription() { if (DescriptionRegistry::hasDescription(__CLASS__)) return DescriptionRegistry::getDescription(__CLASS__); $desc = new Description('String', NativeType::STRING, false); DescriptionRegistry::registerDescriptionFor(__CLASS__, $desc); return $desc; }
php
public static function buildDescription() { if (DescriptionRegistry::hasDescription(__CLASS__)) return DescriptionRegistry::getDescription(__CLASS__); $desc = new Description('String', NativeType::STRING, false); DescriptionRegistry::registerDescriptionFor(__CLASS__, $desc); return $desc; }
[ "public", "static", "function", "buildDescription", "(", ")", "{", "if", "(", "DescriptionRegistry", "::", "hasDescription", "(", "__CLASS__", ")", ")", "return", "DescriptionRegistry", "::", "getDescription", "(", "__CLASS__", ")", ";", "$", "desc", "=", "new", "Description", "(", "'String'", ",", "NativeType", "::", "STRING", ",", "false", ")", ";", "DescriptionRegistry", "::", "registerDescriptionFor", "(", "__CLASS__", ",", "$", "desc", ")", ";", "return", "$", "desc", ";", "}" ]
The description is cached in the internal description property Implement the method to build the description only once and only if it is requested @return Description
[ "The", "description", "is", "cached", "in", "the", "internal", "description", "property" ]
a2947bccbffeecc4ca93a15e38ab53814e3e53e5
https://github.com/prooph/processing/blob/a2947bccbffeecc4ca93a15e38ab53814e3e53e5/library/Type/String.php#L34-L43
train
fxpio/fxp-gluon
Block/Type/PanelSectionType.php
PanelSectionType.setLastRow
protected function setLastRow(BlockInterface $block, BlockInterface $row) { if (!BlockUtil::isBlockType($row, PanelRowSpacerType::class)) { $block->setAttribute('last_row', $row->getName()); } }
php
protected function setLastRow(BlockInterface $block, BlockInterface $row) { if (!BlockUtil::isBlockType($row, PanelRowSpacerType::class)) { $block->setAttribute('last_row', $row->getName()); } }
[ "protected", "function", "setLastRow", "(", "BlockInterface", "$", "block", ",", "BlockInterface", "$", "row", ")", "{", "if", "(", "!", "BlockUtil", "::", "isBlockType", "(", "$", "row", ",", "PanelRowSpacerType", "::", "class", ")", ")", "{", "$", "block", "->", "setAttribute", "(", "'last_row'", ",", "$", "row", "->", "getName", "(", ")", ")", ";", "}", "}" ]
Set the last row. @param BlockInterface $block @param BlockInterface $row
[ "Set", "the", "last", "row", "." ]
0548b7d598ef4b0785b5df3b849a10f439b2dc65
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/PanelSectionType.php#L218-L223
train
fxpio/fxp-gluon
Block/Type/PanelSectionType.php
PanelSectionType.getLastRow
protected function getLastRow(BlockInterface $block) { if ($block->hasAttribute('last_row')) { $row = $block->get($block->getAttribute('last_row')); // return current row if (\count($row) < $row->getOption('column')) { return $row; } } // new row $rowName = BlockUtil::createUniqueName(); $block->add($rowName, PanelRowType::class); return $block->get($rowName); }
php
protected function getLastRow(BlockInterface $block) { if ($block->hasAttribute('last_row')) { $row = $block->get($block->getAttribute('last_row')); // return current row if (\count($row) < $row->getOption('column')) { return $row; } } // new row $rowName = BlockUtil::createUniqueName(); $block->add($rowName, PanelRowType::class); return $block->get($rowName); }
[ "protected", "function", "getLastRow", "(", "BlockInterface", "$", "block", ")", "{", "if", "(", "$", "block", "->", "hasAttribute", "(", "'last_row'", ")", ")", "{", "$", "row", "=", "$", "block", "->", "get", "(", "$", "block", "->", "getAttribute", "(", "'last_row'", ")", ")", ";", "// return current row", "if", "(", "\\", "count", "(", "$", "row", ")", "<", "$", "row", "->", "getOption", "(", "'column'", ")", ")", "{", "return", "$", "row", ";", "}", "}", "// new row", "$", "rowName", "=", "BlockUtil", "::", "createUniqueName", "(", ")", ";", "$", "block", "->", "add", "(", "$", "rowName", ",", "PanelRowType", "::", "class", ")", ";", "return", "$", "block", "->", "get", "(", "$", "rowName", ")", ";", "}" ]
Get the last row. @param BlockInterface $block @return BlockInterface
[ "Get", "the", "last", "row", "." ]
0548b7d598ef4b0785b5df3b849a10f439b2dc65
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/PanelSectionType.php#L232-L248
train
ajaxtown/eaglehorn_framework
src/Eaglehorn/Router.php
Router.execute
static function execute(Base $base) { self::$_base = $base; //first we separate the parameters $request = isset($_REQUEST['route']) ? $_REQUEST['route'] : '/'; if(strpos($request,'?') > 0) { $split = explode('?',$request); $request = $split[0]; } self::$_attr = array_slice(explode('/', trim($request, '/')), 2); self::_run($request); return self::$callback; }
php
static function execute(Base $base) { self::$_base = $base; //first we separate the parameters $request = isset($_REQUEST['route']) ? $_REQUEST['route'] : '/'; if(strpos($request,'?') > 0) { $split = explode('?',$request); $request = $split[0]; } self::$_attr = array_slice(explode('/', trim($request, '/')), 2); self::_run($request); return self::$callback; }
[ "static", "function", "execute", "(", "Base", "$", "base", ")", "{", "self", "::", "$", "_base", "=", "$", "base", ";", "//first we separate the parameters", "$", "request", "=", "isset", "(", "$", "_REQUEST", "[", "'route'", "]", ")", "?", "$", "_REQUEST", "[", "'route'", "]", ":", "'/'", ";", "if", "(", "strpos", "(", "$", "request", ",", "'?'", ")", ">", "0", ")", "{", "$", "split", "=", "explode", "(", "'?'", ",", "$", "request", ")", ";", "$", "request", "=", "$", "split", "[", "0", "]", ";", "}", "self", "::", "$", "_attr", "=", "array_slice", "(", "explode", "(", "'/'", ",", "trim", "(", "$", "request", ",", "'/'", ")", ")", ",", "2", ")", ";", "self", "::", "_run", "(", "$", "request", ")", ";", "return", "self", "::", "$", "callback", ";", "}" ]
Executes the router @return mixed
[ "Executes", "the", "router" ]
5e2a1456ff6c65b3925f1219f115d8a919930f52
https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/Router.php#L59-L76
train
ajaxtown/eaglehorn_framework
src/Eaglehorn/Router.php
Router._run
private static function _run($request) { // Whether or not we have matched the URL to a route $matched_route = false; $request = '/' . $request; //make sure the request has a trailing slash $request = rtrim($request, '/') . '/'; $request = str_replace("//","/",$request); // Sort the array by priority ksort(self::$_routes); // Loop through each priority level foreach (self::$_routes as $priority => $routes) { // Loop through each route for this priority level foreach ($routes as $source => $destination) { // Does the routing rule match the current URL? if (preg_match($source, $request, $matches)) { // A routing rule was matched $matched_route = TRUE; $attr = implode('/',array_intersect_key($matches, array_flip(array_filter(array_keys($matches), 'is_string')))); self::$_attr = explode('/', trim($attr, '/')); self::_set_callback($destination); } } } if(!$matched_route) { if($request != '/') { self::_set_callback($request); } } }
php
private static function _run($request) { // Whether or not we have matched the URL to a route $matched_route = false; $request = '/' . $request; //make sure the request has a trailing slash $request = rtrim($request, '/') . '/'; $request = str_replace("//","/",$request); // Sort the array by priority ksort(self::$_routes); // Loop through each priority level foreach (self::$_routes as $priority => $routes) { // Loop through each route for this priority level foreach ($routes as $source => $destination) { // Does the routing rule match the current URL? if (preg_match($source, $request, $matches)) { // A routing rule was matched $matched_route = TRUE; $attr = implode('/',array_intersect_key($matches, array_flip(array_filter(array_keys($matches), 'is_string')))); self::$_attr = explode('/', trim($attr, '/')); self::_set_callback($destination); } } } if(!$matched_route) { if($request != '/') { self::_set_callback($request); } } }
[ "private", "static", "function", "_run", "(", "$", "request", ")", "{", "// Whether or not we have matched the URL to a route", "$", "matched_route", "=", "false", ";", "$", "request", "=", "'/'", ".", "$", "request", ";", "//make sure the request has a trailing slash", "$", "request", "=", "rtrim", "(", "$", "request", ",", "'/'", ")", ".", "'/'", ";", "$", "request", "=", "str_replace", "(", "\"//\"", ",", "\"/\"", ",", "$", "request", ")", ";", "// Sort the array by priority", "ksort", "(", "self", "::", "$", "_routes", ")", ";", "// Loop through each priority level", "foreach", "(", "self", "::", "$", "_routes", "as", "$", "priority", "=>", "$", "routes", ")", "{", "// Loop through each route for this priority level", "foreach", "(", "$", "routes", "as", "$", "source", "=>", "$", "destination", ")", "{", "// Does the routing rule match the current URL?", "if", "(", "preg_match", "(", "$", "source", ",", "$", "request", ",", "$", "matches", ")", ")", "{", "// A routing rule was matched", "$", "matched_route", "=", "TRUE", ";", "$", "attr", "=", "implode", "(", "'/'", ",", "array_intersect_key", "(", "$", "matches", ",", "array_flip", "(", "array_filter", "(", "array_keys", "(", "$", "matches", ")", ",", "'is_string'", ")", ")", ")", ")", ";", "self", "::", "$", "_attr", "=", "explode", "(", "'/'", ",", "trim", "(", "$", "attr", ",", "'/'", ")", ")", ";", "self", "::", "_set_callback", "(", "$", "destination", ")", ";", "}", "}", "}", "if", "(", "!", "$", "matched_route", ")", "{", "if", "(", "$", "request", "!=", "'/'", ")", "{", "self", "::", "_set_callback", "(", "$", "request", ")", ";", "}", "}", "}" ]
Tries to match one of the URL routes to the current URL, otherwise execute the default function. Sets the callback that needs to be returned @param string $request
[ "Tries", "to", "match", "one", "of", "the", "URL", "routes", "to", "the", "current", "URL", "otherwise", "execute", "the", "default", "function", ".", "Sets", "the", "callback", "that", "needs", "to", "be", "returned" ]
5e2a1456ff6c65b3925f1219f115d8a919930f52
https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/Router.php#L86-L129
train
ajaxtown/eaglehorn_framework
src/Eaglehorn/Router.php
Router._set_callback
private static function _set_callback($destination) { if(is_callable($destination)) { self::$callback = array($destination,self::$_attr); } else { $result = explode('/', trim($destination, '/')); //fix the controller now $controller = ($result[0] == "") ? configItem('site')['default_controller'] : str_replace('-', '/', $result[0]); //if no method, set it to index $method = isset($result[1]) ? $result[1] : 'index'; //if controller is valid file if (self::fileExists($file = ucfirst(configItem('site')['cust_controller_dir']) . $controller . '.php',false)) { self::$callback = array(ucFirst($controller), $method, self::$_attr); } else { header("HTTP/1.0 404 Not Found"); self::$_base->hook('404',array( 'file' => $file, 'controller' => $controller, 'method' => $method, 'message' => '404' )); die(); } } }
php
private static function _set_callback($destination) { if(is_callable($destination)) { self::$callback = array($destination,self::$_attr); } else { $result = explode('/', trim($destination, '/')); //fix the controller now $controller = ($result[0] == "") ? configItem('site')['default_controller'] : str_replace('-', '/', $result[0]); //if no method, set it to index $method = isset($result[1]) ? $result[1] : 'index'; //if controller is valid file if (self::fileExists($file = ucfirst(configItem('site')['cust_controller_dir']) . $controller . '.php',false)) { self::$callback = array(ucFirst($controller), $method, self::$_attr); } else { header("HTTP/1.0 404 Not Found"); self::$_base->hook('404',array( 'file' => $file, 'controller' => $controller, 'method' => $method, 'message' => '404' )); die(); } } }
[ "private", "static", "function", "_set_callback", "(", "$", "destination", ")", "{", "if", "(", "is_callable", "(", "$", "destination", ")", ")", "{", "self", "::", "$", "callback", "=", "array", "(", "$", "destination", ",", "self", "::", "$", "_attr", ")", ";", "}", "else", "{", "$", "result", "=", "explode", "(", "'/'", ",", "trim", "(", "$", "destination", ",", "'/'", ")", ")", ";", "//fix the controller now", "$", "controller", "=", "(", "$", "result", "[", "0", "]", "==", "\"\"", ")", "?", "configItem", "(", "'site'", ")", "[", "'default_controller'", "]", ":", "str_replace", "(", "'-'", ",", "'/'", ",", "$", "result", "[", "0", "]", ")", ";", "//if no method, set it to index", "$", "method", "=", "isset", "(", "$", "result", "[", "1", "]", ")", "?", "$", "result", "[", "1", "]", ":", "'index'", ";", "//if controller is valid file", "if", "(", "self", "::", "fileExists", "(", "$", "file", "=", "ucfirst", "(", "configItem", "(", "'site'", ")", "[", "'cust_controller_dir'", "]", ")", ".", "$", "controller", ".", "'.php'", ",", "false", ")", ")", "{", "self", "::", "$", "callback", "=", "array", "(", "ucFirst", "(", "$", "controller", ")", ",", "$", "method", ",", "self", "::", "$", "_attr", ")", ";", "}", "else", "{", "header", "(", "\"HTTP/1.0 404 Not Found\"", ")", ";", "self", "::", "$", "_base", "->", "hook", "(", "'404'", ",", "array", "(", "'file'", "=>", "$", "file", ",", "'controller'", "=>", "$", "controller", ",", "'method'", "=>", "$", "method", ",", "'message'", "=>", "'404'", ")", ")", ";", "die", "(", ")", ";", "}", "}", "}" ]
Sets the callback as an array containing Controller, Method & Parameters @param string $destination
[ "Sets", "the", "callback", "as", "an", "array", "containing", "Controller", "Method", "&", "Parameters" ]
5e2a1456ff6c65b3925f1219f115d8a919930f52
https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/Router.php#L136-L166
train
phPoirot/Client-OAuth2
src/Grant/aGrantRequest.php
aGrantRequest.__toArray
function __toArray() { $params = __( new HydrateGetters($this) ) ->setExcludeNullValues(); $params = StdTravers::of($params)->toArray(null, true); return $params; }
php
function __toArray() { $params = __( new HydrateGetters($this) ) ->setExcludeNullValues(); $params = StdTravers::of($params)->toArray(null, true); return $params; }
[ "function", "__toArray", "(", ")", "{", "$", "params", "=", "__", "(", "new", "HydrateGetters", "(", "$", "this", ")", ")", "->", "setExcludeNullValues", "(", ")", ";", "$", "params", "=", "StdTravers", "::", "of", "(", "$", "params", ")", "->", "toArray", "(", "null", ",", "true", ")", ";", "return", "$", "params", ";", "}" ]
Get Grant Request Params As Array @return array
[ "Get", "Grant", "Request", "Params", "As", "Array" ]
8745fd54afbbb185669b9e38b1241ecc8ffc7268
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Grant/aGrantRequest.php#L33-L40
train
inhere/php-library-plus
libs/Task/Handlers/Task.php
Task.run
public function run($workload, TaskWrapper $task) { $result = false; $this->id = $task->getId(); $this->name = $task->getName(); try { if (false !== $this->beforeRun($workload, $task)) { $result = $this->doRun($workload, $task); $this->afterRun($result); } } catch (\Exception $e) { $this->onException($e); } return $result; }
php
public function run($workload, TaskWrapper $task) { $result = false; $this->id = $task->getId(); $this->name = $task->getName(); try { if (false !== $this->beforeRun($workload, $task)) { $result = $this->doRun($workload, $task); $this->afterRun($result); } } catch (\Exception $e) { $this->onException($e); } return $result; }
[ "public", "function", "run", "(", "$", "workload", ",", "TaskWrapper", "$", "task", ")", "{", "$", "result", "=", "false", ";", "$", "this", "->", "id", "=", "$", "task", "->", "getId", "(", ")", ";", "$", "this", "->", "name", "=", "$", "task", "->", "getName", "(", ")", ";", "try", "{", "if", "(", "false", "!==", "$", "this", "->", "beforeRun", "(", "$", "workload", ",", "$", "task", ")", ")", "{", "$", "result", "=", "$", "this", "->", "doRun", "(", "$", "workload", ",", "$", "task", ")", ";", "$", "this", "->", "afterRun", "(", "$", "result", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "onException", "(", "$", "e", ")", ";", "}", "return", "$", "result", ";", "}" ]
do the job @param string $workload @param TaskWrapper $task @return mixed
[ "do", "the", "job" ]
8604e037937d31fa2338d79aaf9d0910cb48f559
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Handlers/Task.php#L48-L65
train
schpill/thin
src/Filter/Normalize.php
Normalize.filter
public function filter($value) { // transliteration $value = strtr($value, $this->transliteration); // change to lowercase if($this->transformCase) { $value = mb_convert_case($value, MB_CASE_LOWER, 'utf8'); } // replace punctuation if($this->transformPunctuation) { $value = strtr($value, $this->punctuation); } return $value; }
php
public function filter($value) { // transliteration $value = strtr($value, $this->transliteration); // change to lowercase if($this->transformCase) { $value = mb_convert_case($value, MB_CASE_LOWER, 'utf8'); } // replace punctuation if($this->transformPunctuation) { $value = strtr($value, $this->punctuation); } return $value; }
[ "public", "function", "filter", "(", "$", "value", ")", "{", "// transliteration", "$", "value", "=", "strtr", "(", "$", "value", ",", "$", "this", "->", "transliteration", ")", ";", "// change to lowercase", "if", "(", "$", "this", "->", "transformCase", ")", "{", "$", "value", "=", "mb_convert_case", "(", "$", "value", ",", "MB_CASE_LOWER", ",", "'utf8'", ")", ";", "}", "// replace punctuation", "if", "(", "$", "this", "->", "transformPunctuation", ")", "{", "$", "value", "=", "strtr", "(", "$", "value", ",", "$", "this", "->", "punctuation", ")", ";", "}", "return", "$", "value", ";", "}" ]
Normalise the input string @param string $value String to be normalised @return string Normalised string
[ "Normalise", "the", "input", "string" ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Filter/Normalize.php#L115-L131
train
schpill/thin
src/Filter/Normalize.php
Normalize.setTransliterationReplacements
public function setTransliterationReplacements($replacements) { if(!is_array($replacements)) { throw new \Thin\Exception(__METHOD__ . ': method expects a keyed array as argument.', 500); } foreach($replacements as $key => $value) { $this->transliteration[$key] = $value; } return $this; }
php
public function setTransliterationReplacements($replacements) { if(!is_array($replacements)) { throw new \Thin\Exception(__METHOD__ . ': method expects a keyed array as argument.', 500); } foreach($replacements as $key => $value) { $this->transliteration[$key] = $value; } return $this; }
[ "public", "function", "setTransliterationReplacements", "(", "$", "replacements", ")", "{", "if", "(", "!", "is_array", "(", "$", "replacements", ")", ")", "{", "throw", "new", "\\", "Thin", "\\", "Exception", "(", "__METHOD__", ".", "': method expects a keyed array as argument.'", ",", "500", ")", ";", "}", "foreach", "(", "$", "replacements", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "transliteration", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "$", "this", ";", "}" ]
Set transliteration replacement values. @param array $replacements A keyed array of characters to replace, e.g. ['Ł' => 'L']; @return \Thin\Filter\Normalise Provides a fluent interface @throws \Thin\Exception in case the argument is not an array.
[ "Set", "transliteration", "replacement", "values", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Filter/Normalize.php#L174-L183
train
schpill/thin
src/Filter/Normalize.php
Normalize.setPunctuationReplacements
public function setPunctuationReplacements($replacements) { if(!is_array($replacements)) { throw new \Thin\Exception(__METHOD__ . ': method expects a keyed array as argument.', 500); } foreach($replacements as $key => $value) { $this->punctuation[$key] = $value; } return $this; }
php
public function setPunctuationReplacements($replacements) { if(!is_array($replacements)) { throw new \Thin\Exception(__METHOD__ . ': method expects a keyed array as argument.', 500); } foreach($replacements as $key => $value) { $this->punctuation[$key] = $value; } return $this; }
[ "public", "function", "setPunctuationReplacements", "(", "$", "replacements", ")", "{", "if", "(", "!", "is_array", "(", "$", "replacements", ")", ")", "{", "throw", "new", "\\", "Thin", "\\", "Exception", "(", "__METHOD__", ".", "': method expects a keyed array as argument.'", ",", "500", ")", ";", "}", "foreach", "(", "$", "replacements", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "punctuation", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "$", "this", ";", "}" ]
Set punctuation replacement values. @param array $replacements A keyed array of characters to replace, e.g. [' ' => '_']; @return \Thin\Filter\Normalise Provides a fluent interface @throws \Thin\Exception in case the argument is not an array.
[ "Set", "punctuation", "replacement", "values", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Filter/Normalize.php#L196-L205
train
rkeet/zf-doctrine-mvc
src/Entity/AbstractEntity.php
AbstractEntity.getArrayCopy
public function getArrayCopy() : array { $values = get_object_vars($this); foreach ($values as $property => $value) { // Skip relations if (is_object($value)) { unset($values[$property]); } } return $values; }
php
public function getArrayCopy() : array { $values = get_object_vars($this); foreach ($values as $property => $value) { // Skip relations if (is_object($value)) { unset($values[$property]); } } return $values; }
[ "public", "function", "getArrayCopy", "(", ")", ":", "array", "{", "$", "values", "=", "get_object_vars", "(", "$", "this", ")", ";", "foreach", "(", "$", "values", "as", "$", "property", "=>", "$", "value", ")", "{", "// Skip relations", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "unset", "(", "$", "values", "[", "$", "property", "]", ")", ";", "}", "}", "return", "$", "values", ";", "}" ]
Gets an array copy
[ "Gets", "an", "array", "copy" ]
ec5fb19e453824383b39570d15bd77b85cec3ca1
https://github.com/rkeet/zf-doctrine-mvc/blob/ec5fb19e453824383b39570d15bd77b85cec3ca1/src/Entity/AbstractEntity.php#L144-L155
train
rkeet/zf-doctrine-mvc
src/Entity/AbstractEntity.php
AbstractEntity.exchangeArray
public function exchangeArray($data) { foreach ($data as $property => $value) { if (isset($this->$property)) { $method = 'set' . ucfirst($property); $this->$method($value); } } }
php
public function exchangeArray($data) { foreach ($data as $property => $value) { if (isset($this->$property)) { $method = 'set' . ucfirst($property); $this->$method($value); } } }
[ "public", "function", "exchangeArray", "(", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "property", "=>", "$", "value", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "$", "property", ")", ")", "{", "$", "method", "=", "'set'", ".", "ucfirst", "(", "$", "property", ")", ";", "$", "this", "->", "$", "method", "(", "$", "value", ")", ";", "}", "}", "}" ]
Maps the specified data to the properties of this object @param array $data
[ "Maps", "the", "specified", "data", "to", "the", "properties", "of", "this", "object" ]
ec5fb19e453824383b39570d15bd77b85cec3ca1
https://github.com/rkeet/zf-doctrine-mvc/blob/ec5fb19e453824383b39570d15bd77b85cec3ca1/src/Entity/AbstractEntity.php#L162-L170
train
andyburton/Sonic-Framework
src/Controller/Session.php
Session.callAction
public function callAction () { // Only call the method if the user is authenticated if ($this->checkAuthenticated ()) { $this->view->assign ('user', $this->user); parent::callAction (); } }
php
public function callAction () { // Only call the method if the user is authenticated if ($this->checkAuthenticated ()) { $this->view->assign ('user', $this->user); parent::callAction (); } }
[ "public", "function", "callAction", "(", ")", "{", "// Only call the method if the user is authenticated", "if", "(", "$", "this", "->", "checkAuthenticated", "(", ")", ")", "{", "$", "this", "->", "view", "->", "assign", "(", "'user'", ",", "$", "this", "->", "user", ")", ";", "parent", "::", "callAction", "(", ")", ";", "}", "}" ]
Call controller action method @return void
[ "Call", "controller", "action", "method" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/Session.php#L36-L47
train
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getMetadataByContent
public static function getMetadataByContent( ezpContent $content ) { $aMetadata = array( 'objectName' => $content->name, 'classIdentifier' => $content->classIdentifier, 'datePublished' => (int)$content->datePublished, 'dateModified' => (int)$content->dateModified, 'objectRemoteId' => $content->remote_id, 'objectId' => (int)$content->id ); return $aMetadata; }
php
public static function getMetadataByContent( ezpContent $content ) { $aMetadata = array( 'objectName' => $content->name, 'classIdentifier' => $content->classIdentifier, 'datePublished' => (int)$content->datePublished, 'dateModified' => (int)$content->dateModified, 'objectRemoteId' => $content->remote_id, 'objectId' => (int)$content->id ); return $aMetadata; }
[ "public", "static", "function", "getMetadataByContent", "(", "ezpContent", "$", "content", ")", "{", "$", "aMetadata", "=", "array", "(", "'objectName'", "=>", "$", "content", "->", "name", ",", "'classIdentifier'", "=>", "$", "content", "->", "classIdentifier", ",", "'datePublished'", "=>", "(", "int", ")", "$", "content", "->", "datePublished", ",", "'dateModified'", "=>", "(", "int", ")", "$", "content", "->", "dateModified", ",", "'objectRemoteId'", "=>", "$", "content", "->", "remote_id", ",", "'objectId'", "=>", "(", "int", ")", "$", "content", "->", "id", ")", ";", "return", "$", "aMetadata", ";", "}" ]
Returns metadata for given content as array @param ezpContent $content @return array
[ "Returns", "metadata", "for", "given", "content", "as", "array" ]
98012d22225fca242fa6b87cd7c71bf912ca8cbd
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L19-L31
train
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getMetadataByLocation
public static function getMetadataByLocation( ezpContentLocation $location ) { $url = $location->url_alias; eZURI::transformURI( $url, false, 'full' ); // $url is passed as a reference $aMetadata = array( 'nodeId' => (int)$location->node_id, 'nodeRemoteId' => $location->remote_id, 'fullUrl' => $url ); return $aMetadata; }
php
public static function getMetadataByLocation( ezpContentLocation $location ) { $url = $location->url_alias; eZURI::transformURI( $url, false, 'full' ); // $url is passed as a reference $aMetadata = array( 'nodeId' => (int)$location->node_id, 'nodeRemoteId' => $location->remote_id, 'fullUrl' => $url ); return $aMetadata; }
[ "public", "static", "function", "getMetadataByLocation", "(", "ezpContentLocation", "$", "location", ")", "{", "$", "url", "=", "$", "location", "->", "url_alias", ";", "eZURI", "::", "transformURI", "(", "$", "url", ",", "false", ",", "'full'", ")", ";", "// $url is passed as a reference", "$", "aMetadata", "=", "array", "(", "'nodeId'", "=>", "(", "int", ")", "$", "location", "->", "node_id", ",", "'nodeRemoteId'", "=>", "$", "location", "->", "remote_id", ",", "'fullUrl'", "=>", "$", "url", ")", ";", "return", "$", "aMetadata", ";", "}" ]
Returns metadata for given content location as array @param ezpContentLocation $location @return array
[ "Returns", "metadata", "for", "given", "content", "location", "as", "array" ]
98012d22225fca242fa6b87cd7c71bf912ca8cbd
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L38-L50
train
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getLocationsByContent
public static function getLocationsByContent( ezpContent $content ) { $aReturnLocations = array(); $assignedNodes = $content->assigned_nodes; foreach ( $assignedNodes as $node ) { $location = ezpContentLocation::fromNode( $node ); $locationData = self::getMetadataByLocation( $location ); $locationData['isMain'] = $location->is_main; $aReturnLocations[] = $locationData; } return $aReturnLocations; }
php
public static function getLocationsByContent( ezpContent $content ) { $aReturnLocations = array(); $assignedNodes = $content->assigned_nodes; foreach ( $assignedNodes as $node ) { $location = ezpContentLocation::fromNode( $node ); $locationData = self::getMetadataByLocation( $location ); $locationData['isMain'] = $location->is_main; $aReturnLocations[] = $locationData; } return $aReturnLocations; }
[ "public", "static", "function", "getLocationsByContent", "(", "ezpContent", "$", "content", ")", "{", "$", "aReturnLocations", "=", "array", "(", ")", ";", "$", "assignedNodes", "=", "$", "content", "->", "assigned_nodes", ";", "foreach", "(", "$", "assignedNodes", "as", "$", "node", ")", "{", "$", "location", "=", "ezpContentLocation", "::", "fromNode", "(", "$", "node", ")", ";", "$", "locationData", "=", "self", "::", "getMetadataByLocation", "(", "$", "location", ")", ";", "$", "locationData", "[", "'isMain'", "]", "=", "$", "location", "->", "is_main", ";", "$", "aReturnLocations", "[", "]", "=", "$", "locationData", ";", "}", "return", "$", "aReturnLocations", ";", "}" ]
Returns all locations for provided content as array. @param ezpContent $content @return array Associative array with following keys : - fullUrl => URL for content, including server - nodeId => NodeID for location - remoteId => RemoteID for location - isMain => whether location is main for provided content
[ "Returns", "all", "locations", "for", "provided", "content", "as", "array", "." ]
98012d22225fca242fa6b87cd7c71bf912ca8cbd
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L61-L74
train
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getFieldsByContent
public static function getFieldsByContent( ezpContent $content ) { $aReturnFields = array(); foreach ( $content->fields as $name => $field ) { $aReturnFields[$name] = self::attributeOutputData( $field ); } return $aReturnFields; }
php
public static function getFieldsByContent( ezpContent $content ) { $aReturnFields = array(); foreach ( $content->fields as $name => $field ) { $aReturnFields[$name] = self::attributeOutputData( $field ); } return $aReturnFields; }
[ "public", "static", "function", "getFieldsByContent", "(", "ezpContent", "$", "content", ")", "{", "$", "aReturnFields", "=", "array", "(", ")", ";", "foreach", "(", "$", "content", "->", "fields", "as", "$", "name", "=>", "$", "field", ")", "{", "$", "aReturnFields", "[", "$", "name", "]", "=", "self", "::", "attributeOutputData", "(", "$", "field", ")", ";", "}", "return", "$", "aReturnFields", ";", "}" ]
Returns all fields for provided content @param ezpContent $content @return array Associative array with following keys : - type => Field type (datatype string) - identifier => Attribute identifier - value => String representation of field content - id => Attribute numerical ID - classattribute_id => Numerical class attribute ID
[ "Returns", "all", "fields", "for", "provided", "content" ]
98012d22225fca242fa6b87cd7c71bf912ca8cbd
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L86-L95
train
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.attributeOutputData
public static function attributeOutputData( ezpContentField $field ) { // @TODO move to datatype representation layer switch ( $field->data_type_string ) { case 'ezxmltext': $html = $field->content->attribute( 'output' )->attribute( 'output_text' ); $attributeValue = array( strip_tags( $html ) ); break; case 'ezimage': $strRepImage = $field->toString(); $delimPos = strpos( $strRepImage, '|' ); if ( $delimPos !== false ) { $strRepImage = substr( $strRepImage, 0, $delimPos ); } $attributeValue = array( $strRepImage ); break; default: $datatypeBlacklist = array_fill_keys( eZINI::instance()->variable( 'ContentSettings', 'DatatypeBlackListForExternal' ), true ); if ( isset ( $datatypeBlacklist[$field->data_type_string] ) ) $attributeValue = array( null ); else $attributeValue = array( $field->toString() ); break; } // cleanup values so that the result is consistent: // - no array if one item // - false if no values if ( count( $attributeValue ) == 0 ) { $attributeValue = false; } else if ( count( $attributeValue ) == 1 ) { $attributeValue = current( $attributeValue ); } return array( 'type' => $field->data_type_string, 'identifier' => $field->contentclass_attribute_identifier, 'value' => $attributeValue, 'id' => (int)$field->id, 'classattribute_id' => (int)$field->contentclassattribute_id ); }
php
public static function attributeOutputData( ezpContentField $field ) { // @TODO move to datatype representation layer switch ( $field->data_type_string ) { case 'ezxmltext': $html = $field->content->attribute( 'output' )->attribute( 'output_text' ); $attributeValue = array( strip_tags( $html ) ); break; case 'ezimage': $strRepImage = $field->toString(); $delimPos = strpos( $strRepImage, '|' ); if ( $delimPos !== false ) { $strRepImage = substr( $strRepImage, 0, $delimPos ); } $attributeValue = array( $strRepImage ); break; default: $datatypeBlacklist = array_fill_keys( eZINI::instance()->variable( 'ContentSettings', 'DatatypeBlackListForExternal' ), true ); if ( isset ( $datatypeBlacklist[$field->data_type_string] ) ) $attributeValue = array( null ); else $attributeValue = array( $field->toString() ); break; } // cleanup values so that the result is consistent: // - no array if one item // - false if no values if ( count( $attributeValue ) == 0 ) { $attributeValue = false; } else if ( count( $attributeValue ) == 1 ) { $attributeValue = current( $attributeValue ); } return array( 'type' => $field->data_type_string, 'identifier' => $field->contentclass_attribute_identifier, 'value' => $attributeValue, 'id' => (int)$field->id, 'classattribute_id' => (int)$field->contentclassattribute_id ); }
[ "public", "static", "function", "attributeOutputData", "(", "ezpContentField", "$", "field", ")", "{", "// @TODO move to datatype representation layer", "switch", "(", "$", "field", "->", "data_type_string", ")", "{", "case", "'ezxmltext'", ":", "$", "html", "=", "$", "field", "->", "content", "->", "attribute", "(", "'output'", ")", "->", "attribute", "(", "'output_text'", ")", ";", "$", "attributeValue", "=", "array", "(", "strip_tags", "(", "$", "html", ")", ")", ";", "break", ";", "case", "'ezimage'", ":", "$", "strRepImage", "=", "$", "field", "->", "toString", "(", ")", ";", "$", "delimPos", "=", "strpos", "(", "$", "strRepImage", ",", "'|'", ")", ";", "if", "(", "$", "delimPos", "!==", "false", ")", "{", "$", "strRepImage", "=", "substr", "(", "$", "strRepImage", ",", "0", ",", "$", "delimPos", ")", ";", "}", "$", "attributeValue", "=", "array", "(", "$", "strRepImage", ")", ";", "break", ";", "default", ":", "$", "datatypeBlacklist", "=", "array_fill_keys", "(", "eZINI", "::", "instance", "(", ")", "->", "variable", "(", "'ContentSettings'", ",", "'DatatypeBlackListForExternal'", ")", ",", "true", ")", ";", "if", "(", "isset", "(", "$", "datatypeBlacklist", "[", "$", "field", "->", "data_type_string", "]", ")", ")", "$", "attributeValue", "=", "array", "(", "null", ")", ";", "else", "$", "attributeValue", "=", "array", "(", "$", "field", "->", "toString", "(", ")", ")", ";", "break", ";", "}", "// cleanup values so that the result is consistent:", "// - no array if one item", "// - false if no values", "if", "(", "count", "(", "$", "attributeValue", ")", "==", "0", ")", "{", "$", "attributeValue", "=", "false", ";", "}", "else", "if", "(", "count", "(", "$", "attributeValue", ")", "==", "1", ")", "{", "$", "attributeValue", "=", "current", "(", "$", "attributeValue", ")", ";", "}", "return", "array", "(", "'type'", "=>", "$", "field", "->", "data_type_string", ",", "'identifier'", "=>", "$", "field", "->", "contentclass_attribute_identifier", ",", "'value'", "=>", "$", "attributeValue", ",", "'id'", "=>", "(", "int", ")", "$", "field", "->", "id", ",", "'classattribute_id'", "=>", "(", "int", ")", "$", "field", "->", "contentclassattribute_id", ")", ";", "}" ]
Transforms an ezpContentField in an array representation @todo Refactor, this doesn't really belong here. Either in ezpContentField, or in an extend class @param ezpContentField $field @return array Associative array with following keys : - type => Field type (datatype string) - identifier => Attribute identifier - value => String representation of field content - id => Attribute numerical ID - classattribute_id => Numerical class attribute ID
[ "Transforms", "an", "ezpContentField", "in", "an", "array", "representation" ]
98012d22225fca242fa6b87cd7c71bf912ca8cbd
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L108-L157
train
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getChildrenList
public static function getChildrenList( ezpContentCriteria $c, ezpRestRequest $currentRequest, array $responseGroups = array() ) { $aRetData = array(); $aChildren = ezpContentRepository::query( $c ); foreach ( $aChildren as $childNode ) { $childEntry = self::getMetadataByContent( $childNode ); $childEntry = array_merge( $childEntry, self::getMetadataByLocation( $childNode->locations ) ); // Add fields with their values if requested if ( in_array( ezpRestContentController::VIEWLIST_RESPONSEGROUP_FIELDS, $responseGroups ) ) { $childEntry['fields'] = array(); foreach ( $childNode->fields as $fieldName => $field ) { $childEntry['fields'][$fieldName] = self::attributeOutputData( $field ); } } $aRetData[] = $childEntry; } return $aRetData; }
php
public static function getChildrenList( ezpContentCriteria $c, ezpRestRequest $currentRequest, array $responseGroups = array() ) { $aRetData = array(); $aChildren = ezpContentRepository::query( $c ); foreach ( $aChildren as $childNode ) { $childEntry = self::getMetadataByContent( $childNode ); $childEntry = array_merge( $childEntry, self::getMetadataByLocation( $childNode->locations ) ); // Add fields with their values if requested if ( in_array( ezpRestContentController::VIEWLIST_RESPONSEGROUP_FIELDS, $responseGroups ) ) { $childEntry['fields'] = array(); foreach ( $childNode->fields as $fieldName => $field ) { $childEntry['fields'][$fieldName] = self::attributeOutputData( $field ); } } $aRetData[] = $childEntry; } return $aRetData; }
[ "public", "static", "function", "getChildrenList", "(", "ezpContentCriteria", "$", "c", ",", "ezpRestRequest", "$", "currentRequest", ",", "array", "$", "responseGroups", "=", "array", "(", ")", ")", "{", "$", "aRetData", "=", "array", "(", ")", ";", "$", "aChildren", "=", "ezpContentRepository", "::", "query", "(", "$", "c", ")", ";", "foreach", "(", "$", "aChildren", "as", "$", "childNode", ")", "{", "$", "childEntry", "=", "self", "::", "getMetadataByContent", "(", "$", "childNode", ")", ";", "$", "childEntry", "=", "array_merge", "(", "$", "childEntry", ",", "self", "::", "getMetadataByLocation", "(", "$", "childNode", "->", "locations", ")", ")", ";", "// Add fields with their values if requested", "if", "(", "in_array", "(", "ezpRestContentController", "::", "VIEWLIST_RESPONSEGROUP_FIELDS", ",", "$", "responseGroups", ")", ")", "{", "$", "childEntry", "[", "'fields'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "childNode", "->", "fields", "as", "$", "fieldName", "=>", "$", "field", ")", "{", "$", "childEntry", "[", "'fields'", "]", "[", "$", "fieldName", "]", "=", "self", "::", "attributeOutputData", "(", "$", "field", ")", ";", "}", "}", "$", "aRetData", "[", "]", "=", "$", "childEntry", ";", "}", "return", "$", "aRetData", ";", "}" ]
Returns all children node data, based on the provided criteria object @param ezpContentCriteria $c @param ezpRestRequest $currentRequest @param array $responseGroups Requested ResponseGroups @return array
[ "Returns", "all", "children", "node", "data", "based", "on", "the", "provided", "criteria", "object" ]
98012d22225fca242fa6b87cd7c71bf912ca8cbd
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L189-L213
train
luoxiaojun1992/lb_framework
components/Auth.php
Auth.authQueryString
public static function authQueryString($authKey, $accessToken, $request = null) { return HashHelper::hash($request ? $request->getParam($authKey) : Lb::app()->getParam($authKey)) == $accessToken; }
php
public static function authQueryString($authKey, $accessToken, $request = null) { return HashHelper::hash($request ? $request->getParam($authKey) : Lb::app()->getParam($authKey)) == $accessToken; }
[ "public", "static", "function", "authQueryString", "(", "$", "authKey", ",", "$", "accessToken", ",", "$", "request", "=", "null", ")", "{", "return", "HashHelper", "::", "hash", "(", "$", "request", "?", "$", "request", "->", "getParam", "(", "$", "authKey", ")", ":", "Lb", "::", "app", "(", ")", "->", "getParam", "(", "$", "authKey", ")", ")", "==", "$", "accessToken", ";", "}" ]
Query String Authentication @param $authKey @param $accessToken @param $request RequestContract @return bool
[ "Query", "String", "Authentication" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/Auth.php#L39-L42
train
alphacomm/alpharpc
src/AlphaRPC/Manager/Protocol/ClientHandlerJobRequest.php
ClientHandlerJobRequest.toMessage
public function toMessage() { $m = new Message(array( $this->getRequestId(), $this->getActionName(), )); $m->append($this->getParameters()); return $m; }
php
public function toMessage() { $m = new Message(array( $this->getRequestId(), $this->getActionName(), )); $m->append($this->getParameters()); return $m; }
[ "public", "function", "toMessage", "(", ")", "{", "$", "m", "=", "new", "Message", "(", "array", "(", "$", "this", "->", "getRequestId", "(", ")", ",", "$", "this", "->", "getActionName", "(", ")", ",", ")", ")", ";", "$", "m", "->", "append", "(", "$", "this", "->", "getParameters", "(", ")", ")", ";", "return", "$", "m", ";", "}" ]
Create a new Message from this StorageStatus. @return Message
[ "Create", "a", "new", "Message", "from", "this", "StorageStatus", "." ]
cf162854500554c4ba8d39f2675de35a49c30ed0
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/Protocol/ClientHandlerJobRequest.php#L107-L116
train
rnijveld/pgt
lib/Pgettext/Pgettext.php
Pgettext.msgfmt
public static function msgfmt($po, $mo = null) { $stringset = Po::fromFile($po); if ($mo === null) { $mo = substr($po, 0, -3) . '.mo'; } Mo::toFile($stringset, $mo); }
php
public static function msgfmt($po, $mo = null) { $stringset = Po::fromFile($po); if ($mo === null) { $mo = substr($po, 0, -3) . '.mo'; } Mo::toFile($stringset, $mo); }
[ "public", "static", "function", "msgfmt", "(", "$", "po", ",", "$", "mo", "=", "null", ")", "{", "$", "stringset", "=", "Po", "::", "fromFile", "(", "$", "po", ")", ";", "if", "(", "$", "mo", "===", "null", ")", "{", "$", "mo", "=", "substr", "(", "$", "po", ",", "0", ",", "-", "3", ")", ".", "'.mo'", ";", "}", "Mo", "::", "toFile", "(", "$", "stringset", ",", "$", "mo", ")", ";", "}" ]
Read a po file and store a mo file. If no MO filename is given, one will be generated from the PO filename. @param string $po Filename of the input PO file. @param string $mo Filename of the output MO file. @return void
[ "Read", "a", "po", "file", "and", "store", "a", "mo", "file", ".", "If", "no", "MO", "filename", "is", "given", "one", "will", "be", "generated", "from", "the", "PO", "filename", "." ]
9d64b4858438a9833065265c2e6d2db94b7e6fcd
https://github.com/rnijveld/pgt/blob/9d64b4858438a9833065265c2e6d2db94b7e6fcd/lib/Pgettext/Pgettext.php#L22-L29
train
rnijveld/pgt
lib/Pgettext/Pgettext.php
Pgettext.msgunfmt
public static function msgunfmt($mo, $po = null) { $stringset = Mo::fromFile($mo); if ($po === null) { print Po::toString($stringset); } else { Po::toFile($stringset, $po); } }
php
public static function msgunfmt($mo, $po = null) { $stringset = Mo::fromFile($mo); if ($po === null) { print Po::toString($stringset); } else { Po::toFile($stringset, $po); } }
[ "public", "static", "function", "msgunfmt", "(", "$", "mo", ",", "$", "po", "=", "null", ")", "{", "$", "stringset", "=", "Mo", "::", "fromFile", "(", "$", "mo", ")", ";", "if", "(", "$", "po", "===", "null", ")", "{", "print", "Po", "::", "toString", "(", "$", "stringset", ")", ";", "}", "else", "{", "Po", "::", "toFile", "(", "$", "stringset", ",", "$", "po", ")", ";", "}", "}" ]
Reads a mo file and stores the po file. If no PO file was given, only displays what would be the result. @param string $mo Filename of the input MO file. @param string $po Filename of the output PO file. @return void
[ "Reads", "a", "mo", "file", "and", "stores", "the", "po", "file", ".", "If", "no", "PO", "file", "was", "given", "only", "displays", "what", "would", "be", "the", "result", "." ]
9d64b4858438a9833065265c2e6d2db94b7e6fcd
https://github.com/rnijveld/pgt/blob/9d64b4858438a9833065265c2e6d2db94b7e6fcd/lib/Pgettext/Pgettext.php#L38-L46
train
cmmarslender/post-iterator
includes/Cmmarslender/PostIterator/PostIterator.php
PostIterator.have_pages
public function have_pages() { $this->setup(); $offset = $this->get_query_offset(); return (bool) ( $offset < $this->total_posts ); }
php
public function have_pages() { $this->setup(); $offset = $this->get_query_offset(); return (bool) ( $offset < $this->total_posts ); }
[ "public", "function", "have_pages", "(", ")", "{", "$", "this", "->", "setup", "(", ")", ";", "$", "offset", "=", "$", "this", "->", "get_query_offset", "(", ")", ";", "return", "(", "bool", ")", "(", "$", "offset", "<", "$", "this", "->", "total_posts", ")", ";", "}" ]
Indicates if we have posts to process
[ "Indicates", "if", "we", "have", "posts", "to", "process" ]
5c9007614a4979183c77ea5fb009bb577d44d3a1
https://github.com/cmmarslender/post-iterator/blob/5c9007614a4979183c77ea5fb009bb577d44d3a1/includes/Cmmarslender/PostIterator/PostIterator.php#L94-L100
train
cmmarslender/post-iterator
includes/Cmmarslender/PostIterator/PostIterator.php
PostIterator.count_posts
protected function count_posts() { global $wpdb; $query = $this->get_count_query(); $this->total_posts = $wpdb->get_var( $query ); }
php
protected function count_posts() { global $wpdb; $query = $this->get_count_query(); $this->total_posts = $wpdb->get_var( $query ); }
[ "protected", "function", "count_posts", "(", ")", "{", "global", "$", "wpdb", ";", "$", "query", "=", "$", "this", "->", "get_count_query", "(", ")", ";", "$", "this", "->", "total_posts", "=", "$", "wpdb", "->", "get_var", "(", "$", "query", ")", ";", "}" ]
Counts the total number of posts that match the restrictions, not including pagination.
[ "Counts", "the", "total", "number", "of", "posts", "that", "match", "the", "restrictions", "not", "including", "pagination", "." ]
5c9007614a4979183c77ea5fb009bb577d44d3a1
https://github.com/cmmarslender/post-iterator/blob/5c9007614a4979183c77ea5fb009bb577d44d3a1/includes/Cmmarslender/PostIterator/PostIterator.php#L131-L137
train
bruno-barros/w.eloquent-framework
src/weloquent/Support/Breadcrumb.php
Breadcrumb.getCurrentTaxonomy
protected function getCurrentTaxonomy() { if (!isset($this->args['taxonomies']) || empty($this->args['taxonomies'])) { $this->args['taxonomies'] = $this->getDefaultTaxonomies(); } foreach ($this->args['taxonomies'] as $tax) { if ($tax = get_term_by('slug', get_query_var($tax), $tax)) { return $tax; break; } } return null; }
php
protected function getCurrentTaxonomy() { if (!isset($this->args['taxonomies']) || empty($this->args['taxonomies'])) { $this->args['taxonomies'] = $this->getDefaultTaxonomies(); } foreach ($this->args['taxonomies'] as $tax) { if ($tax = get_term_by('slug', get_query_var($tax), $tax)) { return $tax; break; } } return null; }
[ "protected", "function", "getCurrentTaxonomy", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "args", "[", "'taxonomies'", "]", ")", "||", "empty", "(", "$", "this", "->", "args", "[", "'taxonomies'", "]", ")", ")", "{", "$", "this", "->", "args", "[", "'taxonomies'", "]", "=", "$", "this", "->", "getDefaultTaxonomies", "(", ")", ";", "}", "foreach", "(", "$", "this", "->", "args", "[", "'taxonomies'", "]", "as", "$", "tax", ")", "{", "if", "(", "$", "tax", "=", "get_term_by", "(", "'slug'", ",", "get_query_var", "(", "$", "tax", ")", ",", "$", "tax", ")", ")", "{", "return", "$", "tax", ";", "break", ";", "}", "}", "return", "null", ";", "}" ]
Find a custom taxonomy @return mixed|null
[ "Find", "a", "custom", "taxonomy" ]
d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/Breadcrumb.php#L217-L234
train
bruno-barros/w.eloquent-framework
src/weloquent/Support/Breadcrumb.php
Breadcrumb.getOverloaded
protected function getOverloaded($postType) { if (!isset($this->args['overload'][$postType])) { return null; } return $this->args['overload'][$postType]; }
php
protected function getOverloaded($postType) { if (!isset($this->args['overload'][$postType])) { return null; } return $this->args['overload'][$postType]; }
[ "protected", "function", "getOverloaded", "(", "$", "postType", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "args", "[", "'overload'", "]", "[", "$", "postType", "]", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "args", "[", "'overload'", "]", "[", "$", "postType", "]", ";", "}" ]
return the fake post type @param $postType @return null
[ "return", "the", "fake", "post", "type" ]
d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/Breadcrumb.php#L242-L250
train
fxpio/fxp-doctrine-console
Adapter/ServiceManagerAdapter.php
ServiceManagerAdapter.validate
private function validate($method) { $actionMethod = $method.'Method'; $ref = new \ReflectionClass($this->manager); if (null === $this->$actionMethod || !$ref->hasMethod($this->$actionMethod)) { throw new \RuntimeException(sprintf('The "%s" method for "%s" adapter is does not supported', $method, $this->getClass())); } }
php
private function validate($method) { $actionMethod = $method.'Method'; $ref = new \ReflectionClass($this->manager); if (null === $this->$actionMethod || !$ref->hasMethod($this->$actionMethod)) { throw new \RuntimeException(sprintf('The "%s" method for "%s" adapter is does not supported', $method, $this->getClass())); } }
[ "private", "function", "validate", "(", "$", "method", ")", "{", "$", "actionMethod", "=", "$", "method", ".", "'Method'", ";", "$", "ref", "=", "new", "\\", "ReflectionClass", "(", "$", "this", "->", "manager", ")", ";", "if", "(", "null", "===", "$", "this", "->", "$", "actionMethod", "||", "!", "$", "ref", "->", "hasMethod", "(", "$", "this", "->", "$", "actionMethod", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'The \"%s\" method for \"%s\" adapter is does not supported'", ",", "$", "method", ",", "$", "this", "->", "getClass", "(", ")", ")", ")", ";", "}", "}" ]
Validate the adapter method. @param string $method The method name @throws \RuntimeException When the method does not supported
[ "Validate", "the", "adapter", "method", "." ]
2fc16d7a4eb0f247075c50de225ec2670ca5479a
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ServiceManagerAdapter.php#L254-L262
train
fxpio/fxp-doctrine-console
Adapter/ServiceManagerAdapter.php
ServiceManagerAdapter.validateObject
public function validateObject($instance) { if (null !== $this->validator) { $violations = $this->validator->validate($instance); if (!empty($violations)) { throw new ValidationException($violations); } } }
php
public function validateObject($instance) { if (null !== $this->validator) { $violations = $this->validator->validate($instance); if (!empty($violations)) { throw new ValidationException($violations); } } }
[ "public", "function", "validateObject", "(", "$", "instance", ")", "{", "if", "(", "null", "!==", "$", "this", "->", "validator", ")", "{", "$", "violations", "=", "$", "this", "->", "validator", "->", "validate", "(", "$", "instance", ")", ";", "if", "(", "!", "empty", "(", "$", "violations", ")", ")", "{", "throw", "new", "ValidationException", "(", "$", "violations", ")", ";", "}", "}", "}" ]
Validate the object instance. @param object $instance The object instance @throws ValidationException When an error exist
[ "Validate", "the", "object", "instance", "." ]
2fc16d7a4eb0f247075c50de225ec2670ca5479a
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ServiceManagerAdapter.php#L271-L280
train
Fuzzyma/contao-eloquent-bundle
Hooks/DCAEloquentifier.php
DCAEloquentifier.relationFromField
public static function relationFromField($fieldName, $method = null) { if ($method) return $method; if (substr($fieldName, -3) == '_id') { return substr($fieldName, 0, -3); } if (substr($fieldName, -4) == '_ids') { return substr($fieldName, 0, -4) . 's'; } return $fieldName; }
php
public static function relationFromField($fieldName, $method = null) { if ($method) return $method; if (substr($fieldName, -3) == '_id') { return substr($fieldName, 0, -3); } if (substr($fieldName, -4) == '_ids') { return substr($fieldName, 0, -4) . 's'; } return $fieldName; }
[ "public", "static", "function", "relationFromField", "(", "$", "fieldName", ",", "$", "method", "=", "null", ")", "{", "if", "(", "$", "method", ")", "return", "$", "method", ";", "if", "(", "substr", "(", "$", "fieldName", ",", "-", "3", ")", "==", "'_id'", ")", "{", "return", "substr", "(", "$", "fieldName", ",", "0", ",", "-", "3", ")", ";", "}", "if", "(", "substr", "(", "$", "fieldName", ",", "-", "4", ")", "==", "'_ids'", ")", "{", "return", "substr", "(", "$", "fieldName", ",", "0", ",", "-", "4", ")", ".", "'s'", ";", "}", "return", "$", "fieldName", ";", "}" ]
Consider this as a bit of magic This method will return a "guessed" method name which is used from the relation Since there is no way in Eloquent to "read" the relations from a model, we have to work with what we get This method only does something when no method was set in the dca It takes one $field of the dca and removes the _id So 'topic_id' will be 'topic' and 'topic_ids' will be 'topics'. If no _id is present, it just uses the $fieldName as method name for the relation
[ "Consider", "this", "as", "a", "bit", "of", "magic", "This", "method", "will", "return", "a", "guessed", "method", "name", "which", "is", "used", "from", "the", "relation", "Since", "there", "is", "no", "way", "in", "Eloquent", "to", "read", "the", "relations", "from", "a", "model", "we", "have", "to", "work", "with", "what", "we", "get" ]
d5af2a3f48807db278ec3c92df463171f9514179
https://github.com/Fuzzyma/contao-eloquent-bundle/blob/d5af2a3f48807db278ec3c92df463171f9514179/Hooks/DCAEloquentifier.php#L270-L283
train
addwiki/guzzle-mediawiki-client
src/MediawikiApiClient.php
MediawikiApiClient.factory
public static function factory($config = array()) { $required = array('base_url'); $config = Collection::fromConfig($config, array(), $required); $client = new self($config->get('base_url')); $cookiePlugin = new CookiePlugin(new ArrayCookieJar()); $client->addSubscriber($cookiePlugin); $client->setConfig($config); $client->setUserAgent('addwiki-guzzle-mediawiki-client'); $client->setDescription(ServiceDescription::factory( dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'mediawiki.json')); return $client; }
php
public static function factory($config = array()) { $required = array('base_url'); $config = Collection::fromConfig($config, array(), $required); $client = new self($config->get('base_url')); $cookiePlugin = new CookiePlugin(new ArrayCookieJar()); $client->addSubscriber($cookiePlugin); $client->setConfig($config); $client->setUserAgent('addwiki-guzzle-mediawiki-client'); $client->setDescription(ServiceDescription::factory( dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'mediawiki.json')); return $client; }
[ "public", "static", "function", "factory", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "required", "=", "array", "(", "'base_url'", ")", ";", "$", "config", "=", "Collection", "::", "fromConfig", "(", "$", "config", ",", "array", "(", ")", ",", "$", "required", ")", ";", "$", "client", "=", "new", "self", "(", "$", "config", "->", "get", "(", "'base_url'", ")", ")", ";", "$", "cookiePlugin", "=", "new", "CookiePlugin", "(", "new", "ArrayCookieJar", "(", ")", ")", ";", "$", "client", "->", "addSubscriber", "(", "$", "cookiePlugin", ")", ";", "$", "client", "->", "setConfig", "(", "$", "config", ")", ";", "$", "client", "->", "setUserAgent", "(", "'addwiki-guzzle-mediawiki-client'", ")", ";", "$", "client", "->", "setDescription", "(", "ServiceDescription", "::", "factory", "(", "dirname", "(", "__DIR__", ")", ".", "DIRECTORY_SEPARATOR", ".", "'data'", ".", "DIRECTORY_SEPARATOR", ".", "'mediawiki.json'", ")", ")", ";", "return", "$", "client", ";", "}" ]
Factory method to create a new MediawikiApiClient @param array|Collection $config Configuration data. Array keys: base_url - Base URL of web service @throws InvalidArgumentException @return MediawikiApiClient
[ "Factory", "method", "to", "create", "a", "new", "MediawikiApiClient" ]
60dc2c27d40196f90d1e5eef8cf0fc90b6b4d440
https://github.com/addwiki/guzzle-mediawiki-client/blob/60dc2c27d40196f90d1e5eef8cf0fc90b6b4d440/src/MediawikiApiClient.php#L65-L80
train
rzajac/php-test-helper
src/Database/DbGet.php
DbGet.factory
public static function factory(array $dbConfig): DbItf { /** @var DbItf[] $instances */ static $instances = []; $key = md5(json_encode($dbConfig)); if (isset($instances[$key])) { return $instances[$key]; } switch ($dbConfig[DbItf::DB_CFG_DRIVER]) { case DbItf::DB_DRIVER_MYSQL: $instances[$key] = new MySQL(); $dbConfig[DbItf::DB_CFG_PORT] = (int)$dbConfig[DbItf::DB_CFG_PORT]; break; default: throw new DatabaseEx('Unknown database driver name: ' . $dbConfig[DbItf::DB_CFG_DRIVER]); } $instances[$key]->dbSetup($dbConfig); if ($dbConfig[DbItf::DB_CFG_CONNECT]) { $instances[$key]->dbConnect(); } return $instances[$key]; }
php
public static function factory(array $dbConfig): DbItf { /** @var DbItf[] $instances */ static $instances = []; $key = md5(json_encode($dbConfig)); if (isset($instances[$key])) { return $instances[$key]; } switch ($dbConfig[DbItf::DB_CFG_DRIVER]) { case DbItf::DB_DRIVER_MYSQL: $instances[$key] = new MySQL(); $dbConfig[DbItf::DB_CFG_PORT] = (int)$dbConfig[DbItf::DB_CFG_PORT]; break; default: throw new DatabaseEx('Unknown database driver name: ' . $dbConfig[DbItf::DB_CFG_DRIVER]); } $instances[$key]->dbSetup($dbConfig); if ($dbConfig[DbItf::DB_CFG_CONNECT]) { $instances[$key]->dbConnect(); } return $instances[$key]; }
[ "public", "static", "function", "factory", "(", "array", "$", "dbConfig", ")", ":", "DbItf", "{", "/** @var DbItf[] $instances */", "static", "$", "instances", "=", "[", "]", ";", "$", "key", "=", "md5", "(", "json_encode", "(", "$", "dbConfig", ")", ")", ";", "if", "(", "isset", "(", "$", "instances", "[", "$", "key", "]", ")", ")", "{", "return", "$", "instances", "[", "$", "key", "]", ";", "}", "switch", "(", "$", "dbConfig", "[", "DbItf", "::", "DB_CFG_DRIVER", "]", ")", "{", "case", "DbItf", "::", "DB_DRIVER_MYSQL", ":", "$", "instances", "[", "$", "key", "]", "=", "new", "MySQL", "(", ")", ";", "$", "dbConfig", "[", "DbItf", "::", "DB_CFG_PORT", "]", "=", "(", "int", ")", "$", "dbConfig", "[", "DbItf", "::", "DB_CFG_PORT", "]", ";", "break", ";", "default", ":", "throw", "new", "DatabaseEx", "(", "'Unknown database driver name: '", ".", "$", "dbConfig", "[", "DbItf", "::", "DB_CFG_DRIVER", "]", ")", ";", "}", "$", "instances", "[", "$", "key", "]", "->", "dbSetup", "(", "$", "dbConfig", ")", ";", "if", "(", "$", "dbConfig", "[", "DbItf", "::", "DB_CFG_CONNECT", "]", ")", "{", "$", "instances", "[", "$", "key", "]", "->", "dbConnect", "(", ")", ";", "}", "return", "$", "instances", "[", "$", "key", "]", ";", "}" ]
Database factory. It returns the same instance for the same config. @param array $dbConfig The database configuration @throws DatabaseEx @return DbItf
[ "Database", "factory", "." ]
37280e9ff639b25cf9413909cc080c5d8deb311c
https://github.com/rzajac/php-test-helper/blob/37280e9ff639b25cf9413909cc080c5d8deb311c/src/Database/DbGet.php#L39-L67
train
as3io/modlr
src/Models/Collections/AbstractCollection.php
AbstractCollection.calculateChangeSet
public function calculateChangeSet() { if (false === $this->isDirty()) { return []; } return [ 'old' => empty($this->original) ? null : $this->original, 'new' => empty($this->models) ? null : $this->models, ]; }
php
public function calculateChangeSet() { if (false === $this->isDirty()) { return []; } return [ 'old' => empty($this->original) ? null : $this->original, 'new' => empty($this->models) ? null : $this->models, ]; }
[ "public", "function", "calculateChangeSet", "(", ")", "{", "if", "(", "false", "===", "$", "this", "->", "isDirty", "(", ")", ")", "{", "return", "[", "]", ";", "}", "return", "[", "'old'", "=>", "empty", "(", "$", "this", "->", "original", ")", "?", "null", ":", "$", "this", "->", "original", ",", "'new'", "=>", "empty", "(", "$", "this", "->", "models", ")", "?", "null", ":", "$", "this", "->", "models", ",", "]", ";", "}" ]
Calculates the change set of this collection. @return array
[ "Calculates", "the", "change", "set", "of", "this", "collection", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L105-L114
train
as3io/modlr
src/Models/Collections/AbstractCollection.php
AbstractCollection.has
public function has(AbstractModel $model) { $key = $model->getCompositeKey(); return isset($this->models[$key]); }
php
public function has(AbstractModel $model) { $key = $model->getCompositeKey(); return isset($this->models[$key]); }
[ "public", "function", "has", "(", "AbstractModel", "$", "model", ")", "{", "$", "key", "=", "$", "model", "->", "getCompositeKey", "(", ")", ";", "return", "isset", "(", "$", "this", "->", "models", "[", "$", "key", "]", ")", ";", "}" ]
Determines if the Model is included in the collection. @param AbstractModel $model The model to check. @return bool
[ "Determines", "if", "the", "Model", "is", "included", "in", "the", "collection", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L184-L188
train
as3io/modlr
src/Models/Collections/AbstractCollection.php
AbstractCollection.push
public function push(AbstractModel $model) { $this->validateAdd($model); if (true === $this->willAdd($model)) { return $this; } if (true === $this->willRemove($model)) { $this->evict('removed', $model); $this->set('models', $model); return $this; } if (true === $this->hasOriginal($model)) { return $this; } $this->set('added', $model); $this->set('models', $model); return $this; }
php
public function push(AbstractModel $model) { $this->validateAdd($model); if (true === $this->willAdd($model)) { return $this; } if (true === $this->willRemove($model)) { $this->evict('removed', $model); $this->set('models', $model); return $this; } if (true === $this->hasOriginal($model)) { return $this; } $this->set('added', $model); $this->set('models', $model); return $this; }
[ "public", "function", "push", "(", "AbstractModel", "$", "model", ")", "{", "$", "this", "->", "validateAdd", "(", "$", "model", ")", ";", "if", "(", "true", "===", "$", "this", "->", "willAdd", "(", "$", "model", ")", ")", "{", "return", "$", "this", ";", "}", "if", "(", "true", "===", "$", "this", "->", "willRemove", "(", "$", "model", ")", ")", "{", "$", "this", "->", "evict", "(", "'removed'", ",", "$", "model", ")", ";", "$", "this", "->", "set", "(", "'models'", ",", "$", "model", ")", ";", "return", "$", "this", ";", "}", "if", "(", "true", "===", "$", "this", "->", "hasOriginal", "(", "$", "model", ")", ")", "{", "return", "$", "this", ";", "}", "$", "this", "->", "set", "(", "'added'", ",", "$", "model", ")", ";", "$", "this", "->", "set", "(", "'models'", ",", "$", "model", ")", ";", "return", "$", "this", ";", "}" ]
Pushes a Model into the collection. @param AbstractModel $model The model to push. @return self
[ "Pushes", "a", "Model", "into", "the", "collection", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L257-L274
train
as3io/modlr
src/Models/Collections/AbstractCollection.php
AbstractCollection.rollback
public function rollback() { $this->models = $this->original; $this->added = []; $this->removed = []; return $this; }
php
public function rollback() { $this->models = $this->original; $this->added = []; $this->removed = []; return $this; }
[ "public", "function", "rollback", "(", ")", "{", "$", "this", "->", "models", "=", "$", "this", "->", "original", ";", "$", "this", "->", "added", "=", "[", "]", ";", "$", "this", "->", "removed", "=", "[", "]", ";", "return", "$", "this", ";", "}" ]
Rollsback the collection it it's original state. @return self
[ "Rollsback", "the", "collection", "it", "it", "s", "original", "state", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L315-L321
train
as3io/modlr
src/Models/Collections/AbstractCollection.php
AbstractCollection.willAdd
public function willAdd(AbstractModel $model) { $key = $model->getCompositeKey(); return isset($this->added[$key]); }
php
public function willAdd(AbstractModel $model) { $key = $model->getCompositeKey(); return isset($this->added[$key]); }
[ "public", "function", "willAdd", "(", "AbstractModel", "$", "model", ")", "{", "$", "key", "=", "$", "model", "->", "getCompositeKey", "(", ")", ";", "return", "isset", "(", "$", "this", "->", "added", "[", "$", "key", "]", ")", ";", "}" ]
Determines if the model is scheduled for addition to the collection. @param AbstractModel $model The model to check. @return bool
[ "Determines", "if", "the", "model", "is", "scheduled", "for", "addition", "to", "the", "collection", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L337-L341
train
as3io/modlr
src/Models/Collections/AbstractCollection.php
AbstractCollection.willRemove
public function willRemove(AbstractModel $model) { $key = $model->getCompositeKey(); return isset($this->removed[$key]); }
php
public function willRemove(AbstractModel $model) { $key = $model->getCompositeKey(); return isset($this->removed[$key]); }
[ "public", "function", "willRemove", "(", "AbstractModel", "$", "model", ")", "{", "$", "key", "=", "$", "model", "->", "getCompositeKey", "(", ")", ";", "return", "isset", "(", "$", "this", "->", "removed", "[", "$", "key", "]", ")", ";", "}" ]
Determines if the model is scheduled for removal from the collection. @param AbstractModel $model The model to check. @return bool
[ "Determines", "if", "the", "model", "is", "scheduled", "for", "removal", "from", "the", "collection", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L349-L353
train
as3io/modlr
src/Models/Collections/AbstractCollection.php
AbstractCollection.add
protected function add(AbstractModel $model) { if (true === $this->has($model)) { return $this; } $this->validateAdd($model); if (true === $model->getState()->is('empty')) { $this->loaded = false; } $key = $model->getCompositeKey(); $this->models[$key] = $model; $this->modelKeyMap[] = $key; if (false === $this->hasOriginal($model)) { $this->original[$key] = $model; } return $this; }
php
protected function add(AbstractModel $model) { if (true === $this->has($model)) { return $this; } $this->validateAdd($model); if (true === $model->getState()->is('empty')) { $this->loaded = false; } $key = $model->getCompositeKey(); $this->models[$key] = $model; $this->modelKeyMap[] = $key; if (false === $this->hasOriginal($model)) { $this->original[$key] = $model; } return $this; }
[ "protected", "function", "add", "(", "AbstractModel", "$", "model", ")", "{", "if", "(", "true", "===", "$", "this", "->", "has", "(", "$", "model", ")", ")", "{", "return", "$", "this", ";", "}", "$", "this", "->", "validateAdd", "(", "$", "model", ")", ";", "if", "(", "true", "===", "$", "model", "->", "getState", "(", ")", "->", "is", "(", "'empty'", ")", ")", "{", "$", "this", "->", "loaded", "=", "false", ";", "}", "$", "key", "=", "$", "model", "->", "getCompositeKey", "(", ")", ";", "$", "this", "->", "models", "[", "$", "key", "]", "=", "$", "model", ";", "$", "this", "->", "modelKeyMap", "[", "]", "=", "$", "key", ";", "if", "(", "false", "===", "$", "this", "->", "hasOriginal", "(", "$", "model", ")", ")", "{", "$", "this", "->", "original", "[", "$", "key", "]", "=", "$", "model", ";", "}", "return", "$", "this", ";", "}" ]
Adds an model to this collection. Is used during initial collection construction. @param AbstractModel $model @return self
[ "Adds", "an", "model", "to", "this", "collection", ".", "Is", "used", "during", "initial", "collection", "construction", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L362-L380
train
as3io/modlr
src/Models/Collections/AbstractCollection.php
AbstractCollection.hasOriginal
protected function hasOriginal(AbstractModel $model) { $key = $model->getCompositeKey(); return isset($this->original[$key]); }
php
protected function hasOriginal(AbstractModel $model) { $key = $model->getCompositeKey(); return isset($this->original[$key]); }
[ "protected", "function", "hasOriginal", "(", "AbstractModel", "$", "model", ")", "{", "$", "key", "=", "$", "model", "->", "getCompositeKey", "(", ")", ";", "return", "isset", "(", "$", "this", "->", "original", "[", "$", "key", "]", ")", ";", "}" ]
Determines if the model is included in the original set. @param AbstractModel $model The model to check. @return bool
[ "Determines", "if", "the", "model", "is", "included", "in", "the", "original", "set", "." ]
7e684b88bb22a2e18397df9402075c6533084b16
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L413-L417
train
PhoxPHP/Glider
src/Connection/PlatformResolver.php
PlatformResolver.resolvePlatform
public function resolvePlatform(EventManager $eventManager) { $eventManager->attachSubscriber(new ConnectionAttemptSubscriber()); if (!$this->connectionManager instanceof ConnectionInterface) { throw new RuntimeException('Connection must implement \ConnectionInterface'); } $reflector = new \ReflectionClass($this->connectionManager); $connections = $reflector->getProperty('platformConnector'); $connections->setAccessible('public'); $connections = $connections->getValue($this->connectionManager); $resolvedProvider = $this->getPlatformProvider($connections, $eventManager); if (!$resolvedProvider) { $resolvedProvider = $this->getPlatformProvider( $this->connectionManager->getAlternativeId(ConnectionManager::USE_ALT_KEY), $eventManager ); } if (!is_null($resolvedProvider) && $resolvedProvider == false) { throw new RuntimeException('Unable to resolve database platform.'); } // If connection was successfully established, dispatch `connect.created` event. $this->platformProvider->eventManager->dispatchEvent('connect.created'); return $resolvedProvider; }
php
public function resolvePlatform(EventManager $eventManager) { $eventManager->attachSubscriber(new ConnectionAttemptSubscriber()); if (!$this->connectionManager instanceof ConnectionInterface) { throw new RuntimeException('Connection must implement \ConnectionInterface'); } $reflector = new \ReflectionClass($this->connectionManager); $connections = $reflector->getProperty('platformConnector'); $connections->setAccessible('public'); $connections = $connections->getValue($this->connectionManager); $resolvedProvider = $this->getPlatformProvider($connections, $eventManager); if (!$resolvedProvider) { $resolvedProvider = $this->getPlatformProvider( $this->connectionManager->getAlternativeId(ConnectionManager::USE_ALT_KEY), $eventManager ); } if (!is_null($resolvedProvider) && $resolvedProvider == false) { throw new RuntimeException('Unable to resolve database platform.'); } // If connection was successfully established, dispatch `connect.created` event. $this->platformProvider->eventManager->dispatchEvent('connect.created'); return $resolvedProvider; }
[ "public", "function", "resolvePlatform", "(", "EventManager", "$", "eventManager", ")", "{", "$", "eventManager", "->", "attachSubscriber", "(", "new", "ConnectionAttemptSubscriber", "(", ")", ")", ";", "if", "(", "!", "$", "this", "->", "connectionManager", "instanceof", "ConnectionInterface", ")", "{", "throw", "new", "RuntimeException", "(", "'Connection must implement \\ConnectionInterface'", ")", ";", "}", "$", "reflector", "=", "new", "\\", "ReflectionClass", "(", "$", "this", "->", "connectionManager", ")", ";", "$", "connections", "=", "$", "reflector", "->", "getProperty", "(", "'platformConnector'", ")", ";", "$", "connections", "->", "setAccessible", "(", "'public'", ")", ";", "$", "connections", "=", "$", "connections", "->", "getValue", "(", "$", "this", "->", "connectionManager", ")", ";", "$", "resolvedProvider", "=", "$", "this", "->", "getPlatformProvider", "(", "$", "connections", ",", "$", "eventManager", ")", ";", "if", "(", "!", "$", "resolvedProvider", ")", "{", "$", "resolvedProvider", "=", "$", "this", "->", "getPlatformProvider", "(", "$", "this", "->", "connectionManager", "->", "getAlternativeId", "(", "ConnectionManager", "::", "USE_ALT_KEY", ")", ",", "$", "eventManager", ")", ";", "}", "if", "(", "!", "is_null", "(", "$", "resolvedProvider", ")", "&&", "$", "resolvedProvider", "==", "false", ")", "{", "throw", "new", "RuntimeException", "(", "'Unable to resolve database platform.'", ")", ";", "}", "// If connection was successfully established, dispatch `connect.created` event.", "$", "this", "->", "platformProvider", "->", "eventManager", "->", "dispatchEvent", "(", "'connect.created'", ")", ";", "return", "$", "resolvedProvider", ";", "}" ]
Resolve provided connection's platform. @param $eventManager <Kit\Glider\Events\EventManager> @access public @return <Object> <Kit\Glider\Platform\Contract\PlatformProvider>
[ "Resolve", "provided", "connection", "s", "platform", "." ]
17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connection/PlatformResolver.php#L89-L116
train
PhoxPHP/Glider
src/Connection/PlatformResolver.php
PlatformResolver.getPlatformProvider
private function getPlatformProvider($platform=[], EventManager $eventManager) { if (is_null($platform)) { return false; } $platformId = key($platform); $platform = current($platform); if (!isset($platform['provider'])) { $this->connectionFailed = ':noPlatform'; return false; } $provider = $platform['provider']; if (!class_exists($provider)) { $this->connectionFailed = ':noConnectorProvider'; return false; } $this->preparedConnection = $platform; $platformProvider = new $provider($this, new EventManager()); if (!$platformProvider instanceof PlatformProvider) { return false; } if (isset($platform['domain']) && !Domain::matches($platform['domain'])) { $eventManager->dispatchEvent('domain.notallowed', [$platformId => $platform]); return false; } $this->platformProvider = $platformProvider; $providerConnector = $this->platformProvider; return $providerConnector; }
php
private function getPlatformProvider($platform=[], EventManager $eventManager) { if (is_null($platform)) { return false; } $platformId = key($platform); $platform = current($platform); if (!isset($platform['provider'])) { $this->connectionFailed = ':noPlatform'; return false; } $provider = $platform['provider']; if (!class_exists($provider)) { $this->connectionFailed = ':noConnectorProvider'; return false; } $this->preparedConnection = $platform; $platformProvider = new $provider($this, new EventManager()); if (!$platformProvider instanceof PlatformProvider) { return false; } if (isset($platform['domain']) && !Domain::matches($platform['domain'])) { $eventManager->dispatchEvent('domain.notallowed', [$platformId => $platform]); return false; } $this->platformProvider = $platformProvider; $providerConnector = $this->platformProvider; return $providerConnector; }
[ "private", "function", "getPlatformProvider", "(", "$", "platform", "=", "[", "]", ",", "EventManager", "$", "eventManager", ")", "{", "if", "(", "is_null", "(", "$", "platform", ")", ")", "{", "return", "false", ";", "}", "$", "platformId", "=", "key", "(", "$", "platform", ")", ";", "$", "platform", "=", "current", "(", "$", "platform", ")", ";", "if", "(", "!", "isset", "(", "$", "platform", "[", "'provider'", "]", ")", ")", "{", "$", "this", "->", "connectionFailed", "=", "':noPlatform'", ";", "return", "false", ";", "}", "$", "provider", "=", "$", "platform", "[", "'provider'", "]", ";", "if", "(", "!", "class_exists", "(", "$", "provider", ")", ")", "{", "$", "this", "->", "connectionFailed", "=", "':noConnectorProvider'", ";", "return", "false", ";", "}", "$", "this", "->", "preparedConnection", "=", "$", "platform", ";", "$", "platformProvider", "=", "new", "$", "provider", "(", "$", "this", ",", "new", "EventManager", "(", ")", ")", ";", "if", "(", "!", "$", "platformProvider", "instanceof", "PlatformProvider", ")", "{", "return", "false", ";", "}", "if", "(", "isset", "(", "$", "platform", "[", "'domain'", "]", ")", "&&", "!", "Domain", "::", "matches", "(", "$", "platform", "[", "'domain'", "]", ")", ")", "{", "$", "eventManager", "->", "dispatchEvent", "(", "'domain.notallowed'", ",", "[", "$", "platformId", "=>", "$", "platform", "]", ")", ";", "return", "false", ";", "}", "$", "this", "->", "platformProvider", "=", "$", "platformProvider", ";", "$", "providerConnector", "=", "$", "this", "->", "platformProvider", ";", "return", "$", "providerConnector", ";", "}" ]
Resolves a connector's provider and returns it's object. @param $eventManager <Kit\Glider\Events\EventManager > @param $platform <Array> @access private @return <Mixed>
[ "Resolves", "a", "connector", "s", "provider", "and", "returns", "it", "s", "object", "." ]
17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connection/PlatformResolver.php#L126-L159
train
axypro/codecs-base64vlq
Base64.php
Base64.encode
public function encode($numbers) { $chars = []; $alphabet = $this->alphabet; foreach ($numbers as $number) { if (isset($alphabet[$number])) { $chars[] = $alphabet[$number]; } else { throw new InvalidBase64Input($number); } } return implode('', $chars); }
php
public function encode($numbers) { $chars = []; $alphabet = $this->alphabet; foreach ($numbers as $number) { if (isset($alphabet[$number])) { $chars[] = $alphabet[$number]; } else { throw new InvalidBase64Input($number); } } return implode('', $chars); }
[ "public", "function", "encode", "(", "$", "numbers", ")", "{", "$", "chars", "=", "[", "]", ";", "$", "alphabet", "=", "$", "this", "->", "alphabet", ";", "foreach", "(", "$", "numbers", "as", "$", "number", ")", "{", "if", "(", "isset", "(", "$", "alphabet", "[", "$", "number", "]", ")", ")", "{", "$", "chars", "[", "]", "=", "$", "alphabet", "[", "$", "number", "]", ";", "}", "else", "{", "throw", "new", "InvalidBase64Input", "(", "$", "number", ")", ";", "}", "}", "return", "implode", "(", "''", ",", "$", "chars", ")", ";", "}" ]
Encodes a block of numbers to a base64-string @param int[]|int $numbers @return string @throws \axy\codecs\base64vlq\errors\InvalidBase64Input
[ "Encodes", "a", "block", "of", "numbers", "to", "a", "base64", "-", "string" ]
0d658b7fafdabb824fa1c91c0f6977ebac707dad
https://github.com/axypro/codecs-base64vlq/blob/0d658b7fafdabb824fa1c91c0f6977ebac707dad/Base64.php#L44-L56
train
axypro/codecs-base64vlq
Base64.php
Base64.decode
public function decode($based) { if (!is_array($based)) { $based = str_split($based); } $numbers = []; $char2int = $this->char2int; foreach ($based as $char) { if (isset($char2int[$char])) { $numbers[] = $char2int[$char]; } else { throw new InvalidBase64($based); } } return $numbers; }
php
public function decode($based) { if (!is_array($based)) { $based = str_split($based); } $numbers = []; $char2int = $this->char2int; foreach ($based as $char) { if (isset($char2int[$char])) { $numbers[] = $char2int[$char]; } else { throw new InvalidBase64($based); } } return $numbers; }
[ "public", "function", "decode", "(", "$", "based", ")", "{", "if", "(", "!", "is_array", "(", "$", "based", ")", ")", "{", "$", "based", "=", "str_split", "(", "$", "based", ")", ";", "}", "$", "numbers", "=", "[", "]", ";", "$", "char2int", "=", "$", "this", "->", "char2int", ";", "foreach", "(", "$", "based", "as", "$", "char", ")", "{", "if", "(", "isset", "(", "$", "char2int", "[", "$", "char", "]", ")", ")", "{", "$", "numbers", "[", "]", "=", "$", "char2int", "[", "$", "char", "]", ";", "}", "else", "{", "throw", "new", "InvalidBase64", "(", "$", "based", ")", ";", "}", "}", "return", "$", "numbers", ";", "}" ]
Decodes a base64-string to a block of numbers @param string|string[] $based the base64-string or the array of characters @return int[] @throws \axy\codecs\base64vlq\errors\InvalidBase64
[ "Decodes", "a", "base64", "-", "string", "to", "a", "block", "of", "numbers" ]
0d658b7fafdabb824fa1c91c0f6977ebac707dad
https://github.com/axypro/codecs-base64vlq/blob/0d658b7fafdabb824fa1c91c0f6977ebac707dad/Base64.php#L66-L81
train
pascalchevrel/vcs
src/VCS/Base.php
Base.parseLog
public function parseLog($log) { $commits = $tags = []; for ($i = 0, $lines = count($log); $i < $lines; $i++) { $tmp = explode(': ', $log[$i]); $tmp = array_map('trim', $tmp); if ($tmp[0] == 'changeset') { $commit = $tmp[1]; } if ($tmp[0] == 'user') { $email = $this->extractEmail($tmp[1]); $author = $this->extractAuthor($tmp[1]); } if ($tmp[0] == 'date') { $date = trim($tmp[1]); } if ($tmp[0] == 'tag') { $tags[] = trim($tmp[1]); } if ($tmp[0] == 'summary') { $commits[] = [ 'commit' => trim($commit), 'author' => trim($author), 'email' => trim($email), 'date' => DateTime::createFromFormat('D M j H:i:s Y O', $date), 'summary' => trim($tmp[1]), 'tags' => $tags, 'vcs' => trim($this->repository_type), ]; $tags = []; } } return $commits; }
php
public function parseLog($log) { $commits = $tags = []; for ($i = 0, $lines = count($log); $i < $lines; $i++) { $tmp = explode(': ', $log[$i]); $tmp = array_map('trim', $tmp); if ($tmp[0] == 'changeset') { $commit = $tmp[1]; } if ($tmp[0] == 'user') { $email = $this->extractEmail($tmp[1]); $author = $this->extractAuthor($tmp[1]); } if ($tmp[0] == 'date') { $date = trim($tmp[1]); } if ($tmp[0] == 'tag') { $tags[] = trim($tmp[1]); } if ($tmp[0] == 'summary') { $commits[] = [ 'commit' => trim($commit), 'author' => trim($author), 'email' => trim($email), 'date' => DateTime::createFromFormat('D M j H:i:s Y O', $date), 'summary' => trim($tmp[1]), 'tags' => $tags, 'vcs' => trim($this->repository_type), ]; $tags = []; } } return $commits; }
[ "public", "function", "parseLog", "(", "$", "log", ")", "{", "$", "commits", "=", "$", "tags", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ",", "$", "lines", "=", "count", "(", "$", "log", ")", ";", "$", "i", "<", "$", "lines", ";", "$", "i", "++", ")", "{", "$", "tmp", "=", "explode", "(", "': '", ",", "$", "log", "[", "$", "i", "]", ")", ";", "$", "tmp", "=", "array_map", "(", "'trim'", ",", "$", "tmp", ")", ";", "if", "(", "$", "tmp", "[", "0", "]", "==", "'changeset'", ")", "{", "$", "commit", "=", "$", "tmp", "[", "1", "]", ";", "}", "if", "(", "$", "tmp", "[", "0", "]", "==", "'user'", ")", "{", "$", "email", "=", "$", "this", "->", "extractEmail", "(", "$", "tmp", "[", "1", "]", ")", ";", "$", "author", "=", "$", "this", "->", "extractAuthor", "(", "$", "tmp", "[", "1", "]", ")", ";", "}", "if", "(", "$", "tmp", "[", "0", "]", "==", "'date'", ")", "{", "$", "date", "=", "trim", "(", "$", "tmp", "[", "1", "]", ")", ";", "}", "if", "(", "$", "tmp", "[", "0", "]", "==", "'tag'", ")", "{", "$", "tags", "[", "]", "=", "trim", "(", "$", "tmp", "[", "1", "]", ")", ";", "}", "if", "(", "$", "tmp", "[", "0", "]", "==", "'summary'", ")", "{", "$", "commits", "[", "]", "=", "[", "'commit'", "=>", "trim", "(", "$", "commit", ")", ",", "'author'", "=>", "trim", "(", "$", "author", ")", ",", "'email'", "=>", "trim", "(", "$", "email", ")", ",", "'date'", "=>", "DateTime", "::", "createFromFormat", "(", "'D M j H:i:s Y O'", ",", "$", "date", ")", ",", "'summary'", "=>", "trim", "(", "$", "tmp", "[", "1", "]", ")", ",", "'tags'", "=>", "$", "tags", ",", "'vcs'", "=>", "trim", "(", "$", "this", "->", "repository_type", ")", ",", "]", ";", "$", "tags", "=", "[", "]", ";", "}", "}", "return", "$", "commits", ";", "}" ]
Parse the log provided as a string @param string $log VCS log @return array structured data extracted from the log
[ "Parse", "the", "log", "provided", "as", "a", "string" ]
23d4827d5f8f44f20cd9a59fdf71ee7dfc895bfa
https://github.com/pascalchevrel/vcs/blob/23d4827d5f8f44f20cd9a59fdf71ee7dfc895bfa/src/VCS/Base.php#L33-L73
train
pascalchevrel/vcs
src/VCS/Base.php
Base.extractAuthor
public function extractAuthor($string) { preg_match_all('/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i', $string, $matches); $string = str_replace($matches[0], '', $string); $string = str_replace(['<', '>', '()'], '', $string); $string = trim($string); return empty($string) ? 'Unknown' : $string; }
php
public function extractAuthor($string) { preg_match_all('/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i', $string, $matches); $string = str_replace($matches[0], '', $string); $string = str_replace(['<', '>', '()'], '', $string); $string = trim($string); return empty($string) ? 'Unknown' : $string; }
[ "public", "function", "extractAuthor", "(", "$", "string", ")", "{", "preg_match_all", "(", "'/[\\._a-zA-Z0-9-]+@[\\._a-zA-Z0-9-]+/i'", ",", "$", "string", ",", "$", "matches", ")", ";", "$", "string", "=", "str_replace", "(", "$", "matches", "[", "0", "]", ",", "''", ",", "$", "string", ")", ";", "$", "string", "=", "str_replace", "(", "[", "'<'", ",", "'>'", ",", "'()'", "]", ",", "''", ",", "$", "string", ")", ";", "$", "string", "=", "trim", "(", "$", "string", ")", ";", "return", "empty", "(", "$", "string", ")", "?", "'Unknown'", ":", "$", "string", ";", "}" ]
Extract the Author name from the string, remove emails if they exist @param string $string String to analyze @return string Author name
[ "Extract", "the", "Author", "name", "from", "the", "string", "remove", "emails", "if", "they", "exist" ]
23d4827d5f8f44f20cd9a59fdf71ee7dfc895bfa
https://github.com/pascalchevrel/vcs/blob/23d4827d5f8f44f20cd9a59fdf71ee7dfc895bfa/src/VCS/Base.php#L95-L103
train
schpill/thin
src/Html/Sizer.php
Sizer.save
public function save($savePath, $imageQuality = 95) { // If the image wasn't resized, fetch original image. if (!$this->imageResized) { $this->imageResized = $this->image; } // Get extension of the output file. $extension = Inflector::lower(File::extension($savePath)); // Create and save an image based on it's extension. switch($extension) { case 'jpg': case 'jpeg': if (imagetypes() & IMG_JPG) { imagejpeg($this->imageResized, $savePath, $imageQuality); } break; case 'gif': if (imagetypes() & IMG_GIF) { imagegif($this->imageResized, $savePath); } break; case 'png': // Scale quality from 0-100 to 0-9. $scaleQuality = round(($imageQuality / 100) * 9); // Invert quality setting as 0 is best, not 9. $invertScaleQuality = 9 - $scaleQuality; if (imagetypes() & IMG_PNG) { imagepng($this->imageResized, $savePath, $invertScaleQuality); } break; default: return false; break; } // Remove the resource for the resized image. imagedestroy($this->imageResized); return true; }
php
public function save($savePath, $imageQuality = 95) { // If the image wasn't resized, fetch original image. if (!$this->imageResized) { $this->imageResized = $this->image; } // Get extension of the output file. $extension = Inflector::lower(File::extension($savePath)); // Create and save an image based on it's extension. switch($extension) { case 'jpg': case 'jpeg': if (imagetypes() & IMG_JPG) { imagejpeg($this->imageResized, $savePath, $imageQuality); } break; case 'gif': if (imagetypes() & IMG_GIF) { imagegif($this->imageResized, $savePath); } break; case 'png': // Scale quality from 0-100 to 0-9. $scaleQuality = round(($imageQuality / 100) * 9); // Invert quality setting as 0 is best, not 9. $invertScaleQuality = 9 - $scaleQuality; if (imagetypes() & IMG_PNG) { imagepng($this->imageResized, $savePath, $invertScaleQuality); } break; default: return false; break; } // Remove the resource for the resized image. imagedestroy($this->imageResized); return true; }
[ "public", "function", "save", "(", "$", "savePath", ",", "$", "imageQuality", "=", "95", ")", "{", "// If the image wasn't resized, fetch original image.", "if", "(", "!", "$", "this", "->", "imageResized", ")", "{", "$", "this", "->", "imageResized", "=", "$", "this", "->", "image", ";", "}", "// Get extension of the output file.", "$", "extension", "=", "Inflector", "::", "lower", "(", "File", "::", "extension", "(", "$", "savePath", ")", ")", ";", "// Create and save an image based on it's extension.", "switch", "(", "$", "extension", ")", "{", "case", "'jpg'", ":", "case", "'jpeg'", ":", "if", "(", "imagetypes", "(", ")", "&", "IMG_JPG", ")", "{", "imagejpeg", "(", "$", "this", "->", "imageResized", ",", "$", "savePath", ",", "$", "imageQuality", ")", ";", "}", "break", ";", "case", "'gif'", ":", "if", "(", "imagetypes", "(", ")", "&", "IMG_GIF", ")", "{", "imagegif", "(", "$", "this", "->", "imageResized", ",", "$", "savePath", ")", ";", "}", "break", ";", "case", "'png'", ":", "// Scale quality from 0-100 to 0-9.", "$", "scaleQuality", "=", "round", "(", "(", "$", "imageQuality", "/", "100", ")", "*", "9", ")", ";", "// Invert quality setting as 0 is best, not 9.", "$", "invertScaleQuality", "=", "9", "-", "$", "scaleQuality", ";", "if", "(", "imagetypes", "(", ")", "&", "IMG_PNG", ")", "{", "imagepng", "(", "$", "this", "->", "imageResized", ",", "$", "savePath", ",", "$", "invertScaleQuality", ")", ";", "}", "break", ";", "default", ":", "return", "false", ";", "break", ";", "}", "// Remove the resource for the resized image.", "imagedestroy", "(", "$", "this", "->", "imageResized", ")", ";", "return", "true", ";", "}" ]
Save the image based on its file type. @param string $savePath Where to save the image @param int $imageQuality The output quality of the image @return boolean
[ "Save", "the", "image", "based", "on", "its", "file", "type", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L130-L177
train
schpill/thin
src/Html/Sizer.php
Sizer.get_dimensions
private function get_dimensions($newWidth, $newHeight, $option) { switch ($option) { case 'exact': $optimalWidth = $newWidth; $optimalHeight = $newHeight; break; case 'portrait': $optimalWidth = $this->getSizeByFixedHeight($newHeight); $optimalHeight = $newHeight; break; case 'landscape': $optimalWidth = $newWidth; $optimalHeight = $this->getSizeByFixedWidth($newWidth); break; case 'auto': $option_array = $this->getSizeByAuto($newWidth, $newHeight); $optimalWidth = $option_array['optimalWidth']; $optimalHeight = $option_array['optimalHeight']; break; case 'fit': $option_array = $this->getSizeByFit($newWidth, $newHeight); $optimalWidth = $option_array['optimalWidth']; $optimalHeight = $option_array['optimalHeight']; break; case 'crop': $option_array = $this->getOptimalCrop($newWidth, $newHeight); $optimalWidth = $option_array['optimalWidth']; $optimalHeight = $option_array['optimalHeight']; break; } return array( 'optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight ); }
php
private function get_dimensions($newWidth, $newHeight, $option) { switch ($option) { case 'exact': $optimalWidth = $newWidth; $optimalHeight = $newHeight; break; case 'portrait': $optimalWidth = $this->getSizeByFixedHeight($newHeight); $optimalHeight = $newHeight; break; case 'landscape': $optimalWidth = $newWidth; $optimalHeight = $this->getSizeByFixedWidth($newWidth); break; case 'auto': $option_array = $this->getSizeByAuto($newWidth, $newHeight); $optimalWidth = $option_array['optimalWidth']; $optimalHeight = $option_array['optimalHeight']; break; case 'fit': $option_array = $this->getSizeByFit($newWidth, $newHeight); $optimalWidth = $option_array['optimalWidth']; $optimalHeight = $option_array['optimalHeight']; break; case 'crop': $option_array = $this->getOptimalCrop($newWidth, $newHeight); $optimalWidth = $option_array['optimalWidth']; $optimalHeight = $option_array['optimalHeight']; break; } return array( 'optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight ); }
[ "private", "function", "get_dimensions", "(", "$", "newWidth", ",", "$", "newHeight", ",", "$", "option", ")", "{", "switch", "(", "$", "option", ")", "{", "case", "'exact'", ":", "$", "optimalWidth", "=", "$", "newWidth", ";", "$", "optimalHeight", "=", "$", "newHeight", ";", "break", ";", "case", "'portrait'", ":", "$", "optimalWidth", "=", "$", "this", "->", "getSizeByFixedHeight", "(", "$", "newHeight", ")", ";", "$", "optimalHeight", "=", "$", "newHeight", ";", "break", ";", "case", "'landscape'", ":", "$", "optimalWidth", "=", "$", "newWidth", ";", "$", "optimalHeight", "=", "$", "this", "->", "getSizeByFixedWidth", "(", "$", "newWidth", ")", ";", "break", ";", "case", "'auto'", ":", "$", "option_array", "=", "$", "this", "->", "getSizeByAuto", "(", "$", "newWidth", ",", "$", "newHeight", ")", ";", "$", "optimalWidth", "=", "$", "option_array", "[", "'optimalWidth'", "]", ";", "$", "optimalHeight", "=", "$", "option_array", "[", "'optimalHeight'", "]", ";", "break", ";", "case", "'fit'", ":", "$", "option_array", "=", "$", "this", "->", "getSizeByFit", "(", "$", "newWidth", ",", "$", "newHeight", ")", ";", "$", "optimalWidth", "=", "$", "option_array", "[", "'optimalWidth'", "]", ";", "$", "optimalHeight", "=", "$", "option_array", "[", "'optimalHeight'", "]", ";", "break", ";", "case", "'crop'", ":", "$", "option_array", "=", "$", "this", "->", "getOptimalCrop", "(", "$", "newWidth", ",", "$", "newHeight", ")", ";", "$", "optimalWidth", "=", "$", "option_array", "[", "'optimalWidth'", "]", ";", "$", "optimalHeight", "=", "$", "option_array", "[", "'optimalHeight'", "]", ";", "break", ";", "}", "return", "array", "(", "'optimalWidth'", "=>", "$", "optimalWidth", ",", "'optimalHeight'", "=>", "$", "optimalHeight", ")", ";", "}" ]
Return the image dimensions based on the option that was chosen. @param int $newWidth The width of the image @param int $newHeight The height of the image @param string $option Either exact, portrait, landscape, auto or crop. @return array
[ "Return", "the", "image", "dimensions", "based", "on", "the", "option", "that", "was", "chosen", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L222-L258
train