repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
codeblanche/Web
src/Web/Request/Request.php
Request.value
public function value($name) { if (empty($this->requestOrder)) { throw new RuntimeException('Unable to determine the request order'); } $result = null; foreach ($this->requestOrder as $token) { $method = $this->resolveRequestOrderMethod($token); if (empty($method)) { continue; } $result = $this->$method($name); if (!is_null($result)) { break; } } return $result; }
php
public function value($name) { if (empty($this->requestOrder)) { throw new RuntimeException('Unable to determine the request order'); } $result = null; foreach ($this->requestOrder as $token) { $method = $this->resolveRequestOrderMethod($token); if (empty($method)) { continue; } $result = $this->$method($name); if (!is_null($result)) { break; } } return $result; }
[ "public", "function", "value", "(", "$", "name", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "requestOrder", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'Unable to determine the request order'", ")", ";", "}", "$", "result", "=", "null", ";", "foreach", "(", "$", "this", "->", "requestOrder", "as", "$", "token", ")", "{", "$", "method", "=", "$", "this", "->", "resolveRequestOrderMethod", "(", "$", "token", ")", ";", "if", "(", "empty", "(", "$", "method", ")", ")", "{", "continue", ";", "}", "$", "result", "=", "$", "this", "->", "$", "method", "(", "$", "name", ")", ";", "if", "(", "!", "is_null", "(", "$", "result", ")", ")", "{", "break", ";", "}", "}", "return", "$", "result", ";", "}" ]
Retrieve a value using the configured request order @param string $name @return mixed @throws RuntimeException
[ "Retrieve", "a", "value", "using", "the", "configured", "request", "order" ]
3e9ebf1943d3ea468f619ba99f7cc10714cb16e9
https://github.com/codeblanche/Web/blob/3e9ebf1943d3ea468f619ba99f7cc10714cb16e9/src/Web/Request/Request.php#L146-L169
train
codeblanche/Web
src/Web/Request/Request.php
Request.files
public function files($name, $sanitize = true) { return $this->resolveValue($name, $_FILES, $sanitize, true); }
php
public function files($name, $sanitize = true) { return $this->resolveValue($name, $_FILES, $sanitize, true); }
[ "public", "function", "files", "(", "$", "name", ",", "$", "sanitize", "=", "true", ")", "{", "return", "$", "this", "->", "resolveValue", "(", "$", "name", ",", "$", "_FILES", ",", "$", "sanitize", ",", "true", ")", ";", "}" ]
Retrieve the the date associated with a file upload @param string $name @param bool $sanitize @return array
[ "Retrieve", "the", "the", "date", "associated", "with", "a", "file", "upload" ]
3e9ebf1943d3ea468f619ba99f7cc10714cb16e9
https://github.com/codeblanche/Web/blob/3e9ebf1943d3ea468f619ba99f7cc10714cb16e9/src/Web/Request/Request.php#L222-L225
train
codeblanche/Web
src/Web/Request/Request.php
Request.put
public function put($source = 'php://input', $sanitize = true) { if (is_null($source)) { $source = 'php://input'; } $source = @fopen($source, 'r'); if (!is_resource($source)) { throw new InvalidArgumentException('Expected parameter 1 to be an open-able resource'); } $data = null; while ($buffer = fread($source, 1024)) { $data .= $buffer; } fclose($source); return $sanitize ? filter_var($data, FILTER_SANITIZE_STRING) : $data; }
php
public function put($source = 'php://input', $sanitize = true) { if (is_null($source)) { $source = 'php://input'; } $source = @fopen($source, 'r'); if (!is_resource($source)) { throw new InvalidArgumentException('Expected parameter 1 to be an open-able resource'); } $data = null; while ($buffer = fread($source, 1024)) { $data .= $buffer; } fclose($source); return $sanitize ? filter_var($data, FILTER_SANITIZE_STRING) : $data; }
[ "public", "function", "put", "(", "$", "source", "=", "'php://input'", ",", "$", "sanitize", "=", "true", ")", "{", "if", "(", "is_null", "(", "$", "source", ")", ")", "{", "$", "source", "=", "'php://input'", ";", "}", "$", "source", "=", "@", "fopen", "(", "$", "source", ",", "'r'", ")", ";", "if", "(", "!", "is_resource", "(", "$", "source", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Expected parameter 1 to be an open-able resource'", ")", ";", "}", "$", "data", "=", "null", ";", "while", "(", "$", "buffer", "=", "fread", "(", "$", "source", ",", "1024", ")", ")", "{", "$", "data", ".=", "$", "buffer", ";", "}", "fclose", "(", "$", "source", ")", ";", "return", "$", "sanitize", "?", "filter_var", "(", "$", "data", ",", "FILTER_SANITIZE_STRING", ")", ":", "$", "data", ";", "}" ]
Retrieve date from the input stream @param string $source (Default: 'php://input') @param bool $sanitize @throws \InvalidArgumentException @return mixed
[ "Retrieve", "date", "from", "the", "input", "stream" ]
3e9ebf1943d3ea468f619ba99f7cc10714cb16e9
https://github.com/codeblanche/Web/blob/3e9ebf1943d3ea468f619ba99f7cc10714cb16e9/src/Web/Request/Request.php#L236-L257
train
codeblanche/Web
src/Web/Request/Request.php
Request.domain
public function domain($maxLevels = 0) { $parts = explode('.', $this->uri()->getHost()); return implode('.', array_slice($parts, -1 * $maxLevels)); }
php
public function domain($maxLevels = 0) { $parts = explode('.', $this->uri()->getHost()); return implode('.', array_slice($parts, -1 * $maxLevels)); }
[ "public", "function", "domain", "(", "$", "maxLevels", "=", "0", ")", "{", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "this", "->", "uri", "(", ")", "->", "getHost", "(", ")", ")", ";", "return", "implode", "(", "'.'", ",", "array_slice", "(", "$", "parts", ",", "-", "1", "*", "$", "maxLevels", ")", ")", ";", "}" ]
Retrieve the current domain @param int $maxLevels Trim the domain to max levels @return string
[ "Retrieve", "the", "current", "domain" ]
3e9ebf1943d3ea468f619ba99f7cc10714cb16e9
https://github.com/codeblanche/Web/blob/3e9ebf1943d3ea468f619ba99f7cc10714cb16e9/src/Web/Request/Request.php#L313-L318
train
codeblanche/Web
src/Web/Request/Request.php
Request.protocol
public function protocol($raw = false) { if ($raw) { return $this->server('SERVER_PROTOCOL'); } $parts = explode('/', $this->server('SERVER_PROTOCOL')); return strtolower(array_shift($parts)) . $this->server('HTTPS') === 'on' ? 's' : ''; }
php
public function protocol($raw = false) { if ($raw) { return $this->server('SERVER_PROTOCOL'); } $parts = explode('/', $this->server('SERVER_PROTOCOL')); return strtolower(array_shift($parts)) . $this->server('HTTPS') === 'on' ? 's' : ''; }
[ "public", "function", "protocol", "(", "$", "raw", "=", "false", ")", "{", "if", "(", "$", "raw", ")", "{", "return", "$", "this", "->", "server", "(", "'SERVER_PROTOCOL'", ")", ";", "}", "$", "parts", "=", "explode", "(", "'/'", ",", "$", "this", "->", "server", "(", "'SERVER_PROTOCOL'", ")", ")", ";", "return", "strtolower", "(", "array_shift", "(", "$", "parts", ")", ")", ".", "$", "this", "->", "server", "(", "'HTTPS'", ")", "===", "'on'", "?", "'s'", ":", "''", ";", "}" ]
Retrieve the requests protocol @param bool $raw Also return protocol version if available @return string
[ "Retrieve", "the", "requests", "protocol" ]
3e9ebf1943d3ea468f619ba99f7cc10714cb16e9
https://github.com/codeblanche/Web/blob/3e9ebf1943d3ea468f619ba99f7cc10714cb16e9/src/Web/Request/Request.php#L327-L336
train
n2n/n2n-io
src/app/n2n/io/IoUtils.php
IoUtils.determineFileUploadMaxSize
public static function determineFileUploadMaxSize() { static $maxSize = -1; if ($maxSize < 0) { // Start with post_max_size. $maxSize = self::parsePhpIniSize(ini_get('post_max_size')); // If upload_max_size is less, then reduce. Except if upload_max_size is // zero, which indicates no limit. $upload_max = self::parsePhpIniSize(ini_get('upload_max_filesize')); if ($upload_max > 0 && $upload_max < $maxSize) { $maxSize = $upload_max; } } return $maxSize; }
php
public static function determineFileUploadMaxSize() { static $maxSize = -1; if ($maxSize < 0) { // Start with post_max_size. $maxSize = self::parsePhpIniSize(ini_get('post_max_size')); // If upload_max_size is less, then reduce. Except if upload_max_size is // zero, which indicates no limit. $upload_max = self::parsePhpIniSize(ini_get('upload_max_filesize')); if ($upload_max > 0 && $upload_max < $maxSize) { $maxSize = $upload_max; } } return $maxSize; }
[ "public", "static", "function", "determineFileUploadMaxSize", "(", ")", "{", "static", "$", "maxSize", "=", "-", "1", ";", "if", "(", "$", "maxSize", "<", "0", ")", "{", "// Start with post_max_size.\r", "$", "maxSize", "=", "self", "::", "parsePhpIniSize", "(", "ini_get", "(", "'post_max_size'", ")", ")", ";", "// If upload_max_size is less, then reduce. Except if upload_max_size is\r", "// zero, which indicates no limit.\r", "$", "upload_max", "=", "self", "::", "parsePhpIniSize", "(", "ini_get", "(", "'upload_max_filesize'", ")", ")", ";", "if", "(", "$", "upload_max", ">", "0", "&&", "$", "upload_max", "<", "$", "maxSize", ")", "{", "$", "maxSize", "=", "$", "upload_max", ";", "}", "}", "return", "$", "maxSize", ";", "}" ]
Returns a file size limit in bytes based on the PHP upload_max_filesize and post_max_size @return int
[ "Returns", "a", "file", "size", "limit", "in", "bytes", "based", "on", "the", "PHP", "upload_max_filesize", "and", "post_max_size" ]
ff642e195f0c0db1273b6c067eff1192cf2cd987
https://github.com/n2n/n2n-io/blob/ff642e195f0c0db1273b6c067eff1192cf2cd987/src/app/n2n/io/IoUtils.php#L635-L650
train
NukaCode/core
src/NukaCode/Core/View/Models/ViewModel.php
ViewModel.getView
public function getView() { // If we don't have a prefix, just return the view. if (is_null($this->prefix)) { return $this->getBaseView(); } // Set up modifiable variables. $view = $this->concatViewAndPrefix($this->prefix, $this->view); $prefixes = clone $this->prefixes; $this->attempted($view); // Try to find a valid view. while (! view()->exists($view)) { // If we are out of prefixes and the view still isn't found, back out. if (is_null($this->prefix) && ! view()->exists($view)) { $view = null; break; } // Remove prefixes until we don't have any left. if ($prefixes->count() > 0) { $prefixes->pop(); $prefixes = $this->removeControllerFromPrefixes($prefixes); $this->prefix = $prefixes->count() > 0 ? $prefixes->implode('.') : null; $view = $this->concatViewAndPrefix($this->prefix, $this->view); } else { $this->prefix = null; $view = $this->view; } $this->attempted($view); } $this->view = $view; return $this->view; }
php
public function getView() { // If we don't have a prefix, just return the view. if (is_null($this->prefix)) { return $this->getBaseView(); } // Set up modifiable variables. $view = $this->concatViewAndPrefix($this->prefix, $this->view); $prefixes = clone $this->prefixes; $this->attempted($view); // Try to find a valid view. while (! view()->exists($view)) { // If we are out of prefixes and the view still isn't found, back out. if (is_null($this->prefix) && ! view()->exists($view)) { $view = null; break; } // Remove prefixes until we don't have any left. if ($prefixes->count() > 0) { $prefixes->pop(); $prefixes = $this->removeControllerFromPrefixes($prefixes); $this->prefix = $prefixes->count() > 0 ? $prefixes->implode('.') : null; $view = $this->concatViewAndPrefix($this->prefix, $this->view); } else { $this->prefix = null; $view = $this->view; } $this->attempted($view); } $this->view = $view; return $this->view; }
[ "public", "function", "getView", "(", ")", "{", "// If we don't have a prefix, just return the view.", "if", "(", "is_null", "(", "$", "this", "->", "prefix", ")", ")", "{", "return", "$", "this", "->", "getBaseView", "(", ")", ";", "}", "// Set up modifiable variables.", "$", "view", "=", "$", "this", "->", "concatViewAndPrefix", "(", "$", "this", "->", "prefix", ",", "$", "this", "->", "view", ")", ";", "$", "prefixes", "=", "clone", "$", "this", "->", "prefixes", ";", "$", "this", "->", "attempted", "(", "$", "view", ")", ";", "// Try to find a valid view.", "while", "(", "!", "view", "(", ")", "->", "exists", "(", "$", "view", ")", ")", "{", "// If we are out of prefixes and the view still isn't found, back out.", "if", "(", "is_null", "(", "$", "this", "->", "prefix", ")", "&&", "!", "view", "(", ")", "->", "exists", "(", "$", "view", ")", ")", "{", "$", "view", "=", "null", ";", "break", ";", "}", "// Remove prefixes until we don't have any left.", "if", "(", "$", "prefixes", "->", "count", "(", ")", ">", "0", ")", "{", "$", "prefixes", "->", "pop", "(", ")", ";", "$", "prefixes", "=", "$", "this", "->", "removeControllerFromPrefixes", "(", "$", "prefixes", ")", ";", "$", "this", "->", "prefix", "=", "$", "prefixes", "->", "count", "(", ")", ">", "0", "?", "$", "prefixes", "->", "implode", "(", "'.'", ")", ":", "null", ";", "$", "view", "=", "$", "this", "->", "concatViewAndPrefix", "(", "$", "this", "->", "prefix", ",", "$", "this", "->", "view", ")", ";", "}", "else", "{", "$", "this", "->", "prefix", "=", "null", ";", "$", "view", "=", "$", "this", "->", "view", ";", "}", "$", "this", "->", "attempted", "(", "$", "view", ")", ";", "}", "$", "this", "->", "view", "=", "$", "view", ";", "return", "$", "this", "->", "view", ";", "}" ]
Find the most reasonable view available. @return null
[ "Find", "the", "most", "reasonable", "view", "available", "." ]
75b20903fb068a7df22cdec34ae729279fbaab3c
https://github.com/NukaCode/core/blob/75b20903fb068a7df22cdec34ae729279fbaab3c/src/NukaCode/Core/View/Models/ViewModel.php#L75-L114
train
NukaCode/core
src/NukaCode/Core/View/Models/ViewModel.php
ViewModel.parseController
protected function parseController($class) { $controller = new ReflectionClass($class); $this->fullController = $controller->name; $class = $controller->getShortName(); $this->controller = strtolower(str_replace('Controller', '', $class)); }
php
protected function parseController($class) { $controller = new ReflectionClass($class); $this->fullController = $controller->name; $class = $controller->getShortName(); $this->controller = strtolower(str_replace('Controller', '', $class)); }
[ "protected", "function", "parseController", "(", "$", "class", ")", "{", "$", "controller", "=", "new", "ReflectionClass", "(", "$", "class", ")", ";", "$", "this", "->", "fullController", "=", "$", "controller", "->", "name", ";", "$", "class", "=", "$", "controller", "->", "getShortName", "(", ")", ";", "$", "this", "->", "controller", "=", "strtolower", "(", "str_replace", "(", "'Controller'", ",", "''", ",", "$", "class", ")", ")", ";", "}" ]
Get a properly formatted controller name. @param string $class @return string
[ "Get", "a", "properly", "formatted", "controller", "name", "." ]
75b20903fb068a7df22cdec34ae729279fbaab3c
https://github.com/NukaCode/core/blob/75b20903fb068a7df22cdec34ae729279fbaab3c/src/NukaCode/Core/View/Models/ViewModel.php#L150-L156
train
NukaCode/core
src/NukaCode/Core/View/Models/ViewModel.php
ViewModel.parseAction
protected function parseAction($action) { if ($action === $this->fullController) { return $this->action = null; } $this->action = strtolower( preg_replace(['/^get/', '/^post/', '/^put/', '/^patch/', '/^delete/'], '', $action) ); }
php
protected function parseAction($action) { if ($action === $this->fullController) { return $this->action = null; } $this->action = strtolower( preg_replace(['/^get/', '/^post/', '/^put/', '/^patch/', '/^delete/'], '', $action) ); }
[ "protected", "function", "parseAction", "(", "$", "action", ")", "{", "if", "(", "$", "action", "===", "$", "this", "->", "fullController", ")", "{", "return", "$", "this", "->", "action", "=", "null", ";", "}", "$", "this", "->", "action", "=", "strtolower", "(", "preg_replace", "(", "[", "'/^get/'", ",", "'/^post/'", ",", "'/^put/'", ",", "'/^patch/'", ",", "'/^delete/'", "]", ",", "''", ",", "$", "action", ")", ")", ";", "}" ]
Get a properly formatted action name. @param string $action @return string
[ "Get", "a", "properly", "formatted", "action", "name", "." ]
75b20903fb068a7df22cdec34ae729279fbaab3c
https://github.com/NukaCode/core/blob/75b20903fb068a7df22cdec34ae729279fbaab3c/src/NukaCode/Core/View/Models/ViewModel.php#L165-L174
train
NukaCode/core
src/NukaCode/Core/View/Models/ViewModel.php
ViewModel.getPrefixes
protected function getPrefixes() { $router = app(\Illuminate\Routing\Router::class); $this->prefixes = collect( explode('/', $router->getCurrentRoute()->getPrefix()) ); // Remove the last prefix if it matches the controller. $this->prefixes = $this->removeControllerFromPrefixes($this->prefixes)->filter(); if ($this->prefixes->count() > 0) { $this->prefix = $this->prefixes->filter()->implode('.'); } }
php
protected function getPrefixes() { $router = app(\Illuminate\Routing\Router::class); $this->prefixes = collect( explode('/', $router->getCurrentRoute()->getPrefix()) ); // Remove the last prefix if it matches the controller. $this->prefixes = $this->removeControllerFromPrefixes($this->prefixes)->filter(); if ($this->prefixes->count() > 0) { $this->prefix = $this->prefixes->filter()->implode('.'); } }
[ "protected", "function", "getPrefixes", "(", ")", "{", "$", "router", "=", "app", "(", "\\", "Illuminate", "\\", "Routing", "\\", "Router", "::", "class", ")", ";", "$", "this", "->", "prefixes", "=", "collect", "(", "explode", "(", "'/'", ",", "$", "router", "->", "getCurrentRoute", "(", ")", "->", "getPrefix", "(", ")", ")", ")", ";", "// Remove the last prefix if it matches the controller.", "$", "this", "->", "prefixes", "=", "$", "this", "->", "removeControllerFromPrefixes", "(", "$", "this", "->", "prefixes", ")", "->", "filter", "(", ")", ";", "if", "(", "$", "this", "->", "prefixes", "->", "count", "(", ")", ">", "0", ")", "{", "$", "this", "->", "prefix", "=", "$", "this", "->", "prefixes", "->", "filter", "(", ")", "->", "implode", "(", "'.'", ")", ";", "}", "}" ]
Search for any prefixes attached to this route. @return string
[ "Search", "for", "any", "prefixes", "attached", "to", "this", "route", "." ]
75b20903fb068a7df22cdec34ae729279fbaab3c
https://github.com/NukaCode/core/blob/75b20903fb068a7df22cdec34ae729279fbaab3c/src/NukaCode/Core/View/Models/ViewModel.php#L181-L195
train
NukaCode/core
src/NukaCode/Core/View/Models/ViewModel.php
ViewModel.setView
protected function setView() { $views = [ $this->controller, $this->action, ]; $this->view = implode('.', array_filter($views)); }
php
protected function setView() { $views = [ $this->controller, $this->action, ]; $this->view = implode('.', array_filter($views)); }
[ "protected", "function", "setView", "(", ")", "{", "$", "views", "=", "[", "$", "this", "->", "controller", ",", "$", "this", "->", "action", ",", "]", ";", "$", "this", "->", "view", "=", "implode", "(", "'.'", ",", "array_filter", "(", "$", "views", ")", ")", ";", "}" ]
Combine the controller and action to create a proper view string.
[ "Combine", "the", "controller", "and", "action", "to", "create", "a", "proper", "view", "string", "." ]
75b20903fb068a7df22cdec34ae729279fbaab3c
https://github.com/NukaCode/core/blob/75b20903fb068a7df22cdec34ae729279fbaab3c/src/NukaCode/Core/View/Models/ViewModel.php#L216-L224
train
NukaCode/core
src/NukaCode/Core/View/Models/ViewModel.php
ViewModel.getBaseView
private function getBaseView() { $this->attempted($this->view); return view()->exists($this->view) ? $this->view : null; }
php
private function getBaseView() { $this->attempted($this->view); return view()->exists($this->view) ? $this->view : null; }
[ "private", "function", "getBaseView", "(", ")", "{", "$", "this", "->", "attempted", "(", "$", "this", "->", "view", ")", ";", "return", "view", "(", ")", "->", "exists", "(", "$", "this", "->", "view", ")", "?", "$", "this", "->", "view", ":", "null", ";", "}" ]
Return the base view if it exists. @return null|string
[ "Return", "the", "base", "view", "if", "it", "exists", "." ]
75b20903fb068a7df22cdec34ae729279fbaab3c
https://github.com/NukaCode/core/blob/75b20903fb068a7df22cdec34ae729279fbaab3c/src/NukaCode/Core/View/Models/ViewModel.php#L231-L236
train
NukaCode/core
src/NukaCode/Core/View/Models/ViewModel.php
ViewModel.checkConfig
public function checkConfig() { $views = [ $this->fullController, $this->action, ]; $this->configIndex = implode('.', array_filter($views)); return array_get(config('view-routing'), $this->configIndex); }
php
public function checkConfig() { $views = [ $this->fullController, $this->action, ]; $this->configIndex = implode('.', array_filter($views)); return array_get(config('view-routing'), $this->configIndex); }
[ "public", "function", "checkConfig", "(", ")", "{", "$", "views", "=", "[", "$", "this", "->", "fullController", ",", "$", "this", "->", "action", ",", "]", ";", "$", "this", "->", "configIndex", "=", "implode", "(", "'.'", ",", "array_filter", "(", "$", "views", ")", ")", ";", "return", "array_get", "(", "config", "(", "'view-routing'", ")", ",", "$", "this", "->", "configIndex", ")", ";", "}" ]
Check the view routing config for the controller and method. @return null|string
[ "Check", "the", "view", "routing", "config", "for", "the", "controller", "and", "method", "." ]
75b20903fb068a7df22cdec34ae729279fbaab3c
https://github.com/NukaCode/core/blob/75b20903fb068a7df22cdec34ae729279fbaab3c/src/NukaCode/Core/View/Models/ViewModel.php#L243-L253
train
jenskooij/cloudcontrol
src/util/GlobalFunctions.php
GlobalFunctions.sanitizeOutput
public static function sanitizeOutput($buffer) { if (!isset($_GET['unsanitized'])) { $search = array( '/\>[^\S ]+/s', // strip whitespaces after tags, except space '/[^\S ]+\</s', // strip whitespaces before tags, except space '/(\s)+/s', // shorten multiple whitespace sequences '/<!--(.|\s)*?-->/' // Remove HTML comments ); $replace = array( '>', '<', '\\1', '' ); $buffer = preg_replace($search, $replace, $buffer); return $buffer; } return $buffer; }
php
public static function sanitizeOutput($buffer) { if (!isset($_GET['unsanitized'])) { $search = array( '/\>[^\S ]+/s', // strip whitespaces after tags, except space '/[^\S ]+\</s', // strip whitespaces before tags, except space '/(\s)+/s', // shorten multiple whitespace sequences '/<!--(.|\s)*?-->/' // Remove HTML comments ); $replace = array( '>', '<', '\\1', '' ); $buffer = preg_replace($search, $replace, $buffer); return $buffer; } return $buffer; }
[ "public", "static", "function", "sanitizeOutput", "(", "$", "buffer", ")", "{", "if", "(", "!", "isset", "(", "$", "_GET", "[", "'unsanitized'", "]", ")", ")", "{", "$", "search", "=", "array", "(", "'/\\>[^\\S ]+/s'", ",", "// strip whitespaces after tags, except space", "'/[^\\S ]+\\</s'", ",", "// strip whitespaces before tags, except space", "'/(\\s)+/s'", ",", "// shorten multiple whitespace sequences", "'/<!--(.|\\s)*?-->/'", "// Remove HTML comments", ")", ";", "$", "replace", "=", "array", "(", "'>'", ",", "'<'", ",", "'\\\\1'", ",", "''", ")", ";", "$", "buffer", "=", "preg_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "buffer", ")", ";", "return", "$", "buffer", ";", "}", "return", "$", "buffer", ";", "}" ]
Minify the html for the outputbuffer @param $buffer @return mixed
[ "Minify", "the", "html", "for", "the", "outputbuffer" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/util/GlobalFunctions.php#L61-L84
train
gregorybesson/PlaygroundTemplateHint
src/PlaygroundTemplateHint/View/Renderer/PhpRendererHint.php
PhpRendererHint.resolver
public function resolver($name = null) { if (null === $this->__templateResolver) { $this->setResolver(new TemplatePathStack()); } if (null !== $name) { $viewPath = $this->__templateResolver->resolve($name, $this); //echo $viewPath. "<br>"; return $this->__templateResolver->resolve($name, $this); } return $this->__templateResolver; }
php
public function resolver($name = null) { if (null === $this->__templateResolver) { $this->setResolver(new TemplatePathStack()); } if (null !== $name) { $viewPath = $this->__templateResolver->resolve($name, $this); //echo $viewPath. "<br>"; return $this->__templateResolver->resolve($name, $this); } return $this->__templateResolver; }
[ "public", "function", "resolver", "(", "$", "name", "=", "null", ")", "{", "if", "(", "null", "===", "$", "this", "->", "__templateResolver", ")", "{", "$", "this", "->", "setResolver", "(", "new", "TemplatePathStack", "(", ")", ")", ";", "}", "if", "(", "null", "!==", "$", "name", ")", "{", "$", "viewPath", "=", "$", "this", "->", "__templateResolver", "->", "resolve", "(", "$", "name", ",", "$", "this", ")", ";", "//echo $viewPath. \"<br>\";", "return", "$", "this", "->", "__templateResolver", "->", "resolve", "(", "$", "name", ",", "$", "this", ")", ";", "}", "return", "$", "this", "->", "__templateResolver", ";", "}" ]
Retrieve template name or template resolver @param null|string $name @return string|Resolver
[ "Retrieve", "template", "name", "or", "template", "resolver" ]
dc4a342c86469d18976635a0b3c32d1fb651fc4f
https://github.com/gregorybesson/PlaygroundTemplateHint/blob/dc4a342c86469d18976635a0b3c32d1fb651fc4f/src/PlaygroundTemplateHint/View/Renderer/PhpRendererHint.php#L145-L158
train
gregorybesson/PlaygroundTemplateHint
src/PlaygroundTemplateHint/View/Renderer/PhpRendererHint.php
PhpRendererHint.setVars
public function setVars($variables) { if (!is_array($variables) && !$variables instanceof ArrayAccess) { throw new Exception\InvalidArgumentException(sprintf( 'Expected array or ArrayAccess object; received "%s"', (is_object($variables) ? get_class($variables) : gettype($variables)) )); } // Enforce a Variables container if (!$variables instanceof Variables) { $variablesAsArray = array(); foreach ($variables as $key => $value) { $variablesAsArray[$key] = $value; } $variables = new Variables($variablesAsArray); } $this->__vars = $variables; return $this; }
php
public function setVars($variables) { if (!is_array($variables) && !$variables instanceof ArrayAccess) { throw new Exception\InvalidArgumentException(sprintf( 'Expected array or ArrayAccess object; received "%s"', (is_object($variables) ? get_class($variables) : gettype($variables)) )); } // Enforce a Variables container if (!$variables instanceof Variables) { $variablesAsArray = array(); foreach ($variables as $key => $value) { $variablesAsArray[$key] = $value; } $variables = new Variables($variablesAsArray); } $this->__vars = $variables; return $this; }
[ "public", "function", "setVars", "(", "$", "variables", ")", "{", "if", "(", "!", "is_array", "(", "$", "variables", ")", "&&", "!", "$", "variables", "instanceof", "ArrayAccess", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Expected array or ArrayAccess object; received \"%s\"'", ",", "(", "is_object", "(", "$", "variables", ")", "?", "get_class", "(", "$", "variables", ")", ":", "gettype", "(", "$", "variables", ")", ")", ")", ")", ";", "}", "// Enforce a Variables container", "if", "(", "!", "$", "variables", "instanceof", "Variables", ")", "{", "$", "variablesAsArray", "=", "array", "(", ")", ";", "foreach", "(", "$", "variables", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "variablesAsArray", "[", "$", "key", "]", "=", "$", "value", ";", "}", "$", "variables", "=", "new", "Variables", "(", "$", "variablesAsArray", ")", ";", "}", "$", "this", "->", "__vars", "=", "$", "variables", ";", "return", "$", "this", ";", "}" ]
Set variable storage Expects either an array, or an object implementing ArrayAccess. @param array|ArrayAccess $variables @return PhpRenderer @throws Exception\InvalidArgumentException
[ "Set", "variable", "storage" ]
dc4a342c86469d18976635a0b3c32d1fb651fc4f
https://github.com/gregorybesson/PlaygroundTemplateHint/blob/dc4a342c86469d18976635a0b3c32d1fb651fc4f/src/PlaygroundTemplateHint/View/Renderer/PhpRendererHint.php#L169-L189
train
gregorybesson/PlaygroundTemplateHint
src/PlaygroundTemplateHint/View/Renderer/PhpRendererHint.php
PhpRendererHint.vars
public function vars($key = null) { if (null === $this->__vars) { $this->setVars(new Variables()); } if (null === $key) { return $this->__vars; } return $this->__vars[$key]; }
php
public function vars($key = null) { if (null === $this->__vars) { $this->setVars(new Variables()); } if (null === $key) { return $this->__vars; } return $this->__vars[$key]; }
[ "public", "function", "vars", "(", "$", "key", "=", "null", ")", "{", "if", "(", "null", "===", "$", "this", "->", "__vars", ")", "{", "$", "this", "->", "setVars", "(", "new", "Variables", "(", ")", ")", ";", "}", "if", "(", "null", "===", "$", "key", ")", "{", "return", "$", "this", "->", "__vars", ";", "}", "return", "$", "this", "->", "__vars", "[", "$", "key", "]", ";", "}" ]
Get a single variable, or all variables @param mixed $key @return mixed
[ "Get", "a", "single", "variable", "or", "all", "variables" ]
dc4a342c86469d18976635a0b3c32d1fb651fc4f
https://github.com/gregorybesson/PlaygroundTemplateHint/blob/dc4a342c86469d18976635a0b3c32d1fb651fc4f/src/PlaygroundTemplateHint/View/Renderer/PhpRendererHint.php#L197-L207
train
gregorybesson/PlaygroundTemplateHint
src/PlaygroundTemplateHint/View/Renderer/PhpRendererHint.php
PhpRendererHint.get
public function get($key) { if (null === $this->__vars) { $this->setVars(new Variables()); } return $this->__vars[$key]; }
php
public function get($key) { if (null === $this->__vars) { $this->setVars(new Variables()); } return $this->__vars[$key]; }
[ "public", "function", "get", "(", "$", "key", ")", "{", "if", "(", "null", "===", "$", "this", "->", "__vars", ")", "{", "$", "this", "->", "setVars", "(", "new", "Variables", "(", ")", ")", ";", "}", "return", "$", "this", "->", "__vars", "[", "$", "key", "]", ";", "}" ]
Get a single variable @param mixed $key @return mixed
[ "Get", "a", "single", "variable" ]
dc4a342c86469d18976635a0b3c32d1fb651fc4f
https://github.com/gregorybesson/PlaygroundTemplateHint/blob/dc4a342c86469d18976635a0b3c32d1fb651fc4f/src/PlaygroundTemplateHint/View/Renderer/PhpRendererHint.php#L215-L222
train
arendjantetteroo/guzzle-addons-mozilla
src/AJT/MozillaAddons/MozillaAddonsClient.php
MozillaAddonsClient.factory
public static function factory($config = array()) { $default = array( 'base_url' => 'https://addons.mozilla.org/nl/firefox/addon/', 'debug' => false ); $required = array('base_url', 'app_name'); $config = Collection::fromConfig($config, $default, $required); $client = new self($config->get('base_url').$config->get('app_name') . '/statistics', $config); // Attach a service description to the client $description = ServiceDescription::factory(__DIR__ . '/services.json'); $client->setDescription($description); if($config->get('debug')){ $client->addSubscriber(LogPlugin::getDebugPlugin()); } return $client; }
php
public static function factory($config = array()) { $default = array( 'base_url' => 'https://addons.mozilla.org/nl/firefox/addon/', 'debug' => false ); $required = array('base_url', 'app_name'); $config = Collection::fromConfig($config, $default, $required); $client = new self($config->get('base_url').$config->get('app_name') . '/statistics', $config); // Attach a service description to the client $description = ServiceDescription::factory(__DIR__ . '/services.json'); $client->setDescription($description); if($config->get('debug')){ $client->addSubscriber(LogPlugin::getDebugPlugin()); } return $client; }
[ "public", "static", "function", "factory", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "default", "=", "array", "(", "'base_url'", "=>", "'https://addons.mozilla.org/nl/firefox/addon/'", ",", "'debug'", "=>", "false", ")", ";", "$", "required", "=", "array", "(", "'base_url'", ",", "'app_name'", ")", ";", "$", "config", "=", "Collection", "::", "fromConfig", "(", "$", "config", ",", "$", "default", ",", "$", "required", ")", ";", "$", "client", "=", "new", "self", "(", "$", "config", "->", "get", "(", "'base_url'", ")", ".", "$", "config", "->", "get", "(", "'app_name'", ")", ".", "'/statistics'", ",", "$", "config", ")", ";", "// Attach a service description to the client", "$", "description", "=", "ServiceDescription", "::", "factory", "(", "__DIR__", ".", "'/services.json'", ")", ";", "$", "client", "->", "setDescription", "(", "$", "description", ")", ";", "if", "(", "$", "config", "->", "get", "(", "'debug'", ")", ")", "{", "$", "client", "->", "addSubscriber", "(", "LogPlugin", "::", "getDebugPlugin", "(", ")", ")", ";", "}", "return", "$", "client", ";", "}" ]
Factory method to create a new MozillaAddonsClient The following array keys and values are available options: - base_url: Base URL of web service @param array|Collection $config Configuration data @return MozillaAddonsClient
[ "Factory", "method", "to", "create", "a", "new", "MozillaAddonsClient" ]
7ec7dc464e421ac4c5cbb94a3d4453e30b13e888
https://github.com/arendjantetteroo/guzzle-addons-mozilla/blob/7ec7dc464e421ac4c5cbb94a3d4453e30b13e888/src/AJT/MozillaAddons/MozillaAddonsClient.php#L40-L58
train
Torann/skosh-generator
src/Event.php
Event.insert
public static function insert($name, $callback, $once = false) { if (static::bound($name)) { array_unshift( static::$events[$name], [$once ? 'once' : 'always' => $callback] ); } else { static::bind($name, $callback, $once); } }
php
public static function insert($name, $callback, $once = false) { if (static::bound($name)) { array_unshift( static::$events[$name], [$once ? 'once' : 'always' => $callback] ); } else { static::bind($name, $callback, $once); } }
[ "public", "static", "function", "insert", "(", "$", "name", ",", "$", "callback", ",", "$", "once", "=", "false", ")", "{", "if", "(", "static", "::", "bound", "(", "$", "name", ")", ")", "{", "array_unshift", "(", "static", "::", "$", "events", "[", "$", "name", "]", ",", "[", "$", "once", "?", "'once'", ":", "'always'", "=>", "$", "callback", "]", ")", ";", "}", "else", "{", "static", "::", "bind", "(", "$", "name", ",", "$", "callback", ",", "$", "once", ")", ";", "}", "}" ]
Identical to the append method, except the event handler is added to the start of the queue. @param string $name The name of the event. @param mixed $callback The callback function. @param bool $once Only fire the callback once. @return void
[ "Identical", "to", "the", "append", "method", "except", "the", "event", "handler", "is", "added", "to", "the", "start", "of", "the", "queue", "." ]
ea60e037d92398d7c146eb2349735d5692e3c48c
https://github.com/Torann/skosh-generator/blob/ea60e037d92398d7c146eb2349735d5692e3c48c/src/Event.php#L52-L64
train
Torann/skosh-generator
src/Event.php
Event.fire
public static function fire($name, $data = [], $stop = false) { if (static::bound($name)) { static::$fired[$name] = true; foreach (static::$events[$name] as $key => $value) { list($type, $callback) = each($value); // Call back is a class if (is_string($callback)) { $callback = [$instance = new $callback(), 'handle']; } $responses[] = $response = call_user_func_array($callback, (array) $data); if ($type == 'once') { unset(static::$events[$name][$key]); } if ($stop && !empty($response)) { return $responses; } } } return isset($responses) ? $responses : null; }
php
public static function fire($name, $data = [], $stop = false) { if (static::bound($name)) { static::$fired[$name] = true; foreach (static::$events[$name] as $key => $value) { list($type, $callback) = each($value); // Call back is a class if (is_string($callback)) { $callback = [$instance = new $callback(), 'handle']; } $responses[] = $response = call_user_func_array($callback, (array) $data); if ($type == 'once') { unset(static::$events[$name][$key]); } if ($stop && !empty($response)) { return $responses; } } } return isset($responses) ? $responses : null; }
[ "public", "static", "function", "fire", "(", "$", "name", ",", "$", "data", "=", "[", "]", ",", "$", "stop", "=", "false", ")", "{", "if", "(", "static", "::", "bound", "(", "$", "name", ")", ")", "{", "static", "::", "$", "fired", "[", "$", "name", "]", "=", "true", ";", "foreach", "(", "static", "::", "$", "events", "[", "$", "name", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "list", "(", "$", "type", ",", "$", "callback", ")", "=", "each", "(", "$", "value", ")", ";", "// Call back is a class", "if", "(", "is_string", "(", "$", "callback", ")", ")", "{", "$", "callback", "=", "[", "$", "instance", "=", "new", "$", "callback", "(", ")", ",", "'handle'", "]", ";", "}", "$", "responses", "[", "]", "=", "$", "response", "=", "call_user_func_array", "(", "$", "callback", ",", "(", "array", ")", "$", "data", ")", ";", "if", "(", "$", "type", "==", "'once'", ")", "{", "unset", "(", "static", "::", "$", "events", "[", "$", "name", "]", "[", "$", "key", "]", ")", ";", "}", "if", "(", "$", "stop", "&&", "!", "empty", "(", "$", "response", ")", ")", "{", "return", "$", "responses", ";", "}", "}", "}", "return", "isset", "(", "$", "responses", ")", "?", "$", "responses", ":", "null", ";", "}" ]
Trigger all callback functions for an event. The method returns an array containing the responses from all of the event handlers (even empty responses). Returns NULL if the event has no handlers. @param string $name The name of the event. @param array $data The data passed to the event handlers. @param bool $stop Return after the first non-empty response. @return mixed
[ "Trigger", "all", "callback", "functions", "for", "an", "event", "." ]
ea60e037d92398d7c146eb2349735d5692e3c48c
https://github.com/Torann/skosh-generator/blob/ea60e037d92398d7c146eb2349735d5692e3c48c/src/Event.php#L79-L108
train
Vectrex/vxPHP
src/Database/Adapter/Pgsql.php
Pgsql.setDefaultConnectionAttributes
protected function setDefaultConnectionAttributes() { $config = Application::getInstance()->getConfig(); $options = [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, \PDO::ATTR_STRINGIFY_FETCHES => false ]; // if not explicitly specified, attributes are returned lower case if(!isset($config->keep_key_case) || !$config->keep_key_case) { $options[\PDO::ATTR_CASE] = \PDO::CASE_LOWER; } foreach($options as $key => $value) { $this->connection->setAttribute($key, $value); } }
php
protected function setDefaultConnectionAttributes() { $config = Application::getInstance()->getConfig(); $options = [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, \PDO::ATTR_STRINGIFY_FETCHES => false ]; // if not explicitly specified, attributes are returned lower case if(!isset($config->keep_key_case) || !$config->keep_key_case) { $options[\PDO::ATTR_CASE] = \PDO::CASE_LOWER; } foreach($options as $key => $value) { $this->connection->setAttribute($key, $value); } }
[ "protected", "function", "setDefaultConnectionAttributes", "(", ")", "{", "$", "config", "=", "Application", "::", "getInstance", "(", ")", "->", "getConfig", "(", ")", ";", "$", "options", "=", "[", "\\", "PDO", "::", "ATTR_ERRMODE", "=>", "\\", "PDO", "::", "ERRMODE_EXCEPTION", ",", "\\", "PDO", "::", "ATTR_DEFAULT_FETCH_MODE", "=>", "\\", "PDO", "::", "FETCH_ASSOC", ",", "\\", "PDO", "::", "ATTR_STRINGIFY_FETCHES", "=>", "false", "]", ";", "// if not explicitly specified, attributes are returned lower case", "if", "(", "!", "isset", "(", "$", "config", "->", "keep_key_case", ")", "||", "!", "$", "config", "->", "keep_key_case", ")", "{", "$", "options", "[", "\\", "PDO", "::", "ATTR_CASE", "]", "=", "\\", "PDO", "::", "CASE_LOWER", ";", "}", "foreach", "(", "$", "options", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "connection", "->", "setAttribute", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}" ]
set initial attributes for database connection
[ "set", "initial", "attributes", "for", "database", "connection" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Database/Adapter/Pgsql.php#L151-L171
train
itcreator/custom-cmf
Module/Component/src/Cmf/Component/Grid/Table/Rows/A.php
A.current
public function current() { return isset($this->rows[$this->rowsCounter]) ? $this->rows[$this->rowsCounter] : false; }
php
public function current() { return isset($this->rows[$this->rowsCounter]) ? $this->rows[$this->rowsCounter] : false; }
[ "public", "function", "current", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "rows", "[", "$", "this", "->", "rowsCounter", "]", ")", "?", "$", "this", "->", "rows", "[", "$", "this", "->", "rowsCounter", "]", ":", "false", ";", "}" ]
This method return current row @return \Cmf\Component\Grid\Table\Row\A
[ "This", "method", "return", "current", "row" ]
42fc0535dfa0f641856f06673f6ab596b2020c40
https://github.com/itcreator/custom-cmf/blob/42fc0535dfa0f641856f06673f6ab596b2020c40/Module/Component/src/Cmf/Component/Grid/Table/Rows/A.php#L78-L81
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/Iterator/PagingIterator.php
PagingIterator.appendPage
private function appendPage() { $result = $this->executeNextSdkCommand(); $iterator = $this->commands->parseResult($result, $this->hydrationMode, $this->refresh, $this->readOnly, $this->primers); $this->getInnerIterator()->append($iterator); if ($result instanceof SdkResultIterator) { //TODO: cant use $i here, not preserved by pool (not all commands may have executed successfully when paging=true) foreach ($result as $i => $r) { $this->commands[$i] = $this->commands[$i]->createNextCommand($r); if ($this->commands[$i] === null) { unset($this->commands[$i]); } } if (count($this->commands) === 0) { $this->commands = null; } } else { $this->commands = $this->commands->createNextCommand($result); } }
php
private function appendPage() { $result = $this->executeNextSdkCommand(); $iterator = $this->commands->parseResult($result, $this->hydrationMode, $this->refresh, $this->readOnly, $this->primers); $this->getInnerIterator()->append($iterator); if ($result instanceof SdkResultIterator) { //TODO: cant use $i here, not preserved by pool (not all commands may have executed successfully when paging=true) foreach ($result as $i => $r) { $this->commands[$i] = $this->commands[$i]->createNextCommand($r); if ($this->commands[$i] === null) { unset($this->commands[$i]); } } if (count($this->commands) === 0) { $this->commands = null; } } else { $this->commands = $this->commands->createNextCommand($result); } }
[ "private", "function", "appendPage", "(", ")", "{", "$", "result", "=", "$", "this", "->", "executeNextSdkCommand", "(", ")", ";", "$", "iterator", "=", "$", "this", "->", "commands", "->", "parseResult", "(", "$", "result", ",", "$", "this", "->", "hydrationMode", ",", "$", "this", "->", "refresh", ",", "$", "this", "->", "readOnly", ",", "$", "this", "->", "primers", ")", ";", "$", "this", "->", "getInnerIterator", "(", ")", "->", "append", "(", "$", "iterator", ")", ";", "if", "(", "$", "result", "instanceof", "SdkResultIterator", ")", "{", "//TODO: cant use $i here, not preserved by pool (not all commands may have executed successfully when paging=true)", "foreach", "(", "$", "result", "as", "$", "i", "=>", "$", "r", ")", "{", "$", "this", "->", "commands", "[", "$", "i", "]", "=", "$", "this", "->", "commands", "[", "$", "i", "]", "->", "createNextCommand", "(", "$", "r", ")", ";", "if", "(", "$", "this", "->", "commands", "[", "$", "i", "]", "===", "null", ")", "{", "unset", "(", "$", "this", "->", "commands", "[", "$", "i", "]", ")", ";", "}", "}", "if", "(", "count", "(", "$", "this", "->", "commands", ")", "===", "0", ")", "{", "$", "this", "->", "commands", "=", "null", ";", "}", "}", "else", "{", "$", "this", "->", "commands", "=", "$", "this", "->", "commands", "->", "createNextCommand", "(", "$", "result", ")", ";", "}", "}" ]
Get a result page and populate the inner iterator. @return void
[ "Get", "a", "result", "page", "and", "populate", "the", "inner", "iterator", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Iterator/PagingIterator.php#L96-L118
train
Kris-Kuiper/sFire-Framework
src/Handler/ErrorHandler.php
ErrorHandler.setOptions
public function setOptions($options = []) { if(false === is_array($options)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type array, "%s" given', __METHOD__, gettype($options)), E_USER_ERROR); } $this -> options = array_merge($this -> options, $options); }
php
public function setOptions($options = []) { if(false === is_array($options)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type array, "%s" given', __METHOD__, gettype($options)), E_USER_ERROR); } $this -> options = array_merge($this -> options, $options); }
[ "public", "function", "setOptions", "(", "$", "options", "=", "[", "]", ")", "{", "if", "(", "false", "===", "is_array", "(", "$", "options", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type array, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "options", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "options", "=", "array_merge", "(", "$", "this", "->", "options", ",", "$", "options", ")", ";", "}" ]
Set debug options @param array $options
[ "Set", "debug", "options" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Handler/ErrorHandler.php#L124-L131
train
Kris-Kuiper/sFire-Framework
src/Handler/ErrorHandler.php
ErrorHandler.action
private function action() { $options = (object) $this -> options; if(true === $options -> write) { $this -> writeToFile(); } if(true == $options -> display) { return $this -> displayError(); } exit(); }
php
private function action() { $options = (object) $this -> options; if(true === $options -> write) { $this -> writeToFile(); } if(true == $options -> display) { return $this -> displayError(); } exit(); }
[ "private", "function", "action", "(", ")", "{", "$", "options", "=", "(", "object", ")", "$", "this", "->", "options", ";", "if", "(", "true", "===", "$", "options", "->", "write", ")", "{", "$", "this", "->", "writeToFile", "(", ")", ";", "}", "if", "(", "true", "==", "$", "options", "->", "display", ")", "{", "return", "$", "this", "->", "displayError", "(", ")", ";", "}", "exit", "(", ")", ";", "}" ]
Determines what to do with the error
[ "Determines", "what", "to", "do", "with", "the", "error" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Handler/ErrorHandler.php#L137-L150
train
Kris-Kuiper/sFire-Framework
src/Handler/ErrorHandler.php
ErrorHandler.writeToFile
private function writeToFile() { $logger = $this -> getLogger(); $logger -> setDirectory(Path :: get('log-error')); $error = $this -> error -> toJson($this -> options['types']); if(false === $error) { $this -> error -> setContext(null); $this -> error -> setBacktrace(null); } $error = $this -> error -> toJson($this -> options['types']); $logger -> write($this -> error -> toJson($this -> options['types'])); }
php
private function writeToFile() { $logger = $this -> getLogger(); $logger -> setDirectory(Path :: get('log-error')); $error = $this -> error -> toJson($this -> options['types']); if(false === $error) { $this -> error -> setContext(null); $this -> error -> setBacktrace(null); } $error = $this -> error -> toJson($this -> options['types']); $logger -> write($this -> error -> toJson($this -> options['types'])); }
[ "private", "function", "writeToFile", "(", ")", "{", "$", "logger", "=", "$", "this", "->", "getLogger", "(", ")", ";", "$", "logger", "->", "setDirectory", "(", "Path", "::", "get", "(", "'log-error'", ")", ")", ";", "$", "error", "=", "$", "this", "->", "error", "->", "toJson", "(", "$", "this", "->", "options", "[", "'types'", "]", ")", ";", "if", "(", "false", "===", "$", "error", ")", "{", "$", "this", "->", "error", "->", "setContext", "(", "null", ")", ";", "$", "this", "->", "error", "->", "setBacktrace", "(", "null", ")", ";", "}", "$", "error", "=", "$", "this", "->", "error", "->", "toJson", "(", "$", "this", "->", "options", "[", "'types'", "]", ")", ";", "$", "logger", "->", "write", "(", "$", "this", "->", "error", "->", "toJson", "(", "$", "this", "->", "options", "[", "'types'", "]", ")", ")", ";", "}" ]
Writes current error to log file
[ "Writes", "current", "error", "to", "log", "file" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Handler/ErrorHandler.php#L156-L171
train
Kris-Kuiper/sFire-Framework
src/Handler/ErrorHandler.php
ErrorHandler.displayError
private function displayError() { if(count($this -> options['ip']) === 0 || true === in_array(Request :: getIp(), $this -> options['ip'])) { $error = [ 'type' => $this -> error -> getType(), 'text' => $this -> error -> getMessage(), 'file' => $this -> error -> getFile(), 'line' => $this -> error -> getLine(), 'backtrace' => $this -> formatBacktrace() ]; exit('<pre>' . print_r($error, true) . '</pre>'); } }
php
private function displayError() { if(count($this -> options['ip']) === 0 || true === in_array(Request :: getIp(), $this -> options['ip'])) { $error = [ 'type' => $this -> error -> getType(), 'text' => $this -> error -> getMessage(), 'file' => $this -> error -> getFile(), 'line' => $this -> error -> getLine(), 'backtrace' => $this -> formatBacktrace() ]; exit('<pre>' . print_r($error, true) . '</pre>'); } }
[ "private", "function", "displayError", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "options", "[", "'ip'", "]", ")", "===", "0", "||", "true", "===", "in_array", "(", "Request", "::", "getIp", "(", ")", ",", "$", "this", "->", "options", "[", "'ip'", "]", ")", ")", "{", "$", "error", "=", "[", "'type'", "=>", "$", "this", "->", "error", "->", "getType", "(", ")", ",", "'text'", "=>", "$", "this", "->", "error", "->", "getMessage", "(", ")", ",", "'file'", "=>", "$", "this", "->", "error", "->", "getFile", "(", ")", ",", "'line'", "=>", "$", "this", "->", "error", "->", "getLine", "(", ")", ",", "'backtrace'", "=>", "$", "this", "->", "formatBacktrace", "(", ")", "]", ";", "exit", "(", "'<pre>'", ".", "print_r", "(", "$", "error", ",", "true", ")", ".", "'</pre>'", ")", ";", "}", "}" ]
Prints the error to client
[ "Prints", "the", "error", "to", "client" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Handler/ErrorHandler.php#L177-L192
train
Kris-Kuiper/sFire-Framework
src/Handler/ErrorHandler.php
ErrorHandler.formatBacktrace
private function formatBacktrace() { $backtrace = $this -> error -> getBacktrace(); if(null !== $backtrace) { array_shift($backtrace); array_shift($backtrace); foreach($backtrace as $index => $stack) { foreach(['type', 'args'] as $type) { if(true === isset($backtrace[$index][$type])) { unset($backtrace[$index][$type]); } } } } return $backtrace; }
php
private function formatBacktrace() { $backtrace = $this -> error -> getBacktrace(); if(null !== $backtrace) { array_shift($backtrace); array_shift($backtrace); foreach($backtrace as $index => $stack) { foreach(['type', 'args'] as $type) { if(true === isset($backtrace[$index][$type])) { unset($backtrace[$index][$type]); } } } } return $backtrace; }
[ "private", "function", "formatBacktrace", "(", ")", "{", "$", "backtrace", "=", "$", "this", "->", "error", "->", "getBacktrace", "(", ")", ";", "if", "(", "null", "!==", "$", "backtrace", ")", "{", "array_shift", "(", "$", "backtrace", ")", ";", "array_shift", "(", "$", "backtrace", ")", ";", "foreach", "(", "$", "backtrace", "as", "$", "index", "=>", "$", "stack", ")", "{", "foreach", "(", "[", "'type'", ",", "'args'", "]", "as", "$", "type", ")", "{", "if", "(", "true", "===", "isset", "(", "$", "backtrace", "[", "$", "index", "]", "[", "$", "type", "]", ")", ")", "{", "unset", "(", "$", "backtrace", "[", "$", "index", "]", "[", "$", "type", "]", ")", ";", "}", "}", "}", "}", "return", "$", "backtrace", ";", "}" ]
Formats the backtrace @return array
[ "Formats", "the", "backtrace" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Handler/ErrorHandler.php#L199-L220
train
ScaraMVC/Framework
src/Scara/Html/HtmlBuilder.php
HtmlBuilder.stylesheet
public function stylesheet($file) { $dirtypes = ['css', 'stylesheets', 'styles']; $asset = ''; if ($this->_generator->isValidUrl($file)) { $asset = $file; } else { foreach ($dirtypes as $dir) { $ext = substr($file, strrpos($file, '.') + 1); $file = $file.(($ext != 'css') ? '.css' : ''); $filepath = base_path().'/assets/'.$dir.'/'.$file; $asset = $this->_generator->asset($dir.'/'.$file); if (file_exists($filepath)) { break; } else { $asset = 'no stylesheet found'; } } } return '<link rel="stylesheet" type="text/css" href="'.$asset.'">'; }
php
public function stylesheet($file) { $dirtypes = ['css', 'stylesheets', 'styles']; $asset = ''; if ($this->_generator->isValidUrl($file)) { $asset = $file; } else { foreach ($dirtypes as $dir) { $ext = substr($file, strrpos($file, '.') + 1); $file = $file.(($ext != 'css') ? '.css' : ''); $filepath = base_path().'/assets/'.$dir.'/'.$file; $asset = $this->_generator->asset($dir.'/'.$file); if (file_exists($filepath)) { break; } else { $asset = 'no stylesheet found'; } } } return '<link rel="stylesheet" type="text/css" href="'.$asset.'">'; }
[ "public", "function", "stylesheet", "(", "$", "file", ")", "{", "$", "dirtypes", "=", "[", "'css'", ",", "'stylesheets'", ",", "'styles'", "]", ";", "$", "asset", "=", "''", ";", "if", "(", "$", "this", "->", "_generator", "->", "isValidUrl", "(", "$", "file", ")", ")", "{", "$", "asset", "=", "$", "file", ";", "}", "else", "{", "foreach", "(", "$", "dirtypes", "as", "$", "dir", ")", "{", "$", "ext", "=", "substr", "(", "$", "file", ",", "strrpos", "(", "$", "file", ",", "'.'", ")", "+", "1", ")", ";", "$", "file", "=", "$", "file", ".", "(", "(", "$", "ext", "!=", "'css'", ")", "?", "'.css'", ":", "''", ")", ";", "$", "filepath", "=", "base_path", "(", ")", ".", "'/assets/'", ".", "$", "dir", ".", "'/'", ".", "$", "file", ";", "$", "asset", "=", "$", "this", "->", "_generator", "->", "asset", "(", "$", "dir", ".", "'/'", ".", "$", "file", ")", ";", "if", "(", "file_exists", "(", "$", "filepath", ")", ")", "{", "break", ";", "}", "else", "{", "$", "asset", "=", "'no stylesheet found'", ";", "}", "}", "}", "return", "'<link rel=\"stylesheet\" type=\"text/css\" href=\"'", ".", "$", "asset", ".", "'\">'", ";", "}" ]
Returns a stylesheet HTML tag with given filename. @param string $file @return string
[ "Returns", "a", "stylesheet", "HTML", "tag", "with", "given", "filename", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Html/HtmlBuilder.php#L47-L70
train
ScaraMVC/Framework
src/Scara/Html/HtmlBuilder.php
HtmlBuilder.link
public function link($url, $content = '', $options = [], $safe = false) { if (is_null($content)) { $content = $url; } return '<a href="'.$this->_generator->generateUrl($url).'"'.self::attributes($options).'>'.self::encode($content, $safe).'</a>'; }
php
public function link($url, $content = '', $options = [], $safe = false) { if (is_null($content)) { $content = $url; } return '<a href="'.$this->_generator->generateUrl($url).'"'.self::attributes($options).'>'.self::encode($content, $safe).'</a>'; }
[ "public", "function", "link", "(", "$", "url", ",", "$", "content", "=", "''", ",", "$", "options", "=", "[", "]", ",", "$", "safe", "=", "false", ")", "{", "if", "(", "is_null", "(", "$", "content", ")", ")", "{", "$", "content", "=", "$", "url", ";", "}", "return", "'<a href=\"'", ".", "$", "this", "->", "_generator", "->", "generateUrl", "(", "$", "url", ")", ".", "'\"'", ".", "self", "::", "attributes", "(", "$", "options", ")", ".", "'>'", ".", "self", "::", "encode", "(", "$", "content", ",", "$", "safe", ")", ".", "'</a>'", ";", "}" ]
Generates an anchor tag. @param string $url @param string $content @param array $options @param bool $safe @return mixed
[ "Generates", "an", "anchor", "tag", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Html/HtmlBuilder.php#L126-L133
train
ScaraMVC/Framework
src/Scara/Html/HtmlBuilder.php
HtmlBuilder.image
public function image($url, $alt = null, $options = []) { $options['alt'] = $alt; return '<img src="'.$this->_generator->asset($url).'"'.self::attributes($options).'>'; }
php
public function image($url, $alt = null, $options = []) { $options['alt'] = $alt; return '<img src="'.$this->_generator->asset($url).'"'.self::attributes($options).'>'; }
[ "public", "function", "image", "(", "$", "url", ",", "$", "alt", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "$", "options", "[", "'alt'", "]", "=", "$", "alt", ";", "return", "'<img src=\"'", ".", "$", "this", "->", "_generator", "->", "asset", "(", "$", "url", ")", ".", "'\"'", ".", "self", "::", "attributes", "(", "$", "options", ")", ".", "'>'", ";", "}" ]
Creates an image element. @param string $url @param string $alt @param array $options @return string
[ "Creates", "an", "image", "element", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Html/HtmlBuilder.php#L170-L175
train
narrowspark/collection
src/Collection/Collection.php
Collection.whereInStrict
public function whereInStrict(string $key, $values): Collection { return $this->whereIn($key, $values, true); }
php
public function whereInStrict(string $key, $values): Collection { return $this->whereIn($key, $values, true); }
[ "public", "function", "whereInStrict", "(", "string", "$", "key", ",", "$", "values", ")", ":", "Collection", "{", "return", "$", "this", "->", "whereIn", "(", "$", "key", ",", "$", "values", ",", "true", ")", ";", "}" ]
Filter items by the given key value pair using strict comparison. @param string $key @param mixed $values @return static
[ "Filter", "items", "by", "the", "given", "key", "value", "pair", "using", "strict", "comparison", "." ]
c6ae76b2a7330e9673409d78fe5e61d2e167a8b8
https://github.com/narrowspark/collection/blob/c6ae76b2a7330e9673409d78fe5e61d2e167a8b8/src/Collection/Collection.php#L475-L478
train
narrowspark/collection
src/Collection/Collection.php
Collection.arsort
public function arsort(int $option = SORT_REGULAR): Collection { $index = 0; $items = $this->items; foreach ($items as &$item) { $item = [$index++, $item]; } uasort($items, function ($a, $b) use ($option) { if ($a[1] === $b[1]) { return $a[0] - $b[0]; } $set = [-1 => $b[1], 1 => $a[1]]; asort($set, $option); reset($set); return key($set); }); foreach ($items as &$item) { $item = $item[1]; } return new static($items); }
php
public function arsort(int $option = SORT_REGULAR): Collection { $index = 0; $items = $this->items; foreach ($items as &$item) { $item = [$index++, $item]; } uasort($items, function ($a, $b) use ($option) { if ($a[1] === $b[1]) { return $a[0] - $b[0]; } $set = [-1 => $b[1], 1 => $a[1]]; asort($set, $option); reset($set); return key($set); }); foreach ($items as &$item) { $item = $item[1]; } return new static($items); }
[ "public", "function", "arsort", "(", "int", "$", "option", "=", "SORT_REGULAR", ")", ":", "Collection", "{", "$", "index", "=", "0", ";", "$", "items", "=", "$", "this", "->", "items", ";", "foreach", "(", "$", "items", "as", "&", "$", "item", ")", "{", "$", "item", "=", "[", "$", "index", "++", ",", "$", "item", "]", ";", "}", "uasort", "(", "$", "items", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "option", ")", "{", "if", "(", "$", "a", "[", "1", "]", "===", "$", "b", "[", "1", "]", ")", "{", "return", "$", "a", "[", "0", "]", "-", "$", "b", "[", "0", "]", ";", "}", "$", "set", "=", "[", "-", "1", "=>", "$", "b", "[", "1", "]", ",", "1", "=>", "$", "a", "[", "1", "]", "]", ";", "asort", "(", "$", "set", ",", "$", "option", ")", ";", "reset", "(", "$", "set", ")", ";", "return", "key", "(", "$", "set", ")", ";", "}", ")", ";", "foreach", "(", "$", "items", "as", "&", "$", "item", ")", "{", "$", "item", "=", "$", "item", "[", "1", "]", ";", "}", "return", "new", "static", "(", "$", "items", ")", ";", "}" ]
Sort an array in reverse order and maintain index association. @param int $option @return static
[ "Sort", "an", "array", "in", "reverse", "order", "and", "maintain", "index", "association", "." ]
c6ae76b2a7330e9673409d78fe5e61d2e167a8b8
https://github.com/narrowspark/collection/blob/c6ae76b2a7330e9673409d78fe5e61d2e167a8b8/src/Collection/Collection.php#L1064-L1091
train
narrowspark/collection
src/Collection/Collection.php
Collection.natcasesort
public function natcasesort(): Collection { $index = 0; $items = $this->items; foreach ($items as &$item) { $item = [$index++, $item]; } uasort($items, function ($a, $b) { $result = strnatcasecmp($a[1], $b[1]); return $result === 0 ? $a[0] - $b[0] : $result; }); foreach ($items as &$item) { $item = $item[1]; } return new static($items); }
php
public function natcasesort(): Collection { $index = 0; $items = $this->items; foreach ($items as &$item) { $item = [$index++, $item]; } uasort($items, function ($a, $b) { $result = strnatcasecmp($a[1], $b[1]); return $result === 0 ? $a[0] - $b[0] : $result; }); foreach ($items as &$item) { $item = $item[1]; } return new static($items); }
[ "public", "function", "natcasesort", "(", ")", ":", "Collection", "{", "$", "index", "=", "0", ";", "$", "items", "=", "$", "this", "->", "items", ";", "foreach", "(", "$", "items", "as", "&", "$", "item", ")", "{", "$", "item", "=", "[", "$", "index", "++", ",", "$", "item", "]", ";", "}", "uasort", "(", "$", "items", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "$", "result", "=", "strnatcasecmp", "(", "$", "a", "[", "1", "]", ",", "$", "b", "[", "1", "]", ")", ";", "return", "$", "result", "===", "0", "?", "$", "a", "[", "0", "]", "-", "$", "b", "[", "0", "]", ":", "$", "result", ";", "}", ")", ";", "foreach", "(", "$", "items", "as", "&", "$", "item", ")", "{", "$", "item", "=", "$", "item", "[", "1", "]", ";", "}", "return", "new", "static", "(", "$", "items", ")", ";", "}" ]
Sort an array using a case insensitive "natural order" algorithm. @return static
[ "Sort", "an", "array", "using", "a", "case", "insensitive", "natural", "order", "algorithm", "." ]
c6ae76b2a7330e9673409d78fe5e61d2e167a8b8
https://github.com/narrowspark/collection/blob/c6ae76b2a7330e9673409d78fe5e61d2e167a8b8/src/Collection/Collection.php#L1134-L1154
train
narrowspark/collection
src/Collection/Collection.php
Collection.natsort
public function natsort(): Collection { $index = 0; $items = $this->items; foreach ($items as &$item) { $item = [$index++, $item]; } uasort($items, function ($a, $b) { $result = strnatcmp($a[1], $b[1]); return $result === 0 ? $a[0] - $b[0] : $result; }); foreach ($items as &$item) { $item = $item[1]; } return new static($items); }
php
public function natsort(): Collection { $index = 0; $items = $this->items; foreach ($items as &$item) { $item = [$index++, $item]; } uasort($items, function ($a, $b) { $result = strnatcmp($a[1], $b[1]); return $result === 0 ? $a[0] - $b[0] : $result; }); foreach ($items as &$item) { $item = $item[1]; } return new static($items); }
[ "public", "function", "natsort", "(", ")", ":", "Collection", "{", "$", "index", "=", "0", ";", "$", "items", "=", "$", "this", "->", "items", ";", "foreach", "(", "$", "items", "as", "&", "$", "item", ")", "{", "$", "item", "=", "[", "$", "index", "++", ",", "$", "item", "]", ";", "}", "uasort", "(", "$", "items", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "$", "result", "=", "strnatcmp", "(", "$", "a", "[", "1", "]", ",", "$", "b", "[", "1", "]", ")", ";", "return", "$", "result", "===", "0", "?", "$", "a", "[", "0", "]", "-", "$", "b", "[", "0", "]", ":", "$", "result", ";", "}", ")", ";", "foreach", "(", "$", "items", "as", "&", "$", "item", ")", "{", "$", "item", "=", "$", "item", "[", "1", "]", ";", "}", "return", "new", "static", "(", "$", "items", ")", ";", "}" ]
Sort an array using a "natural order" algorithm. @return static
[ "Sort", "an", "array", "using", "a", "natural", "order", "algorithm", "." ]
c6ae76b2a7330e9673409d78fe5e61d2e167a8b8
https://github.com/narrowspark/collection/blob/c6ae76b2a7330e9673409d78fe5e61d2e167a8b8/src/Collection/Collection.php#L1161-L1181
train
narrowspark/collection
src/Collection/Collection.php
Collection.uksort
public function uksort(callable $callback): Collection { $items = $this->items; $keys = array_combine(array_keys($items), range(1, count($items))); uksort($items, function ($a, $b) use ($callback, $keys) { $result = call_user_func($callback, $a, $b); return $result === 0 ? $keys[$a] - $keys[$b] : $result; }); return new static($items); }
php
public function uksort(callable $callback): Collection { $items = $this->items; $keys = array_combine(array_keys($items), range(1, count($items))); uksort($items, function ($a, $b) use ($callback, $keys) { $result = call_user_func($callback, $a, $b); return $result === 0 ? $keys[$a] - $keys[$b] : $result; }); return new static($items); }
[ "public", "function", "uksort", "(", "callable", "$", "callback", ")", ":", "Collection", "{", "$", "items", "=", "$", "this", "->", "items", ";", "$", "keys", "=", "array_combine", "(", "array_keys", "(", "$", "items", ")", ",", "range", "(", "1", ",", "count", "(", "$", "items", ")", ")", ")", ";", "uksort", "(", "$", "items", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "callback", ",", "$", "keys", ")", "{", "$", "result", "=", "call_user_func", "(", "$", "callback", ",", "$", "a", ",", "$", "b", ")", ";", "return", "$", "result", "===", "0", "?", "$", "keys", "[", "$", "a", "]", "-", "$", "keys", "[", "$", "b", "]", ":", "$", "result", ";", "}", ")", ";", "return", "new", "static", "(", "$", "items", ")", ";", "}" ]
Sort an array by keys using a user-defined comparison function. @param callable $callback @return static
[ "Sort", "an", "array", "by", "keys", "using", "a", "user", "-", "defined", "comparison", "function", "." ]
c6ae76b2a7330e9673409d78fe5e61d2e167a8b8
https://github.com/narrowspark/collection/blob/c6ae76b2a7330e9673409d78fe5e61d2e167a8b8/src/Collection/Collection.php#L1219-L1231
train
narrowspark/collection
src/Collection/Collection.php
Collection.usort
public function usort(callable $callback): Collection { $index = 0; $items = $this->items; foreach ($items as &$item) { $item = [$index++, $item]; } usort($items, function ($a, $b) use ($callback) { $result = call_user_func($callback, $a[1], $b[1]); return $result === 0 ? $a[0] - $b[0] : $result; }); foreach ($items as &$item) { $item = $item[1]; } return new static($items); }
php
public function usort(callable $callback): Collection { $index = 0; $items = $this->items; foreach ($items as &$item) { $item = [$index++, $item]; } usort($items, function ($a, $b) use ($callback) { $result = call_user_func($callback, $a[1], $b[1]); return $result === 0 ? $a[0] - $b[0] : $result; }); foreach ($items as &$item) { $item = $item[1]; } return new static($items); }
[ "public", "function", "usort", "(", "callable", "$", "callback", ")", ":", "Collection", "{", "$", "index", "=", "0", ";", "$", "items", "=", "$", "this", "->", "items", ";", "foreach", "(", "$", "items", "as", "&", "$", "item", ")", "{", "$", "item", "=", "[", "$", "index", "++", ",", "$", "item", "]", ";", "}", "usort", "(", "$", "items", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "callback", ")", "{", "$", "result", "=", "call_user_func", "(", "$", "callback", ",", "$", "a", "[", "1", "]", ",", "$", "b", "[", "1", "]", ")", ";", "return", "$", "result", "===", "0", "?", "$", "a", "[", "0", "]", "-", "$", "b", "[", "0", "]", ":", "$", "result", ";", "}", ")", ";", "foreach", "(", "$", "items", "as", "&", "$", "item", ")", "{", "$", "item", "=", "$", "item", "[", "1", "]", ";", "}", "return", "new", "static", "(", "$", "items", ")", ";", "}" ]
Sort an array by values using a user-defined comparison function. @param callable $callback @return static
[ "Sort", "an", "array", "by", "values", "using", "a", "user", "-", "defined", "comparison", "function", "." ]
c6ae76b2a7330e9673409d78fe5e61d2e167a8b8
https://github.com/narrowspark/collection/blob/c6ae76b2a7330e9673409d78fe5e61d2e167a8b8/src/Collection/Collection.php#L1240-L1260
train
phpguard/listen
src/PhpGuard/Listen/Adapter/InotifyAdapter.php
InotifyAdapter.initialize
public function initialize(Listener $listener) { $this->tracker->initialize($listener); $this->wathedPaths = $listener->getPaths(); }
php
public function initialize(Listener $listener) { $this->tracker->initialize($listener); $this->wathedPaths = $listener->getPaths(); }
[ "public", "function", "initialize", "(", "Listener", "$", "listener", ")", "{", "$", "this", "->", "tracker", "->", "initialize", "(", "$", "listener", ")", ";", "$", "this", "->", "wathedPaths", "=", "$", "listener", "->", "getPaths", "(", ")", ";", "}" ]
Initialize new listener @param Listener $listener @return mixed
[ "Initialize", "new", "listener" ]
cd0cda150858d6d85deb025a72996873d2af3532
https://github.com/phpguard/listen/blob/cd0cda150858d6d85deb025a72996873d2af3532/src/PhpGuard/Listen/Adapter/InotifyAdapter.php#L52-L56
train
phpguard/listen
src/PhpGuard/Listen/Adapter/InotifyAdapter.php
InotifyAdapter.evaluate
public function evaluate() { $this->tracker->clearChangeSet(); $this->modified = array(); $inEvents = inotify_read($this->inotify); $inEvents = is_array($inEvents) ? $inEvents:array(); foreach($inEvents as $inEvent){ $this->translateEvent($inEvent); } }
php
public function evaluate() { $this->tracker->clearChangeSet(); $this->modified = array(); $inEvents = inotify_read($this->inotify); $inEvents = is_array($inEvents) ? $inEvents:array(); foreach($inEvents as $inEvent){ $this->translateEvent($inEvent); } }
[ "public", "function", "evaluate", "(", ")", "{", "$", "this", "->", "tracker", "->", "clearChangeSet", "(", ")", ";", "$", "this", "->", "modified", "=", "array", "(", ")", ";", "$", "inEvents", "=", "inotify_read", "(", "$", "this", "->", "inotify", ")", ";", "$", "inEvents", "=", "is_array", "(", "$", "inEvents", ")", "?", "$", "inEvents", ":", "array", "(", ")", ";", "foreach", "(", "$", "inEvents", "as", "$", "inEvent", ")", "{", "$", "this", "->", "translateEvent", "(", "$", "inEvent", ")", ";", "}", "}" ]
Evaluate Filesystem changes @return mixed
[ "Evaluate", "Filesystem", "changes" ]
cd0cda150858d6d85deb025a72996873d2af3532
https://github.com/phpguard/listen/blob/cd0cda150858d6d85deb025a72996873d2af3532/src/PhpGuard/Listen/Adapter/InotifyAdapter.php#L63-L75
train
jamset/process-load-manager
src/LoadManager/Lm.php
Lm.manage
public function manage() { $this->initLoop(); /** * @var \ZMQContext */ $this->context = new Context($this->loop); $this->initStreams(); $this->pmReplySocket = $this->context->getSocket(\ZMQ::SOCKET_REP); $this->dtoContainer = new DtoContainer(); $this->dtoContainer->setDto(new LmStateDto()); $this->commandsManager = new CommandsManager(); $this->declareGettingLmParams(); $this->managingTimer(); $this->loop->run(); return null; }
php
public function manage() { $this->initLoop(); /** * @var \ZMQContext */ $this->context = new Context($this->loop); $this->initStreams(); $this->pmReplySocket = $this->context->getSocket(\ZMQ::SOCKET_REP); $this->dtoContainer = new DtoContainer(); $this->dtoContainer->setDto(new LmStateDto()); $this->commandsManager = new CommandsManager(); $this->declareGettingLmParams(); $this->managingTimer(); $this->loop->run(); return null; }
[ "public", "function", "manage", "(", ")", "{", "$", "this", "->", "initLoop", "(", ")", ";", "/**\n * @var \\ZMQContext\n */", "$", "this", "->", "context", "=", "new", "Context", "(", "$", "this", "->", "loop", ")", ";", "$", "this", "->", "initStreams", "(", ")", ";", "$", "this", "->", "pmReplySocket", "=", "$", "this", "->", "context", "->", "getSocket", "(", "\\", "ZMQ", "::", "SOCKET_REP", ")", ";", "$", "this", "->", "dtoContainer", "=", "new", "DtoContainer", "(", ")", ";", "$", "this", "->", "dtoContainer", "->", "setDto", "(", "new", "LmStateDto", "(", ")", ")", ";", "$", "this", "->", "commandsManager", "=", "new", "CommandsManager", "(", ")", ";", "$", "this", "->", "declareGettingLmParams", "(", ")", ";", "$", "this", "->", "managingTimer", "(", ")", ";", "$", "this", "->", "loop", "->", "run", "(", ")", ";", "return", "null", ";", "}" ]
Send periodic signals about CPU and memory status; total and per PID
[ "Send", "periodic", "signals", "about", "CPU", "and", "memory", "status", ";", "total", "and", "per", "PID" ]
cffed6ff73bf66617565707ec4f2c9251a497cc6
https://github.com/jamset/process-load-manager/blob/cffed6ff73bf66617565707ec4f2c9251a497cc6/src/LoadManager/Lm.php#L275-L298
train
OpenConext-Attic/OpenConext-engineblock-metadata
src/X509/X509CertificateFactory.php
X509CertificateFactory.fromFile
public function fromFile($filePath) { $pemString = file_get_contents($filePath); if (!$pemString) { throw new RuntimeException("Unable to read file at path '$filePath'."); } try { $certificate = $this->fromString($pemString); } catch (Exception $e) { throw new RuntimeException("File at '$filePath' does not contain a valid certificate.", 0, $e); } return $certificate; }
php
public function fromFile($filePath) { $pemString = file_get_contents($filePath); if (!$pemString) { throw new RuntimeException("Unable to read file at path '$filePath'."); } try { $certificate = $this->fromString($pemString); } catch (Exception $e) { throw new RuntimeException("File at '$filePath' does not contain a valid certificate.", 0, $e); } return $certificate; }
[ "public", "function", "fromFile", "(", "$", "filePath", ")", "{", "$", "pemString", "=", "file_get_contents", "(", "$", "filePath", ")", ";", "if", "(", "!", "$", "pemString", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unable to read file at path '$filePath'.\"", ")", ";", "}", "try", "{", "$", "certificate", "=", "$", "this", "->", "fromString", "(", "$", "pemString", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"File at '$filePath' does not contain a valid certificate.\"", ",", "0", ",", "$", "e", ")", ";", "}", "return", "$", "certificate", ";", "}" ]
Create a certificate from a file path. @param string $filePath @return X509Certificate @throws RuntimeException
[ "Create", "a", "certificate", "from", "a", "file", "path", "." ]
236e2f52ef9cf28e71404544a1c4388f63ee535d
https://github.com/OpenConext-Attic/OpenConext-engineblock-metadata/blob/236e2f52ef9cf28e71404544a1c4388f63ee535d/src/X509/X509CertificateFactory.php#L20-L34
train
OpenConext-Attic/OpenConext-engineblock-metadata
src/X509/X509CertificateFactory.php
X509CertificateFactory.formatKey
private function formatKey($certData) { return X509Certificate::PEM_HEADER . PHP_EOL . // Chunk it in 64 character bytes chunk_split($certData, 64, PHP_EOL) . X509Certificate::PEM_FOOTER . PHP_EOL; }
php
private function formatKey($certData) { return X509Certificate::PEM_HEADER . PHP_EOL . // Chunk it in 64 character bytes chunk_split($certData, 64, PHP_EOL) . X509Certificate::PEM_FOOTER . PHP_EOL; }
[ "private", "function", "formatKey", "(", "$", "certData", ")", "{", "return", "X509Certificate", "::", "PEM_HEADER", ".", "PHP_EOL", ".", "// Chunk it in 64 character bytes", "chunk_split", "(", "$", "certData", ",", "64", ",", "PHP_EOL", ")", ".", "X509Certificate", "::", "PEM_FOOTER", ".", "PHP_EOL", ";", "}" ]
Given the 'certData' string, turn it back into a proper PEM encoded certificate. @param string $certData @return string
[ "Given", "the", "certData", "string", "turn", "it", "back", "into", "a", "proper", "PEM", "encoded", "certificate", "." ]
236e2f52ef9cf28e71404544a1c4388f63ee535d
https://github.com/OpenConext-Attic/OpenConext-engineblock-metadata/blob/236e2f52ef9cf28e71404544a1c4388f63ee535d/src/X509/X509CertificateFactory.php#L88-L96
train
Montage-Inc/php-montage
src/Schema.php
Schema.detail
public function detail() { $url = $this->montage->url('schema-detail', $this->name); return $this->montage->request('get', $url); }
php
public function detail() { $url = $this->montage->url('schema-detail', $this->name); return $this->montage->request('get', $url); }
[ "public", "function", "detail", "(", ")", "{", "$", "url", "=", "$", "this", "->", "montage", "->", "url", "(", "'schema-detail'", ",", "$", "this", "->", "name", ")", ";", "return", "$", "this", "->", "montage", "->", "request", "(", "'get'", ",", "$", "url", ")", ";", "}" ]
Returns the details of a specific Montage schema. @return mixed
[ "Returns", "the", "details", "of", "a", "specific", "Montage", "schema", "." ]
bcd526985447a31c7e5b74555058e167242b23ed
https://github.com/Montage-Inc/php-montage/blob/bcd526985447a31c7e5b74555058e167242b23ed/src/Schema.php#L40-L44
train
zodream/database
src/Query/Components/SelectBuilder.php
SelectBuilder.parseSubSelect
protected function parseSubSelect($query) { if ($query instanceof self) { $query->columns = [$query->columns[0]]; return [$query->toSql(), $query->getBindings()]; } elseif (is_string($query)) { return [$query, []]; } else { throw new \InvalidArgumentException(); } }
php
protected function parseSubSelect($query) { if ($query instanceof self) { $query->columns = [$query->columns[0]]; return [$query->toSql(), $query->getBindings()]; } elseif (is_string($query)) { return [$query, []]; } else { throw new \InvalidArgumentException(); } }
[ "protected", "function", "parseSubSelect", "(", "$", "query", ")", "{", "if", "(", "$", "query", "instanceof", "self", ")", "{", "$", "query", "->", "columns", "=", "[", "$", "query", "->", "columns", "[", "0", "]", "]", ";", "return", "[", "$", "query", "->", "toSql", "(", ")", ",", "$", "query", "->", "getBindings", "(", ")", "]", ";", "}", "elseif", "(", "is_string", "(", "$", "query", ")", ")", "{", "return", "[", "$", "query", ",", "[", "]", "]", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", ")", ";", "}", "}" ]
Parse the sub-select query into SQL and bindings. @param mixed $query @return array
[ "Parse", "the", "sub", "-", "select", "query", "into", "SQL", "and", "bindings", "." ]
03712219c057799d07350a3a2650c55bcc92c28e
https://github.com/zodream/database/blob/03712219c057799d07350a3a2650c55bcc92c28e/src/Query/Components/SelectBuilder.php#L83-L93
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.loadLateLoadProperty
private function loadLateLoadProperty() { // can only lateLateLoad a property if it is the sole primary key $pks = $this->pgClass->getPrimaryKeys(); $this->lateLoadProperty = ( count( $pks ) === 1 ) ? $pks->pop()->name : null ; }
php
private function loadLateLoadProperty() { // can only lateLateLoad a property if it is the sole primary key $pks = $this->pgClass->getPrimaryKeys(); $this->lateLoadProperty = ( count( $pks ) === 1 ) ? $pks->pop()->name : null ; }
[ "private", "function", "loadLateLoadProperty", "(", ")", "{", "// can only lateLateLoad a property if it is the sole primary key", "$", "pks", "=", "$", "this", "->", "pgClass", "->", "getPrimaryKeys", "(", ")", ";", "$", "this", "->", "lateLoadProperty", "=", "(", "count", "(", "$", "pks", ")", "===", "1", ")", "?", "$", "pks", "->", "pop", "(", ")", "->", "name", ":", "null", ";", "}" ]
Determine the lateLoadProperty @return void
[ "Determine", "the", "lateLoadProperty" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L226-L236
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.getIsZombieFunction
private function getIsZombieFunction() { // get primary key reference columns $zombieTests = $this->pgClass->getAttributes()->filter( function ($e) { return $e->isZombie(); } )->map( function ($zombieCol) { return sprintf( "( null === \$this->data['%s'] )", addslashes( $zombieCol->name ) ); } ); if( $zombieTests ) { $this->class->classComponents[] = new FunctionDeclaration( 'data', new Sformatf( <<<'PHP' /** * Is a zombie object? * @inheritDoc */ public function isZombie() { return %s; } PHP , implode( " or ", $zombieTests ) ) ); } }
php
private function getIsZombieFunction() { // get primary key reference columns $zombieTests = $this->pgClass->getAttributes()->filter( function ($e) { return $e->isZombie(); } )->map( function ($zombieCol) { return sprintf( "( null === \$this->data['%s'] )", addslashes( $zombieCol->name ) ); } ); if( $zombieTests ) { $this->class->classComponents[] = new FunctionDeclaration( 'data', new Sformatf( <<<'PHP' /** * Is a zombie object? * @inheritDoc */ public function isZombie() { return %s; } PHP , implode( " or ", $zombieTests ) ) ); } }
[ "private", "function", "getIsZombieFunction", "(", ")", "{", "// get primary key reference columns", "$", "zombieTests", "=", "$", "this", "->", "pgClass", "->", "getAttributes", "(", ")", "->", "filter", "(", "function", "(", "$", "e", ")", "{", "return", "$", "e", "->", "isZombie", "(", ")", ";", "}", ")", "->", "map", "(", "function", "(", "$", "zombieCol", ")", "{", "return", "sprintf", "(", "\"( null === \\$this->data['%s'] )\"", ",", "addslashes", "(", "$", "zombieCol", "->", "name", ")", ")", ";", "}", ")", ";", "if", "(", "$", "zombieTests", ")", "{", "$", "this", "->", "class", "->", "classComponents", "[", "]", "=", "new", "FunctionDeclaration", "(", "'data'", ",", "new", "Sformatf", "(", " <<<'PHP'\n /**\n * Is a zombie object?\n * @inheritDoc\n */\n public function isZombie()\n {\n return %s;\n }\nPHP", ",", "implode", "(", "\" or \"", ",", "$", "zombieTests", ")", ")", ")", ";", "}", "}" ]
Produce the isZombie method
[ "Produce", "the", "isZombie", "method" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L514-L550
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.getSqlInterfaceFunction
private function getSqlInterfaceFunction() { if( count($this->keyProperties) !== 1 ) { $content = " throw new \LogicException('Normality can\\'t (yet) handle tables without a primary key or multi-column primary keys.\\n". "Please extend the generator or overload {$this->pgClass->getEntityName()}->parse().');"; } else { $primaryKey = $this->keyProperties[0]; $dataType = $this->dataTypes[$primaryKey]; // if datatype inheritied we don't need to do anything if( $dataType->isInherited() ) { return array(); } // we're doing something $content = ''; $this->class->addImplements( "SqlInterface"); $this->class->addUses( 'Bond\Sql\QuoteInterface' ); $this->class->addUses( 'Bond\Sql\SqlInterface' ); if( $dataType->getType() === 'int' ) { // can this property be a entity? if( $dataType->isEntity() ) { $content .= <<<PHP if( is_object( \$this->data['{$primaryKey}'] ) and \$this->data['{$primaryKey}'] instanceof SqlInterface ) { return \$this->data['{$primaryKey}']->parse( \$quoting ); }\n PHP ; } // cast integer datatype to int if not null $content .= <<<PHP return \$this->data['{$primaryKey}'] !== null ? (string) (int) \$this->data['{$primaryKey}'] : 'NULL'; PHP ; } else { $content .= <<<PHP return \$quoting->quote( \$this->data['{$primaryKey}'] ); PHP ; } } $fn = new Sformatf( <<<'PHP' /** * Impementation of interface \Bond\Pg\Query->Validate() * @return scalar */ public function parse( QuoteInterface $quoting ) { %s } PHP , $content ); $this->class->classComponents[] = new FunctionDeclaration( "parse", $fn ); }
php
private function getSqlInterfaceFunction() { if( count($this->keyProperties) !== 1 ) { $content = " throw new \LogicException('Normality can\\'t (yet) handle tables without a primary key or multi-column primary keys.\\n". "Please extend the generator or overload {$this->pgClass->getEntityName()}->parse().');"; } else { $primaryKey = $this->keyProperties[0]; $dataType = $this->dataTypes[$primaryKey]; // if datatype inheritied we don't need to do anything if( $dataType->isInherited() ) { return array(); } // we're doing something $content = ''; $this->class->addImplements( "SqlInterface"); $this->class->addUses( 'Bond\Sql\QuoteInterface' ); $this->class->addUses( 'Bond\Sql\SqlInterface' ); if( $dataType->getType() === 'int' ) { // can this property be a entity? if( $dataType->isEntity() ) { $content .= <<<PHP if( is_object( \$this->data['{$primaryKey}'] ) and \$this->data['{$primaryKey}'] instanceof SqlInterface ) { return \$this->data['{$primaryKey}']->parse( \$quoting ); }\n PHP ; } // cast integer datatype to int if not null $content .= <<<PHP return \$this->data['{$primaryKey}'] !== null ? (string) (int) \$this->data['{$primaryKey}'] : 'NULL'; PHP ; } else { $content .= <<<PHP return \$quoting->quote( \$this->data['{$primaryKey}'] ); PHP ; } } $fn = new Sformatf( <<<'PHP' /** * Impementation of interface \Bond\Pg\Query->Validate() * @return scalar */ public function parse( QuoteInterface $quoting ) { %s } PHP , $content ); $this->class->classComponents[] = new FunctionDeclaration( "parse", $fn ); }
[ "private", "function", "getSqlInterfaceFunction", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "keyProperties", ")", "!==", "1", ")", "{", "$", "content", "=", "\" throw new \\LogicException('Normality can\\\\'t (yet) handle tables without a primary key or multi-column primary keys.\\\\n\"", ".", "\"Please extend the generator or overload {$this->pgClass->getEntityName()}->parse().');\"", ";", "}", "else", "{", "$", "primaryKey", "=", "$", "this", "->", "keyProperties", "[", "0", "]", ";", "$", "dataType", "=", "$", "this", "->", "dataTypes", "[", "$", "primaryKey", "]", ";", "// if datatype inheritied we don't need to do anything", "if", "(", "$", "dataType", "->", "isInherited", "(", ")", ")", "{", "return", "array", "(", ")", ";", "}", "// we're doing something", "$", "content", "=", "''", ";", "$", "this", "->", "class", "->", "addImplements", "(", "\"SqlInterface\"", ")", ";", "$", "this", "->", "class", "->", "addUses", "(", "'Bond\\Sql\\QuoteInterface'", ")", ";", "$", "this", "->", "class", "->", "addUses", "(", "'Bond\\Sql\\SqlInterface'", ")", ";", "if", "(", "$", "dataType", "->", "getType", "(", ")", "===", "'int'", ")", "{", "// can this property be a entity?", "if", "(", "$", "dataType", "->", "isEntity", "(", ")", ")", "{", "$", "content", ".=", " <<<PHP\n if( is_object( \\$this->data['{$primaryKey}'] ) and \\$this->data['{$primaryKey}'] instanceof SqlInterface ) {\n return \\$this->data['{$primaryKey}']->parse( \\$quoting );\n }\\n\nPHP", ";", "}", "// cast integer datatype to int if not null", "$", "content", ".=", " <<<PHP\n return \\$this->data['{$primaryKey}'] !== null ? (string) (int) \\$this->data['{$primaryKey}'] : 'NULL';\nPHP", ";", "}", "else", "{", "$", "content", ".=", " <<<PHP\n return \\$quoting->quote( \\$this->data['{$primaryKey}'] );\nPHP", ";", "}", "}", "$", "fn", "=", "new", "Sformatf", "(", " <<<'PHP'\n/**\n * Impementation of interface \\Bond\\Pg\\Query->Validate()\n * @return scalar\n */\npublic function parse( QuoteInterface $quoting )\n{\n%s\n}\n\nPHP", ",", "$", "content", ")", ";", "$", "this", "->", "class", "->", "classComponents", "[", "]", "=", "new", "FunctionDeclaration", "(", "\"parse\"", ",", "$", "fn", ")", ";", "}" ]
Produce the static entity function data @return array $lines
[ "Produce", "the", "static", "entity", "function", "data" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L556-L626
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.generateGetSetLinksCallback
private function generateGetSetLinksCallback( &$get, &$set, $name, $link ) { foreach( $link->foreignEntities as $foreignEntity ) { $nameForeignEntity = $this->getSetAlias( "{$foreignEntity}s", 'data' ); $this->additionalProperties[] = $nameForeignEntity; $this->class->addUses('Bond\\Repository'); $this->class->addUses( 'Bond\\Entity\\StaticMethods' ); // we got a ranking column? $sort = ''; if( isset( $link->linkSortColumn ) ) { $sort = sprintf( "->sortByProperty('%s')", addslashes( $link->linkSortColumn ) ); } // get $getCaseStatement = explode( "\n", sprintf( <<<CASE case '%s': return Repository::linksGet( \$this, '%s', '%s', null, true )%s;\n CASE , $nameForeignEntity, $name, $foreignEntity, $sort )); $get = array_merge( $get, $getCaseStatement ); // set $setCaseStatement = explode( "\n", sprintf( <<<CASE case '%s': return StaticMethods::set_links( \$this, '%s', \$value );\n CASE , $nameForeignEntity, $name )); $set = array_merge( $set, $setCaseStatement ); } }
php
private function generateGetSetLinksCallback( &$get, &$set, $name, $link ) { foreach( $link->foreignEntities as $foreignEntity ) { $nameForeignEntity = $this->getSetAlias( "{$foreignEntity}s", 'data' ); $this->additionalProperties[] = $nameForeignEntity; $this->class->addUses('Bond\\Repository'); $this->class->addUses( 'Bond\\Entity\\StaticMethods' ); // we got a ranking column? $sort = ''; if( isset( $link->linkSortColumn ) ) { $sort = sprintf( "->sortByProperty('%s')", addslashes( $link->linkSortColumn ) ); } // get $getCaseStatement = explode( "\n", sprintf( <<<CASE case '%s': return Repository::linksGet( \$this, '%s', '%s', null, true )%s;\n CASE , $nameForeignEntity, $name, $foreignEntity, $sort )); $get = array_merge( $get, $getCaseStatement ); // set $setCaseStatement = explode( "\n", sprintf( <<<CASE case '%s': return StaticMethods::set_links( \$this, '%s', \$value );\n CASE , $nameForeignEntity, $name )); $set = array_merge( $set, $setCaseStatement ); } }
[ "private", "function", "generateGetSetLinksCallback", "(", "&", "$", "get", ",", "&", "$", "set", ",", "$", "name", ",", "$", "link", ")", "{", "foreach", "(", "$", "link", "->", "foreignEntities", "as", "$", "foreignEntity", ")", "{", "$", "nameForeignEntity", "=", "$", "this", "->", "getSetAlias", "(", "\"{$foreignEntity}s\"", ",", "'data'", ")", ";", "$", "this", "->", "additionalProperties", "[", "]", "=", "$", "nameForeignEntity", ";", "$", "this", "->", "class", "->", "addUses", "(", "'Bond\\\\Repository'", ")", ";", "$", "this", "->", "class", "->", "addUses", "(", "'Bond\\\\Entity\\\\StaticMethods'", ")", ";", "// we got a ranking column?", "$", "sort", "=", "''", ";", "if", "(", "isset", "(", "$", "link", "->", "linkSortColumn", ")", ")", "{", "$", "sort", "=", "sprintf", "(", "\"->sortByProperty('%s')\"", ",", "addslashes", "(", "$", "link", "->", "linkSortColumn", ")", ")", ";", "}", "// get", "$", "getCaseStatement", "=", "explode", "(", "\"\\n\"", ",", "sprintf", "(", " <<<CASE\ncase '%s':\n return Repository::linksGet( \\$this, '%s', '%s', null, true )%s;\\n\nCASE", ",", "$", "nameForeignEntity", ",", "$", "name", ",", "$", "foreignEntity", ",", "$", "sort", ")", ")", ";", "$", "get", "=", "array_merge", "(", "$", "get", ",", "$", "getCaseStatement", ")", ";", "// set", "$", "setCaseStatement", "=", "explode", "(", "\"\\n\"", ",", "sprintf", "(", " <<<CASE\ncase '%s':\n return StaticMethods::set_links( \\$this, '%s', \\$value );\\n\nCASE", ",", "$", "nameForeignEntity", ",", "$", "name", ")", ")", ";", "$", "set", "=", "array_merge", "(", "$", "set", ",", "$", "setCaseStatement", ")", ";", "}", "}" ]
many to many references to foreign entities @param array $get @param array $set @param $reference See, Relation->getLinks()
[ "many", "to", "many", "references", "to", "foreign", "entities" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L772-L821
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.generateGetSetReferenceCallback
private function generateGetSetReferenceCallback( &$get, &$set, $reference ) { // we not on the ignore list? if( !( $property = $this->getSetAlias( $reference, 'reference' ) ) ) { return; } $this->additionalProperties[] = $property; // DEPRECIATED Symfony2 compatible getter / setter // $this->addSymfonyFormCompatibleGetter( $property ); // $this->addSymfonyFormCompatibleSetter( $property ); $this->class->addUses('Bond\\Repository'); $this->class->addUses( 'Bond\\Entity\\StaticMethods' ); // get $getCaseStatement = explode( "\n", sprintf( <<<CASE case '%s': return \$this->r()->referencesGet( \$this, '%s.%s' );\n CASE , $property, $reference[0], $reference[1] )); $get = array_merge( $get, $getCaseStatement ); // set $setCaseStatement = explode( "\n", sprintf( <<<CASE case '%s': return StaticMethods::set_references( \$this, '%s.%s', \$value );\n CASE , $property, $reference[0], $reference[1] )); $set = array_merge( $set, $setCaseStatement ); }
php
private function generateGetSetReferenceCallback( &$get, &$set, $reference ) { // we not on the ignore list? if( !( $property = $this->getSetAlias( $reference, 'reference' ) ) ) { return; } $this->additionalProperties[] = $property; // DEPRECIATED Symfony2 compatible getter / setter // $this->addSymfonyFormCompatibleGetter( $property ); // $this->addSymfonyFormCompatibleSetter( $property ); $this->class->addUses('Bond\\Repository'); $this->class->addUses( 'Bond\\Entity\\StaticMethods' ); // get $getCaseStatement = explode( "\n", sprintf( <<<CASE case '%s': return \$this->r()->referencesGet( \$this, '%s.%s' );\n CASE , $property, $reference[0], $reference[1] )); $get = array_merge( $get, $getCaseStatement ); // set $setCaseStatement = explode( "\n", sprintf( <<<CASE case '%s': return StaticMethods::set_references( \$this, '%s.%s', \$value );\n CASE , $property, $reference[0], $reference[1] )); $set = array_merge( $set, $setCaseStatement ); }
[ "private", "function", "generateGetSetReferenceCallback", "(", "&", "$", "get", ",", "&", "$", "set", ",", "$", "reference", ")", "{", "// we not on the ignore list?", "if", "(", "!", "(", "$", "property", "=", "$", "this", "->", "getSetAlias", "(", "$", "reference", ",", "'reference'", ")", ")", ")", "{", "return", ";", "}", "$", "this", "->", "additionalProperties", "[", "]", "=", "$", "property", ";", "// DEPRECIATED Symfony2 compatible getter / setter", "// $this->addSymfonyFormCompatibleGetter( $property );", "// $this->addSymfonyFormCompatibleSetter( $property );", "$", "this", "->", "class", "->", "addUses", "(", "'Bond\\\\Repository'", ")", ";", "$", "this", "->", "class", "->", "addUses", "(", "'Bond\\\\Entity\\\\StaticMethods'", ")", ";", "// get", "$", "getCaseStatement", "=", "explode", "(", "\"\\n\"", ",", "sprintf", "(", " <<<CASE\ncase '%s':\n return \\$this->r()->referencesGet( \\$this, '%s.%s' );\\n\nCASE", ",", "$", "property", ",", "$", "reference", "[", "0", "]", ",", "$", "reference", "[", "1", "]", ")", ")", ";", "$", "get", "=", "array_merge", "(", "$", "get", ",", "$", "getCaseStatement", ")", ";", "// set", "$", "setCaseStatement", "=", "explode", "(", "\"\\n\"", ",", "sprintf", "(", " <<<CASE\ncase '%s':\n return StaticMethods::set_references( \\$this, '%s.%s', \\$value );\\n\nCASE", ",", "$", "property", ",", "$", "reference", "[", "0", "]", ",", "$", "reference", "[", "1", "]", ")", ")", ";", "$", "set", "=", "array_merge", "(", "$", "set", ",", "$", "setCaseStatement", ")", ";", "}" ]
References to foreign entities in a 1->1 or 1->many way. Think, Contact -> ContactUser or Contact -> Addresses @param array $get @param array $set @param $reference See, Relation->getReferences()
[ "References", "to", "foreign", "entities", "in", "a", "1", "-", ">", "1", "or", "1", "-", ">", "many", "way", ".", "Think", "Contact", "-", ">", "ContactUser", "or", "Contact", "-", ">", "Addresses" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L831-L874
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.generateGetSetBoolCallback
private function generateGetSetBoolCallback( &$get, &$set, $columnName ) { $this->class->classComponents[] = new FunctionDeclaration( "getset.{$columnName}.get", $this->generateGetCallbackForBool( $columnName ) ); $this->class->classComponents[] = new FunctionDeclaration( "getset.{$columnName}.set", $this->generateSetCallbackForBool( $columnName ) ); }
php
private function generateGetSetBoolCallback( &$get, &$set, $columnName ) { $this->class->classComponents[] = new FunctionDeclaration( "getset.{$columnName}.get", $this->generateGetCallbackForBool( $columnName ) ); $this->class->classComponents[] = new FunctionDeclaration( "getset.{$columnName}.set", $this->generateSetCallbackForBool( $columnName ) ); }
[ "private", "function", "generateGetSetBoolCallback", "(", "&", "$", "get", ",", "&", "$", "set", ",", "$", "columnName", ")", "{", "$", "this", "->", "class", "->", "classComponents", "[", "]", "=", "new", "FunctionDeclaration", "(", "\"getset.{$columnName}.get\"", ",", "$", "this", "->", "generateGetCallbackForBool", "(", "$", "columnName", ")", ")", ";", "$", "this", "->", "class", "->", "classComponents", "[", "]", "=", "new", "FunctionDeclaration", "(", "\"getset.{$columnName}.set\"", ",", "$", "this", "->", "generateSetCallbackForBool", "(", "$", "columnName", ")", ")", ";", "}" ]
Bool columns. @param array $get @param array $set @param string $columnName @param string $entity
[ "Bool", "columns", "." ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L884-L897
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.getSymfonyCompatibleGettersAndSetters
private function getSymfonyCompatibleGettersAndSetters() { return array(); if( !$this->symfonyFormGetters ) { return array(); } // build output $output = explode( "\n", <<<PHP /** * Symfony2 compatible getters and setters. * These are __not__ to be used by Bond code. These have be depreciated. */ // /* PHP ); $output = array_merge( $output, $this->symfonyFormGetters, array(''), $this->symfonyFormSetters, array('/**/') ); return $output; }
php
private function getSymfonyCompatibleGettersAndSetters() { return array(); if( !$this->symfonyFormGetters ) { return array(); } // build output $output = explode( "\n", <<<PHP /** * Symfony2 compatible getters and setters. * These are __not__ to be used by Bond code. These have be depreciated. */ // /* PHP ); $output = array_merge( $output, $this->symfonyFormGetters, array(''), $this->symfonyFormSetters, array('/**/') ); return $output; }
[ "private", "function", "getSymfonyCompatibleGettersAndSetters", "(", ")", "{", "return", "array", "(", ")", ";", "if", "(", "!", "$", "this", "->", "symfonyFormGetters", ")", "{", "return", "array", "(", ")", ";", "}", "// build output", "$", "output", "=", "explode", "(", "\"\\n\"", ",", " <<<PHP\n/**\n* Symfony2 compatible getters and setters.\n* These are __not__ to be used by Bond code. These have be depreciated.\n*/\n// /*\nPHP", ")", ";", "$", "output", "=", "array_merge", "(", "$", "output", ",", "$", "this", "->", "symfonyFormGetters", ",", "array", "(", "''", ")", ",", "$", "this", "->", "symfonyFormSetters", ",", "array", "(", "'/**/'", ")", ")", ";", "return", "$", "output", ";", "}" ]
Build normality compatible getters and setters
[ "Build", "normality", "compatible", "getters", "and", "setters" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L1185-L1214
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.addSymfonyFormCompatibleGetter
private function addSymfonyFormCompatibleGetter( $name ) { $fnName = "get".\Bond\pascal_case($name); $fnBody = sprintf( "function %s() { return \$this->get('%s'); }", $fnName, addslashes( $name ) ); $this->class->classComponents[] = new FunctionDeclaration( $fnName, $fnBody ); }
php
private function addSymfonyFormCompatibleGetter( $name ) { $fnName = "get".\Bond\pascal_case($name); $fnBody = sprintf( "function %s() { return \$this->get('%s'); }", $fnName, addslashes( $name ) ); $this->class->classComponents[] = new FunctionDeclaration( $fnName, $fnBody ); }
[ "private", "function", "addSymfonyFormCompatibleGetter", "(", "$", "name", ")", "{", "$", "fnName", "=", "\"get\"", ".", "\\", "Bond", "\\", "pascal_case", "(", "$", "name", ")", ";", "$", "fnBody", "=", "sprintf", "(", "\"function %s() { return \\$this->get('%s'); }\"", ",", "$", "fnName", ",", "addslashes", "(", "$", "name", ")", ")", ";", "$", "this", "->", "class", "->", "classComponents", "[", "]", "=", "new", "FunctionDeclaration", "(", "$", "fnName", ",", "$", "fnBody", ")", ";", "}" ]
Build a symfony2 form compatible getter @param propertyName $name
[ "Build", "a", "symfony2", "form", "compatible", "getter" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L1220-L1232
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.getFormChoiceTextFunction
private function getFormChoiceTextFunction() { // default function only works for tables with a lone primary key $columns = $this->pgClass->getAttributes(); // find columns tagged 'form-choicetext' $columnsSelected = array(); foreach( $columns as $column) { $tags = \Bond\extract_tags( $column, 'normality' ); if( isset( $tags['form-choicetext']) ) { $columnsSelected[] = $column; } } switch( count($columnsSelected) ) { case 0: return; case 1: $columnName = array_pop( $columnsSelected )->name; break; default: throw new \FormChoiceTextConfigurationException( "Multiple columns with tag 'form-choicetext'. Only one column per table can have this tag." ); } $this->class->classComponents[] = new FunctionDeclaration( 'form_choiceText', new Sformatf( <<<'PHP' /** * Function called by \Bond\Bridge\Normality\Form\Type\Normality when displaying text for this entity * @return scalar */ public function form_choiceText() { return $this->get('%s'); } PHP , addslashes( $columnName ) ) ); }
php
private function getFormChoiceTextFunction() { // default function only works for tables with a lone primary key $columns = $this->pgClass->getAttributes(); // find columns tagged 'form-choicetext' $columnsSelected = array(); foreach( $columns as $column) { $tags = \Bond\extract_tags( $column, 'normality' ); if( isset( $tags['form-choicetext']) ) { $columnsSelected[] = $column; } } switch( count($columnsSelected) ) { case 0: return; case 1: $columnName = array_pop( $columnsSelected )->name; break; default: throw new \FormChoiceTextConfigurationException( "Multiple columns with tag 'form-choicetext'. Only one column per table can have this tag." ); } $this->class->classComponents[] = new FunctionDeclaration( 'form_choiceText', new Sformatf( <<<'PHP' /** * Function called by \Bond\Bridge\Normality\Form\Type\Normality when displaying text for this entity * @return scalar */ public function form_choiceText() { return $this->get('%s'); } PHP , addslashes( $columnName ) ) ); }
[ "private", "function", "getFormChoiceTextFunction", "(", ")", "{", "// default function only works for tables with a lone primary key", "$", "columns", "=", "$", "this", "->", "pgClass", "->", "getAttributes", "(", ")", ";", "// find columns tagged 'form-choicetext'", "$", "columnsSelected", "=", "array", "(", ")", ";", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "$", "tags", "=", "\\", "Bond", "\\", "extract_tags", "(", "$", "column", ",", "'normality'", ")", ";", "if", "(", "isset", "(", "$", "tags", "[", "'form-choicetext'", "]", ")", ")", "{", "$", "columnsSelected", "[", "]", "=", "$", "column", ";", "}", "}", "switch", "(", "count", "(", "$", "columnsSelected", ")", ")", "{", "case", "0", ":", "return", ";", "case", "1", ":", "$", "columnName", "=", "array_pop", "(", "$", "columnsSelected", ")", "->", "name", ";", "break", ";", "default", ":", "throw", "new", "\\", "FormChoiceTextConfigurationException", "(", "\"Multiple columns with tag 'form-choicetext'. Only one column per table can have this tag.\"", ")", ";", "}", "$", "this", "->", "class", "->", "classComponents", "[", "]", "=", "new", "FunctionDeclaration", "(", "'form_choiceText'", ",", "new", "Sformatf", "(", " <<<'PHP'\n /**\n * Function called by \\Bond\\Bridge\\Normality\\Form\\Type\\Normality when displaying text for this entity\n * @return scalar\n */\n public function form_choiceText()\n {\n return $this->get('%s');\n }\nPHP", ",", "addslashes", "(", "$", "columnName", ")", ")", ")", ";", "}" ]
Form choice text function @return array $lines
[ "Form", "choice", "text", "function" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L1256-L1297
train
squareproton/Bond
src/Bond/Normality/Builder/Entity.php
Entity.getSymfonyValidatorConstraints
private function getSymfonyValidatorConstraints() { $constraints = array(); $this->loadUnsettableProperties(); foreach ( $this->dataTypes as $column => $type ) { // skip inherited columns if( $type->isInherited() ) { continue; } // Skip Columns designated unsetable. if( in_array( $column, $this->unsetableProperties ) ) { continue; } // Check if column is nullable. if( !$type->isNullable() and !$type->hasDefault() ){ $constraints[] = $this->getSymfonyConstraint( $column, 'NotNull'); } // Normality entity type constraints. if( $type->getEntity() === 'normality' ) { $dataType = $this->options['entityPlaceholder']."\\{$type->getNormality()}"; $constraints[] = $this->getSymfonyTypeConstraint( $column, $dataType ); } elseif( $type->getEntity() ){ $dataType = "Bond\\Entity\\Types\\{$type->getEntity()}"; $constraints[] = $this->getSymfonyTypeConstraint( $column, $dataType ); } elseif( $type->isEnum( $enumName ) ) { $constraints[] = $this->getSymfonyChoiceConstraint( $column, $this->pgClass->getCatalog()->enum->getValues($enumName) ); } else { switch( $type->getType() ) { case 'int': $constraints[] = $this->getSymfonyConstraint( $column, 'RealInt', null, false ); $this->class->addUses( 'Bond\\Bridge\\Normality\\Constraint\\RealInt' ); break; case 'citext': case 'text': $constraints[] = $this->getSymfonyTypeConstraint( $column, 'string' ); if( is_numeric( $type->getLength() ) ) { $constraints[] = $this->getSymfonyConstraint( $column, 'MaxLength', $type->getLength() ); } break; case 'bool': $constraints[] = $this->getSymfonyTypeConstraint( $column, 'bool' ); break; } } $constraints[] = ''; } return implode( "\n", $constraints ); }
php
private function getSymfonyValidatorConstraints() { $constraints = array(); $this->loadUnsettableProperties(); foreach ( $this->dataTypes as $column => $type ) { // skip inherited columns if( $type->isInherited() ) { continue; } // Skip Columns designated unsetable. if( in_array( $column, $this->unsetableProperties ) ) { continue; } // Check if column is nullable. if( !$type->isNullable() and !$type->hasDefault() ){ $constraints[] = $this->getSymfonyConstraint( $column, 'NotNull'); } // Normality entity type constraints. if( $type->getEntity() === 'normality' ) { $dataType = $this->options['entityPlaceholder']."\\{$type->getNormality()}"; $constraints[] = $this->getSymfonyTypeConstraint( $column, $dataType ); } elseif( $type->getEntity() ){ $dataType = "Bond\\Entity\\Types\\{$type->getEntity()}"; $constraints[] = $this->getSymfonyTypeConstraint( $column, $dataType ); } elseif( $type->isEnum( $enumName ) ) { $constraints[] = $this->getSymfonyChoiceConstraint( $column, $this->pgClass->getCatalog()->enum->getValues($enumName) ); } else { switch( $type->getType() ) { case 'int': $constraints[] = $this->getSymfonyConstraint( $column, 'RealInt', null, false ); $this->class->addUses( 'Bond\\Bridge\\Normality\\Constraint\\RealInt' ); break; case 'citext': case 'text': $constraints[] = $this->getSymfonyTypeConstraint( $column, 'string' ); if( is_numeric( $type->getLength() ) ) { $constraints[] = $this->getSymfonyConstraint( $column, 'MaxLength', $type->getLength() ); } break; case 'bool': $constraints[] = $this->getSymfonyTypeConstraint( $column, 'bool' ); break; } } $constraints[] = ''; } return implode( "\n", $constraints ); }
[ "private", "function", "getSymfonyValidatorConstraints", "(", ")", "{", "$", "constraints", "=", "array", "(", ")", ";", "$", "this", "->", "loadUnsettableProperties", "(", ")", ";", "foreach", "(", "$", "this", "->", "dataTypes", "as", "$", "column", "=>", "$", "type", ")", "{", "// skip inherited columns", "if", "(", "$", "type", "->", "isInherited", "(", ")", ")", "{", "continue", ";", "}", "// Skip Columns designated unsetable.", "if", "(", "in_array", "(", "$", "column", ",", "$", "this", "->", "unsetableProperties", ")", ")", "{", "continue", ";", "}", "// Check if column is nullable.", "if", "(", "!", "$", "type", "->", "isNullable", "(", ")", "and", "!", "$", "type", "->", "hasDefault", "(", ")", ")", "{", "$", "constraints", "[", "]", "=", "$", "this", "->", "getSymfonyConstraint", "(", "$", "column", ",", "'NotNull'", ")", ";", "}", "// Normality entity type constraints.", "if", "(", "$", "type", "->", "getEntity", "(", ")", "===", "'normality'", ")", "{", "$", "dataType", "=", "$", "this", "->", "options", "[", "'entityPlaceholder'", "]", ".", "\"\\\\{$type->getNormality()}\"", ";", "$", "constraints", "[", "]", "=", "$", "this", "->", "getSymfonyTypeConstraint", "(", "$", "column", ",", "$", "dataType", ")", ";", "}", "elseif", "(", "$", "type", "->", "getEntity", "(", ")", ")", "{", "$", "dataType", "=", "\"Bond\\\\Entity\\\\Types\\\\{$type->getEntity()}\"", ";", "$", "constraints", "[", "]", "=", "$", "this", "->", "getSymfonyTypeConstraint", "(", "$", "column", ",", "$", "dataType", ")", ";", "}", "elseif", "(", "$", "type", "->", "isEnum", "(", "$", "enumName", ")", ")", "{", "$", "constraints", "[", "]", "=", "$", "this", "->", "getSymfonyChoiceConstraint", "(", "$", "column", ",", "$", "this", "->", "pgClass", "->", "getCatalog", "(", ")", "->", "enum", "->", "getValues", "(", "$", "enumName", ")", ")", ";", "}", "else", "{", "switch", "(", "$", "type", "->", "getType", "(", ")", ")", "{", "case", "'int'", ":", "$", "constraints", "[", "]", "=", "$", "this", "->", "getSymfonyConstraint", "(", "$", "column", ",", "'RealInt'", ",", "null", ",", "false", ")", ";", "$", "this", "->", "class", "->", "addUses", "(", "'Bond\\\\Bridge\\\\Normality\\\\Constraint\\\\RealInt'", ")", ";", "break", ";", "case", "'citext'", ":", "case", "'text'", ":", "$", "constraints", "[", "]", "=", "$", "this", "->", "getSymfonyTypeConstraint", "(", "$", "column", ",", "'string'", ")", ";", "if", "(", "is_numeric", "(", "$", "type", "->", "getLength", "(", ")", ")", ")", "{", "$", "constraints", "[", "]", "=", "$", "this", "->", "getSymfonyConstraint", "(", "$", "column", ",", "'MaxLength'", ",", "$", "type", "->", "getLength", "(", ")", ")", ";", "}", "break", ";", "case", "'bool'", ":", "$", "constraints", "[", "]", "=", "$", "this", "->", "getSymfonyTypeConstraint", "(", "$", "column", ",", "'bool'", ")", ";", "break", ";", "}", "}", "$", "constraints", "[", "]", "=", "''", ";", "}", "return", "implode", "(", "\"\\n\"", ",", "$", "constraints", ")", ";", "}" ]
Get Symfony validator contraints @return string
[ "Get", "Symfony", "validator", "contraints" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Normality/Builder/Entity.php#L1333-L1409
train
ekyna/Table
Bridge/Doctrine/ORM/Type/Filter/EntityType.php
EntityType.getOperators
private function getOperators($dataClass, $propertyPath) { $metadata = $this->registry->getManagerForClass($dataClass)->getClassMetadata($dataClass); if (false === strpos($propertyPath, '.')) { if ($metadata->hasAssociation($propertyPath)) { if ($metadata->isCollectionValuedAssociation($propertyPath)) { return [ FilterOperator::MEMBER, FilterOperator::NOT_MEMBER, ]; } else { return [ FilterOperator::IN, FilterOperator::NOT_IN, ]; } } } else { $paths = explode('.', $propertyPath); $path = array_shift($paths); if ($metadata->hasAssociation($path)) { return $this->getOperators( $metadata->getAssociationTargetClass($path), implode('.', $paths) ); } } throw new InvalidArgumentException("Invalid property path '{$propertyPath}'."); }
php
private function getOperators($dataClass, $propertyPath) { $metadata = $this->registry->getManagerForClass($dataClass)->getClassMetadata($dataClass); if (false === strpos($propertyPath, '.')) { if ($metadata->hasAssociation($propertyPath)) { if ($metadata->isCollectionValuedAssociation($propertyPath)) { return [ FilterOperator::MEMBER, FilterOperator::NOT_MEMBER, ]; } else { return [ FilterOperator::IN, FilterOperator::NOT_IN, ]; } } } else { $paths = explode('.', $propertyPath); $path = array_shift($paths); if ($metadata->hasAssociation($path)) { return $this->getOperators( $metadata->getAssociationTargetClass($path), implode('.', $paths) ); } } throw new InvalidArgumentException("Invalid property path '{$propertyPath}'."); }
[ "private", "function", "getOperators", "(", "$", "dataClass", ",", "$", "propertyPath", ")", "{", "$", "metadata", "=", "$", "this", "->", "registry", "->", "getManagerForClass", "(", "$", "dataClass", ")", "->", "getClassMetadata", "(", "$", "dataClass", ")", ";", "if", "(", "false", "===", "strpos", "(", "$", "propertyPath", ",", "'.'", ")", ")", "{", "if", "(", "$", "metadata", "->", "hasAssociation", "(", "$", "propertyPath", ")", ")", "{", "if", "(", "$", "metadata", "->", "isCollectionValuedAssociation", "(", "$", "propertyPath", ")", ")", "{", "return", "[", "FilterOperator", "::", "MEMBER", ",", "FilterOperator", "::", "NOT_MEMBER", ",", "]", ";", "}", "else", "{", "return", "[", "FilterOperator", "::", "IN", ",", "FilterOperator", "::", "NOT_IN", ",", "]", ";", "}", "}", "}", "else", "{", "$", "paths", "=", "explode", "(", "'.'", ",", "$", "propertyPath", ")", ";", "$", "path", "=", "array_shift", "(", "$", "paths", ")", ";", "if", "(", "$", "metadata", "->", "hasAssociation", "(", "$", "path", ")", ")", "{", "return", "$", "this", "->", "getOperators", "(", "$", "metadata", "->", "getAssociationTargetClass", "(", "$", "path", ")", ",", "implode", "(", "'.'", ",", "$", "paths", ")", ")", ";", "}", "}", "throw", "new", "InvalidArgumentException", "(", "\"Invalid property path '{$propertyPath}'.\"", ")", ";", "}" ]
Returns the operators according to association type targeted by the property path. @param $dataClass @param $propertyPath @return array
[ "Returns", "the", "operators", "according", "to", "association", "type", "targeted", "by", "the", "property", "path", "." ]
6f06e8fd8a3248d52f3a91f10508471344db311a
https://github.com/ekyna/Table/blob/6f06e8fd8a3248d52f3a91f10508471344db311a/Bridge/Doctrine/ORM/Type/Filter/EntityType.php#L180-L211
train
spoom-php/core
src/extension/Exception.php
Exception.log
public static function log( \Throwable $throwable, LoggerInterface $instance, array $context = [] ): \Throwable { // extend data $context = Collection::cast( $context, [] ); $context[ 'exception' ] = $throwable; $context[ 'backtrace' ] = false; $severity = $throwable instanceof Helper\ThrowableInterface ? $throwable->getSeverity() : Application::SEVERITY_CRITICAL; $namespace = get_class( $throwable ) . ':' . ( $throwable instanceof Helper\ThrowableInterface ? $throwable->getId() : $throwable->getCode() ); $instance->create( $throwable->getMessage(), $context, $namespace, $severity ); return $throwable; }
php
public static function log( \Throwable $throwable, LoggerInterface $instance, array $context = [] ): \Throwable { // extend data $context = Collection::cast( $context, [] ); $context[ 'exception' ] = $throwable; $context[ 'backtrace' ] = false; $severity = $throwable instanceof Helper\ThrowableInterface ? $throwable->getSeverity() : Application::SEVERITY_CRITICAL; $namespace = get_class( $throwable ) . ':' . ( $throwable instanceof Helper\ThrowableInterface ? $throwable->getId() : $throwable->getCode() ); $instance->create( $throwable->getMessage(), $context, $namespace, $severity ); return $throwable; }
[ "public", "static", "function", "log", "(", "\\", "Throwable", "$", "throwable", ",", "LoggerInterface", "$", "instance", ",", "array", "$", "context", "=", "[", "]", ")", ":", "\\", "Throwable", "{", "// extend data", "$", "context", "=", "Collection", "::", "cast", "(", "$", "context", ",", "[", "]", ")", ";", "$", "context", "[", "'exception'", "]", "=", "$", "throwable", ";", "$", "context", "[", "'backtrace'", "]", "=", "false", ";", "$", "severity", "=", "$", "throwable", "instanceof", "Helper", "\\", "ThrowableInterface", "?", "$", "throwable", "->", "getSeverity", "(", ")", ":", "Application", "::", "SEVERITY_CRITICAL", ";", "$", "namespace", "=", "get_class", "(", "$", "throwable", ")", ".", "':'", ".", "(", "$", "throwable", "instanceof", "Helper", "\\", "ThrowableInterface", "?", "$", "throwable", "->", "getId", "(", ")", ":", "$", "throwable", "->", "getCode", "(", ")", ")", ";", "$", "instance", "->", "create", "(", "$", "throwable", "->", "getMessage", "(", ")", ",", "$", "context", ",", "$", "namespace", ",", "$", "severity", ")", ";", "return", "$", "throwable", ";", "}" ]
Logger the `\Throwable` with the proper severity and message @param \Throwable $throwable @param LoggerInterface $instance @param array $context @return \Throwable The input `\Throwable`
[ "Logger", "the", "\\", "Throwable", "with", "the", "proper", "severity", "and", "message" ]
ea7184213352fa2fad7636927a019e5798734e04
https://github.com/spoom-php/core/blob/ea7184213352fa2fad7636927a019e5798734e04/src/extension/Exception.php#L44-L56
train
niridoy/LaraveIinstaller
src/Controllers/FinalController.php
FinalController.finish
public function finish(InstalledFileManager $fileManager, FinalInstallManager $finalInstall, EnvironmentManager $environment) { $finalMessages = $finalInstall->runFinal(); $finalStatusMessage = $fileManager->update(); $finalEnvFile = $environment->getEnvContent(); return view('vendor.installer.finished', compact('finalMessages', 'finalStatusMessage', 'finalEnvFile')); }
php
public function finish(InstalledFileManager $fileManager, FinalInstallManager $finalInstall, EnvironmentManager $environment) { $finalMessages = $finalInstall->runFinal(); $finalStatusMessage = $fileManager->update(); $finalEnvFile = $environment->getEnvContent(); return view('vendor.installer.finished', compact('finalMessages', 'finalStatusMessage', 'finalEnvFile')); }
[ "public", "function", "finish", "(", "InstalledFileManager", "$", "fileManager", ",", "FinalInstallManager", "$", "finalInstall", ",", "EnvironmentManager", "$", "environment", ")", "{", "$", "finalMessages", "=", "$", "finalInstall", "->", "runFinal", "(", ")", ";", "$", "finalStatusMessage", "=", "$", "fileManager", "->", "update", "(", ")", ";", "$", "finalEnvFile", "=", "$", "environment", "->", "getEnvContent", "(", ")", ";", "return", "view", "(", "'vendor.installer.finished'", ",", "compact", "(", "'finalMessages'", ",", "'finalStatusMessage'", ",", "'finalEnvFile'", ")", ")", ";", "}" ]
Update installed file and display finished view. @param InstalledFileManager $fileManager @return \Illuminate\View\View
[ "Update", "installed", "file", "and", "display", "finished", "view", "." ]
8339cf45bf393be57fb4e6c63179a6865028f076
https://github.com/niridoy/LaraveIinstaller/blob/8339cf45bf393be57fb4e6c63179a6865028f076/src/Controllers/FinalController.php#L18-L25
train
CroudTech/laravel-repositories
src/Fractal.php
Fractal.item
public function item($item, $transformer, $model_name = '') { $resource = new Item($item, $transformer, $model_name); return $this->manager->createData($resource)->toArray(); }
php
public function item($item, $transformer, $model_name = '') { $resource = new Item($item, $transformer, $model_name); return $this->manager->createData($resource)->toArray(); }
[ "public", "function", "item", "(", "$", "item", ",", "$", "transformer", ",", "$", "model_name", "=", "''", ")", "{", "$", "resource", "=", "new", "Item", "(", "$", "item", ",", "$", "transformer", ",", "$", "model_name", ")", ";", "return", "$", "this", "->", "manager", "->", "createData", "(", "$", "resource", ")", "->", "toArray", "(", ")", ";", "}" ]
Fractal transform a single item @param object $item $item object @param string $transformer Namespaced Transformer @param string $model_name Model Name @return array
[ "Fractal", "transform", "a", "single", "item" ]
3146285be911728fe7b00cf27d2494ad22b773dc
https://github.com/CroudTech/laravel-repositories/blob/3146285be911728fe7b00cf27d2494ad22b773dc/src/Fractal.php#L44-L48
train
Kris-Kuiper/sFire-Framework
src/Cookie/Cookie.php
Cookie.pull
public static function pull($key, $default = NULL) { if(false === is_string($key)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($key)), E_USER_ERROR); } if(true === isset(static :: $data[$key])) { $default = static :: get($key); static :: add($key, null, -1); } return $default; }
php
public static function pull($key, $default = NULL) { if(false === is_string($key)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($key)), E_USER_ERROR); } if(true === isset(static :: $data[$key])) { $default = static :: get($key); static :: add($key, null, -1); } return $default; }
[ "public", "static", "function", "pull", "(", "$", "key", ",", "$", "default", "=", "NULL", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "key", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "key", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "true", "===", "isset", "(", "static", "::", "$", "data", "[", "$", "key", "]", ")", ")", "{", "$", "default", "=", "static", "::", "get", "(", "$", "key", ")", ";", "static", "::", "add", "(", "$", "key", ",", "null", ",", "-", "1", ")", ";", "}", "return", "$", "default", ";", "}" ]
Retrieve and delete an item @param string $key @param default $mixed @return mixed
[ "Retrieve", "and", "delete", "an", "item" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Cookie/Cookie.php#L101-L114
train
Kris-Kuiper/sFire-Framework
src/Cookie/Cookie.php
Cookie.get
public static function get($key, $default = null) { if(false === is_string($key)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($key)), E_USER_ERROR); } if(true === isset(static :: $data[$key])) { return static :: $data[$key]; } $key = rtrim(base64_encode($key), '='); if(true === isset(static :: $data[$key])) { $cookie = Hash :: decrypt(base64_decode(static :: $data[$key]), Application :: get('salt')); return false !== $cookie ? $cookie : $default; } return $default; }
php
public static function get($key, $default = null) { if(false === is_string($key)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($key)), E_USER_ERROR); } if(true === isset(static :: $data[$key])) { return static :: $data[$key]; } $key = rtrim(base64_encode($key), '='); if(true === isset(static :: $data[$key])) { $cookie = Hash :: decrypt(base64_decode(static :: $data[$key]), Application :: get('salt')); return false !== $cookie ? $cookie : $default; } return $default; }
[ "public", "static", "function", "get", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "key", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "key", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "true", "===", "isset", "(", "static", "::", "$", "data", "[", "$", "key", "]", ")", ")", "{", "return", "static", "::", "$", "data", "[", "$", "key", "]", ";", "}", "$", "key", "=", "rtrim", "(", "base64_encode", "(", "$", "key", ")", ",", "'='", ")", ";", "if", "(", "true", "===", "isset", "(", "static", "::", "$", "data", "[", "$", "key", "]", ")", ")", "{", "$", "cookie", "=", "Hash", "::", "decrypt", "(", "base64_decode", "(", "static", "::", "$", "data", "[", "$", "key", "]", ")", ",", "Application", "::", "get", "(", "'salt'", ")", ")", ";", "return", "false", "!==", "$", "cookie", "?", "$", "cookie", ":", "$", "default", ";", "}", "return", "$", "default", ";", "}" ]
Retrieve data based on key @param string $key @param mixed $default @return mixed
[ "Retrieve", "data", "based", "on", "key" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Cookie/Cookie.php#L150-L169
train
Kris-Kuiper/sFire-Framework
src/Cookie/Cookie.php
Cookie.all
public static function all() { $cookies = []; foreach(static :: $data as $key => $value) { if(rtrim(base64_encode(base64_decode($key, true)), '=') === $key) { $cookies[base64_decode($key)] = Hash :: decrypt(static :: $data[$key], Application :: get('salt')); } else { $cookies[$key] = $value; } } return $cookies; }
php
public static function all() { $cookies = []; foreach(static :: $data as $key => $value) { if(rtrim(base64_encode(base64_decode($key, true)), '=') === $key) { $cookies[base64_decode($key)] = Hash :: decrypt(static :: $data[$key], Application :: get('salt')); } else { $cookies[$key] = $value; } } return $cookies; }
[ "public", "static", "function", "all", "(", ")", "{", "$", "cookies", "=", "[", "]", ";", "foreach", "(", "static", "::", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "rtrim", "(", "base64_encode", "(", "base64_decode", "(", "$", "key", ",", "true", ")", ")", ",", "'='", ")", "===", "$", "key", ")", "{", "$", "cookies", "[", "base64_decode", "(", "$", "key", ")", "]", "=", "Hash", "::", "decrypt", "(", "static", "::", "$", "data", "[", "$", "key", "]", ",", "Application", "::", "get", "(", "'salt'", ")", ")", ";", "}", "else", "{", "$", "cookies", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "cookies", ";", "}" ]
Get all data from current session Cookie @return array
[ "Get", "all", "data", "from", "current", "session", "Cookie" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Cookie/Cookie.php#L176-L191
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/http/RequestContext.php
RequestContext.setAttribute
public function setAttribute($key, $val) { if(is_null($val) && array_key_exists($key, $this->attributes)) unset($this->attributes[$key]); else $this->attributes[$key] = $val; }
php
public function setAttribute($key, $val) { if(is_null($val) && array_key_exists($key, $this->attributes)) unset($this->attributes[$key]); else $this->attributes[$key] = $val; }
[ "public", "function", "setAttribute", "(", "$", "key", ",", "$", "val", ")", "{", "if", "(", "is_null", "(", "$", "val", ")", "&&", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "attributes", ")", ")", "unset", "(", "$", "this", "->", "attributes", "[", "$", "key", "]", ")", ";", "else", "$", "this", "->", "attributes", "[", "$", "key", "]", "=", "$", "val", ";", "}" ]
Used to set attributes of the RequestContext @param string $key The name of the attribute @param mixed $val The value for the attribute @return void
[ "Used", "to", "set", "attributes", "of", "the", "RequestContext" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/http/RequestContext.php#L149-L155
train
Wedeto/DB
src/Schema/Column/Column.php
Column.validate
public function validate($value, &$filtered = null) { if (!$this->validator->validate($value, $filtered)) throw new ValidationException($this->validator->getErrorMessage($value)); return true; }
php
public function validate($value, &$filtered = null) { if (!$this->validator->validate($value, $filtered)) throw new ValidationException($this->validator->getErrorMessage($value)); return true; }
[ "public", "function", "validate", "(", "$", "value", ",", "&", "$", "filtered", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "validator", "->", "validate", "(", "$", "value", ",", "$", "filtered", ")", ")", "throw", "new", "ValidationException", "(", "$", "this", "->", "validator", "->", "getErrorMessage", "(", "$", "value", ")", ")", ";", "return", "true", ";", "}" ]
Validate the value for this column. @param mixed $value The value to set @param mixed &$filtered The corrected, filtered value @return bool True when validates. False is never returned. @throws ValidationException when validation fails.
[ "Validate", "the", "value", "for", "this", "column", "." ]
715f8f2e3ae6b53c511c40b620921cb9c87e6f62
https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Schema/Column/Column.php#L218-L224
train
Wedeto/DB
src/Schema/Column/Column.php
Column.parseArray
public static function parseArray(array $data) { $type = strtoupper($data['data_type']); if (!defined(static::class . '::' . $type)) throw new InvalidValueException("Invalid column type: $type"); return array( 'name' => $data['column_name'], 'type' => $type, 'max_length' => $data['character_maximum_length'] ?? null, 'is_nullable' => isset($data['is_nullable']) ? $data['is_nullable'] == true : false, 'column_default' => $data['column_default'] ?? null, 'numeric_precision' => $data['numeric_precision'] ?? null, 'numeric_scale' => $data['numeric_scale'] ?? null, 'serial' => isset($data['serial']) ? $data['serial'] == true : false, 'enum_values' => $data['enum_values'] ?? null ); }
php
public static function parseArray(array $data) { $type = strtoupper($data['data_type']); if (!defined(static::class . '::' . $type)) throw new InvalidValueException("Invalid column type: $type"); return array( 'name' => $data['column_name'], 'type' => $type, 'max_length' => $data['character_maximum_length'] ?? null, 'is_nullable' => isset($data['is_nullable']) ? $data['is_nullable'] == true : false, 'column_default' => $data['column_default'] ?? null, 'numeric_precision' => $data['numeric_precision'] ?? null, 'numeric_scale' => $data['numeric_scale'] ?? null, 'serial' => isset($data['serial']) ? $data['serial'] == true : false, 'enum_values' => $data['enum_values'] ?? null ); }
[ "public", "static", "function", "parseArray", "(", "array", "$", "data", ")", "{", "$", "type", "=", "strtoupper", "(", "$", "data", "[", "'data_type'", "]", ")", ";", "if", "(", "!", "defined", "(", "static", "::", "class", ".", "'::'", ".", "$", "type", ")", ")", "throw", "new", "InvalidValueException", "(", "\"Invalid column type: $type\"", ")", ";", "return", "array", "(", "'name'", "=>", "$", "data", "[", "'column_name'", "]", ",", "'type'", "=>", "$", "type", ",", "'max_length'", "=>", "$", "data", "[", "'character_maximum_length'", "]", "??", "null", ",", "'is_nullable'", "=>", "isset", "(", "$", "data", "[", "'is_nullable'", "]", ")", "?", "$", "data", "[", "'is_nullable'", "]", "==", "true", ":", "false", ",", "'column_default'", "=>", "$", "data", "[", "'column_default'", "]", "??", "null", ",", "'numeric_precision'", "=>", "$", "data", "[", "'numeric_precision'", "]", "??", "null", ",", "'numeric_scale'", "=>", "$", "data", "[", "'numeric_scale'", "]", "??", "null", ",", "'serial'", "=>", "isset", "(", "$", "data", "[", "'serial'", "]", ")", "?", "$", "data", "[", "'serial'", "]", "==", "true", ":", "false", ",", "'enum_values'", "=>", "$", "data", "[", "'enum_values'", "]", "??", "null", ")", ";", "}" ]
Parse deserialized array into valid arguments for column properties. @param array $data The unserialized array @param array A normalized array containing all fields
[ "Parse", "deserialized", "array", "into", "valid", "arguments", "for", "column", "properties", "." ]
715f8f2e3ae6b53c511c40b620921cb9c87e6f62
https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Schema/Column/Column.php#L272-L289
train
Wedeto/DB
src/Schema/Column/Column.php
Column.unserialize
public function unserialize($data) { $data = unserialize($data); $args = self::parseArray($data); $this->__construct($args['name']); foreach ($args as $property => $value) { if (!empty($value)) $this->set($property, $value); } return $col; }
php
public function unserialize($data) { $data = unserialize($data); $args = self::parseArray($data); $this->__construct($args['name']); foreach ($args as $property => $value) { if (!empty($value)) $this->set($property, $value); } return $col; }
[ "public", "function", "unserialize", "(", "$", "data", ")", "{", "$", "data", "=", "unserialize", "(", "$", "data", ")", ";", "$", "args", "=", "self", "::", "parseArray", "(", "$", "data", ")", ";", "$", "this", "->", "__construct", "(", "$", "args", "[", "'name'", "]", ")", ";", "foreach", "(", "$", "args", "as", "$", "property", "=>", "$", "value", ")", "{", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "$", "this", "->", "set", "(", "$", "property", ",", "$", "value", ")", ";", "}", "return", "$", "col", ";", "}" ]
Restore the column from its serialize form @param string $data The serialized data
[ "Restore", "the", "column", "from", "its", "serialize", "form" ]
715f8f2e3ae6b53c511c40b620921cb9c87e6f62
https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Schema/Column/Column.php#L311-L324
train
Wedeto/DB
src/Schema/Column/Column.php
Column.factory
public static function factory(array $data) { $type = ucfirst(strtolower($data['data_type'])); $args = self::parseArray($data); // Execute hook to allow for additional column types or modifications $classname = __NAMESPACE__ . "\\" . ucfirst(strtolower($args['type'])); $params = Hook::execute( 'Wedeto.DB.Schema.Column.Column.FindClass', ['column_defition' => $args, 'input_data' => $data, 'classname' => $classname, 'instance' => null] ); // Check if a hook has already provided an instance if ($params['instance'] !== null && $params['instance'] instanceof Column) return $params['instance']; // Get the selected classname $classname = $params['classname']; if (!class_exists($classname)) throw new InvalidTypeException("Unsupported column type: " . $args['type'] . " (class $classname not found)"); $col = new $classname($args['name']); foreach ($args as $property => $value) { if (!empty($value)) $col->set($property, $value); } return $col; }
php
public static function factory(array $data) { $type = ucfirst(strtolower($data['data_type'])); $args = self::parseArray($data); // Execute hook to allow for additional column types or modifications $classname = __NAMESPACE__ . "\\" . ucfirst(strtolower($args['type'])); $params = Hook::execute( 'Wedeto.DB.Schema.Column.Column.FindClass', ['column_defition' => $args, 'input_data' => $data, 'classname' => $classname, 'instance' => null] ); // Check if a hook has already provided an instance if ($params['instance'] !== null && $params['instance'] instanceof Column) return $params['instance']; // Get the selected classname $classname = $params['classname']; if (!class_exists($classname)) throw new InvalidTypeException("Unsupported column type: " . $args['type'] . " (class $classname not found)"); $col = new $classname($args['name']); foreach ($args as $property => $value) { if (!empty($value)) $col->set($property, $value); } return $col; }
[ "public", "static", "function", "factory", "(", "array", "$", "data", ")", "{", "$", "type", "=", "ucfirst", "(", "strtolower", "(", "$", "data", "[", "'data_type'", "]", ")", ")", ";", "$", "args", "=", "self", "::", "parseArray", "(", "$", "data", ")", ";", "// Execute hook to allow for additional column types or modifications", "$", "classname", "=", "__NAMESPACE__", ".", "\"\\\\\"", ".", "ucfirst", "(", "strtolower", "(", "$", "args", "[", "'type'", "]", ")", ")", ";", "$", "params", "=", "Hook", "::", "execute", "(", "'Wedeto.DB.Schema.Column.Column.FindClass'", ",", "[", "'column_defition'", "=>", "$", "args", ",", "'input_data'", "=>", "$", "data", ",", "'classname'", "=>", "$", "classname", ",", "'instance'", "=>", "null", "]", ")", ";", "// Check if a hook has already provided an instance", "if", "(", "$", "params", "[", "'instance'", "]", "!==", "null", "&&", "$", "params", "[", "'instance'", "]", "instanceof", "Column", ")", "return", "$", "params", "[", "'instance'", "]", ";", "// Get the selected classname", "$", "classname", "=", "$", "params", "[", "'classname'", "]", ";", "if", "(", "!", "class_exists", "(", "$", "classname", ")", ")", "throw", "new", "InvalidTypeException", "(", "\"Unsupported column type: \"", ".", "$", "args", "[", "'type'", "]", ".", "\" (class $classname not found)\"", ")", ";", "$", "col", "=", "new", "$", "classname", "(", "$", "args", "[", "'name'", "]", ")", ";", "foreach", "(", "$", "args", "as", "$", "property", "=>", "$", "value", ")", "{", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "$", "col", "->", "set", "(", "$", "property", ",", "$", "value", ")", ";", "}", "return", "$", "col", ";", "}" ]
Create a column instance from an array. @param array $data The column specification containing name. type, maximum length, numeric scale and precision, default value, nullability and such. @return Column An instantiated column object
[ "Create", "a", "column", "instance", "from", "an", "array", "." ]
715f8f2e3ae6b53c511c40b620921cb9c87e6f62
https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Schema/Column/Column.php#L333-L362
train
faustbrian/HTTP
src/HttpResponse.php
HttpResponse.xml
public function xml(): ?SimpleXMLElement { return simplexml_load_string( utf8_encode($this->response->getBody()->getContents()), 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS ); }
php
public function xml(): ?SimpleXMLElement { return simplexml_load_string( utf8_encode($this->response->getBody()->getContents()), 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS ); }
[ "public", "function", "xml", "(", ")", ":", "?", "SimpleXMLElement", "{", "return", "simplexml_load_string", "(", "utf8_encode", "(", "$", "this", "->", "response", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ")", ",", "'SimpleXMLElement'", ",", "LIBXML_NOCDATA", "|", "LIBXML_NOBLANKS", ")", ";", "}" ]
Gets the body of the message as XML. @return \SimpleXMLElement
[ "Gets", "the", "body", "of", "the", "message", "as", "XML", "." ]
ab24b37ea211eb106237a813ec8d47ec1d4fe199
https://github.com/faustbrian/HTTP/blob/ab24b37ea211eb106237a813ec8d47ec1d4fe199/src/HttpResponse.php#L85-L92
train
faustbrian/HTTP
src/HttpResponse.php
HttpResponse.headers
public function headers(): array { return collect($this->response->getHeaders())->mapWithKeys(function ($v, $k) { return [$k => $v[0]]; })->all(); }
php
public function headers(): array { return collect($this->response->getHeaders())->mapWithKeys(function ($v, $k) { return [$k => $v[0]]; })->all(); }
[ "public", "function", "headers", "(", ")", ":", "array", "{", "return", "collect", "(", "$", "this", "->", "response", "->", "getHeaders", "(", ")", ")", "->", "mapWithKeys", "(", "function", "(", "$", "v", ",", "$", "k", ")", "{", "return", "[", "$", "k", "=>", "$", "v", "[", "0", "]", "]", ";", "}", ")", "->", "all", "(", ")", ";", "}" ]
Retrieves all header values. @param string $header @return array
[ "Retrieves", "all", "header", "values", "." ]
ab24b37ea211eb106237a813ec8d47ec1d4fe199
https://github.com/faustbrian/HTTP/blob/ab24b37ea211eb106237a813ec8d47ec1d4fe199/src/HttpResponse.php#L113-L118
train
ComPHPPuebla/restful-extensions
src/ComPHPPuebla/Slim/Middleware/ContentNegotiationMiddleware.php
ContentNegotiationMiddleware.call
public function call() { if (!$this->responseShouldHaveBody()) { $this->next->call(); return; } $negotiator = new Negotiator(); $format = $negotiator->getBest($this->app->request()->headers('Accept')); if ($format && in_array(($type = $format->getValue()), $this->validContentTypes)) { $this->app->contentType($type); $this->next->call(); return; } $this->app->status(406); //Not acceptable }
php
public function call() { if (!$this->responseShouldHaveBody()) { $this->next->call(); return; } $negotiator = new Negotiator(); $format = $negotiator->getBest($this->app->request()->headers('Accept')); if ($format && in_array(($type = $format->getValue()), $this->validContentTypes)) { $this->app->contentType($type); $this->next->call(); return; } $this->app->status(406); //Not acceptable }
[ "public", "function", "call", "(", ")", "{", "if", "(", "!", "$", "this", "->", "responseShouldHaveBody", "(", ")", ")", "{", "$", "this", "->", "next", "->", "call", "(", ")", ";", "return", ";", "}", "$", "negotiator", "=", "new", "Negotiator", "(", ")", ";", "$", "format", "=", "$", "negotiator", "->", "getBest", "(", "$", "this", "->", "app", "->", "request", "(", ")", "->", "headers", "(", "'Accept'", ")", ")", ";", "if", "(", "$", "format", "&&", "in_array", "(", "(", "$", "type", "=", "$", "format", "->", "getValue", "(", ")", ")", ",", "$", "this", "->", "validContentTypes", ")", ")", "{", "$", "this", "->", "app", "->", "contentType", "(", "$", "type", ")", ";", "$", "this", "->", "next", "->", "call", "(", ")", ";", "return", ";", "}", "$", "this", "->", "app", "->", "status", "(", "406", ")", ";", "//Not acceptable", "}" ]
Ensure the provided content type is valid and set the proper response content type @see \Slim\Middleware::call()
[ "Ensure", "the", "provided", "content", "type", "is", "valid", "and", "set", "the", "proper", "response", "content", "type" ]
3dc5e554d7ebe1305eed4cd4ec71a6944316199c
https://github.com/ComPHPPuebla/restful-extensions/blob/3dc5e554d7ebe1305eed4cd4ec71a6944316199c/src/ComPHPPuebla/Slim/Middleware/ContentNegotiationMiddleware.php#L27-L48
train
mcaskill/tokenlist
src/TokenList/StringTokenList.php
StringTokenList.contains
public function contains( $token ) { $token = (string) $token; $this->__validate( $token ); return $this->__contains( $token ); }
php
public function contains( $token ) { $token = (string) $token; $this->__validate( $token ); return $this->__contains( $token ); }
[ "public", "function", "contains", "(", "$", "token", ")", "{", "$", "token", "=", "(", "string", ")", "$", "token", ";", "$", "this", "->", "__validate", "(", "$", "token", ")", ";", "return", "$", "this", "->", "__contains", "(", "$", "token", ")", ";", "}" ]
Checks if a the list of tokens contains the provided token. @param string A case-sensitive string representing the token. @return bool Returns TRUE if the token exists otherwise FALSE.
[ "Checks", "if", "a", "the", "list", "of", "tokens", "contains", "the", "provided", "token", "." ]
5266dc37157179c86f475a7a9301887d470b3664
https://github.com/mcaskill/tokenlist/blob/5266dc37157179c86f475a7a9301887d470b3664/src/TokenList/StringTokenList.php#L260-L266
train
mcaskill/tokenlist
src/TokenList/StringTokenList.php
StringTokenList.replace
public function replace( $old_token, $new_token ) { $updated = false; $old_token = (string) $old_token; $new_token = (string) $new_token; $this->__validate( $old_token ); $this->__validate( $new_token ); if ( $index = array_search( $old_token, $this->tokens, true ) ) { $this->tokens[ $index ] = $new_token; $updated = true; } if ( $updated ) { $this->__update(); } return $this; }
php
public function replace( $old_token, $new_token ) { $updated = false; $old_token = (string) $old_token; $new_token = (string) $new_token; $this->__validate( $old_token ); $this->__validate( $new_token ); if ( $index = array_search( $old_token, $this->tokens, true ) ) { $this->tokens[ $index ] = $new_token; $updated = true; } if ( $updated ) { $this->__update(); } return $this; }
[ "public", "function", "replace", "(", "$", "old_token", ",", "$", "new_token", ")", "{", "$", "updated", "=", "false", ";", "$", "old_token", "=", "(", "string", ")", "$", "old_token", ";", "$", "new_token", "=", "(", "string", ")", "$", "new_token", ";", "$", "this", "->", "__validate", "(", "$", "old_token", ")", ";", "$", "this", "->", "__validate", "(", "$", "new_token", ")", ";", "if", "(", "$", "index", "=", "array_search", "(", "$", "old_token", ",", "$", "this", "->", "tokens", ",", "true", ")", ")", "{", "$", "this", "->", "tokens", "[", "$", "index", "]", "=", "$", "new_token", ";", "$", "updated", "=", "true", ";", "}", "if", "(", "$", "updated", ")", "{", "$", "this", "->", "__update", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
Replace an existing token for a new one. If the $old_token does not exist, the new one will not be added. This method is a shortcut for StringTokenList::remove( $old_token ) followed by StringTokenList::add( $new_token ). @param string $old_token A case-sensitive string representing an existing token to remove. @param string $new_token A case-sensitive string representing a new token to append. @return $this
[ "Replace", "an", "existing", "token", "for", "a", "new", "one", "." ]
5266dc37157179c86f475a7a9301887d470b3664
https://github.com/mcaskill/tokenlist/blob/5266dc37157179c86f475a7a9301887d470b3664/src/TokenList/StringTokenList.php#L281-L301
train
mcaskill/tokenlist
src/TokenList/StringTokenList.php
StringTokenList.toggle
public function toggle( $token, $force = null ) { $output = null; $contains = $this->contains( $token ); if ( $contains ) { if ( ! $force ) { $this->__remove( [ $token ] ); $change = false; } else { $change = true; } } else { if ( false === $force ) { $change = false; } else { $this->__add( [ $token ] ); $change = true; } } return $change; }
php
public function toggle( $token, $force = null ) { $output = null; $contains = $this->contains( $token ); if ( $contains ) { if ( ! $force ) { $this->__remove( [ $token ] ); $change = false; } else { $change = true; } } else { if ( false === $force ) { $change = false; } else { $this->__add( [ $token ] ); $change = true; } } return $change; }
[ "public", "function", "toggle", "(", "$", "token", ",", "$", "force", "=", "null", ")", "{", "$", "output", "=", "null", ";", "$", "contains", "=", "$", "this", "->", "contains", "(", "$", "token", ")", ";", "if", "(", "$", "contains", ")", "{", "if", "(", "!", "$", "force", ")", "{", "$", "this", "->", "__remove", "(", "[", "$", "token", "]", ")", ";", "$", "change", "=", "false", ";", "}", "else", "{", "$", "change", "=", "true", ";", "}", "}", "else", "{", "if", "(", "false", "===", "$", "force", ")", "{", "$", "change", "=", "false", ";", "}", "else", "{", "$", "this", "->", "__add", "(", "[", "$", "token", "]", ")", ";", "$", "change", "=", "true", ";", "}", "}", "return", "$", "change", ";", "}" ]
If the name exists within the token list, it will be removed. If name does not exist, it will be added. Errors are not thrown If the token does not exist. @param string $tokens A case-sensitive string representing a token. @param bool|null $force When TRUE, adds the token (via self::add()). When FALSE, the token is removed (via self::remove()). If not used (undefined or simply non existent), normal toggle behavior ensues. Useful for adding or removing in one-step based on a condition. @return bool Returns TRUE if token is now present, and FALSE otherwise.
[ "If", "the", "name", "exists", "within", "the", "token", "list", "it", "will", "be", "removed", ".", "If", "name", "does", "not", "exist", "it", "will", "be", "added", "." ]
5266dc37157179c86f475a7a9301887d470b3664
https://github.com/mcaskill/tokenlist/blob/5266dc37157179c86f475a7a9301887d470b3664/src/TokenList/StringTokenList.php#L318-L343
train
mcaskill/tokenlist
src/TokenList/StringTokenList.php
StringTokenList.__modify
protected function __modify( $action, $arguments ) { $tokens = $arguments; $method = "__{$action}"; if ( 1 === count( $arguments ) ) { $tokens = reset( $tokens ); if ( is_string( $tokens ) ) { $tokens = explode( ' ', $tokens ); } } if ( is_array( $tokens ) ) { $tokens = array_map( 'strval', $tokens ); $tokens = array_filter( $tokens, 'strlen' ); } array_walk( $tokens, [ $this, '__validate' ] ); if ( method_exists( $this, $method ) ) { call_user_func( [ $this, $method ], $tokens ); } return $this; }
php
protected function __modify( $action, $arguments ) { $tokens = $arguments; $method = "__{$action}"; if ( 1 === count( $arguments ) ) { $tokens = reset( $tokens ); if ( is_string( $tokens ) ) { $tokens = explode( ' ', $tokens ); } } if ( is_array( $tokens ) ) { $tokens = array_map( 'strval', $tokens ); $tokens = array_filter( $tokens, 'strlen' ); } array_walk( $tokens, [ $this, '__validate' ] ); if ( method_exists( $this, $method ) ) { call_user_func( [ $this, $method ], $tokens ); } return $this; }
[ "protected", "function", "__modify", "(", "$", "action", ",", "$", "arguments", ")", "{", "$", "tokens", "=", "$", "arguments", ";", "$", "method", "=", "\"__{$action}\"", ";", "if", "(", "1", "===", "count", "(", "$", "arguments", ")", ")", "{", "$", "tokens", "=", "reset", "(", "$", "tokens", ")", ";", "if", "(", "is_string", "(", "$", "tokens", ")", ")", "{", "$", "tokens", "=", "explode", "(", "' '", ",", "$", "tokens", ")", ";", "}", "}", "if", "(", "is_array", "(", "$", "tokens", ")", ")", "{", "$", "tokens", "=", "array_map", "(", "'strval'", ",", "$", "tokens", ")", ";", "$", "tokens", "=", "array_filter", "(", "$", "tokens", ",", "'strlen'", ")", ";", "}", "array_walk", "(", "$", "tokens", ",", "[", "$", "this", ",", "'__validate'", "]", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "call_user_func", "(", "[", "$", "this", ",", "$", "method", "]", ",", "$", "tokens", ")", ";", "}", "return", "$", "this", ";", "}" ]
Alters the list of tokens. When adding, if token(s) already exists in the list of tokens, it will not add the token again. When removing, errors are not thrown If the token does not exist. @param string|string[] $tokens One or more case-sensitive tokens. @return $this
[ "Alters", "the", "list", "of", "tokens", "." ]
5266dc37157179c86f475a7a9301887d470b3664
https://github.com/mcaskill/tokenlist/blob/5266dc37157179c86f475a7a9301887d470b3664/src/TokenList/StringTokenList.php#L458-L483
train
mcaskill/tokenlist
src/TokenList/StringTokenList.php
StringTokenList.offsetSet
public function offsetSet( $offset, $value ) { $is_offset_string = is_string( $offset ); $is_value_string = is_string( $value ); /** e.g., `$obj[] = 'foo';` */ if ( null === $offset && $is_value_string ) { $this->add( $value ); } elseif ( is_bool( $value ) && $is_offset_string ) { /** e.g., `$obj['foo'] = true;` */ if ( $value ) { $this->add( $offset ); } /** e.g., `$obj['foo'] = false;` */ else { $this->remove( $offset ); } } elseif ( $is_offset_string && $is_value_string ) { /** e.g., `$obj['foo'] = 'bar';` */ $this->replace( $offset, $value ); } }
php
public function offsetSet( $offset, $value ) { $is_offset_string = is_string( $offset ); $is_value_string = is_string( $value ); /** e.g., `$obj[] = 'foo';` */ if ( null === $offset && $is_value_string ) { $this->add( $value ); } elseif ( is_bool( $value ) && $is_offset_string ) { /** e.g., `$obj['foo'] = true;` */ if ( $value ) { $this->add( $offset ); } /** e.g., `$obj['foo'] = false;` */ else { $this->remove( $offset ); } } elseif ( $is_offset_string && $is_value_string ) { /** e.g., `$obj['foo'] = 'bar';` */ $this->replace( $offset, $value ); } }
[ "public", "function", "offsetSet", "(", "$", "offset", ",", "$", "value", ")", "{", "$", "is_offset_string", "=", "is_string", "(", "$", "offset", ")", ";", "$", "is_value_string", "=", "is_string", "(", "$", "value", ")", ";", "/** e.g., `$obj[] = 'foo';` */", "if", "(", "null", "===", "$", "offset", "&&", "$", "is_value_string", ")", "{", "$", "this", "->", "add", "(", "$", "value", ")", ";", "}", "elseif", "(", "is_bool", "(", "$", "value", ")", "&&", "$", "is_offset_string", ")", "{", "/** e.g., `$obj['foo'] = true;` */", "if", "(", "$", "value", ")", "{", "$", "this", "->", "add", "(", "$", "offset", ")", ";", "}", "/** e.g., `$obj['foo'] = false;` */", "else", "{", "$", "this", "->", "remove", "(", "$", "offset", ")", ";", "}", "}", "elseif", "(", "$", "is_offset_string", "&&", "$", "is_value_string", ")", "{", "/** e.g., `$obj['foo'] = 'bar';` */", "$", "this", "->", "replace", "(", "$", "offset", ",", "$", "value", ")", ";", "}", "}" ]
Append a token to the list and optionally remove an existing token. @link http://php.net/manual/en/arrayaccess.offsetset.php @param int|null $offset The index is ignored. @param int|string|null $value The value to set.
[ "Append", "a", "token", "to", "the", "list", "and", "optionally", "remove", "an", "existing", "token", "." ]
5266dc37157179c86f475a7a9301887d470b3664
https://github.com/mcaskill/tokenlist/blob/5266dc37157179c86f475a7a9301887d470b3664/src/TokenList/StringTokenList.php#L617-L640
train
mcaskill/tokenlist
src/TokenList/StringTokenList.php
StringTokenList.offsetUnset
public function offsetUnset( $offset ) { if ( is_int( $offset ) ) { unset( $this->tokens[ $offset ] ); } else { $this->remove( $offset ); } }
php
public function offsetUnset( $offset ) { if ( is_int( $offset ) ) { unset( $this->tokens[ $offset ] ); } else { $this->remove( $offset ); } }
[ "public", "function", "offsetUnset", "(", "$", "offset", ")", "{", "if", "(", "is_int", "(", "$", "offset", ")", ")", "{", "unset", "(", "$", "this", "->", "tokens", "[", "$", "offset", "]", ")", ";", "}", "else", "{", "$", "this", "->", "remove", "(", "$", "offset", ")", ";", "}", "}" ]
Remove a token. @link http://php.net/manual/en/arrayaccess.offsetunset.php @param int|string $offset The token to unset.
[ "Remove", "a", "token", "." ]
5266dc37157179c86f475a7a9301887d470b3664
https://github.com/mcaskill/tokenlist/blob/5266dc37157179c86f475a7a9301887d470b3664/src/TokenList/StringTokenList.php#L649-L657
train
prolic/HumusMvc
src/HumusMvc/Application.php
Application.init
public static function init($configuration = array()) { $smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array(); $serviceManager = new ServiceManager(new ServiceManagerConfig($smConfig)); $serviceManager->setService('ApplicationConfig', $configuration); $serviceManager->get('ModuleManager')->loadModules(); return $serviceManager->get('Application')->bootstrap(); }
php
public static function init($configuration = array()) { $smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array(); $serviceManager = new ServiceManager(new ServiceManagerConfig($smConfig)); $serviceManager->setService('ApplicationConfig', $configuration); $serviceManager->get('ModuleManager')->loadModules(); return $serviceManager->get('Application')->bootstrap(); }
[ "public", "static", "function", "init", "(", "$", "configuration", "=", "array", "(", ")", ")", "{", "$", "smConfig", "=", "isset", "(", "$", "configuration", "[", "'service_manager'", "]", ")", "?", "$", "configuration", "[", "'service_manager'", "]", ":", "array", "(", ")", ";", "$", "serviceManager", "=", "new", "ServiceManager", "(", "new", "ServiceManagerConfig", "(", "$", "smConfig", ")", ")", ";", "$", "serviceManager", "->", "setService", "(", "'ApplicationConfig'", ",", "$", "configuration", ")", ";", "$", "serviceManager", "->", "get", "(", "'ModuleManager'", ")", "->", "loadModules", "(", ")", ";", "return", "$", "serviceManager", "->", "get", "(", "'Application'", ")", "->", "bootstrap", "(", ")", ";", "}" ]
Static method for quick and easy initialization of the Application. If you use this init() method, you cannot specify a service with the name of 'ApplicationConfig' in your service manager config. This name is reserved to hold the array from application.config.php. The following services can only be overridden from application.config.php: - ModuleManager - SharedEventManager - EventManager & Zend\EventManager\EventManagerInterface All other services are configured after module loading, thus can be overridden by modules. @param array $configuration @return Application
[ "Static", "method", "for", "quick", "and", "easy", "initialization", "of", "the", "Application", "." ]
09e8c6422d84b57745cc643047e10761be2a21a7
https://github.com/prolic/HumusMvc/blob/09e8c6422d84b57745cc643047e10761be2a21a7/src/HumusMvc/Application.php#L235-L242
train
bkstg/schedule-bundle
Controller/ScheduleController.php
ScheduleController.createAction
public function createAction( string $production_slug, AuthorizationCheckerInterface $auth, TokenStorageInterface $token, Request $request ): Response { // Lookup the production by production_slug. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Check permissions for this action, must be an editor or better. if (!$auth->isGranted('GROUP_ROLE_EDITOR', $production)) { throw new AccessDeniedException(); } // Create new schedule in this production. $schedule = new Schedule(); $schedule->setActive(true); $schedule->addGroup($production); $schedule->setAuthor($token->getToken()->getUser()->getUsername()); // Create a form for this schedule and handle it. $form = $this->form->create(ScheduleType::class, $schedule); $form->handleRequest($request); // Form is submitted and valid. if ($form->isSubmitted() && $form->isValid()) { // Match events with schedule. foreach ($schedule->getEvents() as $event) { foreach ($schedule->getGroups() as $group) { if (!$event->hasGroup($group)) { $event->addGroup($group); } } $event->setColour($schedule->getColour()); $event->setLocation($schedule->getLocation()); $event->setActive($schedule->isActive()); $event->setAuthor($schedule->getAuthor()); } // Persist the schedule (will cascade persist). $this->em->persist($schedule); $this->em->flush(); // Set success message and redirect. $this->session->getFlashBag()->add( 'success', $this->translator->trans('schedule.created', [ '%schedule%' => $schedule->getName(), ], BkstgScheduleBundle::TRANSLATION_DOMAIN) ); return new RedirectResponse($this->url_generator->generate( 'bkstg_schedule_read', [ 'id' => $schedule->getId(), 'production_slug' => $production->getSlug(), ] )); } // Render the form. return new Response($this->templating->render('@BkstgSchedule/Schedule/create.html.twig', [ 'form' => $form->createView(), 'production' => $production, ])); }
php
public function createAction( string $production_slug, AuthorizationCheckerInterface $auth, TokenStorageInterface $token, Request $request ): Response { // Lookup the production by production_slug. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Check permissions for this action, must be an editor or better. if (!$auth->isGranted('GROUP_ROLE_EDITOR', $production)) { throw new AccessDeniedException(); } // Create new schedule in this production. $schedule = new Schedule(); $schedule->setActive(true); $schedule->addGroup($production); $schedule->setAuthor($token->getToken()->getUser()->getUsername()); // Create a form for this schedule and handle it. $form = $this->form->create(ScheduleType::class, $schedule); $form->handleRequest($request); // Form is submitted and valid. if ($form->isSubmitted() && $form->isValid()) { // Match events with schedule. foreach ($schedule->getEvents() as $event) { foreach ($schedule->getGroups() as $group) { if (!$event->hasGroup($group)) { $event->addGroup($group); } } $event->setColour($schedule->getColour()); $event->setLocation($schedule->getLocation()); $event->setActive($schedule->isActive()); $event->setAuthor($schedule->getAuthor()); } // Persist the schedule (will cascade persist). $this->em->persist($schedule); $this->em->flush(); // Set success message and redirect. $this->session->getFlashBag()->add( 'success', $this->translator->trans('schedule.created', [ '%schedule%' => $schedule->getName(), ], BkstgScheduleBundle::TRANSLATION_DOMAIN) ); return new RedirectResponse($this->url_generator->generate( 'bkstg_schedule_read', [ 'id' => $schedule->getId(), 'production_slug' => $production->getSlug(), ] )); } // Render the form. return new Response($this->templating->render('@BkstgSchedule/Schedule/create.html.twig', [ 'form' => $form->createView(), 'production' => $production, ])); }
[ "public", "function", "createAction", "(", "string", "$", "production_slug", ",", "AuthorizationCheckerInterface", "$", "auth", ",", "TokenStorageInterface", "$", "token", ",", "Request", "$", "request", ")", ":", "Response", "{", "// Lookup the production by production_slug.", "$", "production_repo", "=", "$", "this", "->", "em", "->", "getRepository", "(", "Production", "::", "class", ")", ";", "if", "(", "null", "===", "$", "production", "=", "$", "production_repo", "->", "findOneBy", "(", "[", "'slug'", "=>", "$", "production_slug", "]", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "// Check permissions for this action, must be an editor or better.", "if", "(", "!", "$", "auth", "->", "isGranted", "(", "'GROUP_ROLE_EDITOR'", ",", "$", "production", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "// Create new schedule in this production.", "$", "schedule", "=", "new", "Schedule", "(", ")", ";", "$", "schedule", "->", "setActive", "(", "true", ")", ";", "$", "schedule", "->", "addGroup", "(", "$", "production", ")", ";", "$", "schedule", "->", "setAuthor", "(", "$", "token", "->", "getToken", "(", ")", "->", "getUser", "(", ")", "->", "getUsername", "(", ")", ")", ";", "// Create a form for this schedule and handle it.", "$", "form", "=", "$", "this", "->", "form", "->", "create", "(", "ScheduleType", "::", "class", ",", "$", "schedule", ")", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "// Form is submitted and valid.", "if", "(", "$", "form", "->", "isSubmitted", "(", ")", "&&", "$", "form", "->", "isValid", "(", ")", ")", "{", "// Match events with schedule.", "foreach", "(", "$", "schedule", "->", "getEvents", "(", ")", "as", "$", "event", ")", "{", "foreach", "(", "$", "schedule", "->", "getGroups", "(", ")", "as", "$", "group", ")", "{", "if", "(", "!", "$", "event", "->", "hasGroup", "(", "$", "group", ")", ")", "{", "$", "event", "->", "addGroup", "(", "$", "group", ")", ";", "}", "}", "$", "event", "->", "setColour", "(", "$", "schedule", "->", "getColour", "(", ")", ")", ";", "$", "event", "->", "setLocation", "(", "$", "schedule", "->", "getLocation", "(", ")", ")", ";", "$", "event", "->", "setActive", "(", "$", "schedule", "->", "isActive", "(", ")", ")", ";", "$", "event", "->", "setAuthor", "(", "$", "schedule", "->", "getAuthor", "(", ")", ")", ";", "}", "// Persist the schedule (will cascade persist).", "$", "this", "->", "em", "->", "persist", "(", "$", "schedule", ")", ";", "$", "this", "->", "em", "->", "flush", "(", ")", ";", "// Set success message and redirect.", "$", "this", "->", "session", "->", "getFlashBag", "(", ")", "->", "add", "(", "'success'", ",", "$", "this", "->", "translator", "->", "trans", "(", "'schedule.created'", ",", "[", "'%schedule%'", "=>", "$", "schedule", "->", "getName", "(", ")", ",", "]", ",", "BkstgScheduleBundle", "::", "TRANSLATION_DOMAIN", ")", ")", ";", "return", "new", "RedirectResponse", "(", "$", "this", "->", "url_generator", "->", "generate", "(", "'bkstg_schedule_read'", ",", "[", "'id'", "=>", "$", "schedule", "->", "getId", "(", ")", ",", "'production_slug'", "=>", "$", "production", "->", "getSlug", "(", ")", ",", "]", ")", ")", ";", "}", "// Render the form.", "return", "new", "Response", "(", "$", "this", "->", "templating", "->", "render", "(", "'@BkstgSchedule/Schedule/create.html.twig'", ",", "[", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", "'production'", "=>", "$", "production", ",", "]", ")", ")", ";", "}" ]
Create a new schedule, which is a collection of events. @param string $production_slug The slug for the production. @param AuthorizationCheckerInterface $auth The authorization checker service. @param TokenStorageInterface $token The user token service. @param Request $request The current request. @throws NotFoundHttpException When the production does not exist. @throws AccessDeniedException When the user is not an editor. @return Response A response.
[ "Create", "a", "new", "schedule", "which", "is", "a", "collection", "of", "events", "." ]
e64ac897aa7b28bc48319470d65de13cd4788afe
https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Controller/ScheduleController.php#L44-L112
train
bkstg/schedule-bundle
Controller/ScheduleController.php
ScheduleController.readAction
public function readAction( int $id, string $production_slug, AuthorizationCheckerInterface $auth, PaginatorInterface $paginator, Request $request ): Response { // Get the schedule and production for this action. list($schedule, $production) = $this->lookupEntity(Schedule::class, $id, $production_slug); // Check permissions for this action. if (!$auth->isGranted('view', $schedule)) { throw new AccessDeniedException(); } // Get and sort the events. $events = $schedule->getEvents()->toArray(); usort($events, function ($a, $b) { return $a->getStart() > $b->getStart(); }); // Render the schedule. return new Response($this->templating->render('@BkstgSchedule/Schedule/read.html.twig', [ 'production' => $production, 'schedule' => $schedule, 'sorted_events' => $events, ])); }
php
public function readAction( int $id, string $production_slug, AuthorizationCheckerInterface $auth, PaginatorInterface $paginator, Request $request ): Response { // Get the schedule and production for this action. list($schedule, $production) = $this->lookupEntity(Schedule::class, $id, $production_slug); // Check permissions for this action. if (!$auth->isGranted('view', $schedule)) { throw new AccessDeniedException(); } // Get and sort the events. $events = $schedule->getEvents()->toArray(); usort($events, function ($a, $b) { return $a->getStart() > $b->getStart(); }); // Render the schedule. return new Response($this->templating->render('@BkstgSchedule/Schedule/read.html.twig', [ 'production' => $production, 'schedule' => $schedule, 'sorted_events' => $events, ])); }
[ "public", "function", "readAction", "(", "int", "$", "id", ",", "string", "$", "production_slug", ",", "AuthorizationCheckerInterface", "$", "auth", ",", "PaginatorInterface", "$", "paginator", ",", "Request", "$", "request", ")", ":", "Response", "{", "// Get the schedule and production for this action.", "list", "(", "$", "schedule", ",", "$", "production", ")", "=", "$", "this", "->", "lookupEntity", "(", "Schedule", "::", "class", ",", "$", "id", ",", "$", "production_slug", ")", ";", "// Check permissions for this action.", "if", "(", "!", "$", "auth", "->", "isGranted", "(", "'view'", ",", "$", "schedule", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "// Get and sort the events.", "$", "events", "=", "$", "schedule", "->", "getEvents", "(", ")", "->", "toArray", "(", ")", ";", "usort", "(", "$", "events", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "return", "$", "a", "->", "getStart", "(", ")", ">", "$", "b", "->", "getStart", "(", ")", ";", "}", ")", ";", "// Render the schedule.", "return", "new", "Response", "(", "$", "this", "->", "templating", "->", "render", "(", "'@BkstgSchedule/Schedule/read.html.twig'", ",", "[", "'production'", "=>", "$", "production", ",", "'schedule'", "=>", "$", "schedule", ",", "'sorted_events'", "=>", "$", "events", ",", "]", ")", ")", ";", "}" ]
Show a single schedule. @param int $id The schedule id. @param string $production_slug The production slug. @param AuthorizationCheckerInterface $auth The authorization checker service. @param PaginatorInterface $paginator The paginator service. @param Request $request The incoming request. @throws AccessDeniedException If the user has no access to view. @return Response
[ "Show", "a", "single", "schedule", "." ]
e64ac897aa7b28bc48319470d65de13cd4788afe
https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Controller/ScheduleController.php#L127-L154
train
bkstg/schedule-bundle
Controller/ScheduleController.php
ScheduleController.deleteAction
public function deleteAction( string $production_slug, int $id, AuthorizationCheckerInterface $auth, Request $request ): Response { // Get the schedule and production for this action. list($schedule, $production) = $this->lookupEntity(Schedule::class, $id, $production_slug); // Check permissions for this action. if (!$auth->isGranted('edit', $schedule)) { throw new AccessDeniedException(); } // Create and handle a fake form to submit. $form = $this->form->createBuilder()->getForm(); $form->handleRequest($request); // If form is submitted and valid. if ($form->isSubmitted() && $form->isValid()) { // Remove the schedule and flush the entity manager. $this->em->remove($schedule); $this->em->flush(); // Create flash message. $this->session->getFlashBag()->add( 'success', $this->translator->trans('schedule.deleted', [ '%schedule%' => $schedule->getName(), ], BkstgScheduleBundle::TRANSLATION_DOMAIN) ); // Redirect to production calendar. return new RedirectResponse($this->url_generator->generate( 'bkstg_calendar_production', ['production_slug' => $production->getSlug()] )); } // Render the delete form. return new Response($this->templating->render('@BkstgSchedule/Schedule/delete.html.twig', [ 'schedule' => $schedule, 'production' => $production, 'form' => $form->createView(), ])); }
php
public function deleteAction( string $production_slug, int $id, AuthorizationCheckerInterface $auth, Request $request ): Response { // Get the schedule and production for this action. list($schedule, $production) = $this->lookupEntity(Schedule::class, $id, $production_slug); // Check permissions for this action. if (!$auth->isGranted('edit', $schedule)) { throw new AccessDeniedException(); } // Create and handle a fake form to submit. $form = $this->form->createBuilder()->getForm(); $form->handleRequest($request); // If form is submitted and valid. if ($form->isSubmitted() && $form->isValid()) { // Remove the schedule and flush the entity manager. $this->em->remove($schedule); $this->em->flush(); // Create flash message. $this->session->getFlashBag()->add( 'success', $this->translator->trans('schedule.deleted', [ '%schedule%' => $schedule->getName(), ], BkstgScheduleBundle::TRANSLATION_DOMAIN) ); // Redirect to production calendar. return new RedirectResponse($this->url_generator->generate( 'bkstg_calendar_production', ['production_slug' => $production->getSlug()] )); } // Render the delete form. return new Response($this->templating->render('@BkstgSchedule/Schedule/delete.html.twig', [ 'schedule' => $schedule, 'production' => $production, 'form' => $form->createView(), ])); }
[ "public", "function", "deleteAction", "(", "string", "$", "production_slug", ",", "int", "$", "id", ",", "AuthorizationCheckerInterface", "$", "auth", ",", "Request", "$", "request", ")", ":", "Response", "{", "// Get the schedule and production for this action.", "list", "(", "$", "schedule", ",", "$", "production", ")", "=", "$", "this", "->", "lookupEntity", "(", "Schedule", "::", "class", ",", "$", "id", ",", "$", "production_slug", ")", ";", "// Check permissions for this action.", "if", "(", "!", "$", "auth", "->", "isGranted", "(", "'edit'", ",", "$", "schedule", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "// Create and handle a fake form to submit.", "$", "form", "=", "$", "this", "->", "form", "->", "createBuilder", "(", ")", "->", "getForm", "(", ")", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "// If form is submitted and valid.", "if", "(", "$", "form", "->", "isSubmitted", "(", ")", "&&", "$", "form", "->", "isValid", "(", ")", ")", "{", "// Remove the schedule and flush the entity manager.", "$", "this", "->", "em", "->", "remove", "(", "$", "schedule", ")", ";", "$", "this", "->", "em", "->", "flush", "(", ")", ";", "// Create flash message.", "$", "this", "->", "session", "->", "getFlashBag", "(", ")", "->", "add", "(", "'success'", ",", "$", "this", "->", "translator", "->", "trans", "(", "'schedule.deleted'", ",", "[", "'%schedule%'", "=>", "$", "schedule", "->", "getName", "(", ")", ",", "]", ",", "BkstgScheduleBundle", "::", "TRANSLATION_DOMAIN", ")", ")", ";", "// Redirect to production calendar.", "return", "new", "RedirectResponse", "(", "$", "this", "->", "url_generator", "->", "generate", "(", "'bkstg_calendar_production'", ",", "[", "'production_slug'", "=>", "$", "production", "->", "getSlug", "(", ")", "]", ")", ")", ";", "}", "// Render the delete form.", "return", "new", "Response", "(", "$", "this", "->", "templating", "->", "render", "(", "'@BkstgSchedule/Schedule/delete.html.twig'", ",", "[", "'schedule'", "=>", "$", "schedule", ",", "'production'", "=>", "$", "production", ",", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", "]", ")", ")", ";", "}" ]
Delete a single schedule. @param string $production_slug The production slug. @param int $id The schedule id. @param AuthorizationCheckerInterface $auth The authorization checker service. @param Request $request The incoming request. @throws AccessDeniedException If the user has no access to edit. @return Response
[ "Delete", "a", "single", "schedule", "." ]
e64ac897aa7b28bc48319470d65de13cd4788afe
https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Controller/ScheduleController.php#L264-L309
train
bkstg/schedule-bundle
Controller/ScheduleController.php
ScheduleController.archiveAction
public function archiveAction( string $production_slug, PaginatorInterface $paginator, AuthorizationCheckerInterface $auth, Request $request ): Response { // Lookup the production by production_slug. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Check permissions for this action. if (!$auth->isGranted('GROUP_ROLE_EDITOR', $production)) { throw new AccessDeniedException(); } // Get a list of archived schedules. $schedule_repo = $this->em->getRepository(Schedule::class); $query = $schedule_repo->findArchivedSchedulesQuery($production); // Paginate and render the results. $schedules = $paginator->paginate($query, $request->query->getInt('page', 1)); return new Response($this->templating->render('@BkstgSchedule/Schedule/archive.html.twig', [ 'schedules' => $schedules, 'production' => $production, ])); }
php
public function archiveAction( string $production_slug, PaginatorInterface $paginator, AuthorizationCheckerInterface $auth, Request $request ): Response { // Lookup the production by production_slug. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Check permissions for this action. if (!$auth->isGranted('GROUP_ROLE_EDITOR', $production)) { throw new AccessDeniedException(); } // Get a list of archived schedules. $schedule_repo = $this->em->getRepository(Schedule::class); $query = $schedule_repo->findArchivedSchedulesQuery($production); // Paginate and render the results. $schedules = $paginator->paginate($query, $request->query->getInt('page', 1)); return new Response($this->templating->render('@BkstgSchedule/Schedule/archive.html.twig', [ 'schedules' => $schedules, 'production' => $production, ])); }
[ "public", "function", "archiveAction", "(", "string", "$", "production_slug", ",", "PaginatorInterface", "$", "paginator", ",", "AuthorizationCheckerInterface", "$", "auth", ",", "Request", "$", "request", ")", ":", "Response", "{", "// Lookup the production by production_slug.", "$", "production_repo", "=", "$", "this", "->", "em", "->", "getRepository", "(", "Production", "::", "class", ")", ";", "if", "(", "null", "===", "$", "production", "=", "$", "production_repo", "->", "findOneBy", "(", "[", "'slug'", "=>", "$", "production_slug", "]", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "// Check permissions for this action.", "if", "(", "!", "$", "auth", "->", "isGranted", "(", "'GROUP_ROLE_EDITOR'", ",", "$", "production", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "// Get a list of archived schedules.", "$", "schedule_repo", "=", "$", "this", "->", "em", "->", "getRepository", "(", "Schedule", "::", "class", ")", ";", "$", "query", "=", "$", "schedule_repo", "->", "findArchivedSchedulesQuery", "(", "$", "production", ")", ";", "// Paginate and render the results.", "$", "schedules", "=", "$", "paginator", "->", "paginate", "(", "$", "query", ",", "$", "request", "->", "query", "->", "getInt", "(", "'page'", ",", "1", ")", ")", ";", "return", "new", "Response", "(", "$", "this", "->", "templating", "->", "render", "(", "'@BkstgSchedule/Schedule/archive.html.twig'", ",", "[", "'schedules'", "=>", "$", "schedules", ",", "'production'", "=>", "$", "production", ",", "]", ")", ")", ";", "}" ]
Show a list of archived schedules. @param string $production_slug The production to look in. @param PaginatorInterface $paginator The paginator service. @param AuthorizationCheckerInterface $auth The authorization checker service. @param Request $request The incoming request. @throws NotFoundHttpException When the production does not exist. @throws AccessDeniedException When the user is not an editor. @return Response
[ "Show", "a", "list", "of", "archived", "schedules", "." ]
e64ac897aa7b28bc48319470d65de13cd4788afe
https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Controller/ScheduleController.php#L324-L352
train
artscorestudio/user-bundle
Controller/AjaxRequestController.php
AjaxRequestController.byUsernameAction
public function byUsernameAction(Request $request) { $term = $request->get('username'); $users = $this->get('asf_user.user.manager')->getRepository()->findByUsernameContains($term); $search = array(); foreach($users as $user) { $search[] = array( 'id' => $user->getId(), 'username' => $user->getUsername(), 'email' => $user->getEmail() ); } $response = new Response(); $response->setContent(json_encode(array( 'total_count' => count($search), 'items' => $search ))); return $response; }
php
public function byUsernameAction(Request $request) { $term = $request->get('username'); $users = $this->get('asf_user.user.manager')->getRepository()->findByUsernameContains($term); $search = array(); foreach($users as $user) { $search[] = array( 'id' => $user->getId(), 'username' => $user->getUsername(), 'email' => $user->getEmail() ); } $response = new Response(); $response->setContent(json_encode(array( 'total_count' => count($search), 'items' => $search ))); return $response; }
[ "public", "function", "byUsernameAction", "(", "Request", "$", "request", ")", "{", "$", "term", "=", "$", "request", "->", "get", "(", "'username'", ")", ";", "$", "users", "=", "$", "this", "->", "get", "(", "'asf_user.user.manager'", ")", "->", "getRepository", "(", ")", "->", "findByUsernameContains", "(", "$", "term", ")", ";", "$", "search", "=", "array", "(", ")", ";", "foreach", "(", "$", "users", "as", "$", "user", ")", "{", "$", "search", "[", "]", "=", "array", "(", "'id'", "=>", "$", "user", "->", "getId", "(", ")", ",", "'username'", "=>", "$", "user", "->", "getUsername", "(", ")", ",", "'email'", "=>", "$", "user", "->", "getEmail", "(", ")", ")", ";", "}", "$", "response", "=", "new", "Response", "(", ")", ";", "$", "response", "->", "setContent", "(", "json_encode", "(", "array", "(", "'total_count'", "=>", "count", "(", "$", "search", ")", ",", "'items'", "=>", "$", "search", ")", ")", ")", ";", "return", "$", "response", ";", "}" ]
Return list of users according to the search by username @param Request $request @return \Symfony\Component\HttpFoundation\Response
[ "Return", "list", "of", "users", "according", "to", "the", "search", "by", "username" ]
83e660d1073e1cbfde6eed0b528b8c99e78a2e53
https://github.com/artscorestudio/user-bundle/blob/83e660d1073e1cbfde6eed0b528b8c99e78a2e53/Controller/AjaxRequestController.php#L30-L51
train
spoom-php/core
src/extension/Helper/Text.php
Text.apply
public static function apply( string $text, $context, string $skip = '', ?callable $callback = null ): string { // $context = Storage::instance( $context ); $output = ''; $delimiter = null; for( $i = 0, $length = strlen( $text ); $i < $length; ++$i ) { // detect skipped blocks (start and end) if( $delimiter == $text{$i} ) $delimiter = null; else if( !$delimiter && strpos( $skip, $text{$i} ) !== false ) $delimiter = $text{$i}; // try to process the insertion if( !$delimiter && $text{$i} == '{' ) { $buffer = ''; for( $j = $i + 1; $j < $length && $text{$j} != '}'; ++$j ) { $buffer .= $text{$j}; } $i = $j; $output .= $callback ? $callback( $buffer, $context ) : $context[ $buffer ]; continue; } $output .= $text{$i}; } return $output; }
php
public static function apply( string $text, $context, string $skip = '', ?callable $callback = null ): string { // $context = Storage::instance( $context ); $output = ''; $delimiter = null; for( $i = 0, $length = strlen( $text ); $i < $length; ++$i ) { // detect skipped blocks (start and end) if( $delimiter == $text{$i} ) $delimiter = null; else if( !$delimiter && strpos( $skip, $text{$i} ) !== false ) $delimiter = $text{$i}; // try to process the insertion if( !$delimiter && $text{$i} == '{' ) { $buffer = ''; for( $j = $i + 1; $j < $length && $text{$j} != '}'; ++$j ) { $buffer .= $text{$j}; } $i = $j; $output .= $callback ? $callback( $buffer, $context ) : $context[ $buffer ]; continue; } $output .= $text{$i}; } return $output; }
[ "public", "static", "function", "apply", "(", "string", "$", "text", ",", "$", "context", ",", "string", "$", "skip", "=", "''", ",", "?", "callable", "$", "callback", "=", "null", ")", ":", "string", "{", "//", "$", "context", "=", "Storage", "::", "instance", "(", "$", "context", ")", ";", "$", "output", "=", "''", ";", "$", "delimiter", "=", "null", ";", "for", "(", "$", "i", "=", "0", ",", "$", "length", "=", "strlen", "(", "$", "text", ")", ";", "$", "i", "<", "$", "length", ";", "++", "$", "i", ")", "{", "// detect skipped blocks (start and end)", "if", "(", "$", "delimiter", "==", "$", "text", "{", "$", "i", "}", ")", "$", "delimiter", "=", "null", ";", "else", "if", "(", "!", "$", "delimiter", "&&", "strpos", "(", "$", "skip", ",", "$", "text", "{", "$", "i", "}", ")", "!==", "false", ")", "$", "delimiter", "=", "$", "text", "{", "$", "i", "}", ";", "// try to process the insertion", "if", "(", "!", "$", "delimiter", "&&", "$", "text", "{", "$", "i", "}", "==", "'{'", ")", "{", "$", "buffer", "=", "''", ";", "for", "(", "$", "j", "=", "$", "i", "+", "1", ";", "$", "j", "<", "$", "length", "&&", "$", "text", "{", "$", "j", "}", "!=", "'}'", ";", "++", "$", "j", ")", "{", "$", "buffer", ".=", "$", "text", "{", "$", "j", "}", ";", "}", "$", "i", "=", "$", "j", ";", "$", "output", ".=", "$", "callback", "?", "$", "callback", "(", "$", "buffer", ",", "$", "context", ")", ":", "$", "context", "[", "$", "buffer", "]", ";", "continue", ";", "}", "$", "output", ".=", "$", "text", "{", "$", "i", "}", ";", "}", "return", "$", "output", ";", "}" ]
Insert variables to the input from insertion array used the regexp constant of class TODO implement condition and loop support @param string $text Input string to insert @param array|object|StorageInterface $context The insertion variables @param string $skip Opener (and closer) characters for blocks in the text that will not processed @param callable|null $callback callback to process replaces @return string
[ "Insert", "variables", "to", "the", "input", "from", "insertion", "array", "used", "the", "regexp", "constant", "of", "class" ]
ea7184213352fa2fad7636927a019e5798734e04
https://github.com/spoom-php/core/blob/ea7184213352fa2fad7636927a019e5798734e04/src/extension/Helper/Text.php#L131-L161
train
spoom-php/core
src/extension/Helper/Text.php
Text.reduce
public static function reduce( string $text, string $chars = ' ' ): string { $text = preg_replace( '/[' . $chars . ']{2,}/', ' ', $text ); return $text; }
php
public static function reduce( string $text, string $chars = ' ' ): string { $text = preg_replace( '/[' . $chars . ']{2,}/', ' ', $text ); return $text; }
[ "public", "static", "function", "reduce", "(", "string", "$", "text", ",", "string", "$", "chars", "=", "' '", ")", ":", "string", "{", "$", "text", "=", "preg_replace", "(", "'/['", ".", "$", "chars", ".", "']{2,}/'", ",", "' '", ",", "$", "text", ")", ";", "return", "$", "text", ";", "}" ]
Clear multiply occurance of chars from text and leave only one @param string $text @param string $chars @return string
[ "Clear", "multiply", "occurance", "of", "chars", "from", "text", "and", "leave", "only", "one" ]
ea7184213352fa2fad7636927a019e5798734e04
https://github.com/spoom-php/core/blob/ea7184213352fa2fad7636927a019e5798734e04/src/extension/Helper/Text.php#L170-L173
train
CrunchPHP/fastcgi
src/Protocol/Header.php
Header.encode
public function encode() { return \pack('CCnnCx', 1, $this->getType()->value(), $this->getRequestId(), $this->getLength(), $this->getPaddingLength()); }
php
public function encode() { return \pack('CCnnCx', 1, $this->getType()->value(), $this->getRequestId(), $this->getLength(), $this->getPaddingLength()); }
[ "public", "function", "encode", "(", ")", "{", "return", "\\", "pack", "(", "'CCnnCx'", ",", "1", ",", "$", "this", "->", "getType", "(", ")", "->", "value", "(", ")", ",", "$", "this", "->", "getRequestId", "(", ")", ",", "$", "this", "->", "getLength", "(", ")", ",", "$", "this", "->", "getPaddingLength", "(", ")", ")", ";", "}" ]
Returns the encoded header as a string. @return string
[ "Returns", "the", "encoded", "header", "as", "a", "string", "." ]
102437193e67e5a841ec5a897549ec345788d1bd
https://github.com/CrunchPHP/fastcgi/blob/102437193e67e5a841ec5a897549ec345788d1bd/src/Protocol/Header.php#L161-L164
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/nonces/Nonces.php
Nonces.verify
public function verify($nonce, $action) { $value = $this->Encryption->decryptSecureCookie($nonce); if(!$value) return false; if(strcmp($value, $action) === 0) return true; return false; }
php
public function verify($nonce, $action) { $value = $this->Encryption->decryptSecureCookie($nonce); if(!$value) return false; if(strcmp($value, $action) === 0) return true; return false; }
[ "public", "function", "verify", "(", "$", "nonce", ",", "$", "action", ")", "{", "$", "value", "=", "$", "this", "->", "Encryption", "->", "decryptSecureCookie", "(", "$", "nonce", ")", ";", "if", "(", "!", "$", "value", ")", "return", "false", ";", "if", "(", "strcmp", "(", "$", "value", ",", "$", "action", ")", "===", "0", ")", "return", "true", ";", "return", "false", ";", "}" ]
Verifies the validity of a nonce against the supplied action. $nonceAcceptableTimePeriods nonce checks are performed, one for the current $nonceTimePeriod period and one for each previous $nonceTimePeriod period. If any time period nonce matches, then the nonce is valid. @param string $nonce Full nonce string supplied by the request @param string $action Arbitrary string action to verify nonce against @return int Time period nonce was found in (ie. 1, 2, etc.) or false if not valid
[ "Verifies", "the", "validity", "of", "a", "nonce", "against", "the", "supplied", "action", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/nonces/Nonces.php#L72-L83
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/nonces/Nonces.php
Nonces.create
public function create($action) { $expire = time() + $this->timePeriod; // 24 hour expiration $user_id = $this->RequestContext->getUserRef(); if(is_null($user_id)) $user_id = $this->Session->getID(); return $this->Encryption->encryptSecureCookie(strtolower($action), $expire, (string)$user_id); }
php
public function create($action) { $expire = time() + $this->timePeriod; // 24 hour expiration $user_id = $this->RequestContext->getUserRef(); if(is_null($user_id)) $user_id = $this->Session->getID(); return $this->Encryption->encryptSecureCookie(strtolower($action), $expire, (string)$user_id); }
[ "public", "function", "create", "(", "$", "action", ")", "{", "$", "expire", "=", "time", "(", ")", "+", "$", "this", "->", "timePeriod", ";", "// 24 hour expiration", "$", "user_id", "=", "$", "this", "->", "RequestContext", "->", "getUserRef", "(", ")", ";", "if", "(", "is_null", "(", "$", "user_id", ")", ")", "$", "user_id", "=", "$", "this", "->", "Session", "->", "getID", "(", ")", ";", "return", "$", "this", "->", "Encryption", "->", "encryptSecureCookie", "(", "strtolower", "(", "$", "action", ")", ",", "$", "expire", ",", "(", "string", ")", "$", "user_id", ")", ";", "}" ]
Creates a new nonce string for the given action, typically derived from the user, a salt, and valid only for a given amount of time @param string $action Arbitrary string action to create nonce for @return string Nonce
[ "Creates", "a", "new", "nonce", "string", "for", "the", "given", "action", "typically", "derived", "from", "the", "user", "a", "salt", "and", "valid", "only", "for", "a", "given", "amount", "of", "time" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/nonces/Nonces.php#L93-L102
train
abtincbrians/HierarchicalConfig
src/config/FileConfig.php
FileConfig.reload
public function reload() { // Rebuild the configuration data // Re-init $this->init( array( self::CONFIG_KEY_FILE_PATH => $this->getConfigFilePath(), ConfigInterface::KEY_CONTEXT => $this->getContext(), ) ); }
php
public function reload() { // Rebuild the configuration data // Re-init $this->init( array( self::CONFIG_KEY_FILE_PATH => $this->getConfigFilePath(), ConfigInterface::KEY_CONTEXT => $this->getContext(), ) ); }
[ "public", "function", "reload", "(", ")", "{", "// Rebuild the configuration data", "// Re-init", "$", "this", "->", "init", "(", "array", "(", "self", "::", "CONFIG_KEY_FILE_PATH", "=>", "$", "this", "->", "getConfigFilePath", "(", ")", ",", "ConfigInterface", "::", "KEY_CONTEXT", "=>", "$", "this", "->", "getContext", "(", ")", ",", ")", ")", ";", "}" ]
Reload the configuration from file. Apply this after changing context or the file path.
[ "Reload", "the", "configuration", "from", "file", "." ]
62ef0f6455fad1399ed1438b1eb544aa01a2af38
https://github.com/abtincbrians/HierarchicalConfig/blob/62ef0f6455fad1399ed1438b1eb544aa01a2af38/src/config/FileConfig.php#L46-L56
train
abtincbrians/HierarchicalConfig
src/config/FileConfig.php
FileConfig.doSetup
protected function doSetup($config = array()) { // Catch the configuration file path if (isset($config[self::CONFIG_KEY_FILE_PATH])) { $this->configFilePath = $config[self::CONFIG_KEY_FILE_PATH]; } else { // Also consider throwing an exception here instead // of failing silently return $config; } // Catch the context if (isset($config[ConfigInterface::KEY_CONTEXT])) { $this->context = $config[ConfigInterface::KEY_CONTEXT]; } return $this->readConfigurationFiles(); }
php
protected function doSetup($config = array()) { // Catch the configuration file path if (isset($config[self::CONFIG_KEY_FILE_PATH])) { $this->configFilePath = $config[self::CONFIG_KEY_FILE_PATH]; } else { // Also consider throwing an exception here instead // of failing silently return $config; } // Catch the context if (isset($config[ConfigInterface::KEY_CONTEXT])) { $this->context = $config[ConfigInterface::KEY_CONTEXT]; } return $this->readConfigurationFiles(); }
[ "protected", "function", "doSetup", "(", "$", "config", "=", "array", "(", ")", ")", "{", "// Catch the configuration file path", "if", "(", "isset", "(", "$", "config", "[", "self", "::", "CONFIG_KEY_FILE_PATH", "]", ")", ")", "{", "$", "this", "->", "configFilePath", "=", "$", "config", "[", "self", "::", "CONFIG_KEY_FILE_PATH", "]", ";", "}", "else", "{", "// Also consider throwing an exception here instead", "// of failing silently", "return", "$", "config", ";", "}", "// Catch the context", "if", "(", "isset", "(", "$", "config", "[", "ConfigInterface", "::", "KEY_CONTEXT", "]", ")", ")", "{", "$", "this", "->", "context", "=", "$", "config", "[", "ConfigInterface", "::", "KEY_CONTEXT", "]", ";", "}", "return", "$", "this", "->", "readConfigurationFiles", "(", ")", ";", "}" ]
Override in child if you need to override core config setup. @param array $config @return array
[ "Override", "in", "child", "if", "you", "need", "to", "override", "core", "config", "setup", "." ]
62ef0f6455fad1399ed1438b1eb544aa01a2af38
https://github.com/abtincbrians/HierarchicalConfig/blob/62ef0f6455fad1399ed1438b1eb544aa01a2af38/src/config/FileConfig.php#L123-L140
train
froq/froq-encoding
src/Encoder.php
Encoder.jsonEncode
public static final function jsonEncode($data, array $options = null): array { $encoder = new JsonEncoder($options); return [$encoder->encode($data), $encoder->hasError() ? new EncoderException('JSON Error: '. $encoder->getError()) : null]; }
php
public static final function jsonEncode($data, array $options = null): array { $encoder = new JsonEncoder($options); return [$encoder->encode($data), $encoder->hasError() ? new EncoderException('JSON Error: '. $encoder->getError()) : null]; }
[ "public", "static", "final", "function", "jsonEncode", "(", "$", "data", ",", "array", "$", "options", "=", "null", ")", ":", "array", "{", "$", "encoder", "=", "new", "JsonEncoder", "(", "$", "options", ")", ";", "return", "[", "$", "encoder", "->", "encode", "(", "$", "data", ")", ",", "$", "encoder", "->", "hasError", "(", ")", "?", "new", "EncoderException", "(", "'JSON Error: '", ".", "$", "encoder", "->", "getError", "(", ")", ")", ":", "null", "]", ";", "}" ]
Json encode. @param any $data @param array|null $options @return array
[ "Json", "encode", "." ]
95a6b707ba6cae5f18bb6767b1df88f2fea0f9b4
https://github.com/froq/froq-encoding/blob/95a6b707ba6cae5f18bb6767b1df88f2fea0f9b4/src/Encoder.php#L126-L132
train
froq/froq-encoding
src/Encoder.php
Encoder.jsonDecode
public static final function jsonDecode($data, array $options = null): array { $encoder = new JsonEncoder($options); return [$encoder->decode($data), $encoder->hasError() ? new EncoderException('JSON Error: '. $encoder->getError()) : null]; }
php
public static final function jsonDecode($data, array $options = null): array { $encoder = new JsonEncoder($options); return [$encoder->decode($data), $encoder->hasError() ? new EncoderException('JSON Error: '. $encoder->getError()) : null]; }
[ "public", "static", "final", "function", "jsonDecode", "(", "$", "data", ",", "array", "$", "options", "=", "null", ")", ":", "array", "{", "$", "encoder", "=", "new", "JsonEncoder", "(", "$", "options", ")", ";", "return", "[", "$", "encoder", "->", "decode", "(", "$", "data", ")", ",", "$", "encoder", "->", "hasError", "(", ")", "?", "new", "EncoderException", "(", "'JSON Error: '", ".", "$", "encoder", "->", "getError", "(", ")", ")", ":", "null", "]", ";", "}" ]
Json decode. @param any $data @param array|null $options @return array
[ "Json", "decode", "." ]
95a6b707ba6cae5f18bb6767b1df88f2fea0f9b4
https://github.com/froq/froq-encoding/blob/95a6b707ba6cae5f18bb6767b1df88f2fea0f9b4/src/Encoder.php#L140-L146
train
froq/froq-encoding
src/Encoder.php
Encoder.gzipEncode
public static final function gzipEncode($data, array $options = null): array { $encoder = new GzipEncoder($options); return [$encoder->encode($data), $encoder->hasError() ? new EncoderException('GZip Error: '. $encoder->getError()) : null]; }
php
public static final function gzipEncode($data, array $options = null): array { $encoder = new GzipEncoder($options); return [$encoder->encode($data), $encoder->hasError() ? new EncoderException('GZip Error: '. $encoder->getError()) : null]; }
[ "public", "static", "final", "function", "gzipEncode", "(", "$", "data", ",", "array", "$", "options", "=", "null", ")", ":", "array", "{", "$", "encoder", "=", "new", "GzipEncoder", "(", "$", "options", ")", ";", "return", "[", "$", "encoder", "->", "encode", "(", "$", "data", ")", ",", "$", "encoder", "->", "hasError", "(", ")", "?", "new", "EncoderException", "(", "'GZip Error: '", ".", "$", "encoder", "->", "getError", "(", ")", ")", ":", "null", "]", ";", "}" ]
Gzip encode. @param ?string $data @param array|null $options @return ?string
[ "Gzip", "encode", "." ]
95a6b707ba6cae5f18bb6767b1df88f2fea0f9b4
https://github.com/froq/froq-encoding/blob/95a6b707ba6cae5f18bb6767b1df88f2fea0f9b4/src/Encoder.php#L154-L160
train
froq/froq-encoding
src/Encoder.php
Encoder.gzipDecode
public static final function gzipDecode($data, array $options = null): array { $encoder = new GzipEncoder($options); return [$encoder->decode($data), $encoder->hasError() ? new EncoderException('GZip Error: '. $encoder->getError()) : null]; }
php
public static final function gzipDecode($data, array $options = null): array { $encoder = new GzipEncoder($options); return [$encoder->decode($data), $encoder->hasError() ? new EncoderException('GZip Error: '. $encoder->getError()) : null]; }
[ "public", "static", "final", "function", "gzipDecode", "(", "$", "data", ",", "array", "$", "options", "=", "null", ")", ":", "array", "{", "$", "encoder", "=", "new", "GzipEncoder", "(", "$", "options", ")", ";", "return", "[", "$", "encoder", "->", "decode", "(", "$", "data", ")", ",", "$", "encoder", "->", "hasError", "(", ")", "?", "new", "EncoderException", "(", "'GZip Error: '", ".", "$", "encoder", "->", "getError", "(", ")", ")", ":", "null", "]", ";", "}" ]
Gzip decode. @param ?string $data @param array|null $options @return ?string
[ "Gzip", "decode", "." ]
95a6b707ba6cae5f18bb6767b1df88f2fea0f9b4
https://github.com/froq/froq-encoding/blob/95a6b707ba6cae5f18bb6767b1df88f2fea0f9b4/src/Encoder.php#L168-L174
train
anime-db/ani-db-filler-bundle
src/Command/UpdateTitlesCommand.php
UpdateTitlesCommand.getOriginDb
protected function getOriginDb(OutputInterface $output, $now) { $url = $this->getContainer()->getParameter('anime_db.ani_db.import_titles'); if (($path = parse_url($url, PHP_URL_PATH)) === false) { throw new \InvalidArgumentException('Failed parse URL: '.$url); } /* @var Filesystem $fs */ $fs = $this->getContainer()->get('filesystem'); $filename = sys_get_temp_dir().'/'.pathinfo($path, PATHINFO_BASENAME); if (!$fs->exists($filename) || filemtime($filename) + self::CACHE_LIFE_TIME < $now) { /* @var $downloader \AnimeDb\Bundle\AppBundle\Service\Downloader */ $downloader = $this->getContainer()->get('anime_db.downloader'); $tmp = tempnam(sys_get_temp_dir(), 'ani_db_titles'); if (!$downloader->download($url, $tmp, true)) { $fs->remove($tmp); throw new \RuntimeException('Failed to download the titles database'); } $fs->rename($tmp, $filename, true); $output->writeln('The titles database is loaded'); } return $filename; }
php
protected function getOriginDb(OutputInterface $output, $now) { $url = $this->getContainer()->getParameter('anime_db.ani_db.import_titles'); if (($path = parse_url($url, PHP_URL_PATH)) === false) { throw new \InvalidArgumentException('Failed parse URL: '.$url); } /* @var Filesystem $fs */ $fs = $this->getContainer()->get('filesystem'); $filename = sys_get_temp_dir().'/'.pathinfo($path, PATHINFO_BASENAME); if (!$fs->exists($filename) || filemtime($filename) + self::CACHE_LIFE_TIME < $now) { /* @var $downloader \AnimeDb\Bundle\AppBundle\Service\Downloader */ $downloader = $this->getContainer()->get('anime_db.downloader'); $tmp = tempnam(sys_get_temp_dir(), 'ani_db_titles'); if (!$downloader->download($url, $tmp, true)) { $fs->remove($tmp); throw new \RuntimeException('Failed to download the titles database'); } $fs->rename($tmp, $filename, true); $output->writeln('The titles database is loaded'); } return $filename; }
[ "protected", "function", "getOriginDb", "(", "OutputInterface", "$", "output", ",", "$", "now", ")", "{", "$", "url", "=", "$", "this", "->", "getContainer", "(", ")", "->", "getParameter", "(", "'anime_db.ani_db.import_titles'", ")", ";", "if", "(", "(", "$", "path", "=", "parse_url", "(", "$", "url", ",", "PHP_URL_PATH", ")", ")", "===", "false", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Failed parse URL: '", ".", "$", "url", ")", ";", "}", "/* @var Filesystem $fs */", "$", "fs", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'filesystem'", ")", ";", "$", "filename", "=", "sys_get_temp_dir", "(", ")", ".", "'/'", ".", "pathinfo", "(", "$", "path", ",", "PATHINFO_BASENAME", ")", ";", "if", "(", "!", "$", "fs", "->", "exists", "(", "$", "filename", ")", "||", "filemtime", "(", "$", "filename", ")", "+", "self", "::", "CACHE_LIFE_TIME", "<", "$", "now", ")", "{", "/* @var $downloader \\AnimeDb\\Bundle\\AppBundle\\Service\\Downloader */", "$", "downloader", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'anime_db.downloader'", ")", ";", "$", "tmp", "=", "tempnam", "(", "sys_get_temp_dir", "(", ")", ",", "'ani_db_titles'", ")", ";", "if", "(", "!", "$", "downloader", "->", "download", "(", "$", "url", ",", "$", "tmp", ",", "true", ")", ")", "{", "$", "fs", "->", "remove", "(", "$", "tmp", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "'Failed to download the titles database'", ")", ";", "}", "$", "fs", "->", "rename", "(", "$", "tmp", ",", "$", "filename", ",", "true", ")", ";", "$", "output", "->", "writeln", "(", "'The titles database is loaded'", ")", ";", "}", "return", "$", "filename", ";", "}" ]
Get original db file. Download the original db if need and cache it in a system temp dir @throws \InvalidArgumentException @throws \RuntimeException @param OutputInterface $output @param int $now @return string
[ "Get", "original", "db", "file", "." ]
7581beda0cd46b11867a703ca429147f0c5b5b46
https://github.com/anime-db/ani-db-filler-bundle/blob/7581beda0cd46b11867a703ca429147f0c5b5b46/src/Command/UpdateTitlesCommand.php#L98-L123
train
naucon/Utility
src/ListAbstract.php
ListAbstract.addWithIndex
public function addWithIndex($index, $element) { if (!is_null($index) && is_scalar($index) ) { if (!$this->hasIndex($index)) { $this->set($index, $element); } else { // index already exist throw new ListException('Element could not be added to list. Index already exist.', E_NOTICE); } } else { // given index name is not valid throw new ListException('Element could not be added to list. Index is not valid.', E_NOTICE); } }
php
public function addWithIndex($index, $element) { if (!is_null($index) && is_scalar($index) ) { if (!$this->hasIndex($index)) { $this->set($index, $element); } else { // index already exist throw new ListException('Element could not be added to list. Index already exist.', E_NOTICE); } } else { // given index name is not valid throw new ListException('Element could not be added to list. Index is not valid.', E_NOTICE); } }
[ "public", "function", "addWithIndex", "(", "$", "index", ",", "$", "element", ")", "{", "if", "(", "!", "is_null", "(", "$", "index", ")", "&&", "is_scalar", "(", "$", "index", ")", ")", "{", "if", "(", "!", "$", "this", "->", "hasIndex", "(", "$", "index", ")", ")", "{", "$", "this", "->", "set", "(", "$", "index", ",", "$", "element", ")", ";", "}", "else", "{", "// index already exist", "throw", "new", "ListException", "(", "'Element could not be added to list. Index already exist.'", ",", "E_NOTICE", ")", ";", "}", "}", "else", "{", "// given index name is not valid", "throw", "new", "ListException", "(", "'Element could not be added to list. Index is not valid.'", ",", "E_NOTICE", ")", ";", "}", "}" ]
add a element to a specified position of the list @param int $index element index @param mixed $element element @return void @throws ListException
[ "add", "a", "element", "to", "a", "specified", "position", "of", "the", "list" ]
d225bb5d09d82400917f710c9d502949a66442c4
https://github.com/naucon/Utility/blob/d225bb5d09d82400917f710c9d502949a66442c4/src/ListAbstract.php#L44-L59
train
naucon/Utility
src/ListAbstract.php
ListAbstract.removeIndex
public function removeIndex($index) { if ($this->hasIndex($index)) { unset($this->_items[$index]); $this->_iterator = null; return true; } return false; }
php
public function removeIndex($index) { if ($this->hasIndex($index)) { unset($this->_items[$index]); $this->_iterator = null; return true; } return false; }
[ "public", "function", "removeIndex", "(", "$", "index", ")", "{", "if", "(", "$", "this", "->", "hasIndex", "(", "$", "index", ")", ")", "{", "unset", "(", "$", "this", "->", "_items", "[", "$", "index", "]", ")", ";", "$", "this", "->", "_iterator", "=", "null", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
remove element with specified position from list @param int $index element index @return bool
[ "remove", "element", "with", "specified", "position", "from", "list" ]
d225bb5d09d82400917f710c9d502949a66442c4
https://github.com/naucon/Utility/blob/d225bb5d09d82400917f710c9d502949a66442c4/src/ListAbstract.php#L95-L103
train
naucon/Utility
src/ListAbstract.php
ListAbstract.set
public function set($index, $element) { if (!is_null($index) && is_scalar($index) ) { $this->_iterator = null; return $this->_items[$index] = $element; } else { // given index name is not valid throw new ListException('Element could not be added to list. Index is not valid.', E_NOTICE); } }
php
public function set($index, $element) { if (!is_null($index) && is_scalar($index) ) { $this->_iterator = null; return $this->_items[$index] = $element; } else { // given index name is not valid throw new ListException('Element could not be added to list. Index is not valid.', E_NOTICE); } }
[ "public", "function", "set", "(", "$", "index", ",", "$", "element", ")", "{", "if", "(", "!", "is_null", "(", "$", "index", ")", "&&", "is_scalar", "(", "$", "index", ")", ")", "{", "$", "this", "->", "_iterator", "=", "null", ";", "return", "$", "this", "->", "_items", "[", "$", "index", "]", "=", "$", "element", ";", "}", "else", "{", "// given index name is not valid", "throw", "new", "ListException", "(", "'Element could not be added to list. Index is not valid.'", ",", "E_NOTICE", ")", ";", "}", "}" ]
add or replace a element to a specified position of the list @param int $index element index @param mixed $element element @return mixed element @throws ListException
[ "add", "or", "replace", "a", "element", "to", "a", "specified", "position", "of", "the", "list" ]
d225bb5d09d82400917f710c9d502949a66442c4
https://github.com/naucon/Utility/blob/d225bb5d09d82400917f710c9d502949a66442c4/src/ListAbstract.php#L113-L124
train
dmt-software/command-bus-validator
src/Validator/ValidationMiddleware.php
ValidationMiddleware.getDefaultValidator
protected function getDefaultValidator(): ValidatorInterface { $loaders = [new StaticMethodLoader()]; if (class_exists(AnnotationReader::class) && class_exists(ArrayCache::class)) { AnnotationRegistry::registerUniqueLoader('class_exists'); $loaders[] = new AnnotationLoader(new CachedReader(new AnnotationReader(), new ArrayCache())); } return (new ValidatorBuilder()) ->setMetadataFactory( new LazyLoadingMetadataFactory( new LoaderChain($loaders) ) ) ->getValidator(); }
php
protected function getDefaultValidator(): ValidatorInterface { $loaders = [new StaticMethodLoader()]; if (class_exists(AnnotationReader::class) && class_exists(ArrayCache::class)) { AnnotationRegistry::registerUniqueLoader('class_exists'); $loaders[] = new AnnotationLoader(new CachedReader(new AnnotationReader(), new ArrayCache())); } return (new ValidatorBuilder()) ->setMetadataFactory( new LazyLoadingMetadataFactory( new LoaderChain($loaders) ) ) ->getValidator(); }
[ "protected", "function", "getDefaultValidator", "(", ")", ":", "ValidatorInterface", "{", "$", "loaders", "=", "[", "new", "StaticMethodLoader", "(", ")", "]", ";", "if", "(", "class_exists", "(", "AnnotationReader", "::", "class", ")", "&&", "class_exists", "(", "ArrayCache", "::", "class", ")", ")", "{", "AnnotationRegistry", "::", "registerUniqueLoader", "(", "'class_exists'", ")", ";", "$", "loaders", "[", "]", "=", "new", "AnnotationLoader", "(", "new", "CachedReader", "(", "new", "AnnotationReader", "(", ")", ",", "new", "ArrayCache", "(", ")", ")", ")", ";", "}", "return", "(", "new", "ValidatorBuilder", "(", ")", ")", "->", "setMetadataFactory", "(", "new", "LazyLoadingMetadataFactory", "(", "new", "LoaderChain", "(", "$", "loaders", ")", ")", ")", "->", "getValidator", "(", ")", ";", "}" ]
Get a default validator. By default the usage of annotations to validate object is off. To enable annotation configuration install `doctrine/annotations` and `doctrine/cache`. @return RecursiveValidator|ValidatorInterface @throws AnnotationException
[ "Get", "a", "default", "validator", "." ]
a16f32e37754cccd3210c4aa17badd86edb8990a
https://github.com/dmt-software/command-bus-validator/blob/a16f32e37754cccd3210c4aa17badd86edb8990a/src/Validator/ValidationMiddleware.php#L73-L89
train
zodream/database
src/Model/Concerns/HasRelation.php
HasRelation.getRelationWhere
protected function getRelationWhere($links, $key = null) { if (is_null($key) && !is_array($links)) { $key = in_array('id', $this->primaryKey) ? 'id' : reset($this->primaryKey); } if (!is_array($links)) { $links = [$links => $key]; } foreach ($links as &$item) { $item = $this->get($item); } return $links; }
php
protected function getRelationWhere($links, $key = null) { if (is_null($key) && !is_array($links)) { $key = in_array('id', $this->primaryKey) ? 'id' : reset($this->primaryKey); } if (!is_array($links)) { $links = [$links => $key]; } foreach ($links as &$item) { $item = $this->get($item); } return $links; }
[ "protected", "function", "getRelationWhere", "(", "$", "links", ",", "$", "key", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "key", ")", "&&", "!", "is_array", "(", "$", "links", ")", ")", "{", "$", "key", "=", "in_array", "(", "'id'", ",", "$", "this", "->", "primaryKey", ")", "?", "'id'", ":", "reset", "(", "$", "this", "->", "primaryKey", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "links", ")", ")", "{", "$", "links", "=", "[", "$", "links", "=>", "$", "key", "]", ";", "}", "foreach", "(", "$", "links", "as", "&", "$", "item", ")", "{", "$", "item", "=", "$", "this", "->", "get", "(", "$", "item", ")", ";", "}", "return", "$", "links", ";", "}" ]
GET RELATION WHERE SQL @param string|array $links @param string $key @return array
[ "GET", "RELATION", "WHERE", "SQL" ]
03712219c057799d07350a3a2650c55bcc92c28e
https://github.com/zodream/database/blob/03712219c057799d07350a3a2650c55bcc92c28e/src/Model/Concerns/HasRelation.php#L43-L54
train
Vibius/Facade
src/ManifestResolver.php
ManifestResolver.findManifests
public function findManifests(){ foreach ($this->src as $component => $source) { $src = $source[0]."/../manifest.php"; if( file_exists($src) && is_readable($src) ){ $this->manifests[$component] = $src; } } }
php
public function findManifests(){ foreach ($this->src as $component => $source) { $src = $source[0]."/../manifest.php"; if( file_exists($src) && is_readable($src) ){ $this->manifests[$component] = $src; } } }
[ "public", "function", "findManifests", "(", ")", "{", "foreach", "(", "$", "this", "->", "src", "as", "$", "component", "=>", "$", "source", ")", "{", "$", "src", "=", "$", "source", "[", "0", "]", ".", "\"/../manifest.php\"", ";", "if", "(", "file_exists", "(", "$", "src", ")", "&&", "is_readable", "(", "$", "src", ")", ")", "{", "$", "this", "->", "manifests", "[", "$", "component", "]", "=", "$", "src", ";", "}", "}", "}" ]
Function is used to find manifests in psr4 loaded packages
[ "Function", "is", "used", "to", "find", "manifests", "in", "psr4", "loaded", "packages" ]
2dac08bae098c436031b70f5a09abc365740aee0
https://github.com/Vibius/Facade/blob/2dac08bae098c436031b70f5a09abc365740aee0/src/ManifestResolver.php#L20-L27
train