repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
maniaplanet/dedicated-server-api
libraries/Maniaplanet/DedicatedServer/Connection.php
Connection.forceSpectatorTarget
function forceSpectatorTarget($spectator, $target, $camera, $multicall = false) { $spectatorLogin = $this->getLogin($spectator, true); if ($spectatorLogin === false) { throw new InvalidArgumentException('player = ' . print_r($spectator, true)); } $targetLogin = $this->getLogin($target, true); if ($targetLogin === false) { throw new InvalidArgumentException('target = ' . print_r($target, true)); } if (!is_int($camera) || $camera < -1 || $camera > 2) { throw new InvalidArgumentException('camera = ' . print_r($camera, true)); } return $this->execute(ucfirst(__FUNCTION__), array($spectatorLogin, $targetLogin, $camera), $multicall); }
php
function forceSpectatorTarget($spectator, $target, $camera, $multicall = false) { $spectatorLogin = $this->getLogin($spectator, true); if ($spectatorLogin === false) { throw new InvalidArgumentException('player = ' . print_r($spectator, true)); } $targetLogin = $this->getLogin($target, true); if ($targetLogin === false) { throw new InvalidArgumentException('target = ' . print_r($target, true)); } if (!is_int($camera) || $camera < -1 || $camera > 2) { throw new InvalidArgumentException('camera = ' . print_r($camera, true)); } return $this->execute(ucfirst(__FUNCTION__), array($spectatorLogin, $targetLogin, $camera), $multicall); }
[ "function", "forceSpectatorTarget", "(", "$", "spectator", ",", "$", "target", ",", "$", "camera", ",", "$", "multicall", "=", "false", ")", "{", "$", "spectatorLogin", "=", "$", "this", "->", "getLogin", "(", "$", "spectator", ",", "true", ")", ";", "...
Force spectators to look at a specific player. Only available to Admin. @param mixed $spectator Login or player object; empty for all @param mixed $target Login or player object; empty for automatic @param int $camera -1: leave unchanged, 0: replay, 1: follow, 2: free @param bool $multicall @return bool @throws InvalidArgumentException
[ "Force", "spectators", "to", "look", "at", "a", "specific", "player", ".", "Only", "available", "to", "Admin", "." ]
train
https://github.com/maniaplanet/dedicated-server-api/blob/c42664b21739fd6335cf2ecfe1907a0eca07c1da/libraries/Maniaplanet/DedicatedServer/Connection.php#L4392-L4407
maniaplanet/dedicated-server-api
libraries/Maniaplanet/DedicatedServer/Connection.php
Connection.getNetworkStats
function getNetworkStats($multicall = false) { if ($multicall) { return $this->execute(ucfirst(__FUNCTION__), array(), $this->structHandler('NetworkStats')); } return Structures\NetworkStats::fromArray($this->execute(ucfirst(__FUNCTION__))); }
php
function getNetworkStats($multicall = false) { if ($multicall) { return $this->execute(ucfirst(__FUNCTION__), array(), $this->structHandler('NetworkStats')); } return Structures\NetworkStats::fromArray($this->execute(ucfirst(__FUNCTION__))); }
[ "function", "getNetworkStats", "(", "$", "multicall", "=", "false", ")", "{", "if", "(", "$", "multicall", ")", "{", "return", "$", "this", "->", "execute", "(", "ucfirst", "(", "__FUNCTION__", ")", ",", "array", "(", ")", ",", "$", "this", "->", "st...
Returns a struct containing the networks stats of the server. Only available to SuperAdmin. @param bool $multicall @return Structures\NetworkStats
[ "Returns", "a", "struct", "containing", "the", "networks", "stats", "of", "the", "server", ".", "Only", "available", "to", "SuperAdmin", "." ]
train
https://github.com/maniaplanet/dedicated-server-api/blob/c42664b21739fd6335cf2ecfe1907a0eca07c1da/libraries/Maniaplanet/DedicatedServer/Connection.php#L4496-L4502
maniaplanet/dedicated-server-api
libraries/Maniaplanet/DedicatedServer/Connection.php
Connection.joinServerLan
function joinServerLan($host, $password = '', $multicall = false) { if (!is_string($host)) { throw new InvalidArgumentException('host = ' . print_r($host, true)); } if (!is_string($password)) { throw new InvalidArgumentException('password = ' . print_r($password, true)); } return $this->execute(ucfirst(__FUNCTION__), array(array('Server' => $host, 'ServerPassword' => $password)), $multicall); }
php
function joinServerLan($host, $password = '', $multicall = false) { if (!is_string($host)) { throw new InvalidArgumentException('host = ' . print_r($host, true)); } if (!is_string($password)) { throw new InvalidArgumentException('password = ' . print_r($password, true)); } return $this->execute(ucfirst(__FUNCTION__), array(array('Server' => $host, 'ServerPassword' => $password)), $multicall); }
[ "function", "joinServerLan", "(", "$", "host", ",", "$", "password", "=", "''", ",", "$", "multicall", "=", "false", ")", "{", "if", "(", "!", "is_string", "(", "$", "host", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'host = '", "...
Join the server on lan. Only available on client. Only available to Admin. @param string $host IPv4 with optionally a port (eg. '192.168.1.42:2350') @param string $password @param bool $multicall @return bool @throws InvalidArgumentException
[ "Join", "the", "server", "on", "lan", ".", "Only", "available", "on", "client", ".", "Only", "available", "to", "Admin", "." ]
train
https://github.com/maniaplanet/dedicated-server-api/blob/c42664b21739fd6335cf2ecfe1907a0eca07c1da/libraries/Maniaplanet/DedicatedServer/Connection.php#L4536-L4546
willemo/flightstats
src/Api/Schedules.php
Schedules.getFlightByArrivalDate
public function getFlightByArrivalDate( $carrier, $flight, DateTime $date, array $queryParams = [] ) { $endpoint = sprintf( 'flight/%s/%s/arriving/%s', $carrier, $flight, $date->format('Y/n/j') ); $response = $this->sendRequest($endpoint, $queryParams); return $this->parseResponse($response); }
php
public function getFlightByArrivalDate( $carrier, $flight, DateTime $date, array $queryParams = [] ) { $endpoint = sprintf( 'flight/%s/%s/arriving/%s', $carrier, $flight, $date->format('Y/n/j') ); $response = $this->sendRequest($endpoint, $queryParams); return $this->parseResponse($response); }
[ "public", "function", "getFlightByArrivalDate", "(", "$", "carrier", ",", "$", "flight", ",", "DateTime", "$", "date", ",", "array", "$", "queryParams", "=", "[", "]", ")", "{", "$", "endpoint", "=", "sprintf", "(", "'flight/%s/%s/arriving/%s'", ",", "$", ...
Get information about a scheduled flight arriving on the given date. @param string $carrier The carrier (airline) code @param integer $flight The flight number @param DateTime $date The arrival date @param array $queryParams Query parameters to add to the request @return array The response from the API
[ "Get", "information", "about", "a", "scheduled", "flight", "arriving", "on", "the", "given", "date", "." ]
train
https://github.com/willemo/flightstats/blob/32ee99110a86a3d418bc15ab7863b89e0ad3a65d/src/Api/Schedules.php#L38-L54
willemo/flightstats
src/Api/Schedules.php
Schedules.parseResponse
protected function parseResponse(array $response) { if (empty($response['scheduledFlights'])) { return []; } $airlines = $this->parseAirlines($response['appendix']['airlines']); $airports = $this->parseAirports($response['appendix']['airports']); $flights = []; foreach ($response['scheduledFlights'] as $flight) { // Set the carrier $carrier = $airlines[$flight['carrierFsCode']]; $flight['carrier'] = $carrier; // Set the departure airport $departureAirport = $airports[$flight['departureAirportFsCode']]; $flight['departureAirport'] = $departureAirport; // Set the arrival airport $arrivalAirport = $airports[$flight['arrivalAirportFsCode']]; $flight['arrivalAirport'] = $arrivalAirport; // Set the UTC departure time $flight['departureDate'] = [ 'dateLocal' => $flight['departureTime'], 'dateUtc' => $this->dateToUtc( $flight['departureTime'], $departureAirport['timeZoneRegionName'] ), ]; // Set the UTC arrival time $flight['arrivalDate'] = [ 'dateLocal' => $flight['arrivalTime'], 'dateUtc' => $this->dateToUtc( $flight['arrivalTime'], $arrivalAirport['timeZoneRegionName'] ), ]; $flights[] = $flight; } return $flights; }
php
protected function parseResponse(array $response) { if (empty($response['scheduledFlights'])) { return []; } $airlines = $this->parseAirlines($response['appendix']['airlines']); $airports = $this->parseAirports($response['appendix']['airports']); $flights = []; foreach ($response['scheduledFlights'] as $flight) { // Set the carrier $carrier = $airlines[$flight['carrierFsCode']]; $flight['carrier'] = $carrier; // Set the departure airport $departureAirport = $airports[$flight['departureAirportFsCode']]; $flight['departureAirport'] = $departureAirport; // Set the arrival airport $arrivalAirport = $airports[$flight['arrivalAirportFsCode']]; $flight['arrivalAirport'] = $arrivalAirport; // Set the UTC departure time $flight['departureDate'] = [ 'dateLocal' => $flight['departureTime'], 'dateUtc' => $this->dateToUtc( $flight['departureTime'], $departureAirport['timeZoneRegionName'] ), ]; // Set the UTC arrival time $flight['arrivalDate'] = [ 'dateLocal' => $flight['arrivalTime'], 'dateUtc' => $this->dateToUtc( $flight['arrivalTime'], $arrivalAirport['timeZoneRegionName'] ), ]; $flights[] = $flight; } return $flights; }
[ "protected", "function", "parseResponse", "(", "array", "$", "response", ")", "{", "if", "(", "empty", "(", "$", "response", "[", "'scheduledFlights'", "]", ")", ")", "{", "return", "[", "]", ";", "}", "$", "airlines", "=", "$", "this", "->", "parseAir...
Parse the response from the API to a more uniform and thorough format. @param array $response The response from the API @return array The parsed response
[ "Parse", "the", "response", "from", "the", "API", "to", "a", "more", "uniform", "and", "thorough", "format", "." ]
train
https://github.com/willemo/flightstats/blob/32ee99110a86a3d418bc15ab7863b89e0ad3a65d/src/Api/Schedules.php#L89-L139
quai10/quai10-template
lib/Config.php
Config.cleanup
public static function cleanup() { remove_action('wp_head', 'feed_links_extra', 3); // remove extra RSS links (as category) remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'wlwmanifest_link'); remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0); remove_filter('dbem_notes', 'wpautop'); global $wp_widget_factory; remove_action('wp_head', [$wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style']); }
php
public static function cleanup() { remove_action('wp_head', 'feed_links_extra', 3); // remove extra RSS links (as category) remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'wlwmanifest_link'); remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0); remove_filter('dbem_notes', 'wpautop'); global $wp_widget_factory; remove_action('wp_head', [$wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style']); }
[ "public", "static", "function", "cleanup", "(", ")", "{", "remove_action", "(", "'wp_head'", ",", "'feed_links_extra'", ",", "3", ")", ";", "// remove extra RSS links (as category)", "remove_action", "(", "'wp_head'", ",", "'rsd_link'", ")", ";", "remove_action", "(...
Cleaning up wp_head(). @return void @link http://mwanoz.fr/nettoyer-le-contenu-de-wp_head-sur-wordpress/
[ "Cleaning", "up", "wp_head", "()", "." ]
train
https://github.com/quai10/quai10-template/blob/3e98b7de031f5507831946200081b6cb35b468b7/lib/Config.php#L20-L31
quai10/quai10-template
lib/Config.php
Config.setupTheme
public static function setupTheme() { /* * Enable plugins to manage the document title * @link http://codex.wordpress.org/Function_Reference/add_theme_support#Title_Tag * */ add_theme_support('title-tag'); /* * Register wp_nav_menus() menus * @link http://codex.wordpress.org/Function_Reference/register_nav_menus * */ register_nav_menus([ 'primary_navigation' => __('Navigation principale', 'quai10'), 'footer1' => __('Pied de page – colonne 1', 'quai10'), 'footer2' => __('Pied de page – colonne 2', 'quai10'), 'footer3' => __('Pied de page – colonne 3', 'quai10'), ]); /* * Add post thumnails * @link http://codex.wordpress.org/Post_Thumbnails * */ add_theme_support('post-thumbnails'); set_post_thumbnail_size(250, 250); /* * Add post formats * @link http://codex.wordpress.org/Post_Formats * */ add_theme_support('post-formats', ['image']); /* * Add HTML5 Markup for captions * @link http://codex.wordpress.org/Function_Reference/add_theme_support#HTML5 * */ add_theme_support('html5', ['caption', 'comment-form', 'comment-list']); }
php
public static function setupTheme() { /* * Enable plugins to manage the document title * @link http://codex.wordpress.org/Function_Reference/add_theme_support#Title_Tag * */ add_theme_support('title-tag'); /* * Register wp_nav_menus() menus * @link http://codex.wordpress.org/Function_Reference/register_nav_menus * */ register_nav_menus([ 'primary_navigation' => __('Navigation principale', 'quai10'), 'footer1' => __('Pied de page – colonne 1', 'quai10'), 'footer2' => __('Pied de page – colonne 2', 'quai10'), 'footer3' => __('Pied de page – colonne 3', 'quai10'), ]); /* * Add post thumnails * @link http://codex.wordpress.org/Post_Thumbnails * */ add_theme_support('post-thumbnails'); set_post_thumbnail_size(250, 250); /* * Add post formats * @link http://codex.wordpress.org/Post_Formats * */ add_theme_support('post-formats', ['image']); /* * Add HTML5 Markup for captions * @link http://codex.wordpress.org/Function_Reference/add_theme_support#HTML5 * */ add_theme_support('html5', ['caption', 'comment-form', 'comment-list']); }
[ "public", "static", "function", "setupTheme", "(", ")", "{", "/*\n * Enable plugins to manage the document title\n * @link http://codex.wordpress.org/Function_Reference/add_theme_support#Title_Tag\n * */", "add_theme_support", "(", "'title-tag'", ")", ";", "/*\n ...
Theme Setup. @return void
[ "Theme", "Setup", "." ]
train
https://github.com/quai10/quai10-template/blob/3e98b7de031f5507831946200081b6cb35b468b7/lib/Config.php#L38-L75
quai10/quai10-template
lib/Config.php
Config.addBodyClass
public static function addBodyClass(array $classes) { if (is_single() || is_page() && !is_front_page()) { if (!in_array(basename(get_permalink()), $classes)) { $classes[] = basename(get_permalink()); } } return $classes; }
php
public static function addBodyClass(array $classes) { if (is_single() || is_page() && !is_front_page()) { if (!in_array(basename(get_permalink()), $classes)) { $classes[] = basename(get_permalink()); } } return $classes; }
[ "public", "static", "function", "addBodyClass", "(", "array", "$", "classes", ")", "{", "if", "(", "is_single", "(", ")", "||", "is_page", "(", ")", "&&", "!", "is_front_page", "(", ")", ")", "{", "if", "(", "!", "in_array", "(", "basename", "(", "ge...
Add a body class with page slug if existing. @param array $classes Classes
[ "Add", "a", "body", "class", "with", "page", "slug", "if", "existing", "." ]
train
https://github.com/quai10/quai10-template/blob/3e98b7de031f5507831946200081b6cb35b468b7/lib/Config.php#L82-L91
dave-redfern/laravel-doctrine-tenancy
src/Routing/RouteUrlGenerator.php
RouteUrlGenerator.replaceRouteParameters
protected function replaceRouteParameters($path, array &$parameters) { $this->ensureTenancyInParameters($path, $parameters); $path = $this->replaceNamedParameters($path, $parameters); $path = preg_replace_callback('/\{.*?\}/', function ($match) use (&$parameters) { return (empty($parameters) && ! Str::endsWith($match[0], '?}')) ? $match[0] : array_shift($parameters); }, $path); return trim(preg_replace('/\{.*?\?\}/', '', $path), '/'); }
php
protected function replaceRouteParameters($path, array &$parameters) { $this->ensureTenancyInParameters($path, $parameters); $path = $this->replaceNamedParameters($path, $parameters); $path = preg_replace_callback('/\{.*?\}/', function ($match) use (&$parameters) { return (empty($parameters) && ! Str::endsWith($match[0], '?}')) ? $match[0] : array_shift($parameters); }, $path); return trim(preg_replace('/\{.*?\?\}/', '', $path), '/'); }
[ "protected", "function", "replaceRouteParameters", "(", "$", "path", ",", "array", "&", "$", "parameters", ")", "{", "$", "this", "->", "ensureTenancyInParameters", "(", "$", "path", ",", "$", "parameters", ")", ";", "$", "path", "=", "$", "this", "->", ...
Replace all of the wildcard parameters for a route path. @param string $path @param array $parameters @return string
[ "Replace", "all", "of", "the", "wildcard", "parameters", "for", "a", "route", "path", "." ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Routing/RouteUrlGenerator.php#L63-L76
dave-redfern/laravel-doctrine-tenancy
src/Routing/RouteUrlGenerator.php
RouteUrlGenerator.replaceNamedParameters
protected function replaceNamedParameters($path, &$parameters) { $this->ensureTenancyInParameters($path, $parameters); return preg_replace_callback('/\{(.*?)\??\}/', function ($m) use (&$parameters) { if (isset($parameters[$m[1]])) { return Arr::pull($parameters, $m[1]); } elseif (isset($this->defaultParameters[$m[1]])) { return $this->defaultParameters[$m[1]]; } else { return $m[0]; } }, $path); }
php
protected function replaceNamedParameters($path, &$parameters) { $this->ensureTenancyInParameters($path, $parameters); return preg_replace_callback('/\{(.*?)\??\}/', function ($m) use (&$parameters) { if (isset($parameters[$m[1]])) { return Arr::pull($parameters, $m[1]); } elseif (isset($this->defaultParameters[$m[1]])) { return $this->defaultParameters[$m[1]]; } else { return $m[0]; } }, $path); }
[ "protected", "function", "replaceNamedParameters", "(", "$", "path", ",", "&", "$", "parameters", ")", "{", "$", "this", "->", "ensureTenancyInParameters", "(", "$", "path", ",", "$", "parameters", ")", ";", "return", "preg_replace_callback", "(", "'/\\{(.*?)\\?...
Replace all of the named parameters in the path. @param string $path @param array $parameters @return string
[ "Replace", "all", "of", "the", "named", "parameters", "in", "the", "path", "." ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Routing/RouteUrlGenerator.php#L85-L98
Kaishiyoku/laravel-menu
src/Kaishiyoku/Menu/Data/Link.php
Link.render
public function render($customAttributes = null) { if ($customAttributes != null && count($customAttributes) > 0) { $attributes = array_merge($this->attributes, $customAttributes); } else { $attributes = $this->attributes; if (count(MenuHelper::getConfig()->getAnchorElementClasses()) > 0) { if (!array_key_exists('class', $attributes)) { $attributes['class'] = ''; } foreach (MenuHelper::getConfig()->getAnchorElementClasses() as $listElementClass) { $attributes['class'] .= ' ' . $listElementClass; } } } return Html::link($this->url, $this->title, $attributes); }
php
public function render($customAttributes = null) { if ($customAttributes != null && count($customAttributes) > 0) { $attributes = array_merge($this->attributes, $customAttributes); } else { $attributes = $this->attributes; if (count(MenuHelper::getConfig()->getAnchorElementClasses()) > 0) { if (!array_key_exists('class', $attributes)) { $attributes['class'] = ''; } foreach (MenuHelper::getConfig()->getAnchorElementClasses() as $listElementClass) { $attributes['class'] .= ' ' . $listElementClass; } } } return Html::link($this->url, $this->title, $attributes); }
[ "public", "function", "render", "(", "$", "customAttributes", "=", "null", ")", "{", "if", "(", "$", "customAttributes", "!=", "null", "&&", "count", "(", "$", "customAttributes", ")", ">", "0", ")", "{", "$", "attributes", "=", "array_merge", "(", "$", ...
Get the evaluated contents of the object. @param null|array $customAttributes @return string
[ "Get", "the", "evaluated", "contents", "of", "the", "object", "." ]
train
https://github.com/Kaishiyoku/laravel-menu/blob/0a1aa772f19002d354f0c338e603d98c49d10a7a/src/Kaishiyoku/Menu/Data/Link.php#L51-L70
krafthaus/bauhaus
src/commands/ScaffoldCommand.php
ScaffoldCommand.fire
public function fire() { $model = $this->option('model'); $plural = Str::plural($model); // Create the model $stub = file_get_contents(__DIR__ . '/stubs/model.txt'); $stub = str_replace('$NAME$', Str::studly($model), $stub); file_put_contents(app_path('models/' . Str::studly($model) . '.php'), $stub); // Create the admin controller $directory = Config::get('bauhaus::admin.directory'); $stub = file_get_contents(__DIR__ . '/stubs/admin.txt'); $stub = str_replace('$NAME$', Str::studly($model), $stub); file_put_contents(app_path($directory . '/' . Str::studly($model) . 'Admin.php'), $stub); // Create the migration $this->call('migrate:make', [ 'name' => sprintf('create_%s_table', $plural), '--table' => $plural, '--create' => true ]); }
php
public function fire() { $model = $this->option('model'); $plural = Str::plural($model); // Create the model $stub = file_get_contents(__DIR__ . '/stubs/model.txt'); $stub = str_replace('$NAME$', Str::studly($model), $stub); file_put_contents(app_path('models/' . Str::studly($model) . '.php'), $stub); // Create the admin controller $directory = Config::get('bauhaus::admin.directory'); $stub = file_get_contents(__DIR__ . '/stubs/admin.txt'); $stub = str_replace('$NAME$', Str::studly($model), $stub); file_put_contents(app_path($directory . '/' . Str::studly($model) . 'Admin.php'), $stub); // Create the migration $this->call('migrate:make', [ 'name' => sprintf('create_%s_table', $plural), '--table' => $plural, '--create' => true ]); }
[ "public", "function", "fire", "(", ")", "{", "$", "model", "=", "$", "this", "->", "option", "(", "'model'", ")", ";", "$", "plural", "=", "Str", "::", "plural", "(", "$", "model", ")", ";", "// Create the model", "$", "stub", "=", "file_get_contents",...
Execute the console command. @access public @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/commands/ScaffoldCommand.php#L45-L68
Syonix/log-viewer-lib
lib/LogManager.php
LogManager.getLogCollection
public function getLogCollection($slug) { foreach ($this->logCollections as $logCollection) { if ($logCollection->getSlug() == $slug) { return $logCollection; } } }
php
public function getLogCollection($slug) { foreach ($this->logCollections as $logCollection) { if ($logCollection->getSlug() == $slug) { return $logCollection; } } }
[ "public", "function", "getLogCollection", "(", "$", "slug", ")", "{", "foreach", "(", "$", "this", "->", "logCollections", "as", "$", "logCollection", ")", "{", "if", "(", "$", "logCollection", "->", "getSlug", "(", ")", "==", "$", "slug", ")", "{", "r...
@param $slug @return LogCollection|null
[ "@param", "$slug" ]
train
https://github.com/Syonix/log-viewer-lib/blob/5212208bf2f0174eb5d0408d2d3028db4d478a74/lib/LogManager.php#L51-L58
txj123/zilf
src/Zilf/System/Zilf.php
Zilf.createObject
public static function createObject($type, array $params = []) { if (is_string($type)) { static::$container->set($type, $type, $params); return static::$container->getShare($type, $params); } elseif (is_array($type) && isset($type['class'])) { $class = $type['class']; unset($type['class']); static::$container->set($class, $class, ['config'=>$type]); return static::$container->getShare($class); } elseif (is_array($type)) { throw new InvalidConfigException('Object configuration must be an array containing a "class" element.'); } else { throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type)); } }
php
public static function createObject($type, array $params = []) { if (is_string($type)) { static::$container->set($type, $type, $params); return static::$container->getShare($type, $params); } elseif (is_array($type) && isset($type['class'])) { $class = $type['class']; unset($type['class']); static::$container->set($class, $class, ['config'=>$type]); return static::$container->getShare($class); } elseif (is_array($type)) { throw new InvalidConfigException('Object configuration must be an array containing a "class" element.'); } else { throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type)); } }
[ "public", "static", "function", "createObject", "(", "$", "type", ",", "array", "$", "params", "=", "[", "]", ")", "{", "if", "(", "is_string", "(", "$", "type", ")", ")", "{", "static", "::", "$", "container", "->", "set", "(", "$", "type", ",", ...
Creates a new object using the given configuration. You may view this method as an enhanced version of the `new` operator. The method supports creating an object based on a class name, a configuration array or an anonymous function. Below are some usage examples: ```php // create an object using a class name $object = Zilf::createObject('Zilf\db\Connection'); // create an object using a configuration array $object = Zilf::createObject([ 'class' => 'Zilf\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]); // create an object with two constructor parameters $object = \Zilf::createObject('MyClass', [$param1, $param2]); ``` Using [[\Zilf\di\Container|dependency injection container]], this method can also identify dependent objects, instantiate them and inject them into the newly created object. @param string|array|callable $type the object type. This can be specified in one of the following forms: - a string: representing the class name of the object to be created - a configuration array: the array must contain a `class` element which is treated as the object class, and the rest of the name-value pairs will be used to initialize the corresponding object properties - a PHP callable: either an anonymous function or an array representing a class method (`[$class or $object, $method]`). The callable should return a new instance of the object being created. @param array $params the constructor parameters @return object the created object @throws InvalidConfigException if the configuration is invalid.
[ "Creates", "a", "new", "object", "using", "the", "given", "configuration", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/System/Zilf.php#L89-L108
txj123/zilf
src/Zilf/Validation/MessageBag.php
MessageBag.isUnique
protected function isUnique($key, $message) { $messages = (array) $this->messages; return !isset($messages[$key]) || !in_array($message, $messages[$key], true); }
php
protected function isUnique($key, $message) { $messages = (array) $this->messages; return !isset($messages[$key]) || !in_array($message, $messages[$key], true); }
[ "protected", "function", "isUnique", "(", "$", "key", ",", "$", "message", ")", "{", "$", "messages", "=", "(", "array", ")", "$", "this", "->", "messages", ";", "return", "!", "isset", "(", "$", "messages", "[", "$", "key", "]", ")", "||", "!", ...
Determine if a key and message combination already exists. @param string $key @param string $message @return bool
[ "Determine", "if", "a", "key", "and", "message", "combination", "already", "exists", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Validation/MessageBag.php#L86-L91
txj123/zilf
src/Zilf/Validation/MessageBag.php
MessageBag.transform
protected function transform($messages, $format, $messageKey) { $messages = (array) $messages; // We will simply spin through the given messages and transform each one // replacing the :message place holder with the real message allowing // the messages to be easily formatted to each developer's desires. foreach ($messages as $key => &$message) { $replace = [':message', ':key']; $message = str_replace($replace, [$message, $messageKey], $format); } return $messages; }
php
protected function transform($messages, $format, $messageKey) { $messages = (array) $messages; // We will simply spin through the given messages and transform each one // replacing the :message place holder with the real message allowing // the messages to be easily formatted to each developer's desires. foreach ($messages as $key => &$message) { $replace = [':message', ':key']; $message = str_replace($replace, [$message, $messageKey], $format); } return $messages; }
[ "protected", "function", "transform", "(", "$", "messages", ",", "$", "format", ",", "$", "messageKey", ")", "{", "$", "messages", "=", "(", "array", ")", "$", "messages", ";", "// We will simply spin through the given messages and transform each one", "// replacing t...
Format an array of messages. @param array $messages @param string $format @param string $messageKey @return array
[ "Format", "an", "array", "of", "messages", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Validation/MessageBag.php#L171-L185
oxygen-cms/core
src/Form/Type/SelectType.php
SelectType.transformInput
public function transformInput(FieldMetadata $metadata, $value) { $isInt = true; foreach(array_keys($metadata->options) as $key => $notUsed) { if(!is_integer($key)) { $isInt = false; } } if($isInt) { return (int)$value; } else { return $value; } }
php
public function transformInput(FieldMetadata $metadata, $value) { $isInt = true; foreach(array_keys($metadata->options) as $key => $notUsed) { if(!is_integer($key)) { $isInt = false; } } if($isInt) { return (int)$value; } else { return $value; } }
[ "public", "function", "transformInput", "(", "FieldMetadata", "$", "metadata", ",", "$", "value", ")", "{", "$", "isInt", "=", "true", ";", "foreach", "(", "array_keys", "(", "$", "metadata", "->", "options", ")", "as", "$", "key", "=>", "$", "notUsed", ...
Takes the given input value and transforms it into a compatible value for storage. @param FieldMetadata $metadata @param string $value @return mixed
[ "Takes", "the", "given", "input", "value", "and", "transforms", "it", "into", "a", "compatible", "value", "for", "storage", "." ]
train
https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Form/Type/SelectType.php#L16-L29
krafthaus/bauhaus
src/KraftHaus/Bauhaus/Field/BaseField.php
BaseField.getLabel
public function getLabel() { if ($this->label === null) { return Str::title($this->getName()); } return $this->label; }
php
public function getLabel() { if ($this->label === null) { return Str::title($this->getName()); } return $this->label; }
[ "public", "function", "getLabel", "(", ")", "{", "if", "(", "$", "this", "->", "label", "===", "null", ")", "{", "return", "Str", "::", "title", "(", "$", "this", "->", "getName", "(", ")", ")", ";", "}", "return", "$", "this", "->", "label", ";"...
Get the field label. @access public @return null|string
[ "Get", "the", "field", "label", "." ]
train
https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Field/BaseField.php#L302-L309
krafthaus/bauhaus
src/KraftHaus/Bauhaus/Field/BaseField.php
BaseField.multiple
public function multiple($limit = null) { $this->attribute('infinite', true) ->isMultiple = true; if ($limit !== null) { $this->setMultipleLimit($limit); } return $this; }
php
public function multiple($limit = null) { $this->attribute('infinite', true) ->isMultiple = true; if ($limit !== null) { $this->setMultipleLimit($limit); } return $this; }
[ "public", "function", "multiple", "(", "$", "limit", "=", "null", ")", "{", "$", "this", "->", "attribute", "(", "'infinite'", ",", "true", ")", "->", "isMultiple", "=", "true", ";", "if", "(", "$", "limit", "!==", "null", ")", "{", "$", "this", "-...
Set this field as a 'multiple' field. @access public @return $this
[ "Set", "this", "field", "as", "a", "multiple", "field", "." ]
train
https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Field/BaseField.php#L419-L429
txj123/zilf
src/Zilf/Queue/Console/WorkCommand.php
WorkCommand.handle
public function handle() { if ($this->downForMaintenance() && $this->option('once')) { return $this->worker->sleep($this->option('sleep')); } // We'll listen to the processed and failed events so we can write information // to the console as jobs are processed, which will let the developer watch // which jobs are coming through a queue and be informed on its progress. // $this->listenForEvents(); $connection = $this->argument('connection') ?: config('queue.default'); // We need to get the right queue for the connection which is set in the queue // configuration file for the application. We will pull it based on the set // connection being run for the queue operation currently being executed. $queue = $this->getQueue($connection); $this->runWorker( $connection, $queue ); }
php
public function handle() { if ($this->downForMaintenance() && $this->option('once')) { return $this->worker->sleep($this->option('sleep')); } // We'll listen to the processed and failed events so we can write information // to the console as jobs are processed, which will let the developer watch // which jobs are coming through a queue and be informed on its progress. // $this->listenForEvents(); $connection = $this->argument('connection') ?: config('queue.default'); // We need to get the right queue for the connection which is set in the queue // configuration file for the application. We will pull it based on the set // connection being run for the queue operation currently being executed. $queue = $this->getQueue($connection); $this->runWorker( $connection, $queue ); }
[ "public", "function", "handle", "(", ")", "{", "if", "(", "$", "this", "->", "downForMaintenance", "(", ")", "&&", "$", "this", "->", "option", "(", "'once'", ")", ")", "{", "return", "$", "this", "->", "worker", "->", "sleep", "(", "$", "this", "-...
Execute the console command. @return void
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Console/WorkCommand.php#L67-L89
txj123/zilf
src/Zilf/Queue/Console/WorkCommand.php
WorkCommand.runWorker
protected function runWorker($connection, $queue) { $this->worker->setCache(Zilf::$container->getShare('cache')->driver()); return $this->worker->{$this->option('once') ? 'runNextJob' : 'daemon'}( $this, $connection, $queue, $this->gatherWorkerOptions() ); }
php
protected function runWorker($connection, $queue) { $this->worker->setCache(Zilf::$container->getShare('cache')->driver()); return $this->worker->{$this->option('once') ? 'runNextJob' : 'daemon'}( $this, $connection, $queue, $this->gatherWorkerOptions() ); }
[ "protected", "function", "runWorker", "(", "$", "connection", ",", "$", "queue", ")", "{", "$", "this", "->", "worker", "->", "setCache", "(", "Zilf", "::", "$", "container", "->", "getShare", "(", "'cache'", ")", "->", "driver", "(", ")", ")", ";", ...
Run the worker instance. @param string $connection @param string $queue @return array
[ "Run", "the", "worker", "instance", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Console/WorkCommand.php#L98-L106
txj123/zilf
src/Zilf/Queue/Console/WorkCommand.php
WorkCommand.writeOutput
public function writeOutput($job, $status) { switch ($status) { case 'starting': return $this->writeStatus($job, 'Processing', 'comment'); case 'success': return $this->writeStatus($job, 'Processed', 'info'); case 'failed': return $this->writeStatus($job, 'Failed', 'error'); } }
php
public function writeOutput($job, $status) { switch ($status) { case 'starting': return $this->writeStatus($job, 'Processing', 'comment'); case 'success': return $this->writeStatus($job, 'Processed', 'info'); case 'failed': return $this->writeStatus($job, 'Failed', 'error'); } }
[ "public", "function", "writeOutput", "(", "$", "job", ",", "$", "status", ")", "{", "switch", "(", "$", "status", ")", "{", "case", "'starting'", ":", "return", "$", "this", "->", "writeStatus", "(", "$", "job", ",", "'Processing'", ",", "'comment'", "...
Write the status output for the queue worker. @param string $status @return void
[ "Write", "the", "status", "output", "for", "the", "queue", "worker", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Console/WorkCommand.php#L151-L161
txj123/zilf
src/Zilf/Queue/Console/WorkCommand.php
WorkCommand.logFailedJob
public function logFailedJob(JobFailed $event) { Zilf::$container->getShare('queue.failer')->log( $event->connectionName, $event->job->getQueue(), $event->job->getRawBody(), $event->exception ); }
php
public function logFailedJob(JobFailed $event) { Zilf::$container->getShare('queue.failer')->log( $event->connectionName, $event->job->getQueue(), $event->job->getRawBody(), $event->exception ); }
[ "public", "function", "logFailedJob", "(", "JobFailed", "$", "event", ")", "{", "Zilf", "::", "$", "container", "->", "getShare", "(", "'queue.failer'", ")", "->", "log", "(", "$", "event", "->", "connectionName", ",", "$", "event", "->", "job", "->", "g...
Store a failed job event. @param \Zilf\Queue\Events\JobFailed $event @return void
[ "Store", "a", "failed", "job", "event", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Console/WorkCommand.php#L189-L195
awurth/SlimHelpers
Controller/ControllerTrait.php
ControllerTrait.params
protected function params(Request $request, array $params, $default = null) { $data = []; foreach ($params as $param) { $data[$param] = $request->getParam($param, $default); } return $data; }
php
protected function params(Request $request, array $params, $default = null) { $data = []; foreach ($params as $param) { $data[$param] = $request->getParam($param, $default); } return $data; }
[ "protected", "function", "params", "(", "Request", "$", "request", ",", "array", "$", "params", ",", "$", "default", "=", "null", ")", "{", "$", "data", "=", "[", "]", ";", "foreach", "(", "$", "params", "as", "$", "param", ")", "{", "$", "data", ...
Gets request parameters. @param Request $request @param string[] $params @param string $default @return string[]
[ "Gets", "request", "parameters", "." ]
train
https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Controller/ControllerTrait.php#L33-L41
crysalead/sql-dialect
src/Dialect.php
Dialect._defaultBuilders
protected function _defaultBuilders() { return [ 'function' => function ($operator, $parts) { $operator = strtoupper(substr($operator, 0, -2)); return "{$operator}(" . join(", ", $parts). ')'; }, 'prefix' => function ($operator, $parts) { return "{$operator} " . reset($parts); }, 'list' => function ($operator, $parts) { $key = array_shift($parts); return "{$key} {$operator} (" . join(", ", $parts) . ')'; }, 'between' => function ($operator, $parts) { $key = array_shift($parts); return "{$key} {$operator} " . reset($parts) . ' AND ' . end($parts); }, 'set' => function ($operator, $parts) { return join(" {$operator} ", $parts); }, 'alias' => function ($operator, $parts) { $expr = array_shift($parts); return "({$expr}) {$operator} " . array_shift($parts); } ]; }
php
protected function _defaultBuilders() { return [ 'function' => function ($operator, $parts) { $operator = strtoupper(substr($operator, 0, -2)); return "{$operator}(" . join(", ", $parts). ')'; }, 'prefix' => function ($operator, $parts) { return "{$operator} " . reset($parts); }, 'list' => function ($operator, $parts) { $key = array_shift($parts); return "{$key} {$operator} (" . join(", ", $parts) . ')'; }, 'between' => function ($operator, $parts) { $key = array_shift($parts); return "{$key} {$operator} " . reset($parts) . ' AND ' . end($parts); }, 'set' => function ($operator, $parts) { return join(" {$operator} ", $parts); }, 'alias' => function ($operator, $parts) { $expr = array_shift($parts); return "({$expr}) {$operator} " . array_shift($parts); } ]; }
[ "protected", "function", "_defaultBuilders", "(", ")", "{", "return", "[", "'function'", "=>", "function", "(", "$", "operator", ",", "$", "parts", ")", "{", "$", "operator", "=", "strtoupper", "(", "substr", "(", "$", "operator", ",", "0", ",", "-", "...
Returns operator builders. @return array
[ "Returns", "operator", "builders", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L178-L204
crysalead/sql-dialect
src/Dialect.php
Dialect._defaultFormatters
protected function _defaultFormatters() { return [ ':name' => function ($value, &$states) { list($alias, $field) = $this->undot($value); if (isset($states['aliases'][$alias])) { $alias = $states['aliases'][$alias]; } $escaped = $this->name($value, $states['aliases']); $schema = isset($states['schemas'][$alias]) ? $states['schemas'][$alias] : null; $states['name'] = $field; $states['schema'] = $schema; return $escaped; }, ':value' => function ($value, $states) { return $this->value($value, $states); }, ':plain' => function ($value, $states) { return (string) $value; } ]; }
php
protected function _defaultFormatters() { return [ ':name' => function ($value, &$states) { list($alias, $field) = $this->undot($value); if (isset($states['aliases'][$alias])) { $alias = $states['aliases'][$alias]; } $escaped = $this->name($value, $states['aliases']); $schema = isset($states['schemas'][$alias]) ? $states['schemas'][$alias] : null; $states['name'] = $field; $states['schema'] = $schema; return $escaped; }, ':value' => function ($value, $states) { return $this->value($value, $states); }, ':plain' => function ($value, $states) { return (string) $value; } ]; }
[ "protected", "function", "_defaultFormatters", "(", ")", "{", "return", "[", "':name'", "=>", "function", "(", "$", "value", ",", "&", "$", "states", ")", "{", "list", "(", "$", "alias", ",", "$", "field", ")", "=", "$", "this", "->", "undot", "(", ...
Returns formatters. @return array
[ "Returns", "formatters", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L211-L232
crysalead/sql-dialect
src/Dialect.php
Dialect.quoter
public function quoter($quoter = null) { if ($quoter !== null) { $this->_quoter = $quoter; } return $this->_quoter; }
php
public function quoter($quoter = null) { if ($quoter !== null) { $this->_quoter = $quoter; } return $this->_quoter; }
[ "public", "function", "quoter", "(", "$", "quoter", "=", "null", ")", "{", "if", "(", "$", "quoter", "!==", "null", ")", "{", "$", "this", "->", "_quoter", "=", "$", "quoter", ";", "}", "return", "$", "this", "->", "_quoter", ";", "}" ]
Gets/sets the quoter handler. @param Closure $quoter The quoter handler. @return Closure Returns the quoter handler.
[ "Gets", "/", "sets", "the", "quoter", "handler", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L240-L246
crysalead/sql-dialect
src/Dialect.php
Dialect.caster
public function caster($caster = null) { if ($caster !== null) { $this->_caster = $caster; } return $this->_caster; }
php
public function caster($caster = null) { if ($caster !== null) { $this->_caster = $caster; } return $this->_caster; }
[ "public", "function", "caster", "(", "$", "caster", "=", "null", ")", "{", "if", "(", "$", "caster", "!==", "null", ")", "{", "$", "this", "->", "_caster", "=", "$", "caster", ";", "}", "return", "$", "this", "->", "_caster", ";", "}" ]
Gets/sets the casting handler. @param Closure $caster The casting handler. @return Closure Returns the casting handler.
[ "Gets", "/", "sets", "the", "casting", "handler", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L254-L260
crysalead/sql-dialect
src/Dialect.php
Dialect.type
public function type($type, $config = null) { if ($config) { $this->_types[$type] = $config; } if (!isset($this->_types[$type])) { throw new SqlException("Column type `'{$type}'` does not exist."); } return $this->_types[$type]; }
php
public function type($type, $config = null) { if ($config) { $this->_types[$type] = $config; } if (!isset($this->_types[$type])) { throw new SqlException("Column type `'{$type}'` does not exist."); } return $this->_types[$type]; }
[ "public", "function", "type", "(", "$", "type", ",", "$", "config", "=", "null", ")", "{", "if", "(", "$", "config", ")", "{", "$", "this", "->", "_types", "[", "$", "type", "]", "=", "$", "config", ";", "}", "if", "(", "!", "isset", "(", "$"...
Gets/sets an internal type definition. @param string $type The type name. @param array $config The type definition. @return array Return the type definition.
[ "Gets", "/", "sets", "an", "internal", "type", "definition", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L269-L278
crysalead/sql-dialect
src/Dialect.php
Dialect.map
public function map($use, $type, $options = []) { if (!isset($this->_maps[$use])) { $this->_maps[$use] = []; } if ($options) { $this->_maps[$use] = array_merge([$type => $options], $this->_maps[$use]); } else { $this->_maps[$use] += [$type => []]; } }
php
public function map($use, $type, $options = []) { if (!isset($this->_maps[$use])) { $this->_maps[$use] = []; } if ($options) { $this->_maps[$use] = array_merge([$type => $options], $this->_maps[$use]); } else { $this->_maps[$use] += [$type => []]; } }
[ "public", "function", "map", "(", "$", "use", ",", "$", "type", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_maps", "[", "$", "use", "]", ")", ")", "{", "$", "this", "->", "_maps", "[", "$...
Sets a type mapping. @param string $type The type name. @param array $config The type definition. @return array Return the type definition.
[ "Sets", "a", "type", "mapping", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L287-L297
crysalead/sql-dialect
src/Dialect.php
Dialect.mapped
public function mapped($options) { if (is_array($options)) { $use = $options['use']; unset($options['use']); } else { $use = $options; $options = []; } if (!isset($this->_maps[$use])) { return 'string'; } foreach ($this->_maps[$use] as $type => $value) { if (!array_diff_assoc($value, $options)) { return $type; } } return 'string'; }
php
public function mapped($options) { if (is_array($options)) { $use = $options['use']; unset($options['use']); } else { $use = $options; $options = []; } if (!isset($this->_maps[$use])) { return 'string'; } foreach ($this->_maps[$use] as $type => $value) { if (!array_diff_assoc($value, $options)) { return $type; } } return 'string'; }
[ "public", "function", "mapped", "(", "$", "options", ")", "{", "if", "(", "is_array", "(", "$", "options", ")", ")", "{", "$", "use", "=", "$", "options", "[", "'use'", "]", ";", "unset", "(", "$", "options", "[", "'use'", "]", ")", ";", "}", "...
Gets a mapped type. @param array $options The column definition or the database type. @param array $config The type definition. @return array Return the type definition.
[ "Gets", "a", "mapped", "type", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L306-L326
crysalead/sql-dialect
src/Dialect.php
Dialect.field
public function field($field) { if (!isset($field['name'])) { throw new SqlException("Missing column name."); } if (!isset($field['use'])) { if (isset($field['type'])) { $field += $this->type($field['type']); } else { $field += $this->type('string'); } } return $field + [ 'name' => null, 'type' => null, 'length' => null, 'precision' => null, 'serial' => false, 'default' => null, 'null' => null ]; }
php
public function field($field) { if (!isset($field['name'])) { throw new SqlException("Missing column name."); } if (!isset($field['use'])) { if (isset($field['type'])) { $field += $this->type($field['type']); } else { $field += $this->type('string'); } } return $field + [ 'name' => null, 'type' => null, 'length' => null, 'precision' => null, 'serial' => false, 'default' => null, 'null' => null ]; }
[ "public", "function", "field", "(", "$", "field", ")", "{", "if", "(", "!", "isset", "(", "$", "field", "[", "'name'", "]", ")", ")", "{", "throw", "new", "SqlException", "(", "\"Missing column name.\"", ")", ";", "}", "if", "(", "!", "isset", "(", ...
Formats a field definition. @param array $field A partial field definition. @return array A complete field definition.
[ "Formats", "a", "field", "definition", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L334-L355
crysalead/sql-dialect
src/Dialect.php
Dialect.statement
public function statement($name, $config = []) { $defaults = ['dialect' => $this]; $config += $defaults; if (!isset($this->_classes[$name])) { throw new SqlException("Unsupported statement `'{$name}'`."); } $statement = $this->_classes[$name]; return new $statement($config); }
php
public function statement($name, $config = []) { $defaults = ['dialect' => $this]; $config += $defaults; if (!isset($this->_classes[$name])) { throw new SqlException("Unsupported statement `'{$name}'`."); } $statement = $this->_classes[$name]; return new $statement($config); }
[ "public", "function", "statement", "(", "$", "name", ",", "$", "config", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'dialect'", "=>", "$", "this", "]", ";", "$", "config", "+=", "$", "defaults", ";", "if", "(", "!", "isset", "(", "$", ...
SQL statement factory. @param string $name The name of the statement to instantiate. @param array $config The configuration options. @return object A statement instance.
[ "SQL", "statement", "factory", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L364-L374
crysalead/sql-dialect
src/Dialect.php
Dialect.escapes
public function escapes($names, $prefix, $aliases = []) { $names = is_array($names) ? $names : [$names]; $sql = []; foreach ($names as $key => $value) { if ($this->isOperator($key)) { $sql[] = $this->conditions($names); } elseif (is_string($value)) { if (!is_numeric($key)) { $name = $this->name($key, $aliases); $value = $this->name($value); $name = $name !== $value ? "{$name} AS {$value}" : $name; } else { $name = $this->name($value, $aliases); } $name = $prefix ? "{$prefix}.{$name}" : $name; $sql[$name] = $name; } elseif (!is_array($value)) { $sql[] = (string) $value; } else { $pfx = $prefix; if (!is_numeric($key)) { $pfx = $this->escape(isset($aliases[$key]) ? $aliases[$key] : $key); } $sql = array_merge($sql, $this->escapes($value, $pfx, $aliases)); } } return $sql; }
php
public function escapes($names, $prefix, $aliases = []) { $names = is_array($names) ? $names : [$names]; $sql = []; foreach ($names as $key => $value) { if ($this->isOperator($key)) { $sql[] = $this->conditions($names); } elseif (is_string($value)) { if (!is_numeric($key)) { $name = $this->name($key, $aliases); $value = $this->name($value); $name = $name !== $value ? "{$name} AS {$value}" : $name; } else { $name = $this->name($value, $aliases); } $name = $prefix ? "{$prefix}.{$name}" : $name; $sql[$name] = $name; } elseif (!is_array($value)) { $sql[] = (string) $value; } else { $pfx = $prefix; if (!is_numeric($key)) { $pfx = $this->escape(isset($aliases[$key]) ? $aliases[$key] : $key); } $sql = array_merge($sql, $this->escapes($value, $pfx, $aliases)); } } return $sql; }
[ "public", "function", "escapes", "(", "$", "names", ",", "$", "prefix", ",", "$", "aliases", "=", "[", "]", ")", "{", "$", "names", "=", "is_array", "(", "$", "names", ")", "?", "$", "names", ":", "[", "$", "names", "]", ";", "$", "sql", "=", ...
Escapes a list of identifers. Note: it ignores duplicates. @param string|array $names A name or an array of names to escapes. @param string $prefix An optionnal table/alias prefix to use. @param array $aliases An aliases map. @return array An array of escaped fields.
[ "Escapes", "a", "list", "of", "identifers", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L398-L426
crysalead/sql-dialect
src/Dialect.php
Dialect.prefix
public function prefix($data, $prefix, $prefixValue = true) { $result = []; foreach ($data as $key => $value) { if ($this->isOperator($key)) { if ($key === ':name') { $value = $this->_prefix($value, $prefix); } else { $value = is_array($value) ? $this->prefix($value, $prefix, false) : $value; } $result[$key] = $value; continue; } if (!is_numeric($key)) { $key = $this->_prefix($key, $prefix); } elseif (is_array($value)) { $value = $this->prefix($value, $prefix, false); } elseif ($prefixValue) { $value = $this->_prefix($value, $prefix); } $result[$key] = $value; } return $result; }
php
public function prefix($data, $prefix, $prefixValue = true) { $result = []; foreach ($data as $key => $value) { if ($this->isOperator($key)) { if ($key === ':name') { $value = $this->_prefix($value, $prefix); } else { $value = is_array($value) ? $this->prefix($value, $prefix, false) : $value; } $result[$key] = $value; continue; } if (!is_numeric($key)) { $key = $this->_prefix($key, $prefix); } elseif (is_array($value)) { $value = $this->prefix($value, $prefix, false); } elseif ($prefixValue) { $value = $this->_prefix($value, $prefix); } $result[$key] = $value; } return $result; }
[ "public", "function", "prefix", "(", "$", "data", ",", "$", "prefix", ",", "$", "prefixValue", "=", "true", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$"...
Prefixes a list of identifers. @param string|array $names A name or an array of names to prefix. @param string $prefix The prefix to use. @param boolean $prefixValue Boolean indicating if prefixing must occurs. @return array The prefixed names.
[ "Prefixes", "a", "list", "of", "identifers", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L436-L459
crysalead/sql-dialect
src/Dialect.php
Dialect._prefix
public function _prefix($name, $prefix) { list($alias, $field) = $this->undot($name); return $alias ? $name : "{$prefix}.{$field}"; }
php
public function _prefix($name, $prefix) { list($alias, $field) = $this->undot($name); return $alias ? $name : "{$prefix}.{$field}"; }
[ "public", "function", "_prefix", "(", "$", "name", ",", "$", "prefix", ")", "{", "list", "(", "$", "alias", ",", "$", "field", ")", "=", "$", "this", "->", "undot", "(", "$", "name", ")", ";", "return", "$", "alias", "?", "$", "name", ":", "\"{...
Prefixes a identifer. @param string $names The name to prefix. @param string $prefix The prefix. @return string The prefixed name.
[ "Prefixes", "a", "identifer", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L468-L472
crysalead/sql-dialect
src/Dialect.php
Dialect.conditions
public function conditions($conditions, $options = []) { if (!$conditions) { return ''; } $defaults = [ 'prepend' => false, 'operator' => ':and', 'schemas' => [], 'aliases' => [], 'schema' => null, 'name' => null, ]; $options += $defaults; if (!is_numeric(key($conditions))) { $conditions = [$conditions]; } $result = $this->_operator(strtolower($options['operator']), $conditions, $options); return ($options['prepend'] && $result) ? "{$options['prepend']} {$result}" : $result; }
php
public function conditions($conditions, $options = []) { if (!$conditions) { return ''; } $defaults = [ 'prepend' => false, 'operator' => ':and', 'schemas' => [], 'aliases' => [], 'schema' => null, 'name' => null, ]; $options += $defaults; if (!is_numeric(key($conditions))) { $conditions = [$conditions]; } $result = $this->_operator(strtolower($options['operator']), $conditions, $options); return ($options['prepend'] && $result) ? "{$options['prepend']} {$result}" : $result; }
[ "public", "function", "conditions", "(", "$", "conditions", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "$", "conditions", ")", "{", "return", "''", ";", "}", "$", "defaults", "=", "[", "'prepend'", "=>", "false", ",", "'operator'",...
Returns a string of formatted conditions to be inserted into the query statement. If the query conditions are defined as an array, key pairs are converted to SQL strings. Conversion rules are as follows: - If `$key` is numeric and `$value` is a string, `$value` is treated as a literal SQL fragment and returned. @param array $conditions The conditions for this query. @param array $options The options. Possible values are: - `prepend` _string_: The string to prepend or `false` for no prefix. - `operator` _string_: The join operator. - `schemas` _array_ : The schemas hash object. @return string Returns an SQL conditions clause.
[ "Returns", "a", "string", "of", "formatted", "conditions", "to", "be", "inserted", "into", "the", "query", "statement", ".", "If", "the", "query", "conditions", "are", "defined", "as", "an", "array", "key", "pairs", "are", "converted", "to", "SQL", "strings"...
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L490-L511
crysalead/sql-dialect
src/Dialect.php
Dialect._operator
protected function _operator($operator, $conditions, &$states) { if (isset($this->_operators[$operator])) { $config = $this->_operators[$operator]; } elseif (substr($operator, -2) === '()') { $op = substr($operator, 0, -2); if (isset($this->_operators[$op])) { return '(' . $this->_operator($op, $conditions, $states) . ')'; } $config = ['builder' => 'function']; } else { throw new SqlException("Unexisting operator `'{$operator}'`."); } $parts = $this->_conditions($conditions, $states); $operator = (is_array($parts) && next($parts) === 'NULL' && isset($config['null'])) ? $config['null'] : $operator; $operator = $operator[0] === ':' ? strtoupper(substr($operator, 1)) : $operator; if (isset($config['builder'])) { $builder = $this->_builders[$config['builder']]; return $builder($operator, $parts); } if (isset($config['format'])) { return sprintf($config['format'], join(", ", $parts)); } return join(" {$operator} ", $parts); }
php
protected function _operator($operator, $conditions, &$states) { if (isset($this->_operators[$operator])) { $config = $this->_operators[$operator]; } elseif (substr($operator, -2) === '()') { $op = substr($operator, 0, -2); if (isset($this->_operators[$op])) { return '(' . $this->_operator($op, $conditions, $states) . ')'; } $config = ['builder' => 'function']; } else { throw new SqlException("Unexisting operator `'{$operator}'`."); } $parts = $this->_conditions($conditions, $states); $operator = (is_array($parts) && next($parts) === 'NULL' && isset($config['null'])) ? $config['null'] : $operator; $operator = $operator[0] === ':' ? strtoupper(substr($operator, 1)) : $operator; if (isset($config['builder'])) { $builder = $this->_builders[$config['builder']]; return $builder($operator, $parts); } if (isset($config['format'])) { return sprintf($config['format'], join(", ", $parts)); } return join(" {$operator} ", $parts); }
[ "protected", "function", "_operator", "(", "$", "operator", ",", "$", "conditions", ",", "&", "$", "states", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_operators", "[", "$", "operator", "]", ")", ")", "{", "$", "config", "=", "$", "thi...
Build a SQL operator statement. @param string $operator The operator. @param array $conditions The data for the operator. @param array $states The current states.. @return string Returns a SQL string.
[ "Build", "a", "SQL", "operator", "statement", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L521-L547
crysalead/sql-dialect
src/Dialect.php
Dialect._conditions
protected function _conditions($conditions, &$states) { $parts = []; foreach ($conditions as $name => $value) { $operator = strtolower($name); if (isset($this->_formatters[$operator])) { $parts[] = $this->format($operator, $value, $states); } elseif ($this->isOperator($operator)) { $parts[] = $this->_operator($operator, $value, $states); } elseif (is_numeric($name)) { if (is_array($value)) { $parts = array_merge($parts, $this->_conditions($value, $states)); } else { $parts[] = $this->value($value, $states); } } else { $parts[] = $this->_name($name, $value, $states); } } return $parts; }
php
protected function _conditions($conditions, &$states) { $parts = []; foreach ($conditions as $name => $value) { $operator = strtolower($name); if (isset($this->_formatters[$operator])) { $parts[] = $this->format($operator, $value, $states); } elseif ($this->isOperator($operator)) { $parts[] = $this->_operator($operator, $value, $states); } elseif (is_numeric($name)) { if (is_array($value)) { $parts = array_merge($parts, $this->_conditions($value, $states)); } else { $parts[] = $this->value($value, $states); } } else { $parts[] = $this->_name($name, $value, $states); } } return $parts; }
[ "protected", "function", "_conditions", "(", "$", "conditions", ",", "&", "$", "states", ")", "{", "$", "parts", "=", "[", "]", ";", "foreach", "(", "$", "conditions", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "operator", "=", "strtolower...
Build a formated array of SQL statement. @param array $conditions A array of conditions. @param array $states The states. @return array Returns a array of SQL string.
[ "Build", "a", "formated", "array", "of", "SQL", "statement", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L567-L587
crysalead/sql-dialect
src/Dialect.php
Dialect._name
protected function _name($name, $value, $states) { list($alias, $field) = $this->undot($name); $escaped = $this->name($name, $states['aliases']); $schema = isset($states['schemas'][$alias]) ? $states['schemas'][$alias] : null; $states['name'] = $field; $states['schema'] = $schema; if (!is_array($value)) { return $this->_operator('=', [[':name' => $name], $value], $states); } $operator = strtolower(key($value)); if (isset($this->_formatters[$operator])) { return "{$escaped} = " . $this->format($operator, current($value), $states); } elseif (!isset($this->_operators[$operator])) { return $this->_operator(':in', [[':name' => $name], $value], $states); } $conditions = current($value); $conditions = is_array($conditions) ? $conditions : [$conditions]; array_unshift($conditions, [':name' => $name]); return $this->_operator($operator, $conditions, $states); }
php
protected function _name($name, $value, $states) { list($alias, $field) = $this->undot($name); $escaped = $this->name($name, $states['aliases']); $schema = isset($states['schemas'][$alias]) ? $states['schemas'][$alias] : null; $states['name'] = $field; $states['schema'] = $schema; if (!is_array($value)) { return $this->_operator('=', [[':name' => $name], $value], $states); } $operator = strtolower(key($value)); if (isset($this->_formatters[$operator])) { return "{$escaped} = " . $this->format($operator, current($value), $states); } elseif (!isset($this->_operators[$operator])) { return $this->_operator(':in', [[':name' => $name], $value], $states); } $conditions = current($value); $conditions = is_array($conditions) ? $conditions : [$conditions]; array_unshift($conditions, [':name' => $name]); return $this->_operator($operator, $conditions, $states); }
[ "protected", "function", "_name", "(", "$", "name", ",", "$", "value", ",", "$", "states", ")", "{", "list", "(", "$", "alias", ",", "$", "field", ")", "=", "$", "this", "->", "undot", "(", "$", "name", ")", ";", "$", "escaped", "=", "$", "this...
Build a <fieldname> = <value> SQL condition. @param string $name The field name. @param mixed $value The data value. @param array $states The current states. @return string Returns a SQL string.
[ "Build", "a", "<fieldname", ">", "=", "<value", ">", "SQL", "condition", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L597-L620
crysalead/sql-dialect
src/Dialect.php
Dialect.format
public function format($operator, $value, &$states = []) { $defaults = [ 'schemas' => [], 'aliases' => [], 'schema' => null ]; $states += $defaults; if (!isset($this->_formatters[$operator])) { throw new SqlException("Unexisting formatter `'{$operator}'`."); } $formatter = $this->_formatters[$operator]; return $formatter($value, $states); }
php
public function format($operator, $value, &$states = []) { $defaults = [ 'schemas' => [], 'aliases' => [], 'schema' => null ]; $states += $defaults; if (!isset($this->_formatters[$operator])) { throw new SqlException("Unexisting formatter `'{$operator}'`."); } $formatter = $this->_formatters[$operator]; return $formatter($value, $states); }
[ "public", "function", "format", "(", "$", "operator", ",", "$", "value", ",", "&", "$", "states", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'schemas'", "=>", "[", "]", ",", "'aliases'", "=>", "[", "]", ",", "'schema'", "=>", "null", "]...
SQL formatter. @param string $operator The format operator. @param mixed $value The value to format. @param array $states The current states. @return string Returns a SQL string.
[ "SQL", "formatter", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L630-L643
crysalead/sql-dialect
src/Dialect.php
Dialect.name
public function name($name, $aliases = []) { if (!is_string($name)) { return $this->names($name, $aliases); } list($alias, $field) = $this->undot($name); if (isset($aliases[$alias])) { $alias = $aliases[$alias]; } return $alias ? $this->escape($alias) . '.' . $this->escape($field) : $this->escape($name); }
php
public function name($name, $aliases = []) { if (!is_string($name)) { return $this->names($name, $aliases); } list($alias, $field) = $this->undot($name); if (isset($aliases[$alias])) { $alias = $aliases[$alias]; } return $alias ? $this->escape($alias) . '.' . $this->escape($field) : $this->escape($name); }
[ "public", "function", "name", "(", "$", "name", ",", "$", "aliases", "=", "[", "]", ")", "{", "if", "(", "!", "is_string", "(", "$", "name", ")", ")", "{", "return", "$", "this", "->", "names", "(", "$", "name", ",", "$", "aliases", ")", ";", ...
Escapes a column/table/schema with dotted syntax support. @param string $name The identifier name. @param array $aliases An aliases map. @return string The escaped identifier.
[ "Escapes", "a", "column", "/", "table", "/", "schema", "with", "dotted", "syntax", "support", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L652-L662
crysalead/sql-dialect
src/Dialect.php
Dialect.undot
public function undot($field) { if (is_string($field) && (($pos = strrpos($field, ".")) !== false)) { return [substr($field, 0, $pos), substr($field, $pos + 1)]; } return ['', $field]; }
php
public function undot($field) { if (is_string($field) && (($pos = strrpos($field, ".")) !== false)) { return [substr($field, 0, $pos), substr($field, $pos + 1)]; } return ['', $field]; }
[ "public", "function", "undot", "(", "$", "field", ")", "{", "if", "(", "is_string", "(", "$", "field", ")", "&&", "(", "(", "$", "pos", "=", "strrpos", "(", "$", "field", ",", "\".\"", ")", ")", "!==", "false", ")", ")", "{", "return", "[", "su...
Split dotted syntax into distinct name. @param string $field A dotted identifier. @return array The parts.
[ "Split", "dotted", "syntax", "into", "distinct", "name", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L681-L687
crysalead/sql-dialect
src/Dialect.php
Dialect.quote
public function quote($string) { if ($quoter = $this->quoter()) { return $quoter($string); } $replacements = array( "\x00"=>'\x00', "\n"=>'\n', "\r"=>'\r', "\\"=>'\\\\', "'"=>"\'", "\x1a"=>'\x1a' ); return "'" . strtr(addcslashes($string, '%_'), $replacements) . "'"; }
php
public function quote($string) { if ($quoter = $this->quoter()) { return $quoter($string); } $replacements = array( "\x00"=>'\x00', "\n"=>'\n', "\r"=>'\r', "\\"=>'\\\\', "'"=>"\'", "\x1a"=>'\x1a' ); return "'" . strtr(addcslashes($string, '%_'), $replacements) . "'"; }
[ "public", "function", "quote", "(", "$", "string", ")", "{", "if", "(", "$", "quoter", "=", "$", "this", "->", "quoter", "(", ")", ")", "{", "return", "$", "quoter", "(", "$", "string", ")", ";", "}", "$", "replacements", "=", "array", "(", "\"\\...
Quotes a string. @param string $string The string to quote. @return string The quoted string.
[ "Quotes", "a", "string", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L695-L709
crysalead/sql-dialect
src/Dialect.php
Dialect.value
public function value($value, $states = []) { if ($caster = $this->caster()) { return $caster($value, $states); } switch (true) { case is_null($value): return 'NULL'; case is_bool($value): return $value ? 'TRUE' : 'FALSE'; case is_string($value): return $this->quote($value); case is_array($value): $cast = function($value) use (&$cast) { $result = []; foreach ($value as $k => $v) { if (is_array($v)) { $result[] = $cast($v); } else { $result[] = $this->value($v); } } return '{' . join(',', $result) . '}'; }; return $cast($value); } return (string) $value; }
php
public function value($value, $states = []) { if ($caster = $this->caster()) { return $caster($value, $states); } switch (true) { case is_null($value): return 'NULL'; case is_bool($value): return $value ? 'TRUE' : 'FALSE'; case is_string($value): return $this->quote($value); case is_array($value): $cast = function($value) use (&$cast) { $result = []; foreach ($value as $k => $v) { if (is_array($v)) { $result[] = $cast($v); } else { $result[] = $this->value($v); } } return '{' . join(',', $result) . '}'; }; return $cast($value); } return (string) $value; }
[ "public", "function", "value", "(", "$", "value", ",", "$", "states", "=", "[", "]", ")", "{", "if", "(", "$", "caster", "=", "$", "this", "->", "caster", "(", ")", ")", "{", "return", "$", "caster", "(", "$", "value", ",", "$", "states", ")", ...
Converts a given value into the proper type based on a given schema definition. @param mixed $value The value to be converted. Arrays will be recursively converted. @param array $states The current states. @return mixed The formatted value.
[ "Converts", "a", "given", "value", "into", "the", "proper", "type", "based", "on", "a", "given", "schema", "definition", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L718-L746
crysalead/sql-dialect
src/Dialect.php
Dialect.column
public function column($field) { $field = $this->field($field); $isNumeric = preg_match('/^(integer|float|boolean)$/', (string) $field['type']); if ($isNumeric && $field['default'] === '') { $field['null'] = true; $field['default'] = null; } $field['use'] = strtolower($field['use']); return $this->_column($field); }
php
public function column($field) { $field = $this->field($field); $isNumeric = preg_match('/^(integer|float|boolean)$/', (string) $field['type']); if ($isNumeric && $field['default'] === '') { $field['null'] = true; $field['default'] = null; } $field['use'] = strtolower($field['use']); return $this->_column($field); }
[ "public", "function", "column", "(", "$", "field", ")", "{", "$", "field", "=", "$", "this", "->", "field", "(", "$", "field", ")", ";", "$", "isNumeric", "=", "preg_match", "(", "'/^(integer|float|boolean)$/'", ",", "(", "string", ")", "$", "field", "...
Generates a database-native column schema string @param array $column A field array structured like the following: `['name' => 'value', 'type' => 'value' [, options]]`, where options can be `'default'`, `'null'`, `'length'` or `'precision'`. @return string A SQL string formated column.
[ "Generates", "a", "database", "-", "native", "column", "schema", "string" ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L756-L767
crysalead/sql-dialect
src/Dialect.php
Dialect._formatColumn
public function _formatColumn($name, $length = null, $precision = null) { $size = []; if ($length) { $size[] = $length; } if ($precision) { $size[] = $precision; } return $size ? $name . '(' . join(',', $size) . ')' : $name; }
php
public function _formatColumn($name, $length = null, $precision = null) { $size = []; if ($length) { $size[] = $length; } if ($precision) { $size[] = $precision; } return $size ? $name . '(' . join(',', $size) . ')' : $name; }
[ "public", "function", "_formatColumn", "(", "$", "name", ",", "$", "length", "=", "null", ",", "$", "precision", "=", "null", ")", "{", "$", "size", "=", "[", "]", ";", "if", "(", "$", "length", ")", "{", "$", "size", "[", "]", "=", "$", "lengt...
Formats a column name. @param string $name A column name. @param integer $length A column length. @param integer $precision A column precision. @return string The formatted column.
[ "Formats", "a", "column", "name", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L777-L787
crysalead/sql-dialect
src/Dialect.php
Dialect.meta
public function meta($type, $data, $names = null) { $result = []; $names = $names ? (array) $names : array_keys($data); foreach ($names as $name) { $value = isset($data[$name]) ? $data[$name] : null; if ($value && $meta = $this->_meta($type, $name, $value)) { $result[] = $meta; } } return join(' ', $result); }
php
public function meta($type, $data, $names = null) { $result = []; $names = $names ? (array) $names : array_keys($data); foreach ($names as $name) { $value = isset($data[$name]) ? $data[$name] : null; if ($value && $meta = $this->_meta($type, $name, $value)) { $result[] = $meta; } } return join(' ', $result); }
[ "public", "function", "meta", "(", "$", "type", ",", "$", "data", ",", "$", "names", "=", "null", ")", "{", "$", "result", "=", "[", "]", ";", "$", "names", "=", "$", "names", "?", "(", "array", ")", "$", "names", ":", "array_keys", "(", "$", ...
Builds a column/table meta. @param string $type The meta type. @param array $data The meta data. @param array $names If `$names` is not `null` only build meta present in `$names`. @return string The SQL meta.
[ "Builds", "a", "column", "/", "table", "meta", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L797-L808
crysalead/sql-dialect
src/Dialect.php
Dialect._meta
protected function _meta($type, $name, $value) { $meta = isset($this->_meta[$type][$name]) ? $this->_meta[$type][$name] : null; if (!$meta || (isset($meta['options']) && !in_array($value, $meta['options']))) { return; } $meta += ['keyword' => '', 'escape' => false, 'join' => ' ']; extract($meta); if ($escape === true) { $value = $this->value($value); } $result = $keyword . $join . $value; return $result !== ' ' ? $result : ''; }
php
protected function _meta($type, $name, $value) { $meta = isset($this->_meta[$type][$name]) ? $this->_meta[$type][$name] : null; if (!$meta || (isset($meta['options']) && !in_array($value, $meta['options']))) { return; } $meta += ['keyword' => '', 'escape' => false, 'join' => ' ']; extract($meta); if ($escape === true) { $value = $this->value($value); } $result = $keyword . $join . $value; return $result !== ' ' ? $result : ''; }
[ "protected", "function", "_meta", "(", "$", "type", ",", "$", "name", ",", "$", "value", ")", "{", "$", "meta", "=", "isset", "(", "$", "this", "->", "_meta", "[", "$", "type", "]", "[", "$", "name", "]", ")", "?", "$", "this", "->", "_meta", ...
Helper for building a column/table single meta string. @param string $type The type of the meta to build (possible values: 'table' or 'column') @param string $name The name of the meta to build @param mixed $value The meta value. @return string The SQL meta.
[ "Helper", "for", "building", "a", "column", "/", "table", "single", "meta", "string", "." ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L818-L831
crysalead/sql-dialect
src/Dialect.php
Dialect.constraint
public function constraint($name, $value, $options = []) { $value += ['options' => []]; $meta = isset($this->_constraints[$name]) ? $this->_constraints[$name] : null; if (!($template = isset($meta['template']) ? $meta['template'] : null)) { throw new SqlException("Invalid constraint template `'{$name}'`."); } $data = []; foreach ($value as $name => $value) { switch ($name) { case 'key': case 'index': if (isset($meta[$name])) { $data['index'] = $meta[$name]; } break; case 'to': $data[$name] = $this->name($value); break; case 'on': $data[$name] = "ON {$value}"; break; case 'constraint': $data[$name] = "CONSTRAINT " . $this->name($value); break; case 'expr': $data[$name] = $this->conditions(is_array($value) ? $value : [$value], $options); break; case 'column': case 'primaryKey': case 'foreignKey': $data[$name] = join(', ', array_map([$this, 'name'], (array) $value)); $data['name'] = $this->name(join('_', (array) $value)); break; } } return trim(Text::insert($template, $data, ['clean' => ['method' => 'text']])); }
php
public function constraint($name, $value, $options = []) { $value += ['options' => []]; $meta = isset($this->_constraints[$name]) ? $this->_constraints[$name] : null; if (!($template = isset($meta['template']) ? $meta['template'] : null)) { throw new SqlException("Invalid constraint template `'{$name}'`."); } $data = []; foreach ($value as $name => $value) { switch ($name) { case 'key': case 'index': if (isset($meta[$name])) { $data['index'] = $meta[$name]; } break; case 'to': $data[$name] = $this->name($value); break; case 'on': $data[$name] = "ON {$value}"; break; case 'constraint': $data[$name] = "CONSTRAINT " . $this->name($value); break; case 'expr': $data[$name] = $this->conditions(is_array($value) ? $value : [$value], $options); break; case 'column': case 'primaryKey': case 'foreignKey': $data[$name] = join(', ', array_map([$this, 'name'], (array) $value)); $data['name'] = $this->name(join('_', (array) $value)); break; } } return trim(Text::insert($template, $data, ['clean' => ['method' => 'text']])); }
[ "public", "function", "constraint", "(", "$", "name", ",", "$", "value", ",", "$", "options", "=", "[", "]", ")", "{", "$", "value", "+=", "[", "'options'", "=>", "[", "]", "]", ";", "$", "meta", "=", "isset", "(", "$", "this", "->", "_constraint...
Build a SQL column constraint @param string $name The name of the meta to build. @param mixed $constraint The constraint value. @param array $options The constraint options. @return string The SQL meta string.
[ "Build", "a", "SQL", "column", "constraint" ]
train
https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Dialect.php#L841-L880
txj123/zilf
src/Zilf/Support/Composer.php
Composer.dumpAutoloads
public function dumpAutoloads($extra = '') { $process = $this->getProcess(); $process->setCommandLine(trim($this->findComposer().' dump-autoload '.$extra)); $process->run(); }
php
public function dumpAutoloads($extra = '') { $process = $this->getProcess(); $process->setCommandLine(trim($this->findComposer().' dump-autoload '.$extra)); $process->run(); }
[ "public", "function", "dumpAutoloads", "(", "$", "extra", "=", "''", ")", "{", "$", "process", "=", "$", "this", "->", "getProcess", "(", ")", ";", "$", "process", "->", "setCommandLine", "(", "trim", "(", "$", "this", "->", "findComposer", "(", ")", ...
Regenerate the Composer autoloader files. @param string $extra @return void
[ "Regenerate", "the", "Composer", "autoloader", "files", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Support/Composer.php#L44-L51
txj123/zilf
src/Zilf/Support/Composer.php
Composer.findComposer
protected function findComposer() { if ($this->files->exists($this->workingPath.'/composer.phar')) { return ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false)).' composer.phar'; } return 'composer'; }
php
protected function findComposer() { if ($this->files->exists($this->workingPath.'/composer.phar')) { return ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false)).' composer.phar'; } return 'composer'; }
[ "protected", "function", "findComposer", "(", ")", "{", "if", "(", "$", "this", "->", "files", "->", "exists", "(", "$", "this", "->", "workingPath", ".", "'/composer.phar'", ")", ")", "{", "return", "ProcessUtils", "::", "escapeArgument", "(", "(", "new",...
Get the composer command for the environment. @return string
[ "Get", "the", "composer", "command", "for", "the", "environment", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Support/Composer.php#L68-L75
txj123/zilf
src/Zilf/Queue/Queue.php
Queue.createPayload
protected function createPayload($job, $data = '') { $payload = json_encode($this->createPayloadArray($job, $data)); if (JSON_ERROR_NONE !== json_last_error()) { throw new InvalidPayloadException( 'Unable to JSON encode payload. Error code: '.json_last_error() ); } return $payload; }
php
protected function createPayload($job, $data = '') { $payload = json_encode($this->createPayloadArray($job, $data)); if (JSON_ERROR_NONE !== json_last_error()) { throw new InvalidPayloadException( 'Unable to JSON encode payload. Error code: '.json_last_error() ); } return $payload; }
[ "protected", "function", "createPayload", "(", "$", "job", ",", "$", "data", "=", "''", ")", "{", "$", "payload", "=", "json_encode", "(", "$", "this", "->", "createPayloadArray", "(", "$", "job", ",", "$", "data", ")", ")", ";", "if", "(", "JSON_ERR...
Create a payload string from the given job and data. @param string $job @param mixed $data @return string @throws \Illuminate\Queue\InvalidPayloadException
[ "Create", "a", "payload", "string", "from", "the", "given", "job", "and", "data", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Queue.php#L70-L81
txj123/zilf
src/Zilf/Queue/Queue.php
Queue.createPayloadArray
protected function createPayloadArray($job, $data = '') { return is_object($job) ? $this->createObjectPayload($job) : $this->createStringPayload($job, $data); }
php
protected function createPayloadArray($job, $data = '') { return is_object($job) ? $this->createObjectPayload($job) : $this->createStringPayload($job, $data); }
[ "protected", "function", "createPayloadArray", "(", "$", "job", ",", "$", "data", "=", "''", ")", "{", "return", "is_object", "(", "$", "job", ")", "?", "$", "this", "->", "createObjectPayload", "(", "$", "job", ")", ":", "$", "this", "->", "createStri...
Create a payload array from the given job and data. @param mixed $job @param mixed $data @return array
[ "Create", "a", "payload", "array", "from", "the", "given", "job", "and", "data", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Queue.php#L90-L95
txj123/zilf
src/Zilf/Queue/Queue.php
Queue.createObjectPayload
protected function createObjectPayload($job) { return [ 'displayName' => $this->getDisplayName($job), 'job' => 'Zilf\Queue\CallQueuedHandler@call', 'maxTries' => $job->tries ?? null, 'timeout' => $job->timeout ?? null, 'timeoutAt' => $this->getJobExpiration($job), 'data' => [ 'commandName' => get_class($job), 'command' => serialize(clone $job), ], ]; }
php
protected function createObjectPayload($job) { return [ 'displayName' => $this->getDisplayName($job), 'job' => 'Zilf\Queue\CallQueuedHandler@call', 'maxTries' => $job->tries ?? null, 'timeout' => $job->timeout ?? null, 'timeoutAt' => $this->getJobExpiration($job), 'data' => [ 'commandName' => get_class($job), 'command' => serialize(clone $job), ], ]; }
[ "protected", "function", "createObjectPayload", "(", "$", "job", ")", "{", "return", "[", "'displayName'", "=>", "$", "this", "->", "getDisplayName", "(", "$", "job", ")", ",", "'job'", "=>", "'Zilf\\Queue\\CallQueuedHandler@call'", ",", "'maxTries'", "=>", "$",...
Create a payload for an object-based queue handler. @param mixed $job @return array
[ "Create", "a", "payload", "for", "an", "object", "-", "based", "queue", "handler", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Queue.php#L103-L116
txj123/zilf
src/Zilf/Queue/Queue.php
Queue.createStringPayload
protected function createStringPayload($job, $data) { return [ 'displayName' => is_string($job) ? explode('@', $job)[0] : null, 'job' => $job, 'maxTries' => null, 'timeout' => null, 'data' => $data, ]; }
php
protected function createStringPayload($job, $data) { return [ 'displayName' => is_string($job) ? explode('@', $job)[0] : null, 'job' => $job, 'maxTries' => null, 'timeout' => null, 'data' => $data, ]; }
[ "protected", "function", "createStringPayload", "(", "$", "job", ",", "$", "data", ")", "{", "return", "[", "'displayName'", "=>", "is_string", "(", "$", "job", ")", "?", "explode", "(", "'@'", ",", "$", "job", ")", "[", "0", "]", ":", "null", ",", ...
Create a typical, string based queue payload array. @param string $job @param mixed $data @return array
[ "Create", "a", "typical", "string", "based", "queue", "payload", "array", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Queue.php#L155-L162
yuru-yuri/vk-audio-url-decoder-php
src/Vaud/Decoder.php
Decoder.decode
public function decode(string $url): string { if (\strpos($url, 'audio_api_unavailable') !== false) { $t = \explode('#', \explode('?extra=', $url)[1]); $n = $t[1] === '' ? '' : $this->decode_r($t[1]); $t = $this->decode_r($t[0]); if (!$t || !\is_string($t)) { return $url; } $n = $n ? \explode(\chr(9), $n) : []; $n_len = \count($n); while ($n_len) { --$n_len; $s = \explode(\chr(11), $n[$n_len]); [$a, $s] = $this->splice($s, 0, 1, $t); $a = $a[0]; if (!\method_exists($this, $a)) { return $url; } $t = $this->{$a}(...$s); } if (0 === \strpos($t, 'http')) { return $t; } } return $url; }
php
public function decode(string $url): string { if (\strpos($url, 'audio_api_unavailable') !== false) { $t = \explode('#', \explode('?extra=', $url)[1]); $n = $t[1] === '' ? '' : $this->decode_r($t[1]); $t = $this->decode_r($t[0]); if (!$t || !\is_string($t)) { return $url; } $n = $n ? \explode(\chr(9), $n) : []; $n_len = \count($n); while ($n_len) { --$n_len; $s = \explode(\chr(11), $n[$n_len]); [$a, $s] = $this->splice($s, 0, 1, $t); $a = $a[0]; if (!\method_exists($this, $a)) { return $url; } $t = $this->{$a}(...$s); } if (0 === \strpos($t, 'http')) { return $t; } } return $url; }
[ "public", "function", "decode", "(", "string", "$", "url", ")", ":", "string", "{", "if", "(", "\\", "strpos", "(", "$", "url", ",", "'audio_api_unavailable'", ")", "!==", "false", ")", "{", "$", "t", "=", "\\", "explode", "(", "'#'", ",", "\\", "e...
@param string $url @return string
[ "@param", "string", "$url" ]
train
https://github.com/yuru-yuri/vk-audio-url-decoder-php/blob/02e71c668d88aba654b93354f5df26251dfdadda/src/Vaud/Decoder.php#L31-L65
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Loader.php
Zend_Loader.loadFile
public static function loadFile($filename, $dirs = null, $once = false) { self::_securityCheck($filename); /** * Search in provided directories, as well as include_path */ $incPath = false; if (!empty($dirs) && (is_array($dirs) || is_string($dirs))) { if (is_array($dirs)) { $dirs = implode(PATH_SEPARATOR, $dirs); } $incPath = get_include_path(); set_include_path($dirs . PATH_SEPARATOR . $incPath); } /** * Try finding for the plain filename in the include_path. */ if ($once) { include_once $filename; } else { include $filename; } /** * If searching in directories, reset include_path */ if ($incPath) { set_include_path($incPath); } return true; }
php
public static function loadFile($filename, $dirs = null, $once = false) { self::_securityCheck($filename); /** * Search in provided directories, as well as include_path */ $incPath = false; if (!empty($dirs) && (is_array($dirs) || is_string($dirs))) { if (is_array($dirs)) { $dirs = implode(PATH_SEPARATOR, $dirs); } $incPath = get_include_path(); set_include_path($dirs . PATH_SEPARATOR . $incPath); } /** * Try finding for the plain filename in the include_path. */ if ($once) { include_once $filename; } else { include $filename; } /** * If searching in directories, reset include_path */ if ($incPath) { set_include_path($incPath); } return true; }
[ "public", "static", "function", "loadFile", "(", "$", "filename", ",", "$", "dirs", "=", "null", ",", "$", "once", "=", "false", ")", "{", "self", "::", "_securityCheck", "(", "$", "filename", ")", ";", "/**\n * Search in provided directories, as well as...
Loads a PHP file. This is a wrapper for PHP's include() function. $filename must be the complete filename, including any extension such as ".php". Note that a security check is performed that does not permit extended characters in the filename. This method is intended for loading Zend Framework files. If $dirs is a string or an array, it will search the directories in the order supplied, and attempt to load the first matching file. If the file was not found in the $dirs, or if no $dirs were specified, it will attempt to load it from PHP's include_path. If $once is TRUE, it will use include_once() instead of include(). @param string $filename @param string|array $dirs - OPTIONAL either a path or array of paths to search. @param boolean $once @return boolean @throws Zend_Exception
[ "Loads", "a", "PHP", "file", ".", "This", "is", "a", "wrapper", "for", "PHP", "s", "include", "()", "function", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Loader.php#L115-L148
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Loader.php
Zend_Loader.isReadable
public static function isReadable($filename) { if (!$fh = @fopen($filename, 'r', true)) { return false; } @fclose($fh); return true; }
php
public static function isReadable($filename) { if (!$fh = @fopen($filename, 'r', true)) { return false; } @fclose($fh); return true; }
[ "public", "static", "function", "isReadable", "(", "$", "filename", ")", "{", "if", "(", "!", "$", "fh", "=", "@", "fopen", "(", "$", "filename", ",", "'r'", ",", "true", ")", ")", "{", "return", "false", ";", "}", "@", "fclose", "(", "$", "fh", ...
Returns TRUE if the $filename is readable, or FALSE otherwise. This function uses the PHP include_path, where PHP's is_readable() does not. @param string $filename @return boolean
[ "Returns", "TRUE", "if", "the", "$filename", "is", "readable", "or", "FALSE", "otherwise", ".", "This", "function", "uses", "the", "PHP", "include_path", "where", "PHP", "s", "is_readable", "()", "does", "not", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Loader.php#L158-L165
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Loader.php
Zend_Loader.registerAutoload
public static function registerAutoload($class = 'Zend_Loader', $enabled = true) { if (!function_exists('spl_autoload_register')) { include_once 'Zend/Exception.php'; throw new Zend_Exception('spl_autoload does not exist in this PHP installation'); } self::loadClass($class); $methods = get_class_methods($class); if (!in_array('autoload', (array) $methods)) { include_once 'Zend/Exception.php'; throw new Zend_Exception("The class \"$class\" does not have an autoload() method"); } if ($enabled === true) { spl_autoload_register(array($class, 'autoload')); } else { spl_autoload_unregister(array($class, 'autoload')); } }
php
public static function registerAutoload($class = 'Zend_Loader', $enabled = true) { if (!function_exists('spl_autoload_register')) { include_once 'Zend/Exception.php'; throw new Zend_Exception('spl_autoload does not exist in this PHP installation'); } self::loadClass($class); $methods = get_class_methods($class); if (!in_array('autoload', (array) $methods)) { include_once 'Zend/Exception.php'; throw new Zend_Exception("The class \"$class\" does not have an autoload() method"); } if ($enabled === true) { spl_autoload_register(array($class, 'autoload')); } else { spl_autoload_unregister(array($class, 'autoload')); } }
[ "public", "static", "function", "registerAutoload", "(", "$", "class", "=", "'Zend_Loader'", ",", "$", "enabled", "=", "true", ")", "{", "if", "(", "!", "function_exists", "(", "'spl_autoload_register'", ")", ")", "{", "include_once", "'Zend/Exception.php'", ";"...
Register {@link autoload()} with spl_autoload() @param string $class (optional) @param boolean $enabled (optional) @return void @throws Zend_Exception if spl_autoload() is not found or if the specified class does not have an autoload() method.
[ "Register", "{", "@link", "autoload", "()", "}", "with", "spl_autoload", "()" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Loader.php#L197-L216
krafthaus/bauhaus
src/KraftHaus/Bauhaus/Builder/ListBuilder.php
ListBuilder.build
public function build() { $listMapper = $this->getMapper(); $model = $this->getModel(); $items = $model::with([]); $primaryKey = (new $model)->getKeyName(); // Field ordering if (Input::has('_order_by')) { $items->orderBy(Input::get('_order_by'), Input::get('_order')); } // Field filters foreach (Input::all() as $key => $value) { if (empty($value) || substr($key, 0, 1) == '_' || $key == 'page') { continue; } $items->where($key, 'LIKE', '%' . $value . '%'); } // Result scopes if (Input::has('_scope')) { $items->{Input::get('_scope')}(); } $items = $items->paginate($listMapper->getAdmin()->getPerPage()); $this->setPaginator($items); $result = []; foreach ($items as $item) { $row = new ListResult; $row->setIdentifier($item->{$primaryKey}); foreach ($listMapper->getFields() as $field) { $clone = clone $field; $name = $clone->getName(); $value = $item->{$name}; if ($clone->hasBefore()) { $before = $clone->getBefore(); $value = $before($value); } if ($clone->isMultiple()) { $value = Value::decode(Config::get('bauhaus::admin.multiple-serializer'), $value); $value = implode(', ', $value); } $clone ->setContext(BaseField::CONTEXT_LIST) ->setRowId($item->{$primaryKey}) ->setValue($value); $row->addField($name, $clone); } $result[] = $row; } $this->setResult($result); }
php
public function build() { $listMapper = $this->getMapper(); $model = $this->getModel(); $items = $model::with([]); $primaryKey = (new $model)->getKeyName(); // Field ordering if (Input::has('_order_by')) { $items->orderBy(Input::get('_order_by'), Input::get('_order')); } // Field filters foreach (Input::all() as $key => $value) { if (empty($value) || substr($key, 0, 1) == '_' || $key == 'page') { continue; } $items->where($key, 'LIKE', '%' . $value . '%'); } // Result scopes if (Input::has('_scope')) { $items->{Input::get('_scope')}(); } $items = $items->paginate($listMapper->getAdmin()->getPerPage()); $this->setPaginator($items); $result = []; foreach ($items as $item) { $row = new ListResult; $row->setIdentifier($item->{$primaryKey}); foreach ($listMapper->getFields() as $field) { $clone = clone $field; $name = $clone->getName(); $value = $item->{$name}; if ($clone->hasBefore()) { $before = $clone->getBefore(); $value = $before($value); } if ($clone->isMultiple()) { $value = Value::decode(Config::get('bauhaus::admin.multiple-serializer'), $value); $value = implode(', ', $value); } $clone ->setContext(BaseField::CONTEXT_LIST) ->setRowId($item->{$primaryKey}) ->setValue($value); $row->addField($name, $clone); } $result[] = $row; } $this->setResult($result); }
[ "public", "function", "build", "(", ")", "{", "$", "listMapper", "=", "$", "this", "->", "getMapper", "(", ")", ";", "$", "model", "=", "$", "this", "->", "getModel", "(", ")", ";", "$", "items", "=", "$", "model", "::", "with", "(", "[", "]", ...
Build the list data. @access public @return mixed|void
[ "Build", "the", "list", "data", "." ]
train
https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Builder/ListBuilder.php#L45-L107
txj123/zilf
src/Zilf/Db/base/InlineAction.php
InlineAction.runWithParams
public function runWithParams($params) { $args = $this->controller->bindActionParams($this, $params); Log::debug('Running action: ' . get_class($this->controller) . '::' . $this->actionMethod . '()' . __METHOD__); if (Zilf::$app->requestedParams === null) { Zilf::$app->requestedParams = $args; } return call_user_func_array([$this->controller, $this->actionMethod], $args); }
php
public function runWithParams($params) { $args = $this->controller->bindActionParams($this, $params); Log::debug('Running action: ' . get_class($this->controller) . '::' . $this->actionMethod . '()' . __METHOD__); if (Zilf::$app->requestedParams === null) { Zilf::$app->requestedParams = $args; } return call_user_func_array([$this->controller, $this->actionMethod], $args); }
[ "public", "function", "runWithParams", "(", "$", "params", ")", "{", "$", "args", "=", "$", "this", "->", "controller", "->", "bindActionParams", "(", "$", "this", ",", "$", "params", ")", ";", "Log", "::", "debug", "(", "'Running action: '", ".", "get_c...
Runs this action with the specified parameters. This method is mainly invoked by the controller. @param array $params action parameters @return mixed the result of the action
[ "Runs", "this", "action", "with", "the", "specified", "parameters", ".", "This", "method", "is", "mainly", "invoked", "by", "the", "controller", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/InlineAction.php#L51-L60
txj123/zilf
src/Zilf/HttpFoundation/Session/Storage/MockArraySessionStorage.php
MockArraySessionStorage.clear
public function clear() { // clear out the bags foreach ($this->bags as $bag) { $bag->clear(); } // clear out the session $this->data = array(); // reconnect the bags to the session $this->loadSession(); }
php
public function clear() { // clear out the bags foreach ($this->bags as $bag) { $bag->clear(); } // clear out the session $this->data = array(); // reconnect the bags to the session $this->loadSession(); }
[ "public", "function", "clear", "(", ")", "{", "// clear out the bags", "foreach", "(", "$", "this", "->", "bags", "as", "$", "bag", ")", "{", "$", "bag", "->", "clear", "(", ")", ";", "}", "// clear out the session", "$", "this", "->", "data", "=", "ar...
{@inheritdoc}
[ "{" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/MockArraySessionStorage.php#L172-L184
krafthaus/bauhaus
src/KraftHaus/Bauhaus/Field/BelongsToManyField.php
BelongsToManyField.render
public function render() { if ($this->getDisplayField() === null) { throw new \InvalidArgumentException(sprintf('Please provide a display field for the `%s` relation.', $this->getName())); } switch ($this->getContext()) { case BaseField::CONTEXT_LIST: $baseModel = $this->getAdmin()->getModel(); $baseModel = new $baseModel; $relatedModel = $baseModel->{$this->getName()}()->getRelated(); $primaryKey = $relatedModel->getKeyName(); $values = []; foreach ($this->getValue() as $item) { $values[$item->{$primaryKey}] = $item->{$this->getDisplayField()}; } return implode(', ', $values); break; case BaseField::CONTEXT_FORM: $baseModel = $this->getAdmin()->getModel(); $baseModel = new $baseModel; $primaryKey = $baseModel->getKeyName(); $relatedModel = $baseModel->{$this->getName()}()->getRelated(); $items = []; foreach ($relatedModel::all() as $item) { $items[$item->{$primaryKey}] = $item->{$this->getDisplayField()}; } $id = $this->getAdmin()->getFormBuilder()->getIdentifier(); $values = []; if ($id !== null) { foreach ($baseModel::find($id)->{$relatedModel->getTable()} as $item) { $values[$item->{$primaryKey}] = $item->{$primaryKey}; } } return View::make('krafthaus/bauhaus::models.fields._belongs_to_many') ->with('field', $this) ->with('items', $items) ->with('values', $values); } }
php
public function render() { if ($this->getDisplayField() === null) { throw new \InvalidArgumentException(sprintf('Please provide a display field for the `%s` relation.', $this->getName())); } switch ($this->getContext()) { case BaseField::CONTEXT_LIST: $baseModel = $this->getAdmin()->getModel(); $baseModel = new $baseModel; $relatedModel = $baseModel->{$this->getName()}()->getRelated(); $primaryKey = $relatedModel->getKeyName(); $values = []; foreach ($this->getValue() as $item) { $values[$item->{$primaryKey}] = $item->{$this->getDisplayField()}; } return implode(', ', $values); break; case BaseField::CONTEXT_FORM: $baseModel = $this->getAdmin()->getModel(); $baseModel = new $baseModel; $primaryKey = $baseModel->getKeyName(); $relatedModel = $baseModel->{$this->getName()}()->getRelated(); $items = []; foreach ($relatedModel::all() as $item) { $items[$item->{$primaryKey}] = $item->{$this->getDisplayField()}; } $id = $this->getAdmin()->getFormBuilder()->getIdentifier(); $values = []; if ($id !== null) { foreach ($baseModel::find($id)->{$relatedModel->getTable()} as $item) { $values[$item->{$primaryKey}] = $item->{$primaryKey}; } } return View::make('krafthaus/bauhaus::models.fields._belongs_to_many') ->with('field', $this) ->with('items', $items) ->with('values', $values); } }
[ "public", "function", "render", "(", ")", "{", "if", "(", "$", "this", "->", "getDisplayField", "(", ")", "===", "null", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Please provide a display field for the `%s` relation.'", ","...
Render the field. @access public @return mixed|string
[ "Render", "the", "field", "." ]
train
https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Field/BelongsToManyField.php#L31-L79
damonjones/Vebra-PHP-API-Wrapper
lib/YDD/Vebra/API.php
API.getBranches
public function getBranches() { $branches = array(); $xml = $this->execute('branch'); foreach ($xml->branch as $xmlBranch) { $branch = new BranchSummary; $branch->setName(self::normalise($xmlBranch->name, 'string')); $branch->setFirmId(self::normalise($xmlBranch->firmid, 'int')); $branch->setBranchId(self::normalise($xmlBranch->branchid, 'int')); $branch->setUrl(self::normalise($xmlBranch->url, 'string')); $branches[] = $branch; } return $branches; }
php
public function getBranches() { $branches = array(); $xml = $this->execute('branch'); foreach ($xml->branch as $xmlBranch) { $branch = new BranchSummary; $branch->setName(self::normalise($xmlBranch->name, 'string')); $branch->setFirmId(self::normalise($xmlBranch->firmid, 'int')); $branch->setBranchId(self::normalise($xmlBranch->branchid, 'int')); $branch->setUrl(self::normalise($xmlBranch->url, 'string')); $branches[] = $branch; } return $branches; }
[ "public", "function", "getBranches", "(", ")", "{", "$", "branches", "=", "array", "(", ")", ";", "$", "xml", "=", "$", "this", "->", "execute", "(", "'branch'", ")", ";", "foreach", "(", "$", "xml", "->", "branch", "as", "$", "xmlBranch", ")", "{"...
get Branches @return array
[ "get", "Branches" ]
train
https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/API.php#L210-L226
damonjones/Vebra-PHP-API-Wrapper
lib/YDD/Vebra/API.php
API.getBranch
public function getBranch($clientId) { if (!is_int($clientId)) { throw new \InvalidArgumentException('Client ID must be an integer.'); } $xml = $this->execute(sprintf('branch/%s', $clientId)); $branch = new Branch; $branch->setClientId($clientId); $branch->setFirmId(self::normalise($xml{'FirmID'}, 'int')); $branch->setBranchId(self::normalise($xml->{'BranchID'}, 'int')); $branch->setName(self::normalise($xml->name, 'string')); $branch->setStreet(self::normalise($xml->street, 'string')); $branch->setTown(self::normalise($xml->town, 'string')); $branch->setCounty(self::normalise($xml->county, 'string')); $branch->setPostcode(self::normalise($xml->postcode, 'string')); $branch->setPhone(self::normalise($xml->phone, 'string')); $branch->setEmail(self::normalise($xml->email, 'string')); return $branch; }
php
public function getBranch($clientId) { if (!is_int($clientId)) { throw new \InvalidArgumentException('Client ID must be an integer.'); } $xml = $this->execute(sprintf('branch/%s', $clientId)); $branch = new Branch; $branch->setClientId($clientId); $branch->setFirmId(self::normalise($xml{'FirmID'}, 'int')); $branch->setBranchId(self::normalise($xml->{'BranchID'}, 'int')); $branch->setName(self::normalise($xml->name, 'string')); $branch->setStreet(self::normalise($xml->street, 'string')); $branch->setTown(self::normalise($xml->town, 'string')); $branch->setCounty(self::normalise($xml->county, 'string')); $branch->setPostcode(self::normalise($xml->postcode, 'string')); $branch->setPhone(self::normalise($xml->phone, 'string')); $branch->setEmail(self::normalise($xml->email, 'string')); return $branch; }
[ "public", "function", "getBranch", "(", "$", "clientId", ")", "{", "if", "(", "!", "is_int", "(", "$", "clientId", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Client ID must be an integer.'", ")", ";", "}", "$", "xml", "=", "$",...
get Branch @param int $clientId The client ID @throws \InvalidArgumentException @return Branch
[ "get", "Branch" ]
train
https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/API.php#L237-L258
damonjones/Vebra-PHP-API-Wrapper
lib/YDD/Vebra/API.php
API.getPropertyList
public function getPropertyList($clientId) { if (!is_int($clientId)) { throw new \InvalidArgumentException('Client ID must be an integer.'); } $properties = array(); $xml = $this->execute(sprintf('branch/%d/property', $clientId)); foreach ($xml->property as $xmlProperty) { $property = new PropertySummary; $property->setPropId(self::normalise($xmlProperty->{'prop_id'}, 'int')); $property->setLastChanged(self::normalise($xmlProperty->lastchanged, 'datetime')); $property->setUrl(self::normalise($xmlProperty->url, 'string')); $properties[] = $property; } return $properties; }
php
public function getPropertyList($clientId) { if (!is_int($clientId)) { throw new \InvalidArgumentException('Client ID must be an integer.'); } $properties = array(); $xml = $this->execute(sprintf('branch/%d/property', $clientId)); foreach ($xml->property as $xmlProperty) { $property = new PropertySummary; $property->setPropId(self::normalise($xmlProperty->{'prop_id'}, 'int')); $property->setLastChanged(self::normalise($xmlProperty->lastchanged, 'datetime')); $property->setUrl(self::normalise($xmlProperty->url, 'string')); $properties[] = $property; } return $properties; }
[ "public", "function", "getPropertyList", "(", "$", "clientId", ")", "{", "if", "(", "!", "is_int", "(", "$", "clientId", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Client ID must be an integer.'", ")", ";", "}", "$", "properties", ...
get PropertyList @param int $clientId The client ID @throws \InvalidArgumentException @return array
[ "get", "PropertyList" ]
train
https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/API.php#L269-L288
damonjones/Vebra-PHP-API-Wrapper
lib/YDD/Vebra/API.php
API.getProperty
public function getProperty($clientId, $propertyId) { if (!is_int($clientId)) { throw new \InvalidArgumentException('Client ID must be an integer.'); } if (!is_int($propertyId)) { throw new \InvalidArgumentException('Property ID must be an integer.'); } $xml = $this->execute(sprintf('branch/%d/property/%d', $clientId, $propertyId)); $property = new Property; $property->setAttributes($xml->attributes()); $property->setAgentReference(self::normalise($xml->reference->agents, 'string')); $address = new Address; $address ->setName(self::normalise($xml->address->name, 'string')) ->setStreet(self::normalise($xml->address->street, 'string')) ->setLocality(self::normalise($xml->address->locality, 'string')) ->setTown(self::normalise($xml->address->town, 'string')) ->setCounty(self::normalise($xml->address->county, 'string')) ->setPostcode(self::normalise($xml->address->postcode, 'string')) ->setCustomLocation(self::normalise($xml->address->custom_location, 'string')) ->setDisplay(self::normalise($xml->address->display, 'string')); $property->setAddress($address); $price = new Price(self::normalise($xml->price, 'int')); $price->setAttributes($xml->price->attributes()); $property->setPrice($price); $property->setRentalFees(self::normalise($xml->rentalfees, 'string')); $property->setLettingsFee(self::normalise($xml->lettingsfee, 'string')); $property->setRmQualifier(self::normalise($xml->{'rm_qualifier'}, 'int')); $property->setAvailable(self::normalise($xml->available, 'string')); $property->setUploaded(self::normalise($xml->uploaded, 'string')); $property->setLongitude(self::normalise($xml->longitude, 'float')); $property->setLatitude(self::normalise($xml->latitude, 'float')); $property->setEasting(self::normalise($xml->easting, 'int')); $property->setNorthing(self::normalise($xml->northing, 'int')); $property->setWebStatus(self::normalise($xml->{'web_status'}, 'int')); $property->setCustomStatus(self::normalise($xml->{'custom_status'}, 'string')); $property->setCommRent(self::normalise($xml->{'comm_rent'}, 'string')); $property->setPremium(self::normalise($xml->premium, 'string')); $property->setServiceCharge(self::normalise($xml->{'service_charge'}, 'string')); $property->setRateableValue(self::normalise($xml->{'rateable_value'}, 'string')); $property->setType(self::normalise($xml->type, 'string')); $property->setFurnished(self::normalise($xml->furnished, 'int')); $property->setRmType(self::normalise($xml->{'rm_type'}, 'int')); $property->setLetBond(self::normalise($xml->{'let_bond'}, 'int')); $property->setRmLetTypeId(self::normalise($xml->{'rm_let_type_id'}, 'int')); $property->setBedrooms(self::normalise($xml->bedrooms, 'int')); $property->setReceptions(self::normalise($xml->receptions, 'int')); $property->setBathrooms(self::normalise($xml->bathrooms, 'int')); $property->setUserField1(self::normalise($xml->userfield1, 'string')); $property->setUserField2(self::normalise($xml->userfield2, 'int')); $property->setSoldDate(self::normalise($xml->solddate, 'datetime')); $property->setLeaseEnd(self::normalise($xml->leaseend, 'datetime')); $property->setInstructed(self::normalise($xml->instructed, 'datetime')); $property->setSoldPrice(self::normalise($xml->soldprice, 'int')); $property->setGarden(self::normalise($xml->garden, 'boolean')); $property->setParking(self::normalise($xml->parking, 'boolean')); $property->setNewBuild(self::normalise($xml->newbuild, 'boolean')); $property->setGroundRent(self::normalise($xml->groundrent, 'string')); $property->setCommission(self::normalise($xml->commission, 'string')); if ($xml->landarea) { $landArea = new LandArea( self::normalise($xml->landarea->area, 'float') ); $landArea->setAttributes($xml->landarea->attributes()); $property->setLandArea($landArea); } $property->setStreetView( new StreetView( self::normalise($xml->streetview->pov_latitude, 'float'), self::normalise($xml->streetview->pov_longitude, 'float'), self::normalise($xml->streetview->pov_pitch, 'float'), self::normalise($xml->streetview->pov_heading, 'float'), self::normalise($xml->streetview->pov_zoom, 'int') ) ); $arr = array(); foreach ($xml->area as $a) { $area = new Area( self::normalise($a->min, 'float'), self::normalise($a->max, 'float') ); $area->setAttributes($a->attributes()); $arr[] = $area; } $property->setArea($arr); $property->setDescription(self::normalise($xml->description, 'string')); $property->setEnergyEfficiency( new EnergyRatingPair( self::normalise($xml->hip->energy_performance->energy_efficiency->current, 'int'), self::normalise($xml->hip->energy_performance->energy_efficiency->potential, 'int') ) ); $property->setEnvironmentalImpact( new EnergyRatingPair( self::normalise($xml->hip->energy_performance->environmental_impact->current, 'int'), self::normalise($xml->hip->energy_performance->environmental_impact->potential, 'int') ) ); $arr = array(); foreach ($xml->paragraphs->paragraph as $p) { $paragraph = new Paragraph; $paragraph->setName(self::normalise($p->name, 'string')); $paragraph->setFile(self::normalise($p->file->attributes()['ref'], 'int')); $paragraph->setDimension( new Dimension( self::normalise($p->dimensions->metric, 'string'), self::normalise($p->dimensions->imperial, 'string'), self::normalise($p->dimensions->mixed, 'string') ) ); $paragraph->setText(self::normalise($p->text, 'string')); $paragraph->setAttributes($p->attributes()); $arr[] = $paragraph; } $property->setParagraphs($arr); $arr = array(); foreach ($xml->bullets->bullet as $b) { $bullet = new Bullet(self::normalise($b, 'string')); $bullet->setAttributes($b->attributes()); $arr[$bullet->getAttribute('id')] = $bullet; } $property->setBullets($arr); $arr = array(); foreach ($xml->files->file as $f) { $file = new File; $file->setName(self::normalise($f->name, 'string')); $file->setUrl(self::normalise($f->url, 'string')); $file->setUpdated(self::normalise($f->updated, 'datetime')); $file->setAttributes($f->attributes()); $arr[$file->getAttribute('id')] = $file; } $property->setFiles($arr); return $property; }
php
public function getProperty($clientId, $propertyId) { if (!is_int($clientId)) { throw new \InvalidArgumentException('Client ID must be an integer.'); } if (!is_int($propertyId)) { throw new \InvalidArgumentException('Property ID must be an integer.'); } $xml = $this->execute(sprintf('branch/%d/property/%d', $clientId, $propertyId)); $property = new Property; $property->setAttributes($xml->attributes()); $property->setAgentReference(self::normalise($xml->reference->agents, 'string')); $address = new Address; $address ->setName(self::normalise($xml->address->name, 'string')) ->setStreet(self::normalise($xml->address->street, 'string')) ->setLocality(self::normalise($xml->address->locality, 'string')) ->setTown(self::normalise($xml->address->town, 'string')) ->setCounty(self::normalise($xml->address->county, 'string')) ->setPostcode(self::normalise($xml->address->postcode, 'string')) ->setCustomLocation(self::normalise($xml->address->custom_location, 'string')) ->setDisplay(self::normalise($xml->address->display, 'string')); $property->setAddress($address); $price = new Price(self::normalise($xml->price, 'int')); $price->setAttributes($xml->price->attributes()); $property->setPrice($price); $property->setRentalFees(self::normalise($xml->rentalfees, 'string')); $property->setLettingsFee(self::normalise($xml->lettingsfee, 'string')); $property->setRmQualifier(self::normalise($xml->{'rm_qualifier'}, 'int')); $property->setAvailable(self::normalise($xml->available, 'string')); $property->setUploaded(self::normalise($xml->uploaded, 'string')); $property->setLongitude(self::normalise($xml->longitude, 'float')); $property->setLatitude(self::normalise($xml->latitude, 'float')); $property->setEasting(self::normalise($xml->easting, 'int')); $property->setNorthing(self::normalise($xml->northing, 'int')); $property->setWebStatus(self::normalise($xml->{'web_status'}, 'int')); $property->setCustomStatus(self::normalise($xml->{'custom_status'}, 'string')); $property->setCommRent(self::normalise($xml->{'comm_rent'}, 'string')); $property->setPremium(self::normalise($xml->premium, 'string')); $property->setServiceCharge(self::normalise($xml->{'service_charge'}, 'string')); $property->setRateableValue(self::normalise($xml->{'rateable_value'}, 'string')); $property->setType(self::normalise($xml->type, 'string')); $property->setFurnished(self::normalise($xml->furnished, 'int')); $property->setRmType(self::normalise($xml->{'rm_type'}, 'int')); $property->setLetBond(self::normalise($xml->{'let_bond'}, 'int')); $property->setRmLetTypeId(self::normalise($xml->{'rm_let_type_id'}, 'int')); $property->setBedrooms(self::normalise($xml->bedrooms, 'int')); $property->setReceptions(self::normalise($xml->receptions, 'int')); $property->setBathrooms(self::normalise($xml->bathrooms, 'int')); $property->setUserField1(self::normalise($xml->userfield1, 'string')); $property->setUserField2(self::normalise($xml->userfield2, 'int')); $property->setSoldDate(self::normalise($xml->solddate, 'datetime')); $property->setLeaseEnd(self::normalise($xml->leaseend, 'datetime')); $property->setInstructed(self::normalise($xml->instructed, 'datetime')); $property->setSoldPrice(self::normalise($xml->soldprice, 'int')); $property->setGarden(self::normalise($xml->garden, 'boolean')); $property->setParking(self::normalise($xml->parking, 'boolean')); $property->setNewBuild(self::normalise($xml->newbuild, 'boolean')); $property->setGroundRent(self::normalise($xml->groundrent, 'string')); $property->setCommission(self::normalise($xml->commission, 'string')); if ($xml->landarea) { $landArea = new LandArea( self::normalise($xml->landarea->area, 'float') ); $landArea->setAttributes($xml->landarea->attributes()); $property->setLandArea($landArea); } $property->setStreetView( new StreetView( self::normalise($xml->streetview->pov_latitude, 'float'), self::normalise($xml->streetview->pov_longitude, 'float'), self::normalise($xml->streetview->pov_pitch, 'float'), self::normalise($xml->streetview->pov_heading, 'float'), self::normalise($xml->streetview->pov_zoom, 'int') ) ); $arr = array(); foreach ($xml->area as $a) { $area = new Area( self::normalise($a->min, 'float'), self::normalise($a->max, 'float') ); $area->setAttributes($a->attributes()); $arr[] = $area; } $property->setArea($arr); $property->setDescription(self::normalise($xml->description, 'string')); $property->setEnergyEfficiency( new EnergyRatingPair( self::normalise($xml->hip->energy_performance->energy_efficiency->current, 'int'), self::normalise($xml->hip->energy_performance->energy_efficiency->potential, 'int') ) ); $property->setEnvironmentalImpact( new EnergyRatingPair( self::normalise($xml->hip->energy_performance->environmental_impact->current, 'int'), self::normalise($xml->hip->energy_performance->environmental_impact->potential, 'int') ) ); $arr = array(); foreach ($xml->paragraphs->paragraph as $p) { $paragraph = new Paragraph; $paragraph->setName(self::normalise($p->name, 'string')); $paragraph->setFile(self::normalise($p->file->attributes()['ref'], 'int')); $paragraph->setDimension( new Dimension( self::normalise($p->dimensions->metric, 'string'), self::normalise($p->dimensions->imperial, 'string'), self::normalise($p->dimensions->mixed, 'string') ) ); $paragraph->setText(self::normalise($p->text, 'string')); $paragraph->setAttributes($p->attributes()); $arr[] = $paragraph; } $property->setParagraphs($arr); $arr = array(); foreach ($xml->bullets->bullet as $b) { $bullet = new Bullet(self::normalise($b, 'string')); $bullet->setAttributes($b->attributes()); $arr[$bullet->getAttribute('id')] = $bullet; } $property->setBullets($arr); $arr = array(); foreach ($xml->files->file as $f) { $file = new File; $file->setName(self::normalise($f->name, 'string')); $file->setUrl(self::normalise($f->url, 'string')); $file->setUpdated(self::normalise($f->updated, 'datetime')); $file->setAttributes($f->attributes()); $arr[$file->getAttribute('id')] = $file; } $property->setFiles($arr); return $property; }
[ "public", "function", "getProperty", "(", "$", "clientId", ",", "$", "propertyId", ")", "{", "if", "(", "!", "is_int", "(", "$", "clientId", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Client ID must be an integer.'", ")", ";", "}...
get Property @param int $clientId The client ID @param int $propertyId The property ID @throws \InvalidArgumentException @return Property
[ "get", "Property" ]
train
https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/API.php#L300-L453
damonjones/Vebra-PHP-API-Wrapper
lib/YDD/Vebra/API.php
API.getChangedProperties
public function getChangedProperties(\DateTime $date) { $properties = array(); $xml = $this->execute(sprintf('property/%s', $date->format('Y/m/d/H/i/s'))); foreach ($xml->property as $xmlProperty) { $property = new ChangedPropertySummary; $property->setPropId(self::normalise($xmlProperty->propid, 'int')); $property->setLastChanged(self::normalise($xmlProperty->lastchanged, 'datetime')); $property->setLastAction(self::normalise($xmlProperty->action, 'string')); $property->setUrl(self::normalise($xmlProperty->url, 'string')); $properties[] = $property; } return $properties; }
php
public function getChangedProperties(\DateTime $date) { $properties = array(); $xml = $this->execute(sprintf('property/%s', $date->format('Y/m/d/H/i/s'))); foreach ($xml->property as $xmlProperty) { $property = new ChangedPropertySummary; $property->setPropId(self::normalise($xmlProperty->propid, 'int')); $property->setLastChanged(self::normalise($xmlProperty->lastchanged, 'datetime')); $property->setLastAction(self::normalise($xmlProperty->action, 'string')); $property->setUrl(self::normalise($xmlProperty->url, 'string')); $properties[] = $property; } return $properties; }
[ "public", "function", "getChangedProperties", "(", "\\", "DateTime", "$", "date", ")", "{", "$", "properties", "=", "array", "(", ")", ";", "$", "xml", "=", "$", "this", "->", "execute", "(", "sprintf", "(", "'property/%s'", ",", "$", "date", "->", "fo...
get ChangedProperties @param \DateTime $date The changed date @return array
[ "get", "ChangedProperties" ]
train
https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/API.php#L462-L478
damonjones/Vebra-PHP-API-Wrapper
lib/YDD/Vebra/API.php
API.getChangedFiles
public function getChangedFiles(\DateTime $date) { $files = array(); $xml = $this->execute(sprintf('files/%s', $date->format('Y/m/d/H/i/s'))); foreach ($xml->file as $xmlFile) { $file = new ChangedFileSummary; $file->setFileId(self::normalise($xmlFile->{'file_id'}, 'int')); $file->setFilePropId(self::normalise($xmlFile->{'file_propid'}, 'int')); $file->setLastChanged(self::normalise($xmlFile->updated, 'datetime')); $file->setIsDeleted(self::normalise($xmlFile->deleted, 'bool')); $file->setUrl(self::normalise($xmlFile->url, 'string')); $file->setPropUrl(self::normalise($xmlFile->{'prop_url'}, 'string')); $files[] = $file; } return $files; }
php
public function getChangedFiles(\DateTime $date) { $files = array(); $xml = $this->execute(sprintf('files/%s', $date->format('Y/m/d/H/i/s'))); foreach ($xml->file as $xmlFile) { $file = new ChangedFileSummary; $file->setFileId(self::normalise($xmlFile->{'file_id'}, 'int')); $file->setFilePropId(self::normalise($xmlFile->{'file_propid'}, 'int')); $file->setLastChanged(self::normalise($xmlFile->updated, 'datetime')); $file->setIsDeleted(self::normalise($xmlFile->deleted, 'bool')); $file->setUrl(self::normalise($xmlFile->url, 'string')); $file->setPropUrl(self::normalise($xmlFile->{'prop_url'}, 'string')); $files[] = $file; } return $files; }
[ "public", "function", "getChangedFiles", "(", "\\", "DateTime", "$", "date", ")", "{", "$", "files", "=", "array", "(", ")", ";", "$", "xml", "=", "$", "this", "->", "execute", "(", "sprintf", "(", "'files/%s'", ",", "$", "date", "->", "format", "(",...
get ChangedFiles @param \DateTime $date The changed date @return array
[ "get", "ChangedFiles" ]
train
https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/API.php#L487-L505
damonjones/Vebra-PHP-API-Wrapper
lib/YDD/Vebra/API.php
API.normalise
protected static function normalise($xml, $cast = null) { if (!$xml || empty($xml)) { return null; } switch (strtolower($cast)) { case 'string': return (string) $xml; case 'integer': case 'int': return (int) $xml; case 'float': return (float) $xml; case 'boolean': case 'bool': return (string) $xml === 'true'; case 'datetime': return new \DateTime((string) $xml); default: return $xml; } }
php
protected static function normalise($xml, $cast = null) { if (!$xml || empty($xml)) { return null; } switch (strtolower($cast)) { case 'string': return (string) $xml; case 'integer': case 'int': return (int) $xml; case 'float': return (float) $xml; case 'boolean': case 'bool': return (string) $xml === 'true'; case 'datetime': return new \DateTime((string) $xml); default: return $xml; } }
[ "protected", "static", "function", "normalise", "(", "$", "xml", ",", "$", "cast", "=", "null", ")", "{", "if", "(", "!", "$", "xml", "||", "empty", "(", "$", "xml", ")", ")", "{", "return", "null", ";", "}", "switch", "(", "strtolower", "(", "$"...
normalise @param \SimpleXMLElement $xml The xml element @param string $cast The type to cast to @return mixed
[ "normalise" ]
train
https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/API.php#L515-L537
txj123/zilf
src/Zilf/Db/pgsql/QueryBuilder.php
QueryBuilder.alterColumn
public function alterColumn($table, $column, $type) { // https://github.com/Zilfsoft/Zilf2/issues/4492 // http://www.postgresql.org/docs/9.1/static/sql-altertable.html if (!preg_match('/^(DROP|SET|RESET)\s+/i', $type)) { $type = 'TYPE ' . $this->getColumnType($type); } return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ALTER COLUMN ' . $this->db->quoteColumnName($column) . ' ' . $type; }
php
public function alterColumn($table, $column, $type) { // https://github.com/Zilfsoft/Zilf2/issues/4492 // http://www.postgresql.org/docs/9.1/static/sql-altertable.html if (!preg_match('/^(DROP|SET|RESET)\s+/i', $type)) { $type = 'TYPE ' . $this->getColumnType($type); } return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ALTER COLUMN ' . $this->db->quoteColumnName($column) . ' ' . $type; }
[ "public", "function", "alterColumn", "(", "$", "table", ",", "$", "column", ",", "$", "type", ")", "{", "// https://github.com/Zilfsoft/Zilf2/issues/4492", "// http://www.postgresql.org/docs/9.1/static/sql-altertable.html", "if", "(", "!", "preg_match", "(", "'/^(DROP|SET|R...
Builds a SQL statement for changing the definition of a column. @param string $table the table whose column is to be changed. The table name will be properly quoted by the method. @param string $column the name of the column to be changed. The name will be properly quoted by the method. @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`. @return string the SQL statement for changing the definition of a column.
[ "Builds", "a", "SQL", "statement", "for", "changing", "the", "definition", "of", "a", "column", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/pgsql/QueryBuilder.php#L269-L279
txj123/zilf
src/Zilf/Db/pgsql/QueryBuilder.php
QueryBuilder.oldUpsert
private function oldUpsert($table, $insertColumns, $updateColumns, &$params) { /** * @var Constraint[] $constraints */ list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints); if (empty($uniqueNames)) { return $this->insert($table, $insertColumns, $params); } /** * @var Schema $schema */ $schema = $this->db->getSchema(); if (!$insertColumns instanceof Query) { $tableSchema = $schema->getTableSchema($table); $columnSchemas = $tableSchema !== null ? $tableSchema->columns : []; foreach ($insertColumns as $name => $value) { // NULLs and numeric values must be type hinted in order to be used in SET assigments // NVM, let's cast them all if (isset($columnSchemas[$name])) { $phName = self::PARAM_PREFIX . count($params); $params[$phName] = $value; $insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->dbType})"); } } } list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params); $updateCondition = ['or']; $insertCondition = ['or']; $quotedTableName = $schema->quoteTableName($table); foreach ($constraints as $constraint) { $constraintUpdateCondition = ['and']; $constraintInsertCondition = ['and']; foreach ($constraint->columnNames as $name) { $quotedName = $schema->quoteColumnName($name); $constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName"; $constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName"; } $updateCondition[] = $constraintUpdateCondition; $insertCondition[] = $constraintInsertCondition; } $withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames) . ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')'; if ($updateColumns === false) { $selectSubQuery = (new Query()) ->select(new Expression('1')) ->from($table) ->where($updateCondition); $insertSelectSubQuery = (new Query()) ->select($insertNames) ->from('EXCLUDED') ->where(['not exists', $selectSubQuery]); $insertSql = $this->insert($table, $insertSelectSubQuery, $params); return "$withSql $insertSql"; } if ($updateColumns === true) { $updateColumns = []; foreach ($updateNames as $name) { $quotedName = $this->db->quoteColumnName($name); if (strrpos($quotedName, '.') === false) { $quotedName = '"EXCLUDED".' . $quotedName; } $updateColumns[$name] = new Expression($quotedName); } } list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params); $updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates) . ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params) . ' RETURNING ' . $this->db->quoteTableName($table) .'.*'; $selectUpsertSubQuery = (new Query()) ->select(new Expression('1')) ->from('upsert') ->where($insertCondition); $insertSelectSubQuery = (new Query()) ->select($insertNames) ->from('EXCLUDED') ->where(['not exists', $selectUpsertSubQuery]); $insertSql = $this->insert($table, $insertSelectSubQuery, $params); return "$withSql, \"upsert\" AS ($updateSql) $insertSql"; }
php
private function oldUpsert($table, $insertColumns, $updateColumns, &$params) { /** * @var Constraint[] $constraints */ list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints); if (empty($uniqueNames)) { return $this->insert($table, $insertColumns, $params); } /** * @var Schema $schema */ $schema = $this->db->getSchema(); if (!$insertColumns instanceof Query) { $tableSchema = $schema->getTableSchema($table); $columnSchemas = $tableSchema !== null ? $tableSchema->columns : []; foreach ($insertColumns as $name => $value) { // NULLs and numeric values must be type hinted in order to be used in SET assigments // NVM, let's cast them all if (isset($columnSchemas[$name])) { $phName = self::PARAM_PREFIX . count($params); $params[$phName] = $value; $insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->dbType})"); } } } list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params); $updateCondition = ['or']; $insertCondition = ['or']; $quotedTableName = $schema->quoteTableName($table); foreach ($constraints as $constraint) { $constraintUpdateCondition = ['and']; $constraintInsertCondition = ['and']; foreach ($constraint->columnNames as $name) { $quotedName = $schema->quoteColumnName($name); $constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName"; $constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName"; } $updateCondition[] = $constraintUpdateCondition; $insertCondition[] = $constraintInsertCondition; } $withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames) . ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')'; if ($updateColumns === false) { $selectSubQuery = (new Query()) ->select(new Expression('1')) ->from($table) ->where($updateCondition); $insertSelectSubQuery = (new Query()) ->select($insertNames) ->from('EXCLUDED') ->where(['not exists', $selectSubQuery]); $insertSql = $this->insert($table, $insertSelectSubQuery, $params); return "$withSql $insertSql"; } if ($updateColumns === true) { $updateColumns = []; foreach ($updateNames as $name) { $quotedName = $this->db->quoteColumnName($name); if (strrpos($quotedName, '.') === false) { $quotedName = '"EXCLUDED".' . $quotedName; } $updateColumns[$name] = new Expression($quotedName); } } list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params); $updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates) . ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params) . ' RETURNING ' . $this->db->quoteTableName($table) .'.*'; $selectUpsertSubQuery = (new Query()) ->select(new Expression('1')) ->from('upsert') ->where($insertCondition); $insertSelectSubQuery = (new Query()) ->select($insertNames) ->from('EXCLUDED') ->where(['not exists', $selectUpsertSubQuery]); $insertSql = $this->insert($table, $insertSelectSubQuery, $params); return "$withSql, \"upsert\" AS ($updateSql) $insertSql"; }
[ "private", "function", "oldUpsert", "(", "$", "table", ",", "$", "insertColumns", ",", "$", "updateColumns", ",", "&", "$", "params", ")", "{", "/**\n * @var Constraint[] $constraints \n*/", "list", "(", "$", "uniqueNames", ",", "$", "insertNames", ",", "$", "...
[[upsert()]] implementation for PostgreSQL older than 9.5. @param string $table @param array|Query $insertColumns @param array|bool $updateColumns @param array $params @return string
[ "[[", "upsert", "()", "]]", "implementation", "for", "PostgreSQL", "older", "than", "9", ".", "5", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/pgsql/QueryBuilder.php#L348-L429
dave-redfern/laravel-doctrine-tenancy
src/Twig/TenantExtension.php
TenantExtension.getFunctions
public function getFunctions() { return [ new Twig_SimpleFunction('current_tenant_owner_id', [$this->tenant, 'getTenantOwnerId']), new Twig_SimpleFunction('current_tenant_creator_id', [$this->tenant, 'getTenantCreatorId']), new Twig_SimpleFunction('current_tenant_owner', [$this->tenant, 'getTenantOwner']), new Twig_SimpleFunction('current_tenant_creator', [$this->tenant, 'getTenantCreator']), new Twig_SimpleFunction('current_tenant_security_model', [$this->tenant, 'getSecurityModel']), ]; }
php
public function getFunctions() { return [ new Twig_SimpleFunction('current_tenant_owner_id', [$this->tenant, 'getTenantOwnerId']), new Twig_SimpleFunction('current_tenant_creator_id', [$this->tenant, 'getTenantCreatorId']), new Twig_SimpleFunction('current_tenant_owner', [$this->tenant, 'getTenantOwner']), new Twig_SimpleFunction('current_tenant_creator', [$this->tenant, 'getTenantCreator']), new Twig_SimpleFunction('current_tenant_security_model', [$this->tenant, 'getSecurityModel']), ]; }
[ "public", "function", "getFunctions", "(", ")", "{", "return", "[", "new", "Twig_SimpleFunction", "(", "'current_tenant_owner_id'", ",", "[", "$", "this", "->", "tenant", ",", "'getTenantOwnerId'", "]", ")", ",", "new", "Twig_SimpleFunction", "(", "'current_tenant...
{@inheritDoc}
[ "{" ]
train
https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Twig/TenantExtension.php#L64-L73
krafthaus/bauhaus
src/commands/ViewsExportCommand.php
ViewsExportCommand.fire
public function fire() { $source = realpath(__DIR__ . '/../views'); $destination = app_path('views/bauhaus'); File::copyDirectory($source, $destination); $this->info(sprintf('Views exported to `%s`', $destination)); }
php
public function fire() { $source = realpath(__DIR__ . '/../views'); $destination = app_path('views/bauhaus'); File::copyDirectory($source, $destination); $this->info(sprintf('Views exported to `%s`', $destination)); }
[ "public", "function", "fire", "(", ")", "{", "$", "source", "=", "realpath", "(", "__DIR__", ".", "'/../views'", ")", ";", "$", "destination", "=", "app_path", "(", "'views/bauhaus'", ")", ";", "File", "::", "copyDirectory", "(", "$", "source", ",", "$",...
Execute the console command. @access public @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/commands/ViewsExportCommand.php#L46-L54
txj123/zilf
src/Zilf/Db/base/Application.php
Application.bootstrap
protected function bootstrap() { if ($this->extensions === null) { $file = Zilf::getAlias('@vendor/Zilfsoft/extensions.php'); $this->extensions = is_file($file) ? include $file : []; } foreach ($this->extensions as $extension) { if (!empty($extension['alias'])) { foreach ($extension['alias'] as $name => $path) { Zilf::setAlias($name, $path); } } if (isset($extension['bootstrap'])) { $component = Zilf::createObject($extension['bootstrap']); if ($component instanceof BootstrapInterface) { Zilf::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__); $component->bootstrap($this); } else { Zilf::debug('Bootstrap with ' . get_class($component), __METHOD__); } } } foreach ($this->bootstrap as $mixed) { $component = null; if ($mixed instanceof \Closure) { Zilf::debug('Bootstrap with Closure', __METHOD__); if (!$component = call_user_func($mixed, $this)) { continue; } } elseif (is_string($mixed)) { if ($this->has($mixed)) { $component = $this->get($mixed); } elseif ($this->hasModule($mixed)) { $component = $this->getModule($mixed); } elseif (strpos($mixed, '\\') === false) { throw new InvalidConfigException("Unknown bootstrapping component ID: $mixed"); } } if (!isset($component)) { $component = Zilf::createObject($mixed); } if ($component instanceof BootstrapInterface) { Zilf::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__); $component->bootstrap($this); } else { Zilf::debug('Bootstrap with ' . get_class($component), __METHOD__); } } }
php
protected function bootstrap() { if ($this->extensions === null) { $file = Zilf::getAlias('@vendor/Zilfsoft/extensions.php'); $this->extensions = is_file($file) ? include $file : []; } foreach ($this->extensions as $extension) { if (!empty($extension['alias'])) { foreach ($extension['alias'] as $name => $path) { Zilf::setAlias($name, $path); } } if (isset($extension['bootstrap'])) { $component = Zilf::createObject($extension['bootstrap']); if ($component instanceof BootstrapInterface) { Zilf::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__); $component->bootstrap($this); } else { Zilf::debug('Bootstrap with ' . get_class($component), __METHOD__); } } } foreach ($this->bootstrap as $mixed) { $component = null; if ($mixed instanceof \Closure) { Zilf::debug('Bootstrap with Closure', __METHOD__); if (!$component = call_user_func($mixed, $this)) { continue; } } elseif (is_string($mixed)) { if ($this->has($mixed)) { $component = $this->get($mixed); } elseif ($this->hasModule($mixed)) { $component = $this->getModule($mixed); } elseif (strpos($mixed, '\\') === false) { throw new InvalidConfigException("Unknown bootstrapping component ID: $mixed"); } } if (!isset($component)) { $component = Zilf::createObject($mixed); } if ($component instanceof BootstrapInterface) { Zilf::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__); $component->bootstrap($this); } else { Zilf::debug('Bootstrap with ' . get_class($component), __METHOD__); } } }
[ "protected", "function", "bootstrap", "(", ")", "{", "if", "(", "$", "this", "->", "extensions", "===", "null", ")", "{", "$", "file", "=", "Zilf", "::", "getAlias", "(", "'@vendor/Zilfsoft/extensions.php'", ")", ";", "$", "this", "->", "extensions", "=", ...
Initializes extensions and executes bootstrap components. This method is called by [[init()]] after the application has been fully configured. If you override this method, make sure you also call the parent implementation.
[ "Initializes", "extensions", "and", "executes", "bootstrap", "components", ".", "This", "method", "is", "called", "by", "[[", "init", "()", "]]", "after", "the", "application", "has", "been", "fully", "configured", ".", "If", "you", "override", "this", "method...
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/Application.php#L283-L334
txj123/zilf
src/Zilf/Db/base/Application.php
Application.registerErrorHandler
protected function registerErrorHandler(&$config) { if (Zilf_ENABLE_ERROR_HANDLER) { if (!isset($config['components']['errorHandler']['class'])) { echo "Error: no errorHandler component is configured.\n"; exit(1); } $this->set('errorHandler', $config['components']['errorHandler']); unset($config['components']['errorHandler']); $this->getErrorHandler()->register(); } }
php
protected function registerErrorHandler(&$config) { if (Zilf_ENABLE_ERROR_HANDLER) { if (!isset($config['components']['errorHandler']['class'])) { echo "Error: no errorHandler component is configured.\n"; exit(1); } $this->set('errorHandler', $config['components']['errorHandler']); unset($config['components']['errorHandler']); $this->getErrorHandler()->register(); } }
[ "protected", "function", "registerErrorHandler", "(", "&", "$", "config", ")", "{", "if", "(", "Zilf_ENABLE_ERROR_HANDLER", ")", "{", "if", "(", "!", "isset", "(", "$", "config", "[", "'components'", "]", "[", "'errorHandler'", "]", "[", "'class'", "]", ")...
Registers the errorHandler component as a PHP error handler. @param array $config application config
[ "Registers", "the", "errorHandler", "component", "as", "a", "PHP", "error", "handler", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/Application.php#L341-L352
txj123/zilf
src/Zilf/Db/base/Application.php
Application.setRuntimePath
public function setRuntimePath($path) { $this->_runtimePath = Zilf::getAlias($path); Zilf::setAlias('@runtime', $this->_runtimePath); }
php
public function setRuntimePath($path) { $this->_runtimePath = Zilf::getAlias($path); Zilf::setAlias('@runtime', $this->_runtimePath); }
[ "public", "function", "setRuntimePath", "(", "$", "path", ")", "{", "$", "this", "->", "_runtimePath", "=", "Zilf", "::", "getAlias", "(", "$", "path", ")", ";", "Zilf", "::", "setAlias", "(", "'@runtime'", ",", "$", "this", "->", "_runtimePath", ")", ...
Sets the directory that stores runtime files. @param string $path the directory that stores runtime files.
[ "Sets", "the", "directory", "that", "stores", "runtime", "files", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/Application.php#L442-L446
txj123/zilf
src/Zilf/Db/base/Application.php
Application.setVendorPath
public function setVendorPath($path) { $this->_vendorPath = Zilf::getAlias($path); Zilf::setAlias('@vendor', $this->_vendorPath); Zilf::setAlias('@bower', $this->_vendorPath . DIRECTORY_SEPARATOR . 'bower'); Zilf::setAlias('@npm', $this->_vendorPath . DIRECTORY_SEPARATOR . 'npm'); }
php
public function setVendorPath($path) { $this->_vendorPath = Zilf::getAlias($path); Zilf::setAlias('@vendor', $this->_vendorPath); Zilf::setAlias('@bower', $this->_vendorPath . DIRECTORY_SEPARATOR . 'bower'); Zilf::setAlias('@npm', $this->_vendorPath . DIRECTORY_SEPARATOR . 'npm'); }
[ "public", "function", "setVendorPath", "(", "$", "path", ")", "{", "$", "this", "->", "_vendorPath", "=", "Zilf", "::", "getAlias", "(", "$", "path", ")", ";", "Zilf", "::", "setAlias", "(", "'@vendor'", ",", "$", "this", "->", "_vendorPath", ")", ";",...
Sets the directory that stores vendor files. @param string $path the directory that stores vendor files.
[ "Sets", "the", "directory", "that", "stores", "vendor", "files", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/Application.php#L470-L476
railken/search-query
src/Languages/BoomTree/Resolvers/AndResolver.php
AndResolver.resolvePreviousNode
public function resolvePreviousNode(NodeContract $node, NodeContract $new_node) { if ($new_node->prev() !== null) { $new_node->moveNodeAsChild($new_node->prev()); } else { throw new Exceptions\QuerySyntaxException($node->getRoot()->getValue()); } }
php
public function resolvePreviousNode(NodeContract $node, NodeContract $new_node) { if ($new_node->prev() !== null) { $new_node->moveNodeAsChild($new_node->prev()); } else { throw new Exceptions\QuerySyntaxException($node->getRoot()->getValue()); } }
[ "public", "function", "resolvePreviousNode", "(", "NodeContract", "$", "node", ",", "NodeContract", "$", "new_node", ")", "{", "if", "(", "$", "new_node", "->", "prev", "(", ")", "!==", "null", ")", "{", "$", "new_node", "->", "moveNodeAsChild", "(", "$", ...
Resolve previous node match. @param NodeContract $node @param NodeContract $new_node
[ "Resolve", "previous", "node", "match", "." ]
train
https://github.com/railken/search-query/blob/06e1bfb3eb59347afec9ca764d6f8c3b691d6889/src/Languages/BoomTree/Resolvers/AndResolver.php#L34-L41
railken/search-query
src/Languages/BoomTree/Resolvers/AndResolver.php
AndResolver.resolveRelationsNode
public function resolveRelationsNode(NodeContract $node, NodeContract $new_node) { $this->resolvePreviousNode($node, $new_node); $this->resolveNextNode($node, $new_node); $this->resolveGroupParent($node, $new_node); }
php
public function resolveRelationsNode(NodeContract $node, NodeContract $new_node) { $this->resolvePreviousNode($node, $new_node); $this->resolveNextNode($node, $new_node); $this->resolveGroupParent($node, $new_node); }
[ "public", "function", "resolveRelationsNode", "(", "NodeContract", "$", "node", ",", "NodeContract", "$", "new_node", ")", "{", "$", "this", "->", "resolvePreviousNode", "(", "$", "node", ",", "$", "new_node", ")", ";", "$", "this", "->", "resolveNextNode", ...
Resolve node relations with other nodes. @param NodeContract $node @param NodeContract $new_node
[ "Resolve", "node", "relations", "with", "other", "nodes", "." ]
train
https://github.com/railken/search-query/blob/06e1bfb3eb59347afec9ca764d6f8c3b691d6889/src/Languages/BoomTree/Resolvers/AndResolver.php#L64-L69
railken/search-query
src/Languages/BoomTree/Resolvers/AndResolver.php
AndResolver.resolveGroupParent
public function resolveGroupParent(NodeContract $node, NodeContract $new_node) { foreach ($new_node->getChildren() as $child) { if (get_class($child) === $this->node) { $new_node->replaceChild($child->getIndex(), $child->getChildren()); } } if ($new_node->getParent() instanceof Nodes\GroupNode && $new_node->getParent()->countChildren() === 1 && $new_node->getParent()->getParent() !== null) { $new_node->swapParentAndDelete($new_node->getParent(), $new_node->getParent()->getParent()); } }
php
public function resolveGroupParent(NodeContract $node, NodeContract $new_node) { foreach ($new_node->getChildren() as $child) { if (get_class($child) === $this->node) { $new_node->replaceChild($child->getIndex(), $child->getChildren()); } } if ($new_node->getParent() instanceof Nodes\GroupNode && $new_node->getParent()->countChildren() === 1 && $new_node->getParent()->getParent() !== null) { $new_node->swapParentAndDelete($new_node->getParent(), $new_node->getParent()->getParent()); } }
[ "public", "function", "resolveGroupParent", "(", "NodeContract", "$", "node", ",", "NodeContract", "$", "new_node", ")", "{", "foreach", "(", "$", "new_node", "->", "getChildren", "(", ")", "as", "$", "child", ")", "{", "if", "(", "get_class", "(", "$", ...
Resolve node relations with other nodes. @param NodeContract $node @param NodeContract $new_node
[ "Resolve", "node", "relations", "with", "other", "nodes", "." ]
train
https://github.com/railken/search-query/blob/06e1bfb3eb59347afec9ca764d6f8c3b691d6889/src/Languages/BoomTree/Resolvers/AndResolver.php#L77-L88
txj123/zilf
src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Hostname.php
Zend_Validate_Hostname.isValid
public function isValid($value) { $valueString = (string) $value; $this->_setValue($valueString); // Check input against IP address schema if ($this->_ipValidator->setTranslator($this->getTranslator())->isValid($valueString)) { if (!($this->_allow & self::ALLOW_IP)) { $this->_error(self::IP_ADDRESS_NOT_ALLOWED); return false; } else{ return true; } } // Check input against DNS hostname schema $domainParts = explode('.', $valueString); if ((count($domainParts) > 1) && (strlen($valueString) >= 4) && (strlen($valueString) <= 254)) { $status = false; do { // First check TLD if (preg_match('/([a-z]{2,10})$/i', end($domainParts), $matches)) { reset($domainParts); // Hostname characters are: *(label dot)(label dot label); max 254 chars // label: id-prefix [*ldh{61} id-prefix]; max 63 chars // id-prefix: alpha / digit // ldh: alpha / digit / dash // Match TLD against known list $this->_tld = strtolower($matches[1]); if ($this->_validateTld) { if (!in_array($this->_tld, $this->_validTlds)) { $this->_error(self::UNKNOWN_TLD); $status = false; break; } } /** * Match against IDN hostnames * * @see Zend_Validate_Hostname_Interface */ $labelChars = 'a-z0-9'; $utf8 = false; $classFile = 'Zend/Validate/Hostname/' . ucfirst($this->_tld) . '.php'; if ($this->_validateIdn) { if (Zend_Loader::isReadable($classFile)) { // Load additional characters $className = 'Zend_Validate_Hostname_' . ucfirst($this->_tld); Zend_Loader::loadClass($className); $labelChars .= call_user_func(array($className, 'getCharacters')); $utf8 = true; } } // Keep label regex short to avoid issues with long patterns when matching IDN hostnames $regexLabel = '/^[' . $labelChars . '\x2d]{1,63}$/i'; if ($utf8) { $regexLabel .= 'u'; } // Check each hostname part $valid = true; foreach ($domainParts as $domainPart) { // Check dash (-) does not start, end or appear in 3rd and 4th positions if (strpos($domainPart, '-') === 0 || (strlen($domainPart) > 2 && strpos($domainPart, '-', 2) == 2 && strpos($domainPart, '-', 3) == 3) || strrpos($domainPart, '-') === strlen($domainPart) - 1 ) { $this->_error(self::INVALID_DASH); $status = false; break 2; } // Check each domain part $status = @preg_match($regexLabel, $domainPart); if ($status === false) { /** * Regex error * * @see Zend_Validate_Exception */ include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Internal error: DNS validation failed'); } elseif ($status === 0) { $valid = false; } } // If all labels didn't match, the hostname is invalid if (!$valid) { $this->_error(self::INVALID_HOSTNAME_SCHEMA); $status = false; } } else { // Hostname not long enough $this->_error(self::UNDECIPHERABLE_TLD); $status = false; } } while (false); // If the input passes as an Internet domain name, and domain names are allowed, then the hostname // passes validation if ($status && ($this->_allow & self::ALLOW_DNS)) { return true; } } else { $this->_error(self::INVALID_HOSTNAME); } // Check input against local network name schema; last chance to pass validation $regexLocal = '/^(([a-zA-Z0-9\x2d]{1,63}\x2e)*[a-zA-Z0-9\x2d]{1,63}){1,254}$/'; $status = @preg_match($regexLocal, $valueString); if (false === $status) { /** * Regex error * * @see Zend_Validate_Exception */ include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Internal error: local network name validation failed'); } // If the input passes as a local network name, and local network names are allowed, then the // hostname passes validation $allowLocal = $this->_allow & self::ALLOW_LOCAL; if ($status && $allowLocal) { return true; } // If the input does not pass as a local network name, add a message if (!$status) { $this->_error(self::INVALID_LOCAL_NAME); } // If local network names are not allowed, add a message if ($status && !$allowLocal) { $this->_error(self::LOCAL_NAME_NOT_ALLOWED); } return false; }
php
public function isValid($value) { $valueString = (string) $value; $this->_setValue($valueString); // Check input against IP address schema if ($this->_ipValidator->setTranslator($this->getTranslator())->isValid($valueString)) { if (!($this->_allow & self::ALLOW_IP)) { $this->_error(self::IP_ADDRESS_NOT_ALLOWED); return false; } else{ return true; } } // Check input against DNS hostname schema $domainParts = explode('.', $valueString); if ((count($domainParts) > 1) && (strlen($valueString) >= 4) && (strlen($valueString) <= 254)) { $status = false; do { // First check TLD if (preg_match('/([a-z]{2,10})$/i', end($domainParts), $matches)) { reset($domainParts); // Hostname characters are: *(label dot)(label dot label); max 254 chars // label: id-prefix [*ldh{61} id-prefix]; max 63 chars // id-prefix: alpha / digit // ldh: alpha / digit / dash // Match TLD against known list $this->_tld = strtolower($matches[1]); if ($this->_validateTld) { if (!in_array($this->_tld, $this->_validTlds)) { $this->_error(self::UNKNOWN_TLD); $status = false; break; } } /** * Match against IDN hostnames * * @see Zend_Validate_Hostname_Interface */ $labelChars = 'a-z0-9'; $utf8 = false; $classFile = 'Zend/Validate/Hostname/' . ucfirst($this->_tld) . '.php'; if ($this->_validateIdn) { if (Zend_Loader::isReadable($classFile)) { // Load additional characters $className = 'Zend_Validate_Hostname_' . ucfirst($this->_tld); Zend_Loader::loadClass($className); $labelChars .= call_user_func(array($className, 'getCharacters')); $utf8 = true; } } // Keep label regex short to avoid issues with long patterns when matching IDN hostnames $regexLabel = '/^[' . $labelChars . '\x2d]{1,63}$/i'; if ($utf8) { $regexLabel .= 'u'; } // Check each hostname part $valid = true; foreach ($domainParts as $domainPart) { // Check dash (-) does not start, end or appear in 3rd and 4th positions if (strpos($domainPart, '-') === 0 || (strlen($domainPart) > 2 && strpos($domainPart, '-', 2) == 2 && strpos($domainPart, '-', 3) == 3) || strrpos($domainPart, '-') === strlen($domainPart) - 1 ) { $this->_error(self::INVALID_DASH); $status = false; break 2; } // Check each domain part $status = @preg_match($regexLabel, $domainPart); if ($status === false) { /** * Regex error * * @see Zend_Validate_Exception */ include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Internal error: DNS validation failed'); } elseif ($status === 0) { $valid = false; } } // If all labels didn't match, the hostname is invalid if (!$valid) { $this->_error(self::INVALID_HOSTNAME_SCHEMA); $status = false; } } else { // Hostname not long enough $this->_error(self::UNDECIPHERABLE_TLD); $status = false; } } while (false); // If the input passes as an Internet domain name, and domain names are allowed, then the hostname // passes validation if ($status && ($this->_allow & self::ALLOW_DNS)) { return true; } } else { $this->_error(self::INVALID_HOSTNAME); } // Check input against local network name schema; last chance to pass validation $regexLocal = '/^(([a-zA-Z0-9\x2d]{1,63}\x2e)*[a-zA-Z0-9\x2d]{1,63}){1,254}$/'; $status = @preg_match($regexLocal, $valueString); if (false === $status) { /** * Regex error * * @see Zend_Validate_Exception */ include_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Internal error: local network name validation failed'); } // If the input passes as a local network name, and local network names are allowed, then the // hostname passes validation $allowLocal = $this->_allow & self::ALLOW_LOCAL; if ($status && $allowLocal) { return true; } // If the input does not pass as a local network name, add a message if (!$status) { $this->_error(self::INVALID_LOCAL_NAME); } // If local network names are not allowed, add a message if ($status && !$allowLocal) { $this->_error(self::LOCAL_NAME_NOT_ALLOWED); } return false; }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "$", "valueString", "=", "(", "string", ")", "$", "value", ";", "$", "this", "->", "_setValue", "(", "$", "valueString", ")", ";", "// Check input against IP address schema", "if", "(", "$", "th...
Defined by Zend_Validate_Interface Returns true if and only if the $value is a valid hostname with respect to the current allow option @param string $value @throws Zend_Validate_Exception if a fatal error occurs for validation process @return boolean
[ "Defined", "by", "Zend_Validate_Interface" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Hostname.php#L277-L427
txj123/zilf
src/Zilf/System/Bootstrap/LoadConfiguration.php
LoadConfiguration.bootstrap
public function bootstrap() { $config = Zilf::$container->getShare('config'); $this->loadConfigurationFiles($config); Zilf::$app->environment = $config->get('app.app_env'); date_default_timezone_set($config->get('app.timezone', 'UTC')); mb_internal_encoding('UTF-8'); }
php
public function bootstrap() { $config = Zilf::$container->getShare('config'); $this->loadConfigurationFiles($config); Zilf::$app->environment = $config->get('app.app_env'); date_default_timezone_set($config->get('app.timezone', 'UTC')); mb_internal_encoding('UTF-8'); }
[ "public", "function", "bootstrap", "(", ")", "{", "$", "config", "=", "Zilf", "::", "$", "container", "->", "getShare", "(", "'config'", ")", ";", "$", "this", "->", "loadConfigurationFiles", "(", "$", "config", ")", ";", "Zilf", "::", "$", "app", "->"...
Bootstrap the given application. @return void
[ "Bootstrap", "the", "given", "application", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/System/Bootstrap/LoadConfiguration.php#L18-L29
txj123/zilf
src/Zilf/System/Bootstrap/LoadConfiguration.php
LoadConfiguration.loadConfigurationFiles
protected function loadConfigurationFiles(Repository $repository) { $files = $this->getConfigurationFiles(); if (!isset($files['app'])) { throw new Exception('Unable to load the "app" configuration file.'); } foreach ($files as $key => $path) { $repository->set($key, include $path); } }
php
protected function loadConfigurationFiles(Repository $repository) { $files = $this->getConfigurationFiles(); if (!isset($files['app'])) { throw new Exception('Unable to load the "app" configuration file.'); } foreach ($files as $key => $path) { $repository->set($key, include $path); } }
[ "protected", "function", "loadConfigurationFiles", "(", "Repository", "$", "repository", ")", "{", "$", "files", "=", "$", "this", "->", "getConfigurationFiles", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "files", "[", "'app'", "]", ")", ")", "{",...
Load the configuration items from all of the files. @param \Zilf\Config\Repository $repository @return void @throws \Exception
[ "Load", "the", "configuration", "items", "from", "all", "of", "the", "files", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/System/Bootstrap/LoadConfiguration.php#L38-L49
krafthaus/bauhaus
src/KraftHaus/Bauhaus/Field/HasManyField.php
HasManyField.render
public function render() { switch ($this->getContext()) { case BaseField::CONTEXT_LIST: $values = []; foreach ($this->getValue() as $item) { $values[] = $item->{$this->getDisplayField()}; } return implode(', ', $values); break; case BaseField::CONTEXT_FORM: $baseModel = $this->getAdmin()->getModel(); $baseModel = new $baseModel; $primaryKey = $baseModel->getKeyName(); $relatedModel = $baseModel->{$this->getName()}()->getRelated(); $relatedModel = get_class($relatedModel); $items = []; foreach ($relatedModel::all() as $item) { $items[$item->{$primaryKey}] = $item->{$this->getDisplayField()}; } $id = $this->getAdmin()->getFormBuilder()->getIdentifier(); $values = []; foreach ($relatedModel::where(Str::singular($baseModel->getTable()) . '_id', $id)->get() as $item) { $values[] = (string) $item->{$primaryKey}; } return View::make('krafthaus/bauhaus::models.fields._has_many') ->with('field', $this) ->with('items', $items) ->with('values', $values); break; } }
php
public function render() { switch ($this->getContext()) { case BaseField::CONTEXT_LIST: $values = []; foreach ($this->getValue() as $item) { $values[] = $item->{$this->getDisplayField()}; } return implode(', ', $values); break; case BaseField::CONTEXT_FORM: $baseModel = $this->getAdmin()->getModel(); $baseModel = new $baseModel; $primaryKey = $baseModel->getKeyName(); $relatedModel = $baseModel->{$this->getName()}()->getRelated(); $relatedModel = get_class($relatedModel); $items = []; foreach ($relatedModel::all() as $item) { $items[$item->{$primaryKey}] = $item->{$this->getDisplayField()}; } $id = $this->getAdmin()->getFormBuilder()->getIdentifier(); $values = []; foreach ($relatedModel::where(Str::singular($baseModel->getTable()) . '_id', $id)->get() as $item) { $values[] = (string) $item->{$primaryKey}; } return View::make('krafthaus/bauhaus::models.fields._has_many') ->with('field', $this) ->with('items', $items) ->with('values', $values); break; } }
[ "public", "function", "render", "(", ")", "{", "switch", "(", "$", "this", "->", "getContext", "(", ")", ")", "{", "case", "BaseField", "::", "CONTEXT_LIST", ":", "$", "values", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getValue", "(", ...
Render the field. @access public @return mixed|string
[ "Render", "the", "field", "." ]
train
https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Field/HasManyField.php#L31-L71
phug-php/compiler
src/Phug/Compiler/Element/BlockElement.php
BlockElement.addCompiler
public function addCompiler(CompilerInterface $compiler) { if (!in_array($compiler, $this->compilers)) { $blocks = &$compiler->getBlocksByName($this->name); $blocks[] = $this; $this->compilers[] = $compiler; } return $this; }
php
public function addCompiler(CompilerInterface $compiler) { if (!in_array($compiler, $this->compilers)) { $blocks = &$compiler->getBlocksByName($this->name); $blocks[] = $this; $this->compilers[] = $compiler; } return $this; }
[ "public", "function", "addCompiler", "(", "CompilerInterface", "$", "compiler", ")", "{", "if", "(", "!", "in_array", "(", "$", "compiler", ",", "$", "this", "->", "compilers", ")", ")", "{", "$", "blocks", "=", "&", "$", "compiler", "->", "getBlocksByNa...
Link another compiler. @param CompilerInterface $compiler @return $this
[ "Link", "another", "compiler", "." ]
train
https://github.com/phug-php/compiler/blob/13fc3f44ef783fbdb4f052e3982eda33e1291a76/src/Phug/Compiler/Element/BlockElement.php#L52-L61
webbuilders-group/silverstripe-frontendgridfield
code/forms/FrontEndGridField.php
FrontEndGridField.FieldHolder
public function FieldHolder($properties=array()) { Requirements::block(FRAMEWORK_DIR.'/css/GridField.css'); Requirements::themedCSS('FrontEndGridField', FRONTEND_GRIDFIELD_BASE); Requirements::add_i18n_javascript(FRAMEWORK_DIR.'/javascript/lang'); Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js'); Requirements::javascript(THIRDPARTY_DIR.'/jquery-ui/jquery-ui.js'); Requirements::javascript(FRAMEWORK_ADMIN_DIR.'/javascript/ssui.core.js'); Requirements::javascript(FRAMEWORK_ADMIN_DIR.'/javascript/lib.js'); Requirements::javascript(THIRDPARTY_DIR.'/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript(FRONTEND_GRIDFIELD_BASE.'/javascript/FrontEndGridField.js'); return parent::FieldHolder(); }
php
public function FieldHolder($properties=array()) { Requirements::block(FRAMEWORK_DIR.'/css/GridField.css'); Requirements::themedCSS('FrontEndGridField', FRONTEND_GRIDFIELD_BASE); Requirements::add_i18n_javascript(FRAMEWORK_DIR.'/javascript/lang'); Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js'); Requirements::javascript(THIRDPARTY_DIR.'/jquery-ui/jquery-ui.js'); Requirements::javascript(FRAMEWORK_ADMIN_DIR.'/javascript/ssui.core.js'); Requirements::javascript(FRAMEWORK_ADMIN_DIR.'/javascript/lib.js'); Requirements::javascript(THIRDPARTY_DIR.'/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript(FRONTEND_GRIDFIELD_BASE.'/javascript/FrontEndGridField.js'); return parent::FieldHolder(); }
[ "public", "function", "FieldHolder", "(", "$", "properties", "=", "array", "(", ")", ")", "{", "Requirements", "::", "block", "(", "FRAMEWORK_DIR", ".", "'/css/GridField.css'", ")", ";", "Requirements", "::", "themedCSS", "(", "'FrontEndGridField'", ",", "FRONTE...
Returns the whole gridfield rendered with all the attached components @return string
[ "Returns", "the", "whole", "gridfield", "rendered", "with", "all", "the", "attached", "components" ]
train
https://github.com/webbuilders-group/silverstripe-frontendgridfield/blob/e3ff8d3208c279e9af6e15a750af02632876b914/code/forms/FrontEndGridField.php#L7-L21
quai10/quai10-template
lib/Blog.php
Blog.getArticles
public static function getArticles($nbposts) { $args = [ 'post_type' => 'post', 'category_name' => 'blog', 'posts_per_page' => $nbposts, 'order' => 'DESC', ]; $loop = new \WP_Query($args); while ($loop->have_posts()) { $loop->the_post(); get_template_part('template-parts/blog', 'article'); } wp_reset_query(); }
php
public static function getArticles($nbposts) { $args = [ 'post_type' => 'post', 'category_name' => 'blog', 'posts_per_page' => $nbposts, 'order' => 'DESC', ]; $loop = new \WP_Query($args); while ($loop->have_posts()) { $loop->the_post(); get_template_part('template-parts/blog', 'article'); } wp_reset_query(); }
[ "public", "static", "function", "getArticles", "(", "$", "nbposts", ")", "{", "$", "args", "=", "[", "'post_type'", "=>", "'post'", ",", "'category_name'", "=>", "'blog'", ",", "'posts_per_page'", "=>", "$", "nbposts", ",", "'order'", "=>", "'DESC'", ",", ...
Loop Article Blog. @param int $nbposts Number of posts to display. @return void
[ "Loop", "Article", "Blog", "." ]
train
https://github.com/quai10/quai10-template/blob/3e98b7de031f5507831946200081b6cb35b468b7/lib/Blog.php#L20-L34
txj123/zilf
src/Zilf/Db/base/ErrorHandler.php
ErrorHandler.handleException
public function handleException($exception) { if ($exception instanceof ExitException) { return; } $this->exception = $exception; // disable error capturing to avoid recursive errors while handling exceptions $this->unregister(); // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent // HTTP exceptions will override this value in renderException() if (PHP_SAPI !== 'cli') { http_response_code(500); } try { $this->logException($exception); if ($this->discardExistingOutput) { $this->clearOutput(); } $this->renderException($exception); if (!Zilf_ENV_TEST) { \Zilf::getLogger()->flush(true); if (defined('HHVM_VERSION')) { flush(); } exit(1); } } catch (\Exception $e) { // an other exception could be thrown while displaying the exception $this->handleFallbackExceptionMessage($e, $exception); } catch (\Throwable $e) { // additional check for \Throwable introduced in PHP 7 $this->handleFallbackExceptionMessage($e, $exception); } $this->exception = null; }
php
public function handleException($exception) { if ($exception instanceof ExitException) { return; } $this->exception = $exception; // disable error capturing to avoid recursive errors while handling exceptions $this->unregister(); // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent // HTTP exceptions will override this value in renderException() if (PHP_SAPI !== 'cli') { http_response_code(500); } try { $this->logException($exception); if ($this->discardExistingOutput) { $this->clearOutput(); } $this->renderException($exception); if (!Zilf_ENV_TEST) { \Zilf::getLogger()->flush(true); if (defined('HHVM_VERSION')) { flush(); } exit(1); } } catch (\Exception $e) { // an other exception could be thrown while displaying the exception $this->handleFallbackExceptionMessage($e, $exception); } catch (\Throwable $e) { // additional check for \Throwable introduced in PHP 7 $this->handleFallbackExceptionMessage($e, $exception); } $this->exception = null; }
[ "public", "function", "handleException", "(", "$", "exception", ")", "{", "if", "(", "$", "exception", "instanceof", "ExitException", ")", "{", "return", ";", "}", "$", "this", "->", "exception", "=", "$", "exception", ";", "// disable error capturing to avoid r...
Handles uncaught PHP exceptions. This method is implemented as a PHP exception handler. @param \Exception $exception the exception that is not caught
[ "Handles", "uncaught", "PHP", "exceptions", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/ErrorHandler.php#L89-L128
txj123/zilf
src/Zilf/Db/base/ErrorHandler.php
ErrorHandler.handleFatalError
public function handleFatalError() { unset($this->_memoryReserve); // load ErrorException manually here because autoloading them will not work // when error occurs while autoloading a class if (!class_exists('Zilf\\base\\ErrorException', false)) { include_once __DIR__ . '/ErrorException.php'; } $error = error_get_last(); if (ErrorException::isFatalError($error)) { if (!empty($this->_hhvmException)) { $exception = $this->_hhvmException; } else { $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']); } $this->exception = $exception; $this->logException($exception); if ($this->discardExistingOutput) { $this->clearOutput(); } $this->renderException($exception); // need to explicitly flush logs because exit() next will terminate the app immediately Zilf::getLogger()->flush(true); if (defined('HHVM_VERSION')) { flush(); } exit(1); } }
php
public function handleFatalError() { unset($this->_memoryReserve); // load ErrorException manually here because autoloading them will not work // when error occurs while autoloading a class if (!class_exists('Zilf\\base\\ErrorException', false)) { include_once __DIR__ . '/ErrorException.php'; } $error = error_get_last(); if (ErrorException::isFatalError($error)) { if (!empty($this->_hhvmException)) { $exception = $this->_hhvmException; } else { $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']); } $this->exception = $exception; $this->logException($exception); if ($this->discardExistingOutput) { $this->clearOutput(); } $this->renderException($exception); // need to explicitly flush logs because exit() next will terminate the app immediately Zilf::getLogger()->flush(true); if (defined('HHVM_VERSION')) { flush(); } exit(1); } }
[ "public", "function", "handleFatalError", "(", ")", "{", "unset", "(", "$", "this", "->", "_memoryReserve", ")", ";", "// load ErrorException manually here because autoloading them will not work", "// when error occurs while autoloading a class", "if", "(", "!", "class_exists",...
Handles fatal PHP errors.
[ "Handles", "fatal", "PHP", "errors", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/ErrorHandler.php#L238-L272
txj123/zilf
src/Zilf/Db/base/ErrorHandler.php
ErrorHandler.logException
public function logException($exception) { $category = get_class($exception); if ($exception instanceof HttpException) { $category = 'Zilf\\web\\HttpException:' . $exception->statusCode; } elseif ($exception instanceof \ErrorException) { $category .= ':' . $exception->getSeverity(); } Zilf::error($exception, $category); }
php
public function logException($exception) { $category = get_class($exception); if ($exception instanceof HttpException) { $category = 'Zilf\\web\\HttpException:' . $exception->statusCode; } elseif ($exception instanceof \ErrorException) { $category .= ':' . $exception->getSeverity(); } Zilf::error($exception, $category); }
[ "public", "function", "logException", "(", "$", "exception", ")", "{", "$", "category", "=", "get_class", "(", "$", "exception", ")", ";", "if", "(", "$", "exception", "instanceof", "HttpException", ")", "{", "$", "category", "=", "'Zilf\\\\web\\\\HttpExceptio...
Logs the given exception. @param \Exception $exception the exception to be logged @since 2.0.3 this method is now public.
[ "Logs", "the", "given", "exception", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/ErrorHandler.php#L287-L296
morrislaptop/LaravelFivePackageBridges
src/Repository.php
Repository.loadConfigurationFiles
protected function loadConfigurationFiles($path, $namespace) { foreach ($this->getConfigurationFiles($path) as $key => $file) { $configs = require $file; $this->setConfigsInNamespace($configs, $key, $namespace); } }
php
protected function loadConfigurationFiles($path, $namespace) { foreach ($this->getConfigurationFiles($path) as $key => $file) { $configs = require $file; $this->setConfigsInNamespace($configs, $key, $namespace); } }
[ "protected", "function", "loadConfigurationFiles", "(", "$", "path", ",", "$", "namespace", ")", "{", "foreach", "(", "$", "this", "->", "getConfigurationFiles", "(", "$", "path", ")", "as", "$", "key", "=>", "$", "file", ")", "{", "$", "configs", "=", ...
Load the configuration items from all of the files. @param $path @param $namespace
[ "Load", "the", "configuration", "items", "from", "all", "of", "the", "files", "." ]
train
https://github.com/morrislaptop/LaravelFivePackageBridges/blob/9515972cc86544b470989ce22f16e1f09eddf85e/src/Repository.php#L40-L47
morrislaptop/LaravelFivePackageBridges
src/Repository.php
Repository.getConfigurationFiles
protected function getConfigurationFiles($path) { $files = []; foreach (Finder::create()->files()->name('*.php')->in($path) as $file) { $files[basename($file->getRealPath(), '.php')] = $file->getRealPath(); } return $files; }
php
protected function getConfigurationFiles($path) { $files = []; foreach (Finder::create()->files()->name('*.php')->in($path) as $file) { $files[basename($file->getRealPath(), '.php')] = $file->getRealPath(); } return $files; }
[ "protected", "function", "getConfigurationFiles", "(", "$", "path", ")", "{", "$", "files", "=", "[", "]", ";", "foreach", "(", "Finder", "::", "create", "(", ")", "->", "files", "(", ")", "->", "name", "(", "'*.php'", ")", "->", "in", "(", "$", "p...
Get all of the configuration files for the application. @param $path @return array
[ "Get", "all", "of", "the", "configuration", "files", "for", "the", "application", "." ]
train
https://github.com/morrislaptop/LaravelFivePackageBridges/blob/9515972cc86544b470989ce22f16e1f09eddf85e/src/Repository.php#L55-L65
oxygen-cms/core
src/Console/FieldSetDetailCommand.php
FieldSetDetailCommand.handle
public function handle(Container $container) { $fieldSet = $container->make($this->argument('field')); $this->heading('Field Set'); $fields = []; foreach($fieldSet->getFields() as $field) { $fields[] = $this->getFieldInformation($field); } $this->table($this->fieldHeaders, $fields); }
php
public function handle(Container $container) { $fieldSet = $container->make($this->argument('field')); $this->heading('Field Set'); $fields = []; foreach($fieldSet->getFields() as $field) { $fields[] = $this->getFieldInformation($field); } $this->table($this->fieldHeaders, $fields); }
[ "public", "function", "handle", "(", "Container", "$", "container", ")", "{", "$", "fieldSet", "=", "$", "container", "->", "make", "(", "$", "this", "->", "argument", "(", "'field'", ")", ")", ";", "$", "this", "->", "heading", "(", "'Field Set'", ")"...
Execute the console command. @param \Illuminate\Contracts\Container\Container $container @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Console/FieldSetDetailCommand.php#L44-L54
oxygen-cms/core
src/Console/FieldSetDetailCommand.php
FieldSetDetailCommand.getFieldInformation
protected function getFieldInformation(FieldMetadata $field) { return [ $field->name, $field->label, $field->type, Formatter::boolean($field->editable), Formatter::keyedArray($field->attributes), Formatter::keyedArray($field->options) ]; }
php
protected function getFieldInformation(FieldMetadata $field) { return [ $field->name, $field->label, $field->type, Formatter::boolean($field->editable), Formatter::keyedArray($field->attributes), Formatter::keyedArray($field->options) ]; }
[ "protected", "function", "getFieldInformation", "(", "FieldMetadata", "$", "field", ")", "{", "return", "[", "$", "field", "->", "name", ",", "$", "field", "->", "label", ",", "$", "field", "->", "type", ",", "Formatter", "::", "boolean", "(", "$", "fiel...
Get information about a Field. @param FieldMetadata $field @return array
[ "Get", "information", "about", "a", "Field", "." ]
train
https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Console/FieldSetDetailCommand.php#L63-L72
txj123/zilf
src/Zilf/Curl/CurlResponse.php
CurlResponse._init
private function _init() { $pos = stripos($this->_response, '<!DOCTYPE'); if ($pos != 0) { //方法一 分离头信息 和 body $this->_response_header = substr($this->_response, 0, $pos); $this->_response = substr($this->_response, $pos); } else { //方法二 分离头信息 和 body if (!(strpos($this->_response, "\r\n\r\n") === false)) { list($this->_response_header, $this->_response) = explode("\r\n\r\n", $this->_response, 2); while (strtolower(trim($this->_response_header)) === 'http/1.1 100 continue') { list($this->_response_header, $this->_response) = explode("\r\n\r\n", $this->_response, 2); } } } }
php
private function _init() { $pos = stripos($this->_response, '<!DOCTYPE'); if ($pos != 0) { //方法一 分离头信息 和 body $this->_response_header = substr($this->_response, 0, $pos); $this->_response = substr($this->_response, $pos); } else { //方法二 分离头信息 和 body if (!(strpos($this->_response, "\r\n\r\n") === false)) { list($this->_response_header, $this->_response) = explode("\r\n\r\n", $this->_response, 2); while (strtolower(trim($this->_response_header)) === 'http/1.1 100 continue') { list($this->_response_header, $this->_response) = explode("\r\n\r\n", $this->_response, 2); } } } }
[ "private", "function", "_init", "(", ")", "{", "$", "pos", "=", "stripos", "(", "$", "this", "->", "_response", ",", "'<!DOCTYPE'", ")", ";", "if", "(", "$", "pos", "!=", "0", ")", "{", "//方法一 分离头信息 和 body", "$", "this", "->", "_response_header", "=", ...
分离头信息 和 body
[ "分离头信息", "和", "body" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Curl/CurlResponse.php#L92-L112
txj123/zilf
src/Zilf/Curl/CurlResponse.php
CurlResponse.get_all
function get_all() { return array( 'url' => $this->getClient()->get_url(), 'method' => $this->getClient()->get_method(), 'parameters' => $this->getClient()->get_parameters(), 'curl_error_code' => $this->get_curl_error_code(), 'curl_error_message' => $this->get_curl_error_message(), 'charset' => $this->get_charset(), 'curl_getInfo' => $this->get_info(), 'response_headers' => $this->get_response_headers(), // 'response' => $this->get_content() ); }
php
function get_all() { return array( 'url' => $this->getClient()->get_url(), 'method' => $this->getClient()->get_method(), 'parameters' => $this->getClient()->get_parameters(), 'curl_error_code' => $this->get_curl_error_code(), 'curl_error_message' => $this->get_curl_error_message(), 'charset' => $this->get_charset(), 'curl_getInfo' => $this->get_info(), 'response_headers' => $this->get_response_headers(), // 'response' => $this->get_content() ); }
[ "function", "get_all", "(", ")", "{", "return", "array", "(", "'url'", "=>", "$", "this", "->", "getClient", "(", ")", "->", "get_url", "(", ")", ",", "'method'", "=>", "$", "this", "->", "getClient", "(", ")", "->", "get_method", "(", ")", ",", "'...
显示采集的日志信息
[ "显示采集的日志信息" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Curl/CurlResponse.php#L256-L270
txj123/zilf
src/Zilf/Db/ActiveQuery.php
ActiveQuery.prepare
public function prepare($builder) { // NOTE: because the same ActiveQuery may be used to build different SQL statements // (e.g. by ActiveDataProvider, one for count query, the other for row data query, // it is important to make sure the same ActiveQuery can be used to build SQL statements // multiple times. if (!empty($this->joinWith)) { $this->buildJoinWith(); $this->joinWith = null; // clean it up to avoid issue https://github.com/Zilfsoft/Zilf2/issues/2687 } if (empty($this->from)) { $this->from = [$this->getPrimaryTableName()]; } if (empty($this->select) && !empty($this->join)) { list(, $alias) = $this->getTableNameAndAlias(); $this->select = ["$alias.*"]; } if ($this->primaryModel === null) { // eager loading $query = Query::create($this); } else { // lazy loading of a relation $where = $this->where; if ($this->via instanceof self) { // via junction table $viaModels = $this->via->findJunctionRows([$this->primaryModel]); $this->filterByModels($viaModels); } elseif (is_array($this->via)) { // via relation /* @var $viaQuery ActiveQuery */ list($viaName, $viaQuery) = $this->via; if ($viaQuery->multiple) { $viaModels = $viaQuery->all(); $this->primaryModel->populateRelation($viaName, $viaModels); } else { $model = $viaQuery->one(); $this->primaryModel->populateRelation($viaName, $model); $viaModels = $model === null ? [] : [$model]; } $this->filterByModels($viaModels); } else { $this->filterByModels([$this->primaryModel]); } $query = Query::create($this); $this->where = $where; } if (!empty($this->on)) { $query->andWhere($this->on); } return $query; }
php
public function prepare($builder) { // NOTE: because the same ActiveQuery may be used to build different SQL statements // (e.g. by ActiveDataProvider, one for count query, the other for row data query, // it is important to make sure the same ActiveQuery can be used to build SQL statements // multiple times. if (!empty($this->joinWith)) { $this->buildJoinWith(); $this->joinWith = null; // clean it up to avoid issue https://github.com/Zilfsoft/Zilf2/issues/2687 } if (empty($this->from)) { $this->from = [$this->getPrimaryTableName()]; } if (empty($this->select) && !empty($this->join)) { list(, $alias) = $this->getTableNameAndAlias(); $this->select = ["$alias.*"]; } if ($this->primaryModel === null) { // eager loading $query = Query::create($this); } else { // lazy loading of a relation $where = $this->where; if ($this->via instanceof self) { // via junction table $viaModels = $this->via->findJunctionRows([$this->primaryModel]); $this->filterByModels($viaModels); } elseif (is_array($this->via)) { // via relation /* @var $viaQuery ActiveQuery */ list($viaName, $viaQuery) = $this->via; if ($viaQuery->multiple) { $viaModels = $viaQuery->all(); $this->primaryModel->populateRelation($viaName, $viaModels); } else { $model = $viaQuery->one(); $this->primaryModel->populateRelation($viaName, $model); $viaModels = $model === null ? [] : [$model]; } $this->filterByModels($viaModels); } else { $this->filterByModels([$this->primaryModel]); } $query = Query::create($this); $this->where = $where; } if (!empty($this->on)) { $query->andWhere($this->on); } return $query; }
[ "public", "function", "prepare", "(", "$", "builder", ")", "{", "// NOTE: because the same ActiveQuery may be used to build different SQL statements", "// (e.g. by ActiveDataProvider, one for count query, the other for row data query,", "// it is important to make sure the same ActiveQuery can b...
{@inheritdoc}
[ "{" ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/ActiveQuery.php#L141-L198
txj123/zilf
src/Zilf/Db/ActiveQuery.php
ActiveQuery.viaTable
public function viaTable($tableName, $link, callable $callable = null) { $modelClass = $this->primaryModel !== null ? get_class($this->primaryModel) : __CLASS__; $relation = new self( $modelClass, [ 'from' => [$tableName], 'link' => $link, 'multiple' => true, 'asArray' => true, ] ); $this->via = $relation; if ($callable !== null) { call_user_func($callable, $relation); } return $this; }
php
public function viaTable($tableName, $link, callable $callable = null) { $modelClass = $this->primaryModel !== null ? get_class($this->primaryModel) : __CLASS__; $relation = new self( $modelClass, [ 'from' => [$tableName], 'link' => $link, 'multiple' => true, 'asArray' => true, ] ); $this->via = $relation; if ($callable !== null) { call_user_func($callable, $relation); } return $this; }
[ "public", "function", "viaTable", "(", "$", "tableName", ",", "$", "link", ",", "callable", "$", "callable", "=", "null", ")", "{", "$", "modelClass", "=", "$", "this", "->", "primaryModel", "!==", "null", "?", "get_class", "(", "$", "this", "->", "pri...
Specifies the junction table for a relational query. Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class: ```php public function getItems() { return $this->hasMany(Item::className(), ['id' => 'item_id']) ->viaTable('order_item', ['order_id' => 'id']); } ``` @param string $tableName the name of the junction table. @param array $link the link between the junction table and the table associated with [[primaryModel]]. The keys of the array represent the columns in the junction table, and the values represent the columns in the [[primaryModel]] table. @param callable $callable a PHP callback for customizing the relation associated with the junction table. Its signature should be `function($query)`, where `$query` is the query to be customized. @return $this the query object itself @see via()
[ "Specifies", "the", "junction", "table", "for", "a", "relational", "query", "." ]
train
https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/ActiveQuery.php#L772-L790