repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
FuzeWorks/Core
src/FuzeWorks/Layout.php
Layout.getFileFromString
public function getFileFromString($string, $directory, $extensions = array()): string { $directory = preg_replace('#/+#', '/', (!is_null($directory) ? $directory : $this->directory).DS); if (strpbrk($directory, "\\/?%*:|\"<>") === TRUE || strpbrk($string, "\\/?%*:|\"<>") === TRUE) { throw new LayoutException('Could not get file. Invalid file string', 1); } if (!file_exists($directory)) { throw new LayoutException('Could not get file. Directory does not exist', 1); } // Set the file name and location $layoutSelector = explode('/', $string); if (count($layoutSelector) == 1) { $layoutSelector = 'layout.'.$layoutSelector[0]; } else { // Get last file $file = end($layoutSelector); // Reset to start reset($layoutSelector); // Remove last value array_pop($layoutSelector); $layoutSelector[] = 'layout.'.$file; // And create the final value $layoutSelector = implode(DS, $layoutSelector); } // Then try and select a file $fileSelected = false; $selectedFile = null; foreach ($extensions as $extension) { $file = $directory.$layoutSelector.'.'.strtolower($extension); $file = preg_replace('#/+#', '/', $file); if (file_exists($file) && !$fileSelected) { $selectedFile = $file; $fileSelected = true; Logger::log("Found matching file: '".$file."'"); } elseif (file_exists($file) && $fileSelected) { throw new LayoutException('Could not select template. Multiple valid extensions detected. Can not choose.', 1); } } // And choose what to output if (!$fileSelected) { throw new LayoutException('Could not select template. No matching file found.'); } return $selectedFile; }
php
public function getFileFromString($string, $directory, $extensions = array()): string { $directory = preg_replace('#/+#', '/', (!is_null($directory) ? $directory : $this->directory).DS); if (strpbrk($directory, "\\/?%*:|\"<>") === TRUE || strpbrk($string, "\\/?%*:|\"<>") === TRUE) { throw new LayoutException('Could not get file. Invalid file string', 1); } if (!file_exists($directory)) { throw new LayoutException('Could not get file. Directory does not exist', 1); } // Set the file name and location $layoutSelector = explode('/', $string); if (count($layoutSelector) == 1) { $layoutSelector = 'layout.'.$layoutSelector[0]; } else { // Get last file $file = end($layoutSelector); // Reset to start reset($layoutSelector); // Remove last value array_pop($layoutSelector); $layoutSelector[] = 'layout.'.$file; // And create the final value $layoutSelector = implode(DS, $layoutSelector); } // Then try and select a file $fileSelected = false; $selectedFile = null; foreach ($extensions as $extension) { $file = $directory.$layoutSelector.'.'.strtolower($extension); $file = preg_replace('#/+#', '/', $file); if (file_exists($file) && !$fileSelected) { $selectedFile = $file; $fileSelected = true; Logger::log("Found matching file: '".$file."'"); } elseif (file_exists($file) && $fileSelected) { throw new LayoutException('Could not select template. Multiple valid extensions detected. Can not choose.', 1); } } // And choose what to output if (!$fileSelected) { throw new LayoutException('Could not select template. No matching file found.'); } return $selectedFile; }
[ "public", "function", "getFileFromString", "(", "$", "string", ",", "$", "directory", ",", "$", "extensions", "=", "array", "(", ")", ")", ":", "string", "{", "$", "directory", "=", "preg_replace", "(", "'#/+#'", ",", "'/'", ",", "(", "!", "is_null", "(", "$", "directory", ")", "?", "$", "directory", ":", "$", "this", "->", "directory", ")", ".", "DS", ")", ";", "if", "(", "strpbrk", "(", "$", "directory", ",", "\"\\\\/?%*:|\\\"<>\"", ")", "===", "TRUE", "||", "strpbrk", "(", "$", "string", ",", "\"\\\\/?%*:|\\\"<>\"", ")", "===", "TRUE", ")", "{", "throw", "new", "LayoutException", "(", "'Could not get file. Invalid file string'", ",", "1", ")", ";", "}", "if", "(", "!", "file_exists", "(", "$", "directory", ")", ")", "{", "throw", "new", "LayoutException", "(", "'Could not get file. Directory does not exist'", ",", "1", ")", ";", "}", "// Set the file name and location", "$", "layoutSelector", "=", "explode", "(", "'/'", ",", "$", "string", ")", ";", "if", "(", "count", "(", "$", "layoutSelector", ")", "==", "1", ")", "{", "$", "layoutSelector", "=", "'layout.'", ".", "$", "layoutSelector", "[", "0", "]", ";", "}", "else", "{", "// Get last file", "$", "file", "=", "end", "(", "$", "layoutSelector", ")", ";", "// Reset to start", "reset", "(", "$", "layoutSelector", ")", ";", "// Remove last value", "array_pop", "(", "$", "layoutSelector", ")", ";", "$", "layoutSelector", "[", "]", "=", "'layout.'", ".", "$", "file", ";", "// And create the final value", "$", "layoutSelector", "=", "implode", "(", "DS", ",", "$", "layoutSelector", ")", ";", "}", "// Then try and select a file", "$", "fileSelected", "=", "false", ";", "$", "selectedFile", "=", "null", ";", "foreach", "(", "$", "extensions", "as", "$", "extension", ")", "{", "$", "file", "=", "$", "directory", ".", "$", "layoutSelector", ".", "'.'", ".", "strtolower", "(", "$", "extension", ")", ";", "$", "file", "=", "preg_replace", "(", "'#/+#'", ",", "'/'", ",", "$", "file", ")", ";", "if", "(", "file_exists", "(", "$", "file", ")", "&&", "!", "$", "fileSelected", ")", "{", "$", "selectedFile", "=", "$", "file", ";", "$", "fileSelected", "=", "true", ";", "Logger", "::", "log", "(", "\"Found matching file: '\"", ".", "$", "file", ".", "\"'\"", ")", ";", "}", "elseif", "(", "file_exists", "(", "$", "file", ")", "&&", "$", "fileSelected", ")", "{", "throw", "new", "LayoutException", "(", "'Could not select template. Multiple valid extensions detected. Can not choose.'", ",", "1", ")", ";", "}", "}", "// And choose what to output", "if", "(", "!", "$", "fileSelected", ")", "{", "throw", "new", "LayoutException", "(", "'Could not select template. No matching file found.'", ")", ";", "}", "return", "$", "selectedFile", ";", "}" ]
Converts a layout string to a file using the directory and the used extensions. It will detect whether the file exists and choose a file according to the provided extensions @param string $string The string used by a controller. eg: 'dashboard/home' @param string $directory The directory to search in for the template @param array $extensions Extensions to use for this template. Eg array('php', 'tpl') etc. @return string Filepath of the template @throws LayoutException On error
[ "Converts", "a", "layout", "string", "to", "a", "file", "using", "the", "directory", "and", "the", "used", "extensions", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Layout.php#L241-L295
train
FuzeWorks/Core
src/FuzeWorks/Layout.php
Layout.setFileFromString
public function setFileFromString($string, $directory, $extensions = array()) { $this->file = $this->getFileFromString($string, $directory, $extensions); $this->directory = preg_replace('#/+#', '/', (!is_null($directory) ? $directory : $this->directory).DS); }
php
public function setFileFromString($string, $directory, $extensions = array()) { $this->file = $this->getFileFromString($string, $directory, $extensions); $this->directory = preg_replace('#/+#', '/', (!is_null($directory) ? $directory : $this->directory).DS); }
[ "public", "function", "setFileFromString", "(", "$", "string", ",", "$", "directory", ",", "$", "extensions", "=", "array", "(", ")", ")", "{", "$", "this", "->", "file", "=", "$", "this", "->", "getFileFromString", "(", "$", "string", ",", "$", "directory", ",", "$", "extensions", ")", ";", "$", "this", "->", "directory", "=", "preg_replace", "(", "'#/+#'", ",", "'/'", ",", "(", "!", "is_null", "(", "$", "directory", ")", "?", "$", "directory", ":", "$", "this", "->", "directory", ")", ".", "DS", ")", ";", "}" ]
Converts a layout string to a file using the directory and the used extensions. It also sets the file variable of this class. It will detect whether the file exists and choose a file according to the provided extensions @param string $string The string used by a controller. eg: 'dashboard/home' @param string $directory The directory to search in for the template @param array $extensions Extensions to use for this template. Eg array('php', 'tpl') etc. @return string Filepath of the template @throws LayoutException On error
[ "Converts", "a", "layout", "string", "to", "a", "file", "using", "the", "directory", "and", "the", "used", "extensions", ".", "It", "also", "sets", "the", "file", "variable", "of", "this", "class", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Layout.php#L310-L314
train
FuzeWorks/Core
src/FuzeWorks/Layout.php
Layout.setEngine
public function setEngine($name): bool { $this->loadTemplateEngines(); if (isset($this->engines[$name])) { $this->current_engine = $this->engines[$name]; Logger::log('Set the Template Engine to '.$name); return true; } throw new LayoutException('Could not set engine. Engine does not exist', 1); }
php
public function setEngine($name): bool { $this->loadTemplateEngines(); if (isset($this->engines[$name])) { $this->current_engine = $this->engines[$name]; Logger::log('Set the Template Engine to '.$name); return true; } throw new LayoutException('Could not set engine. Engine does not exist', 1); }
[ "public", "function", "setEngine", "(", "$", "name", ")", ":", "bool", "{", "$", "this", "->", "loadTemplateEngines", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "engines", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "current_engine", "=", "$", "this", "->", "engines", "[", "$", "name", "]", ";", "Logger", "::", "log", "(", "'Set the Template Engine to '", ".", "$", "name", ")", ";", "return", "true", ";", "}", "throw", "new", "LayoutException", "(", "'Could not set engine. Engine does not exist'", ",", "1", ")", ";", "}" ]
Set the engine for the next layout. @param string $name Name of the template engine @return bool true on success @throws LayoutException on error
[ "Set", "the", "engine", "for", "the", "next", "layout", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Layout.php#L399-L409
train
FuzeWorks/Core
src/FuzeWorks/Layout.php
Layout.getEngine
public function getEngine($name): TemplateEngine { $this->loadTemplateEngines(); if (isset($this->engines[$name])) { return $this->engines[$name]; } throw new LayoutException('Could not return engine. Engine does not exist', 1); }
php
public function getEngine($name): TemplateEngine { $this->loadTemplateEngines(); if (isset($this->engines[$name])) { return $this->engines[$name]; } throw new LayoutException('Could not return engine. Engine does not exist', 1); }
[ "public", "function", "getEngine", "(", "$", "name", ")", ":", "TemplateEngine", "{", "$", "this", "->", "loadTemplateEngines", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "engines", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "engines", "[", "$", "name", "]", ";", "}", "throw", "new", "LayoutException", "(", "'Could not return engine. Engine does not exist'", ",", "1", ")", ";", "}" ]
Get a loaded template engine. @param string $name Name of the template engine @return TemplateEngine
[ "Get", "a", "loaded", "template", "engine", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Layout.php#L418-L425
train
FuzeWorks/Core
src/FuzeWorks/Layout.php
Layout.registerEngine
public function registerEngine($engineClass, $engineName, $engineFileExtensions = array()): bool { // First check if the engine already exists if (isset($this->engines[$engineName])) { throw new LayoutException("Could not register engine. Engine '".$engineName."' already registered", 1); } // Then check if the object is correct if ($engineClass instanceof TemplateEngine) { // Install it $this->engines[$engineName] = $engineClass; // Then define for what file extensions this Template Engine will work if (!is_array($engineFileExtensions)) { throw new LayoutException('Could not register engine. File extensions must be an array', 1); } // Then install them foreach ($engineFileExtensions as $extension) { if (isset($this->file_extensions[strtolower($extension)])) { throw new LayoutException('Could not register engine. File extension already bound to engine', 1); } // And add it $this->file_extensions[strtolower($extension)] = $engineName; } // And log it Logger::log('Registered Template Engine: '.$engineName); return true; } throw new LayoutException("Could not register engine. Engine must implement \FuzeWorks\TemplateEngine", 1); }
php
public function registerEngine($engineClass, $engineName, $engineFileExtensions = array()): bool { // First check if the engine already exists if (isset($this->engines[$engineName])) { throw new LayoutException("Could not register engine. Engine '".$engineName."' already registered", 1); } // Then check if the object is correct if ($engineClass instanceof TemplateEngine) { // Install it $this->engines[$engineName] = $engineClass; // Then define for what file extensions this Template Engine will work if (!is_array($engineFileExtensions)) { throw new LayoutException('Could not register engine. File extensions must be an array', 1); } // Then install them foreach ($engineFileExtensions as $extension) { if (isset($this->file_extensions[strtolower($extension)])) { throw new LayoutException('Could not register engine. File extension already bound to engine', 1); } // And add it $this->file_extensions[strtolower($extension)] = $engineName; } // And log it Logger::log('Registered Template Engine: '.$engineName); return true; } throw new LayoutException("Could not register engine. Engine must implement \FuzeWorks\TemplateEngine", 1); }
[ "public", "function", "registerEngine", "(", "$", "engineClass", ",", "$", "engineName", ",", "$", "engineFileExtensions", "=", "array", "(", ")", ")", ":", "bool", "{", "// First check if the engine already exists", "if", "(", "isset", "(", "$", "this", "->", "engines", "[", "$", "engineName", "]", ")", ")", "{", "throw", "new", "LayoutException", "(", "\"Could not register engine. Engine '\"", ".", "$", "engineName", ".", "\"' already registered\"", ",", "1", ")", ";", "}", "// Then check if the object is correct", "if", "(", "$", "engineClass", "instanceof", "TemplateEngine", ")", "{", "// Install it", "$", "this", "->", "engines", "[", "$", "engineName", "]", "=", "$", "engineClass", ";", "// Then define for what file extensions this Template Engine will work", "if", "(", "!", "is_array", "(", "$", "engineFileExtensions", ")", ")", "{", "throw", "new", "LayoutException", "(", "'Could not register engine. File extensions must be an array'", ",", "1", ")", ";", "}", "// Then install them", "foreach", "(", "$", "engineFileExtensions", "as", "$", "extension", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "file_extensions", "[", "strtolower", "(", "$", "extension", ")", "]", ")", ")", "{", "throw", "new", "LayoutException", "(", "'Could not register engine. File extension already bound to engine'", ",", "1", ")", ";", "}", "// And add it", "$", "this", "->", "file_extensions", "[", "strtolower", "(", "$", "extension", ")", "]", "=", "$", "engineName", ";", "}", "// And log it", "Logger", "::", "log", "(", "'Registered Template Engine: '", ".", "$", "engineName", ")", ";", "return", "true", ";", "}", "throw", "new", "LayoutException", "(", "\"Could not register engine. Engine must implement \\FuzeWorks\\TemplateEngine\"", ",", "1", ")", ";", "}" ]
Register a new template engine. @param object $engineClass Object that implements the \FuzeWorks\TemplateEngine @param string $engineName Name of the template engine @param array $engineFileExtensions File extensions this template engine should be used for @return bool true on success @throws LayoutException
[ "Register", "a", "new", "template", "engine", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Layout.php#L437-L471
train
FuzeWorks/Core
src/FuzeWorks/Layout.php
Layout.loadTemplateEngines
public function loadTemplateEngines() { if (!$this->engines_loaded) { Events::fireEvent('layoutLoadEngineEvent'); // Load the engines provided in this file $this->registerEngine(new PHPEngine(), 'PHP', array('php')); $this->registerEngine(new JsonEngine(), 'JSON', array('json')); $this->registerEngine(new SmartyEngine(), 'Smarty', array('tpl')); $this->registerEngine(new LatteEngine(), 'Latte', array('latte')); $this->engines_loaded = true; } }
php
public function loadTemplateEngines() { if (!$this->engines_loaded) { Events::fireEvent('layoutLoadEngineEvent'); // Load the engines provided in this file $this->registerEngine(new PHPEngine(), 'PHP', array('php')); $this->registerEngine(new JsonEngine(), 'JSON', array('json')); $this->registerEngine(new SmartyEngine(), 'Smarty', array('tpl')); $this->registerEngine(new LatteEngine(), 'Latte', array('latte')); $this->engines_loaded = true; } }
[ "public", "function", "loadTemplateEngines", "(", ")", "{", "if", "(", "!", "$", "this", "->", "engines_loaded", ")", "{", "Events", "::", "fireEvent", "(", "'layoutLoadEngineEvent'", ")", ";", "// Load the engines provided in this file", "$", "this", "->", "registerEngine", "(", "new", "PHPEngine", "(", ")", ",", "'PHP'", ",", "array", "(", "'php'", ")", ")", ";", "$", "this", "->", "registerEngine", "(", "new", "JsonEngine", "(", ")", ",", "'JSON'", ",", "array", "(", "'json'", ")", ")", ";", "$", "this", "->", "registerEngine", "(", "new", "SmartyEngine", "(", ")", ",", "'Smarty'", ",", "array", "(", "'tpl'", ")", ")", ";", "$", "this", "->", "registerEngine", "(", "new", "LatteEngine", "(", ")", ",", "'Latte'", ",", "array", "(", "'latte'", ")", ")", ";", "$", "this", "->", "engines_loaded", "=", "true", ";", "}", "}" ]
Load the template engines by sending a layoutLoadEngineEvent.
[ "Load", "the", "template", "engines", "by", "sending", "a", "layoutLoadEngineEvent", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Layout.php#L476-L488
train
FuzeWorks/Core
src/FuzeWorks/Layout.php
Layout.reset
public function reset() { if (!is_null($this->current_engine)) { $this->current_engine->reset(); } // Unload the engines $this->engines = array(); $this->engines_loaded = false; $this->file_extensions = array(); $this->current_engine = null; $this->assigned_variables = array(); $this->directory = Core::$appDir . DS . 'Layout'; Logger::log('Reset the layout manager to its default state'); }
php
public function reset() { if (!is_null($this->current_engine)) { $this->current_engine->reset(); } // Unload the engines $this->engines = array(); $this->engines_loaded = false; $this->file_extensions = array(); $this->current_engine = null; $this->assigned_variables = array(); $this->directory = Core::$appDir . DS . 'Layout'; Logger::log('Reset the layout manager to its default state'); }
[ "public", "function", "reset", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "current_engine", ")", ")", "{", "$", "this", "->", "current_engine", "->", "reset", "(", ")", ";", "}", "// Unload the engines", "$", "this", "->", "engines", "=", "array", "(", ")", ";", "$", "this", "->", "engines_loaded", "=", "false", ";", "$", "this", "->", "file_extensions", "=", "array", "(", ")", ";", "$", "this", "->", "current_engine", "=", "null", ";", "$", "this", "->", "assigned_variables", "=", "array", "(", ")", ";", "$", "this", "->", "directory", "=", "Core", "::", "$", "appDir", ".", "DS", ".", "'Layout'", ";", "Logger", "::", "log", "(", "'Reset the layout manager to its default state'", ")", ";", "}" ]
Resets the layout manager to its default state.
[ "Resets", "the", "layout", "manager", "to", "its", "default", "state", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Layout.php#L513-L528
train
frodosghost/PublishBundle
DependencyInjection/ManhattanPublishExtension.php
ManhattanPublishExtension.remapPublishStates
protected function remapPublishStates(array $config, ContainerBuilder $container) { $publishStates = array(); foreach ($config as $role) { $publishStates[$role['value']] = $role['name']; } $container->setParameter('manhattan.publish.states', $publishStates); }
php
protected function remapPublishStates(array $config, ContainerBuilder $container) { $publishStates = array(); foreach ($config as $role) { $publishStates[$role['value']] = $role['name']; } $container->setParameter('manhattan.publish.states', $publishStates); }
[ "protected", "function", "remapPublishStates", "(", "array", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "publishStates", "=", "array", "(", ")", ";", "foreach", "(", "$", "config", "as", "$", "role", ")", "{", "$", "publishStates", "[", "$", "role", "[", "'value'", "]", "]", "=", "$", "role", "[", "'name'", "]", ";", "}", "$", "container", "->", "setParameter", "(", "'manhattan.publish.states'", ",", "$", "publishStates", ")", ";", "}" ]
Remaps parsed array for default into Choices field @param array $config @param ContainerBuilder $container
[ "Remaps", "parsed", "array", "for", "default", "into", "Choices", "field" ]
7aaf7d7567a14e57e87b8d7474fbdd064f7b09bc
https://github.com/frodosghost/PublishBundle/blob/7aaf7d7567a14e57e87b8d7474fbdd064f7b09bc/DependencyInjection/ManhattanPublishExtension.php#L39-L48
train
frodosghost/PublishBundle
DependencyInjection/ManhattanPublishExtension.php
ManhattanPublishExtension.prepend
public function prepend(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); // Once Manhattan Console is registered include the additional configuration files if (isset($bundles['ManhattanPublishBundle'])) { $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('config.yml'); } }
php
public function prepend(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); // Once Manhattan Console is registered include the additional configuration files if (isset($bundles['ManhattanPublishBundle'])) { $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('config.yml'); } }
[ "public", "function", "prepend", "(", "ContainerBuilder", "$", "container", ")", "{", "$", "bundles", "=", "$", "container", "->", "getParameter", "(", "'kernel.bundles'", ")", ";", "// Once Manhattan Console is registered include the additional configuration files", "if", "(", "isset", "(", "$", "bundles", "[", "'ManhattanPublishBundle'", "]", ")", ")", "{", "$", "loader", "=", "new", "Loader", "\\", "YamlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/../Resources/config'", ")", ")", ";", "$", "loader", "->", "load", "(", "'config.yml'", ")", ";", "}", "}" ]
Prepend extension to load in config file {@inheritDoc}
[ "Prepend", "extension", "to", "load", "in", "config", "file" ]
7aaf7d7567a14e57e87b8d7474fbdd064f7b09bc
https://github.com/frodosghost/PublishBundle/blob/7aaf7d7567a14e57e87b8d7474fbdd064f7b09bc/DependencyInjection/ManhattanPublishExtension.php#L55-L64
train
linpax/microphp-framework
src/mvc/controllers/ViewController.php
ViewController.redirect
public function redirect($path, $status = 301) { if (!$this->asWidget) { /** @var ResponseInterface $response */ $response = (new ResponseInjector)->build(); if (!$response) { throw new Exception('Component `response` not configured'); } $response = $response->withStatus($status); $response = $response->getHeaderLine('Location: '.$path); return $response; } return false; }
php
public function redirect($path, $status = 301) { if (!$this->asWidget) { /** @var ResponseInterface $response */ $response = (new ResponseInjector)->build(); if (!$response) { throw new Exception('Component `response` not configured'); } $response = $response->withStatus($status); $response = $response->getHeaderLine('Location: '.$path); return $response; } return false; }
[ "public", "function", "redirect", "(", "$", "path", ",", "$", "status", "=", "301", ")", "{", "if", "(", "!", "$", "this", "->", "asWidget", ")", "{", "/** @var ResponseInterface $response */", "$", "response", "=", "(", "new", "ResponseInjector", ")", "->", "build", "(", ")", ";", "if", "(", "!", "$", "response", ")", "{", "throw", "new", "Exception", "(", "'Component `response` not configured'", ")", ";", "}", "$", "response", "=", "$", "response", "->", "withStatus", "(", "$", "status", ")", ";", "$", "response", "=", "$", "response", "->", "getHeaderLine", "(", "'Location: '", ".", "$", "path", ")", ";", "return", "$", "response", ";", "}", "return", "false", ";", "}" ]
Redirect user to path @access public @param string $path path to redirect @param integer $status status for redirect @return false|ResponseInterface @throws Exception|\InvalidArgumentException
[ "Redirect", "user", "to", "path" ]
11f3370f3f64c516cce9b84ecd8276c6e9ae8df9
https://github.com/linpax/microphp-framework/blob/11f3370f3f64c516cce9b84ecd8276c6e9ae8df9/src/mvc/controllers/ViewController.php#L94-L110
train
Kris-Kuiper/sFire-Framework
src/Routing/Extend/Forward.php
Forward.params
public function params($params) { if(false === is_array($params)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type array, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR); } $this -> params = $params; return $this; }
php
public function params($params) { if(false === is_array($params)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type array, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR); } $this -> params = $params; return $this; }
[ "public", "function", "params", "(", "$", "params", ")", "{", "if", "(", "false", "===", "is_array", "(", "$", "params", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type array, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "data", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "params", "=", "$", "params", ";", "return", "$", "this", ";", "}" ]
Set the parameters @param array $param @return sFire\Router\Forward
[ "Set", "the", "parameters" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Routing/Extend/Forward.php#L74-L83
train
Kris-Kuiper/sFire-Framework
src/Routing/Extend/Forward.php
Forward.domain
public function domain($domain, $protocol = null) { if(false === is_string($domain)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR); } //Check if identifier exists if(false === Router :: routeExists($this -> identifier, $domain)) { return trigger_error(sprintf('Identifier "%s" with domain "%s" does not exists', $this -> identifier, $domain), E_USER_ERROR); } if(null !== $protocol && false === is_string($protocol)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($protocol)), E_USER_ERROR); } if(null === $protocol) { $protocol = Request :: getScheme(); } $this -> domain = sprintf('%s://%s', $protocol, $domain); return $this; }
php
public function domain($domain, $protocol = null) { if(false === is_string($domain)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR); } //Check if identifier exists if(false === Router :: routeExists($this -> identifier, $domain)) { return trigger_error(sprintf('Identifier "%s" with domain "%s" does not exists', $this -> identifier, $domain), E_USER_ERROR); } if(null !== $protocol && false === is_string($protocol)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($protocol)), E_USER_ERROR); } if(null === $protocol) { $protocol = Request :: getScheme(); } $this -> domain = sprintf('%s://%s', $protocol, $domain); return $this; }
[ "public", "function", "domain", "(", "$", "domain", ",", "$", "protocol", "=", "null", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "domain", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "domain", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "//Check if identifier exists\r", "if", "(", "false", "===", "Router", "::", "routeExists", "(", "$", "this", "->", "identifier", ",", "$", "domain", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Identifier \"%s\" with domain \"%s\" does not exists'", ",", "$", "this", "->", "identifier", ",", "$", "domain", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "null", "!==", "$", "protocol", "&&", "false", "===", "is_string", "(", "$", "protocol", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 2 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "protocol", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "null", "===", "$", "protocol", ")", "{", "$", "protocol", "=", "Request", "::", "getScheme", "(", ")", ";", "}", "$", "this", "->", "domain", "=", "sprintf", "(", "'%s://%s'", ",", "$", "protocol", ",", "$", "domain", ")", ";", "return", "$", "this", ";", "}" ]
Set the domain name with HTTP protocol @param string $domain @param string $protocol @return sFire\Router\Forward
[ "Set", "the", "domain", "name", "with", "HTTP", "protocol" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Routing/Extend/Forward.php#L92-L114
train
Kris-Kuiper/sFire-Framework
src/Routing/Extend/Forward.php
Forward.seconds
public function seconds($seconds) { if(false === ('-' . intval($seconds) == '-' . $seconds)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($seconds)), E_USER_ERROR); } $this -> seconds = $seconds; return $this; }
php
public function seconds($seconds) { if(false === ('-' . intval($seconds) == '-' . $seconds)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($seconds)), E_USER_ERROR); } $this -> seconds = $seconds; return $this; }
[ "public", "function", "seconds", "(", "$", "seconds", ")", "{", "if", "(", "false", "===", "(", "'-'", ".", "intval", "(", "$", "seconds", ")", "==", "'-'", ".", "$", "seconds", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type integer, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "seconds", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "seconds", "=", "$", "seconds", ";", "return", "$", "this", ";", "}" ]
Set the amount of seconds @param number $seconds @return sFire\Router\Forward
[ "Set", "the", "amount", "of", "seconds" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Routing/Extend/Forward.php#L122-L131
train
Kris-Kuiper/sFire-Framework
src/Routing/Extend/Forward.php
Forward.execute
public function execute($code = null) { if(null !== $code && false === ('-' . intval($code) == '-' . $code)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($code)), E_USER_ERROR); } $this -> setUrl(); if(null !== $this -> seconds) { return Response :: addHeader('refresh', sprintf('%d;url=%s', $this -> seconds, $this -> url), $code); } Response :: addHeader('Location', $this -> url, $code); }
php
public function execute($code = null) { if(null !== $code && false === ('-' . intval($code) == '-' . $code)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($code)), E_USER_ERROR); } $this -> setUrl(); if(null !== $this -> seconds) { return Response :: addHeader('refresh', sprintf('%d;url=%s', $this -> seconds, $this -> url), $code); } Response :: addHeader('Location', $this -> url, $code); }
[ "public", "function", "execute", "(", "$", "code", "=", "null", ")", "{", "if", "(", "null", "!==", "$", "code", "&&", "false", "===", "(", "'-'", ".", "intval", "(", "$", "code", ")", "==", "'-'", ".", "$", "code", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type integer, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "code", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "setUrl", "(", ")", ";", "if", "(", "null", "!==", "$", "this", "->", "seconds", ")", "{", "return", "Response", "::", "addHeader", "(", "'refresh'", ",", "sprintf", "(", "'%d;url=%s'", ",", "$", "this", "->", "seconds", ",", "$", "this", "->", "url", ")", ",", "$", "code", ")", ";", "}", "Response", "::", "addHeader", "(", "'Location'", ",", "$", "this", "->", "url", ",", "$", "code", ")", ";", "}" ]
Execute forward, with options HTTP status code @param integer $code
[ "Execute", "forward", "with", "options", "HTTP", "status", "code" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Routing/Extend/Forward.php#L138-L151
train
kaiohken1982/NeobazaarDocumentModule
src/Document/Model/Image.php
Image.deleteImages
public function deleteImages() { $thumb = false; $img = false; if(file_exists($this->path)) { unlink($this->path); } if(file_exists($this->thumbnailPath)) { unlink($this->thumbnailPath); } $img = !file_exists($this->path); $thumb = !file_exists($this->thumbnailPath); return $img && $thumb; }
php
public function deleteImages() { $thumb = false; $img = false; if(file_exists($this->path)) { unlink($this->path); } if(file_exists($this->thumbnailPath)) { unlink($this->thumbnailPath); } $img = !file_exists($this->path); $thumb = !file_exists($this->thumbnailPath); return $img && $thumb; }
[ "public", "function", "deleteImages", "(", ")", "{", "$", "thumb", "=", "false", ";", "$", "img", "=", "false", ";", "if", "(", "file_exists", "(", "$", "this", "->", "path", ")", ")", "{", "unlink", "(", "$", "this", "->", "path", ")", ";", "}", "if", "(", "file_exists", "(", "$", "this", "->", "thumbnailPath", ")", ")", "{", "unlink", "(", "$", "this", "->", "thumbnailPath", ")", ";", "}", "$", "img", "=", "!", "file_exists", "(", "$", "this", "->", "path", ")", ";", "$", "thumb", "=", "!", "file_exists", "(", "$", "this", "->", "thumbnailPath", ")", ";", "return", "$", "img", "&&", "$", "thumb", ";", "}" ]
Phisically remove images that are related to this doument entity. It does not touch anything on the database! @return boolean
[ "Phisically", "remove", "images", "that", "are", "related", "to", "this", "doument", "entity", ".", "It", "does", "not", "touch", "anything", "on", "the", "database!" ]
edb0223878fe02e791d2a0266c5a7c0f2029e3fe
https://github.com/kaiohken1982/NeobazaarDocumentModule/blob/edb0223878fe02e791d2a0266c5a7c0f2029e3fe/src/Document/Model/Image.php#L118-L135
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
XmlFileLoader.parseFileToDOM
private function parseFileToDOM($file) { try { $dom = XmlUtils::loadFile($file, array($this, 'validateSchema')); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e); } $this->validateExtensions($dom, $file); return $dom; }
php
private function parseFileToDOM($file) { try { $dom = XmlUtils::loadFile($file, array($this, 'validateSchema')); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e); } $this->validateExtensions($dom, $file); return $dom; }
[ "private", "function", "parseFileToDOM", "(", "$", "file", ")", "{", "try", "{", "$", "dom", "=", "XmlUtils", "::", "loadFile", "(", "$", "file", ",", "array", "(", "$", "this", ",", "'validateSchema'", ")", ")", ";", "}", "catch", "(", "\\", "InvalidArgumentException", "$", "e", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Unable to parse file \"%s\".'", ",", "$", "file", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "}", "$", "this", "->", "validateExtensions", "(", "$", "dom", ",", "$", "file", ")", ";", "return", "$", "dom", ";", "}" ]
Parses a XML file to a \DOMDocument. @param string $file Path to a file @return \DOMDocument @throws InvalidArgumentException When loading of XML file returns error
[ "Parses", "a", "XML", "file", "to", "a", "\\", "DOMDocument", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php#L381-L392
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
XmlFileLoader.validateExtensions
private function validateExtensions(\DOMDocument $dom, $file) { foreach ($dom->documentElement->childNodes as $node) { if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) { continue; } // can it be handled by an extension? if (!$this->container->hasExtension($node->namespaceURI)) { $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions())); throw new InvalidArgumentException(sprintf( 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s', $node->tagName, $file, $node->namespaceURI, $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none' )); } } }
php
private function validateExtensions(\DOMDocument $dom, $file) { foreach ($dom->documentElement->childNodes as $node) { if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) { continue; } // can it be handled by an extension? if (!$this->container->hasExtension($node->namespaceURI)) { $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions())); throw new InvalidArgumentException(sprintf( 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s', $node->tagName, $file, $node->namespaceURI, $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none' )); } } }
[ "private", "function", "validateExtensions", "(", "\\", "DOMDocument", "$", "dom", ",", "$", "file", ")", "{", "foreach", "(", "$", "dom", "->", "documentElement", "->", "childNodes", "as", "$", "node", ")", "{", "if", "(", "!", "$", "node", "instanceof", "\\", "DOMElement", "||", "'http://symfony.com/schema/dic/services'", "===", "$", "node", "->", "namespaceURI", ")", "{", "continue", ";", "}", "// can it be handled by an extension?", "if", "(", "!", "$", "this", "->", "container", "->", "hasExtension", "(", "$", "node", "->", "namespaceURI", ")", ")", "{", "$", "extensionNamespaces", "=", "array_filter", "(", "array_map", "(", "function", "(", "$", "ext", ")", "{", "return", "$", "ext", "->", "getNamespace", "(", ")", ";", "}", ",", "$", "this", "->", "container", "->", "getExtensions", "(", ")", ")", ")", ";", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'There is no extension able to load the configuration for \"%s\" (in %s). Looked for namespace \"%s\", found %s'", ",", "$", "node", "->", "tagName", ",", "$", "file", ",", "$", "node", "->", "namespaceURI", ",", "$", "extensionNamespaces", "?", "sprintf", "(", "'\"%s\"'", ",", "implode", "(", "'\", \"'", ",", "$", "extensionNamespaces", ")", ")", ":", "'none'", ")", ")", ";", "}", "}", "}" ]
Validates an extension. @param \DOMDocument $dom @param string $file @throws InvalidArgumentException When no extension is found corresponding to a tag
[ "Validates", "an", "extension", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php#L673-L692
train
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
XmlFileLoader.loadFromExtensions
private function loadFromExtensions(\DOMDocument $xml) { foreach ($xml->documentElement->childNodes as $node) { if (!$node instanceof \DOMElement || self::NS === $node->namespaceURI) { continue; } $values = static::convertDomElementToArray($node); if (!is_array($values)) { $values = array(); } $this->container->loadFromExtension($node->namespaceURI, $values); } }
php
private function loadFromExtensions(\DOMDocument $xml) { foreach ($xml->documentElement->childNodes as $node) { if (!$node instanceof \DOMElement || self::NS === $node->namespaceURI) { continue; } $values = static::convertDomElementToArray($node); if (!is_array($values)) { $values = array(); } $this->container->loadFromExtension($node->namespaceURI, $values); } }
[ "private", "function", "loadFromExtensions", "(", "\\", "DOMDocument", "$", "xml", ")", "{", "foreach", "(", "$", "xml", "->", "documentElement", "->", "childNodes", "as", "$", "node", ")", "{", "if", "(", "!", "$", "node", "instanceof", "\\", "DOMElement", "||", "self", "::", "NS", "===", "$", "node", "->", "namespaceURI", ")", "{", "continue", ";", "}", "$", "values", "=", "static", "::", "convertDomElementToArray", "(", "$", "node", ")", ";", "if", "(", "!", "is_array", "(", "$", "values", ")", ")", "{", "$", "values", "=", "array", "(", ")", ";", "}", "$", "this", "->", "container", "->", "loadFromExtension", "(", "$", "node", "->", "namespaceURI", ",", "$", "values", ")", ";", "}", "}" ]
Loads from an extension. @param \DOMDocument $xml
[ "Loads", "from", "an", "extension", "." ]
d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php#L699-L713
train
Aviogram/Common
src/PHPClass/ScopeTrait.php
ScopeTrait.setScope
public function setScope($scope) { if (in_array($scope, $this->scopes) === false) { throw Exception\Scope::invalidScope($scope, $this->scopes); } $this->scope = $scope; return $this; }
php
public function setScope($scope) { if (in_array($scope, $this->scopes) === false) { throw Exception\Scope::invalidScope($scope, $this->scopes); } $this->scope = $scope; return $this; }
[ "public", "function", "setScope", "(", "$", "scope", ")", "{", "if", "(", "in_array", "(", "$", "scope", ",", "$", "this", "->", "scopes", ")", "===", "false", ")", "{", "throw", "Exception", "\\", "Scope", "::", "invalidScope", "(", "$", "scope", ",", "$", "this", "->", "scopes", ")", ";", "}", "$", "this", "->", "scope", "=", "$", "scope", ";", "return", "$", "this", ";", "}" ]
Set the current scope @param string $scope (See ScopeInterface::SCOPE_*) @return $this @throws Exception\Scope When the scope does not exists
[ "Set", "the", "current", "scope" ]
bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/PHPClass/ScopeTrait.php#L25-L34
train
eloquent/blox
src/BloxParser.php
BloxParser.parseBlockComment
public function parseBlockComment($blockComment) { $blockCommentLines = $this->parseBlockCommentLines($blockComment); return new Element\DocumentationBlock( $this->parseBlockCommentTags($blockCommentLines), $this->parseBlockCommentSummary($blockCommentLines), $this->parseBlockCommentBody($blockCommentLines) ); }
php
public function parseBlockComment($blockComment) { $blockCommentLines = $this->parseBlockCommentLines($blockComment); return new Element\DocumentationBlock( $this->parseBlockCommentTags($blockCommentLines), $this->parseBlockCommentSummary($blockCommentLines), $this->parseBlockCommentBody($blockCommentLines) ); }
[ "public", "function", "parseBlockComment", "(", "$", "blockComment", ")", "{", "$", "blockCommentLines", "=", "$", "this", "->", "parseBlockCommentLines", "(", "$", "blockComment", ")", ";", "return", "new", "Element", "\\", "DocumentationBlock", "(", "$", "this", "->", "parseBlockCommentTags", "(", "$", "blockCommentLines", ")", ",", "$", "this", "->", "parseBlockCommentSummary", "(", "$", "blockCommentLines", ")", ",", "$", "this", "->", "parseBlockCommentBody", "(", "$", "blockCommentLines", ")", ")", ";", "}" ]
Parse a documentation block comment. @param string $blockComment The documentation block comment. @return DocumentationBlock The parsed documentation block object.
[ "Parse", "a", "documentation", "block", "comment", "." ]
dcfe82a0a703124ab5807d894979530d6fdb536b
https://github.com/eloquent/blox/blob/dcfe82a0a703124ab5807d894979530d6fdb536b/src/BloxParser.php#L26-L35
train
nicmart/DomainSpecificQuery
src/Language/Compiler/LanguageCompiler.php
LanguageCompiler.value
public function value($value) { //terminal case if (!is_array($value)) { if (strpbrk($value, Lexer::ESCAPED_STRING) !== false) { if (!(substr($value, 0, 1) == '"' && substr($value, -1) == '"')) { return '(' . addcslashes($value, Lexer::ESCAPED_STRING_PAREN_ENCAPSED) . ')'; } } return $value; } //composite value case $pairs = array(); foreach ($value as $key => $subval) { $pairs[] = "{$this->identifier($key)} = {$this->value($subval)}"; } return '(' . implode(', ', $pairs) . ')'; }
php
public function value($value) { //terminal case if (!is_array($value)) { if (strpbrk($value, Lexer::ESCAPED_STRING) !== false) { if (!(substr($value, 0, 1) == '"' && substr($value, -1) == '"')) { return '(' . addcslashes($value, Lexer::ESCAPED_STRING_PAREN_ENCAPSED) . ')'; } } return $value; } //composite value case $pairs = array(); foreach ($value as $key => $subval) { $pairs[] = "{$this->identifier($key)} = {$this->value($subval)}"; } return '(' . implode(', ', $pairs) . ')'; }
[ "public", "function", "value", "(", "$", "value", ")", "{", "//terminal case", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "if", "(", "strpbrk", "(", "$", "value", ",", "Lexer", "::", "ESCAPED_STRING", ")", "!==", "false", ")", "{", "if", "(", "!", "(", "substr", "(", "$", "value", ",", "0", ",", "1", ")", "==", "'\"'", "&&", "substr", "(", "$", "value", ",", "-", "1", ")", "==", "'\"'", ")", ")", "{", "return", "'('", ".", "addcslashes", "(", "$", "value", ",", "Lexer", "::", "ESCAPED_STRING_PAREN_ENCAPSED", ")", ".", "')'", ";", "}", "}", "return", "$", "value", ";", "}", "//composite value case", "$", "pairs", "=", "array", "(", ")", ";", "foreach", "(", "$", "value", "as", "$", "key", "=>", "$", "subval", ")", "{", "$", "pairs", "[", "]", "=", "\"{$this->identifier($key)} = {$this->value($subval)}\"", ";", "}", "return", "'('", ".", "implode", "(", "', '", ",", "$", "pairs", ")", ".", "')'", ";", "}" ]
Compile a value @param string $value @return string
[ "Compile", "a", "value" ]
7c01fe94337afdfae5884809e8b5487127a63ac3
https://github.com/nicmart/DomainSpecificQuery/blob/7c01fe94337afdfae5884809e8b5487127a63ac3/src/Language/Compiler/LanguageCompiler.php#L45-L64
train
nicmart/DomainSpecificQuery
src/Language/Compiler/LanguageCompiler.php
LanguageCompiler.isAnInExpression
public function isAnInExpression(TreeExpression $expr) { $count = $expr->count(); if ($count <= 1 || strtolower($expr->getValue()) != 'or' ) return false; $children = $expr->getChildren(); if (!$children[0] instanceof FieldExpression) return false; for ($i = 1; $i < $count; $i++) { if (!$children[$i] instanceof FieldExpression) return false; if ($children[$i]->getField() != $children[$i-1]->getField()) return false; } return true; }
php
public function isAnInExpression(TreeExpression $expr) { $count = $expr->count(); if ($count <= 1 || strtolower($expr->getValue()) != 'or' ) return false; $children = $expr->getChildren(); if (!$children[0] instanceof FieldExpression) return false; for ($i = 1; $i < $count; $i++) { if (!$children[$i] instanceof FieldExpression) return false; if ($children[$i]->getField() != $children[$i-1]->getField()) return false; } return true; }
[ "public", "function", "isAnInExpression", "(", "TreeExpression", "$", "expr", ")", "{", "$", "count", "=", "$", "expr", "->", "count", "(", ")", ";", "if", "(", "$", "count", "<=", "1", "||", "strtolower", "(", "$", "expr", "->", "getValue", "(", ")", ")", "!=", "'or'", ")", "return", "false", ";", "$", "children", "=", "$", "expr", "->", "getChildren", "(", ")", ";", "if", "(", "!", "$", "children", "[", "0", "]", "instanceof", "FieldExpression", ")", "return", "false", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "if", "(", "!", "$", "children", "[", "$", "i", "]", "instanceof", "FieldExpression", ")", "return", "false", ";", "if", "(", "$", "children", "[", "$", "i", "]", "->", "getField", "(", ")", "!=", "$", "children", "[", "$", "i", "-", "1", "]", "->", "getField", "(", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Can be the tree expression converted in a "FIELD IN ..." expression? @param TreeExpression $expr @return bool
[ "Can", "be", "the", "tree", "expression", "converted", "in", "a", "FIELD", "IN", "...", "expression?" ]
7c01fe94337afdfae5884809e8b5487127a63ac3
https://github.com/nicmart/DomainSpecificQuery/blob/7c01fe94337afdfae5884809e8b5487127a63ac3/src/Language/Compiler/LanguageCompiler.php#L95-L113
train
SysControllers/Admin
public/assets/global/plugins/kcfinder/lib/helper_text.php
text.xmlData
static function xmlData($string, $cdata=false) { $string = str_replace("]]>", "]]]]><![CDATA[>", $string); if (!$cdata) $string = "<![CDATA[$string]]>"; return $string; }
php
static function xmlData($string, $cdata=false) { $string = str_replace("]]>", "]]]]><![CDATA[>", $string); if (!$cdata) $string = "<![CDATA[$string]]>"; return $string; }
[ "static", "function", "xmlData", "(", "$", "string", ",", "$", "cdata", "=", "false", ")", "{", "$", "string", "=", "str_replace", "(", "\"]]>\"", ",", "\"]]]]><![CDATA[>\"", ",", "$", "string", ")", ";", "if", "(", "!", "$", "cdata", ")", "$", "string", "=", "\"<![CDATA[$string]]>\"", ";", "return", "$", "string", ";", "}" ]
Normalize the string for XML tag content data @param string $string @param bool $cdata
[ "Normalize", "the", "string", "for", "XML", "tag", "content", "data" ]
8f1df46aca422b87f2f522fbba610dcfa0c5f7f3
https://github.com/SysControllers/Admin/blob/8f1df46aca422b87f2f522fbba610dcfa0c5f7f3/public/assets/global/plugins/kcfinder/lib/helper_text.php#L55-L60
train
SysControllers/Admin
public/assets/global/plugins/kcfinder/lib/helper_text.php
text.compressCSS
static function compressCSS($code) { $code = self::clearWhitespaces($code); $code = preg_replace('/ ?\{ ?/', "{", $code); $code = preg_replace('/ ?\} ?/', "}", $code); $code = preg_replace('/ ?\; ?/', ";", $code); $code = preg_replace('/ ?\> ?/', ">", $code); $code = preg_replace('/ ?\, ?/', ",", $code); $code = preg_replace('/ ?\: ?/', ":", $code); $code = str_replace(";}", "}", $code); return $code; }
php
static function compressCSS($code) { $code = self::clearWhitespaces($code); $code = preg_replace('/ ?\{ ?/', "{", $code); $code = preg_replace('/ ?\} ?/', "}", $code); $code = preg_replace('/ ?\; ?/', ";", $code); $code = preg_replace('/ ?\> ?/', ">", $code); $code = preg_replace('/ ?\, ?/', ",", $code); $code = preg_replace('/ ?\: ?/', ":", $code); $code = str_replace(";}", "}", $code); return $code; }
[ "static", "function", "compressCSS", "(", "$", "code", ")", "{", "$", "code", "=", "self", "::", "clearWhitespaces", "(", "$", "code", ")", ";", "$", "code", "=", "preg_replace", "(", "'/ ?\\{ ?/'", ",", "\"{\"", ",", "$", "code", ")", ";", "$", "code", "=", "preg_replace", "(", "'/ ?\\} ?/'", ",", "\"}\"", ",", "$", "code", ")", ";", "$", "code", "=", "preg_replace", "(", "'/ ?\\; ?/'", ",", "\";\"", ",", "$", "code", ")", ";", "$", "code", "=", "preg_replace", "(", "'/ ?\\> ?/'", ",", "\">\"", ",", "$", "code", ")", ";", "$", "code", "=", "preg_replace", "(", "'/ ?\\, ?/'", ",", "\",\"", ",", "$", "code", ")", ";", "$", "code", "=", "preg_replace", "(", "'/ ?\\: ?/'", ",", "\":\"", ",", "$", "code", ")", ";", "$", "code", "=", "str_replace", "(", "\";}\"", ",", "\"}\"", ",", "$", "code", ")", ";", "return", "$", "code", ";", "}" ]
Returns compressed content of given CSS code @param string $code @return string
[ "Returns", "compressed", "content", "of", "given", "CSS", "code" ]
8f1df46aca422b87f2f522fbba610dcfa0c5f7f3
https://github.com/SysControllers/Admin/blob/8f1df46aca422b87f2f522fbba610dcfa0c5f7f3/public/assets/global/plugins/kcfinder/lib/helper_text.php#L66-L76
train
williamcarril/model-validation
src/WGPC/Eloquent/Model.php
Model.putErrors
public function putErrors($errors) { if (!is_array($errors) && !($errors instanceof MessageProvider)) { $errors = [$errors]; } $this->errors->merge($errors); }
php
public function putErrors($errors) { if (!is_array($errors) && !($errors instanceof MessageProvider)) { $errors = [$errors]; } $this->errors->merge($errors); }
[ "public", "function", "putErrors", "(", "$", "errors", ")", "{", "if", "(", "!", "is_array", "(", "$", "errors", ")", "&&", "!", "(", "$", "errors", "instanceof", "MessageProvider", ")", ")", "{", "$", "errors", "=", "[", "$", "errors", "]", ";", "}", "$", "this", "->", "errors", "->", "merge", "(", "$", "errors", ")", ";", "}" ]
Puts more errors in its message bag. @return boolean
[ "Puts", "more", "errors", "in", "its", "message", "bag", "." ]
a6008d04c3ee7e54b87160f471c445d183d41367
https://github.com/williamcarril/model-validation/blob/a6008d04c3ee7e54b87160f471c445d183d41367/src/WGPC/Eloquent/Model.php#L105-L110
train
WellCommerce/DistributionBundle
Controller/Admin/PackageController.php
PackageController.syncAction
public function syncAction() { $this->manager->syncPackages(PackageHelperInterface::DEFAULT_PACKAGE_BUNDLE_TYPE); $this->manager->syncPackages(PackageHelperInterface::DEFAULT_PACKAGE_THEME_TYPE); $this->manager->getFlashHelper()->addSuccess('package.flash.sync.success'); return $this->getRouterHelper()->redirectToAction('index'); }
php
public function syncAction() { $this->manager->syncPackages(PackageHelperInterface::DEFAULT_PACKAGE_BUNDLE_TYPE); $this->manager->syncPackages(PackageHelperInterface::DEFAULT_PACKAGE_THEME_TYPE); $this->manager->getFlashHelper()->addSuccess('package.flash.sync.success'); return $this->getRouterHelper()->redirectToAction('index'); }
[ "public", "function", "syncAction", "(", ")", "{", "$", "this", "->", "manager", "->", "syncPackages", "(", "PackageHelperInterface", "::", "DEFAULT_PACKAGE_BUNDLE_TYPE", ")", ";", "$", "this", "->", "manager", "->", "syncPackages", "(", "PackageHelperInterface", "::", "DEFAULT_PACKAGE_THEME_TYPE", ")", ";", "$", "this", "->", "manager", "->", "getFlashHelper", "(", ")", "->", "addSuccess", "(", "'package.flash.sync.success'", ")", ";", "return", "$", "this", "->", "getRouterHelper", "(", ")", "->", "redirectToAction", "(", "'index'", ")", ";", "}" ]
Action used to sync packages from remote servers ie. packagist.org @return \Symfony\Component\HttpFoundation\RedirectResponse
[ "Action", "used", "to", "sync", "packages", "from", "remote", "servers", "ie", ".", "packagist", ".", "org" ]
82b1b4c2c5a59536aaae22506b23ccd5d141cbb0
https://github.com/WellCommerce/DistributionBundle/blob/82b1b4c2c5a59536aaae22506b23ccd5d141cbb0/Controller/Admin/PackageController.php#L32-L39
train
ekyna/PaymentBundle
Controller/PaymentController.php
PaymentController.notifyAction
public function notifyAction(Request $request) { $token = $this->getHttpRequestVerifier()->verify($request); $gateway = $this->getPayum()->getGateway($token->getGatewayName()); $gateway->execute($notify = new Notify($token)); /** @var \Ekyna\Component\Sale\Payment\PaymentInterface $payment */ $payment = $notify->getFirstModel(); $event = new PaymentEvent($payment); $this->getDispatcher()->dispatch(PaymentEvents::NOTIFY, $event); return new Response('', 204); }
php
public function notifyAction(Request $request) { $token = $this->getHttpRequestVerifier()->verify($request); $gateway = $this->getPayum()->getGateway($token->getGatewayName()); $gateway->execute($notify = new Notify($token)); /** @var \Ekyna\Component\Sale\Payment\PaymentInterface $payment */ $payment = $notify->getFirstModel(); $event = new PaymentEvent($payment); $this->getDispatcher()->dispatch(PaymentEvents::NOTIFY, $event); return new Response('', 204); }
[ "public", "function", "notifyAction", "(", "Request", "$", "request", ")", "{", "$", "token", "=", "$", "this", "->", "getHttpRequestVerifier", "(", ")", "->", "verify", "(", "$", "request", ")", ";", "$", "gateway", "=", "$", "this", "->", "getPayum", "(", ")", "->", "getGateway", "(", "$", "token", "->", "getGatewayName", "(", ")", ")", ";", "$", "gateway", "->", "execute", "(", "$", "notify", "=", "new", "Notify", "(", "$", "token", ")", ")", ";", "/** @var \\Ekyna\\Component\\Sale\\Payment\\PaymentInterface $payment */", "$", "payment", "=", "$", "notify", "->", "getFirstModel", "(", ")", ";", "$", "event", "=", "new", "PaymentEvent", "(", "$", "payment", ")", ";", "$", "this", "->", "getDispatcher", "(", ")", "->", "dispatch", "(", "PaymentEvents", "::", "NOTIFY", ",", "$", "event", ")", ";", "return", "new", "Response", "(", "''", ",", "204", ")", ";", "}" ]
Notify action. @param Request $request @return Response
[ "Notify", "action", "." ]
1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1
https://github.com/ekyna/PaymentBundle/blob/1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1/Controller/PaymentController.php#L27-L42
train
ekyna/PaymentBundle
Controller/PaymentController.php
PaymentController.doneAction
public function doneAction(Request $request) { $debug = $this->container->getParameter('kernel.debug'); $token = $this->getHttpRequestVerifier()->verify($request); $gateway = $this->getPayum()->getGateway($token->getGatewayName()); $gateway->execute($done = new Done($token)); if (!$debug) { $this->getHttpRequestVerifier()->invalidate($token); } /** @var \Ekyna\Component\Sale\Payment\PaymentInterface $payment */ $payment = $done->getFirstModel(); $event = new PaymentEvent($payment); $this->getDispatcher()->dispatch(PaymentEvents::DONE, $event); if (null !== $response = $event->getResponse()) { return $response; } if ($debug) { return $this->render('EkynaPaymentBundle:Payment:done.html.twig', [ 'payment' => $payment, ]); } return $this->redirect('/'); }
php
public function doneAction(Request $request) { $debug = $this->container->getParameter('kernel.debug'); $token = $this->getHttpRequestVerifier()->verify($request); $gateway = $this->getPayum()->getGateway($token->getGatewayName()); $gateway->execute($done = new Done($token)); if (!$debug) { $this->getHttpRequestVerifier()->invalidate($token); } /** @var \Ekyna\Component\Sale\Payment\PaymentInterface $payment */ $payment = $done->getFirstModel(); $event = new PaymentEvent($payment); $this->getDispatcher()->dispatch(PaymentEvents::DONE, $event); if (null !== $response = $event->getResponse()) { return $response; } if ($debug) { return $this->render('EkynaPaymentBundle:Payment:done.html.twig', [ 'payment' => $payment, ]); } return $this->redirect('/'); }
[ "public", "function", "doneAction", "(", "Request", "$", "request", ")", "{", "$", "debug", "=", "$", "this", "->", "container", "->", "getParameter", "(", "'kernel.debug'", ")", ";", "$", "token", "=", "$", "this", "->", "getHttpRequestVerifier", "(", ")", "->", "verify", "(", "$", "request", ")", ";", "$", "gateway", "=", "$", "this", "->", "getPayum", "(", ")", "->", "getGateway", "(", "$", "token", "->", "getGatewayName", "(", ")", ")", ";", "$", "gateway", "->", "execute", "(", "$", "done", "=", "new", "Done", "(", "$", "token", ")", ")", ";", "if", "(", "!", "$", "debug", ")", "{", "$", "this", "->", "getHttpRequestVerifier", "(", ")", "->", "invalidate", "(", "$", "token", ")", ";", "}", "/** @var \\Ekyna\\Component\\Sale\\Payment\\PaymentInterface $payment */", "$", "payment", "=", "$", "done", "->", "getFirstModel", "(", ")", ";", "$", "event", "=", "new", "PaymentEvent", "(", "$", "payment", ")", ";", "$", "this", "->", "getDispatcher", "(", ")", "->", "dispatch", "(", "PaymentEvents", "::", "DONE", ",", "$", "event", ")", ";", "if", "(", "null", "!==", "$", "response", "=", "$", "event", "->", "getResponse", "(", ")", ")", "{", "return", "$", "response", ";", "}", "if", "(", "$", "debug", ")", "{", "return", "$", "this", "->", "render", "(", "'EkynaPaymentBundle:Payment:done.html.twig'", ",", "[", "'payment'", "=>", "$", "payment", ",", "]", ")", ";", "}", "return", "$", "this", "->", "redirect", "(", "'/'", ")", ";", "}" ]
Done action. @param Request $request @return Response
[ "Done", "action", "." ]
1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1
https://github.com/ekyna/PaymentBundle/blob/1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1/Controller/PaymentController.php#L50-L80
train
phpguard/listen
src/PhpGuard/Listen/Adapter/Tracker.php
Tracker.add
public function add(TrackedObject $tracked) { $id = $tracked->getID(); if(isset($this->map[$id])){ return; } $this->map[$id] = $tracked; $this->adapter->watch($tracked); }
php
public function add(TrackedObject $tracked) { $id = $tracked->getID(); if(isset($this->map[$id])){ return; } $this->map[$id] = $tracked; $this->adapter->watch($tracked); }
[ "public", "function", "add", "(", "TrackedObject", "$", "tracked", ")", "{", "$", "id", "=", "$", "tracked", "->", "getID", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "map", "[", "$", "id", "]", ")", ")", "{", "return", ";", "}", "$", "this", "->", "map", "[", "$", "id", "]", "=", "$", "tracked", ";", "$", "this", "->", "adapter", "->", "watch", "(", "$", "tracked", ")", ";", "}" ]
Add a new TrackedObject into map @param TrackedObject $tracked
[ "Add", "a", "new", "TrackedObject", "into", "map" ]
cd0cda150858d6d85deb025a72996873d2af3532
https://github.com/phpguard/listen/blob/cd0cda150858d6d85deb025a72996873d2af3532/src/PhpGuard/Listen/Adapter/Tracker.php#L110-L118
train
phpguard/listen
src/PhpGuard/Listen/Adapter/Tracker.php
Tracker.addChangeSet
public function addChangeSet($tracked,$eventMask) { if($tracked instanceof TrackedObject){ $path = $tracked->getResource(); if($this->fileOnly && !$tracked->getResource() instanceof FileResource){ return; } }else{ $path = $tracked; } $event = new FilesystemEvent($path,$eventMask); $id = md5($path); $this->changeSet[$id] = $event; }
php
public function addChangeSet($tracked,$eventMask) { if($tracked instanceof TrackedObject){ $path = $tracked->getResource(); if($this->fileOnly && !$tracked->getResource() instanceof FileResource){ return; } }else{ $path = $tracked; } $event = new FilesystemEvent($path,$eventMask); $id = md5($path); $this->changeSet[$id] = $event; }
[ "public", "function", "addChangeSet", "(", "$", "tracked", ",", "$", "eventMask", ")", "{", "if", "(", "$", "tracked", "instanceof", "TrackedObject", ")", "{", "$", "path", "=", "$", "tracked", "->", "getResource", "(", ")", ";", "if", "(", "$", "this", "->", "fileOnly", "&&", "!", "$", "tracked", "->", "getResource", "(", ")", "instanceof", "FileResource", ")", "{", "return", ";", "}", "}", "else", "{", "$", "path", "=", "$", "tracked", ";", "}", "$", "event", "=", "new", "FilesystemEvent", "(", "$", "path", ",", "$", "eventMask", ")", ";", "$", "id", "=", "md5", "(", "$", "path", ")", ";", "$", "this", "->", "changeSet", "[", "$", "id", "]", "=", "$", "event", ";", "}" ]
Add a new event to changeset @param TrackedObject $tracked @param int $eventMask
[ "Add", "a", "new", "event", "to", "changeset" ]
cd0cda150858d6d85deb025a72996873d2af3532
https://github.com/phpguard/listen/blob/cd0cda150858d6d85deb025a72996873d2af3532/src/PhpGuard/Listen/Adapter/Tracker.php#L251-L264
train
phpguard/listen
src/PhpGuard/Listen/Adapter/Tracker.php
Tracker.scanDir
private function scanDir($path) { if(!is_dir($path)) return; /* @var \Symfony\Component\Finder\SplFileInfo $spl */ $finder = $this->createFinder(); $rootSPL = new DirectoryResource($path); $rootResource = new DirectoryResource($rootSPL); $rootResource = $this->createTrackedObject($rootResource); $this->add($rootResource); foreach($finder->in($path) as $spl) { if($spl->isFile()){ $resource = new FileResource($spl); }else{ $resource = new DirectoryResource($spl); } $trackedResource = $this->createTrackedObject($resource); $this->add($trackedResource); } }
php
private function scanDir($path) { if(!is_dir($path)) return; /* @var \Symfony\Component\Finder\SplFileInfo $spl */ $finder = $this->createFinder(); $rootSPL = new DirectoryResource($path); $rootResource = new DirectoryResource($rootSPL); $rootResource = $this->createTrackedObject($rootResource); $this->add($rootResource); foreach($finder->in($path) as $spl) { if($spl->isFile()){ $resource = new FileResource($spl); }else{ $resource = new DirectoryResource($spl); } $trackedResource = $this->createTrackedObject($resource); $this->add($trackedResource); } }
[ "private", "function", "scanDir", "(", "$", "path", ")", "{", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "return", ";", "/* @var \\Symfony\\Component\\Finder\\SplFileInfo $spl */", "$", "finder", "=", "$", "this", "->", "createFinder", "(", ")", ";", "$", "rootSPL", "=", "new", "DirectoryResource", "(", "$", "path", ")", ";", "$", "rootResource", "=", "new", "DirectoryResource", "(", "$", "rootSPL", ")", ";", "$", "rootResource", "=", "$", "this", "->", "createTrackedObject", "(", "$", "rootResource", ")", ";", "$", "this", "->", "add", "(", "$", "rootResource", ")", ";", "foreach", "(", "$", "finder", "->", "in", "(", "$", "path", ")", "as", "$", "spl", ")", "{", "if", "(", "$", "spl", "->", "isFile", "(", ")", ")", "{", "$", "resource", "=", "new", "FileResource", "(", "$", "spl", ")", ";", "}", "else", "{", "$", "resource", "=", "new", "DirectoryResource", "(", "$", "spl", ")", ";", "}", "$", "trackedResource", "=", "$", "this", "->", "createTrackedObject", "(", "$", "resource", ")", ";", "$", "this", "->", "add", "(", "$", "trackedResource", ")", ";", "}", "}" ]
Scan path and add it to listener @param string $path
[ "Scan", "path", "and", "add", "it", "to", "listener" ]
cd0cda150858d6d85deb025a72996873d2af3532
https://github.com/phpguard/listen/blob/cd0cda150858d6d85deb025a72996873d2af3532/src/PhpGuard/Listen/Adapter/Tracker.php#L270-L293
train
phpguard/listen
src/PhpGuard/Listen/Adapter/Tracker.php
Tracker.createTrackedObject
public function createTrackedObject(ResourceInterface $resource) { $tracked = new TrackedObject(); $tracked->setResource($resource); $tracked->setChecksum($resource->getChecksum()); if(is_null($tracked->getID())){ $tracked->setID(PathUtil::createPathID($resource->getResource())); } return $tracked; }
php
public function createTrackedObject(ResourceInterface $resource) { $tracked = new TrackedObject(); $tracked->setResource($resource); $tracked->setChecksum($resource->getChecksum()); if(is_null($tracked->getID())){ $tracked->setID(PathUtil::createPathID($resource->getResource())); } return $tracked; }
[ "public", "function", "createTrackedObject", "(", "ResourceInterface", "$", "resource", ")", "{", "$", "tracked", "=", "new", "TrackedObject", "(", ")", ";", "$", "tracked", "->", "setResource", "(", "$", "resource", ")", ";", "$", "tracked", "->", "setChecksum", "(", "$", "resource", "->", "getChecksum", "(", ")", ")", ";", "if", "(", "is_null", "(", "$", "tracked", "->", "getID", "(", ")", ")", ")", "{", "$", "tracked", "->", "setID", "(", "PathUtil", "::", "createPathID", "(", "$", "resource", "->", "getResource", "(", ")", ")", ")", ";", "}", "return", "$", "tracked", ";", "}" ]
Create new TrackedObject @param ResourceInterface $resource @return TrackedObject
[ "Create", "new", "TrackedObject" ]
cd0cda150858d6d85deb025a72996873d2af3532
https://github.com/phpguard/listen/blob/cd0cda150858d6d85deb025a72996873d2af3532/src/PhpGuard/Listen/Adapter/Tracker.php#L301-L311
train
modulusphp/http
Controllers/Auth/RegisterController.php
RegisterController.create
protected function create(Request $request) : Model { return User::create([ 'name' => $request->input('name'), 'email' => $request->input('email'), 'password' => Hash::make($request->input('password')) ]); }
php
protected function create(Request $request) : Model { return User::create([ 'name' => $request->input('name'), 'email' => $request->input('email'), 'password' => Hash::make($request->input('password')) ]); }
[ "protected", "function", "create", "(", "Request", "$", "request", ")", ":", "Model", "{", "return", "User", "::", "create", "(", "[", "'name'", "=>", "$", "request", "->", "input", "(", "'name'", ")", ",", "'email'", "=>", "$", "request", "->", "input", "(", "'email'", ")", ",", "'password'", "=>", "Hash", "::", "make", "(", "$", "request", "->", "input", "(", "'password'", ")", ")", "]", ")", ";", "}" ]
Add new a new user @param \Modulus\Http\Request $request @return \App\User
[ "Add", "new", "a", "new", "user" ]
fc5c0f2b582a04de1685578d3fb790686a0a240c
https://github.com/modulusphp/http/blob/fc5c0f2b582a04de1685578d3fb790686a0a240c/Controllers/Auth/RegisterController.php#L50-L57
train
DreadLabs/typo3-cms-phing-helper
Classes/Filters/LocalConfigurationFilter.php
LocalConfigurationFilter.chain
public function chain(Reader $reader) { $newFilter = new LocalConfigurationFilter($reader); $newFilter->setProject($this->getProject()); $newFilter->setCacheDir($this->getCacheDir()); $newFilter->setTYPO3Version($this->getTYPO3Version()); $newFilter->addInstallTool($this->installTool); $newFilter->setInitialized(true); return $newFilter; }
php
public function chain(Reader $reader) { $newFilter = new LocalConfigurationFilter($reader); $newFilter->setProject($this->getProject()); $newFilter->setCacheDir($this->getCacheDir()); $newFilter->setTYPO3Version($this->getTYPO3Version()); $newFilter->addInstallTool($this->installTool); $newFilter->setInitialized(true); return $newFilter; }
[ "public", "function", "chain", "(", "Reader", "$", "reader", ")", "{", "$", "newFilter", "=", "new", "LocalConfigurationFilter", "(", "$", "reader", ")", ";", "$", "newFilter", "->", "setProject", "(", "$", "this", "->", "getProject", "(", ")", ")", ";", "$", "newFilter", "->", "setCacheDir", "(", "$", "this", "->", "getCacheDir", "(", ")", ")", ";", "$", "newFilter", "->", "setTYPO3Version", "(", "$", "this", "->", "getTYPO3Version", "(", ")", ")", ";", "$", "newFilter", "->", "addInstallTool", "(", "$", "this", "->", "installTool", ")", ";", "$", "newFilter", "->", "setInitialized", "(", "true", ")", ";", "return", "$", "newFilter", ";", "}" ]
Creates a new LocalConfigurationFilter using the passed in Reader for instantiation. @param Reader A Reader object providing the underlying stream. Must not be <code>null</code>. @return Reader A new filter based on this configuration, but filtering the specified reader
[ "Creates", "a", "new", "LocalConfigurationFilter", "using", "the", "passed", "in", "Reader", "for", "instantiation", "." ]
b6606102c4702a92bc1872eba962febceaa0e645
https://github.com/DreadLabs/typo3-cms-phing-helper/blob/b6606102c4702a92bc1872eba962febceaa0e645/Classes/Filters/LocalConfigurationFilter.php#L139-L149
train
DreadLabs/typo3-cms-phing-helper
Classes/Filters/LocalConfigurationFilter.php
LocalConfigurationFilter.read
public function read($len = null) { if (FALSE === $this->getInitialized()) { $this->initialize(); $this->setInitialized(TRUE); } $defaultConfiguration = ''; if (-1 === version_compare($this->getTYPO3Version(), '0.0.0')) { throw new BuildException('You must pass a TYPO3 version via the corresponding parameter in your build file!'); } while (($data = $this->in->read($len)) !== -1) { $defaultConfiguration .= $data; } if ('' === $defaultConfiguration) { return -1; } $this->setDefaultConfiguration($defaultConfiguration); $comments = $this->installTool->getDefaultConfigArrayComments($defaultConfiguration); $out = $this->createPropertyPathsFromCommentArray($comments); return $out; }
php
public function read($len = null) { if (FALSE === $this->getInitialized()) { $this->initialize(); $this->setInitialized(TRUE); } $defaultConfiguration = ''; if (-1 === version_compare($this->getTYPO3Version(), '0.0.0')) { throw new BuildException('You must pass a TYPO3 version via the corresponding parameter in your build file!'); } while (($data = $this->in->read($len)) !== -1) { $defaultConfiguration .= $data; } if ('' === $defaultConfiguration) { return -1; } $this->setDefaultConfiguration($defaultConfiguration); $comments = $this->installTool->getDefaultConfigArrayComments($defaultConfiguration); $out = $this->createPropertyPathsFromCommentArray($comments); return $out; }
[ "public", "function", "read", "(", "$", "len", "=", "null", ")", "{", "if", "(", "FALSE", "===", "$", "this", "->", "getInitialized", "(", ")", ")", "{", "$", "this", "->", "initialize", "(", ")", ";", "$", "this", "->", "setInitialized", "(", "TRUE", ")", ";", "}", "$", "defaultConfiguration", "=", "''", ";", "if", "(", "-", "1", "===", "version_compare", "(", "$", "this", "->", "getTYPO3Version", "(", ")", ",", "'0.0.0'", ")", ")", "{", "throw", "new", "BuildException", "(", "'You must pass a TYPO3 version via the corresponding parameter in your build file!'", ")", ";", "}", "while", "(", "(", "$", "data", "=", "$", "this", "->", "in", "->", "read", "(", "$", "len", ")", ")", "!==", "-", "1", ")", "{", "$", "defaultConfiguration", ".=", "$", "data", ";", "}", "if", "(", "''", "===", "$", "defaultConfiguration", ")", "{", "return", "-", "1", ";", "}", "$", "this", "->", "setDefaultConfiguration", "(", "$", "defaultConfiguration", ")", ";", "$", "comments", "=", "$", "this", "->", "installTool", "->", "getDefaultConfigArrayComments", "(", "$", "defaultConfiguration", ")", ";", "$", "out", "=", "$", "this", "->", "createPropertyPathsFromCommentArray", "(", "$", "comments", ")", ";", "return", "$", "out", ";", "}" ]
Reads stream, applies property file formatting and returns resulting stream. @return string transformed buffer. @throws BuildException if TYPO3version is not set in unresolveableReplacementPairs
[ "Reads", "stream", "applies", "property", "file", "formatting", "and", "returns", "resulting", "stream", "." ]
b6606102c4702a92bc1872eba962febceaa0e645
https://github.com/DreadLabs/typo3-cms-phing-helper/blob/b6606102c4702a92bc1872eba962febceaa0e645/Classes/Filters/LocalConfigurationFilter.php#L157-L185
train
DreadLabs/typo3-cms-phing-helper
Classes/Filters/LocalConfigurationFilter.php
LocalConfigurationFilter.initialize
private function initialize() { $params = $this->getParameters(); if ($params) { foreach ($params as $param) { $setter = 'set' . str_replace(' ', '', ucwords(str_replace('-', ' ', $param->getName()))); if (FALSE === method_exists($this, $setter)) { $msg = sprintf('Unknown parameter "%s" for LocalConfigurationFilter!', $param->getName()); throw new BuildException($msg); } call_user_func(array($this, $setter), $param->getValue()); } } if (NULL === $this->installTool) { $this->addInstallTool(); } }
php
private function initialize() { $params = $this->getParameters(); if ($params) { foreach ($params as $param) { $setter = 'set' . str_replace(' ', '', ucwords(str_replace('-', ' ', $param->getName()))); if (FALSE === method_exists($this, $setter)) { $msg = sprintf('Unknown parameter "%s" for LocalConfigurationFilter!', $param->getName()); throw new BuildException($msg); } call_user_func(array($this, $setter), $param->getValue()); } } if (NULL === $this->installTool) { $this->addInstallTool(); } }
[ "private", "function", "initialize", "(", ")", "{", "$", "params", "=", "$", "this", "->", "getParameters", "(", ")", ";", "if", "(", "$", "params", ")", "{", "foreach", "(", "$", "params", "as", "$", "param", ")", "{", "$", "setter", "=", "'set'", ".", "str_replace", "(", "' '", ",", "''", ",", "ucwords", "(", "str_replace", "(", "'-'", ",", "' '", ",", "$", "param", "->", "getName", "(", ")", ")", ")", ")", ";", "if", "(", "FALSE", "===", "method_exists", "(", "$", "this", ",", "$", "setter", ")", ")", "{", "$", "msg", "=", "sprintf", "(", "'Unknown parameter \"%s\" for LocalConfigurationFilter!'", ",", "$", "param", "->", "getName", "(", ")", ")", ";", "throw", "new", "BuildException", "(", "$", "msg", ")", ";", "}", "call_user_func", "(", "array", "(", "$", "this", ",", "$", "setter", ")", ",", "$", "param", "->", "getValue", "(", ")", ")", ";", "}", "}", "if", "(", "NULL", "===", "$", "this", "->", "installTool", ")", "{", "$", "this", "->", "addInstallTool", "(", ")", ";", "}", "}" ]
Initializes any parameters This method is only called when this filter is used through a <filterreader> tag in build file. @return void
[ "Initializes", "any", "parameters" ]
b6606102c4702a92bc1872eba962febceaa0e645
https://github.com/DreadLabs/typo3-cms-phing-helper/blob/b6606102c4702a92bc1872eba962febceaa0e645/Classes/Filters/LocalConfigurationFilter.php#L194-L213
train
DreadLabs/typo3-cms-phing-helper
Classes/Filters/LocalConfigurationFilter.php
LocalConfigurationFilter.setDefaultConfiguration
protected function setDefaultConfiguration($rawContent) { $resolvedContent = strtr($rawContent, $this->unresolveableReplacementPairs); $cacheFile = tempnam($this->cacheDir, 'tmp'); $fh = fopen($cacheFile, 'w'); fwrite($fh, $resolvedContent); fclose($fh); $this->defaultConfiguration = include($cacheFile); unlink($cacheFile); }
php
protected function setDefaultConfiguration($rawContent) { $resolvedContent = strtr($rawContent, $this->unresolveableReplacementPairs); $cacheFile = tempnam($this->cacheDir, 'tmp'); $fh = fopen($cacheFile, 'w'); fwrite($fh, $resolvedContent); fclose($fh); $this->defaultConfiguration = include($cacheFile); unlink($cacheFile); }
[ "protected", "function", "setDefaultConfiguration", "(", "$", "rawContent", ")", "{", "$", "resolvedContent", "=", "strtr", "(", "$", "rawContent", ",", "$", "this", "->", "unresolveableReplacementPairs", ")", ";", "$", "cacheFile", "=", "tempnam", "(", "$", "this", "->", "cacheDir", ",", "'tmp'", ")", ";", "$", "fh", "=", "fopen", "(", "$", "cacheFile", ",", "'w'", ")", ";", "fwrite", "(", "$", "fh", ",", "$", "resolvedContent", ")", ";", "fclose", "(", "$", "fh", ")", ";", "$", "this", "->", "defaultConfiguration", "=", "include", "(", "$", "cacheFile", ")", ";", "unlink", "(", "$", "cacheFile", ")", ";", "}" ]
modifies the given raw content by creating a temp file and resolving some TYPO3 CMS constants @param string $rawContent @return void
[ "modifies", "the", "given", "raw", "content", "by", "creating", "a", "temp", "file", "and", "resolving", "some", "TYPO3", "CMS", "constants" ]
b6606102c4702a92bc1872eba962febceaa0e645
https://github.com/DreadLabs/typo3-cms-phing-helper/blob/b6606102c4702a92bc1872eba962febceaa0e645/Classes/Filters/LocalConfigurationFilter.php#L221-L236
train
DreadLabs/typo3-cms-phing-helper
Classes/Filters/LocalConfigurationFilter.php
LocalConfigurationFilter.createPropertyPathsFromCommentArray
public function createPropertyPathsFromCommentArray($comments) { $out = ''; foreach ($comments as $mainKey => $subKeys) { foreach ($subKeys as $subKey => $comment) { // uncommented entries are undocumented & for internal use only (I guess) if ('' === $comment) { continue; } $defaultConfigurationValue = $this->defaultConfiguration[$mainKey][$subKey]; // non-scalar values are not available in InstallTool (& also not handled by phing properties) if (FALSE === is_scalar($defaultConfigurationValue)) { continue; } $out .= strtr($this->outputLine, array( '%newline%' => chr(10), '%comment%' => $comment, '%mainKey%' => $mainKey, '%subKey%' => $subKey, '%defaultConfigurationValue%' => $defaultConfigurationValue, )); } } return $out; }
php
public function createPropertyPathsFromCommentArray($comments) { $out = ''; foreach ($comments as $mainKey => $subKeys) { foreach ($subKeys as $subKey => $comment) { // uncommented entries are undocumented & for internal use only (I guess) if ('' === $comment) { continue; } $defaultConfigurationValue = $this->defaultConfiguration[$mainKey][$subKey]; // non-scalar values are not available in InstallTool (& also not handled by phing properties) if (FALSE === is_scalar($defaultConfigurationValue)) { continue; } $out .= strtr($this->outputLine, array( '%newline%' => chr(10), '%comment%' => $comment, '%mainKey%' => $mainKey, '%subKey%' => $subKey, '%defaultConfigurationValue%' => $defaultConfigurationValue, )); } } return $out; }
[ "public", "function", "createPropertyPathsFromCommentArray", "(", "$", "comments", ")", "{", "$", "out", "=", "''", ";", "foreach", "(", "$", "comments", "as", "$", "mainKey", "=>", "$", "subKeys", ")", "{", "foreach", "(", "$", "subKeys", "as", "$", "subKey", "=>", "$", "comment", ")", "{", "// uncommented entries are undocumented & for internal use only (I guess)", "if", "(", "''", "===", "$", "comment", ")", "{", "continue", ";", "}", "$", "defaultConfigurationValue", "=", "$", "this", "->", "defaultConfiguration", "[", "$", "mainKey", "]", "[", "$", "subKey", "]", ";", "// non-scalar values are not available in InstallTool (& also not handled by phing properties)", "if", "(", "FALSE", "===", "is_scalar", "(", "$", "defaultConfigurationValue", ")", ")", "{", "continue", ";", "}", "$", "out", ".=", "strtr", "(", "$", "this", "->", "outputLine", ",", "array", "(", "'%newline%'", "=>", "chr", "(", "10", ")", ",", "'%comment%'", "=>", "$", "comment", ",", "'%mainKey%'", "=>", "$", "mainKey", ",", "'%subKey%'", "=>", "$", "subKey", ",", "'%defaultConfigurationValue%'", "=>", "$", "defaultConfigurationValue", ",", ")", ")", ";", "}", "}", "return", "$", "out", ";", "}" ]
creates the property file lines for the given comments array @param array $comments @return string
[ "creates", "the", "property", "file", "lines", "for", "the", "given", "comments", "array" ]
b6606102c4702a92bc1872eba962febceaa0e645
https://github.com/DreadLabs/typo3-cms-phing-helper/blob/b6606102c4702a92bc1872eba962febceaa0e645/Classes/Filters/LocalConfigurationFilter.php#L244-L273
train
translationexchange/tml-php-clientsdk
library/Tr8n/Base.php
Base.toArray
public function toArray($keys=array()) { $vars = get_object_vars($this); $results = array(); if (count($keys) == 0) { foreach($vars as $name=>$value) { if (is_string($value) || is_numeric($value) || is_bool($value)) { $results[$name] = $value; } } return $results; } foreach($keys as $key) { if (!isset($vars[$key])) continue; $results[$key] = $vars[$key]; } return $results; }
php
public function toArray($keys=array()) { $vars = get_object_vars($this); $results = array(); if (count($keys) == 0) { foreach($vars as $name=>$value) { if (is_string($value) || is_numeric($value) || is_bool($value)) { $results[$name] = $value; } } return $results; } foreach($keys as $key) { if (!isset($vars[$key])) continue; $results[$key] = $vars[$key]; } return $results; }
[ "public", "function", "toArray", "(", "$", "keys", "=", "array", "(", ")", ")", "{", "$", "vars", "=", "get_object_vars", "(", "$", "this", ")", ";", "$", "results", "=", "array", "(", ")", ";", "if", "(", "count", "(", "$", "keys", ")", "==", "0", ")", "{", "foreach", "(", "$", "vars", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", "||", "is_numeric", "(", "$", "value", ")", "||", "is_bool", "(", "$", "value", ")", ")", "{", "$", "results", "[", "$", "name", "]", "=", "$", "value", ";", "}", "}", "return", "$", "results", ";", "}", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "vars", "[", "$", "key", "]", ")", ")", "continue", ";", "$", "results", "[", "$", "key", "]", "=", "$", "vars", "[", "$", "key", "]", ";", "}", "return", "$", "results", ";", "}" ]
Serializes an object into a dictionary @param array $keys @return array
[ "Serializes", "an", "object", "into", "a", "dictionary" ]
fe51473824e62cfd883c6aa0c6a3783a16ce8425
https://github.com/translationexchange/tml-php-clientsdk/blob/fe51473824e62cfd883c6aa0c6a3783a16ce8425/library/Tr8n/Base.php#L54-L73
train
cinnamonlab/framework
src/Framework/Response.php
Response.json
static function json( $data, $code = 200 ) { return (new Response()) ->setCode($code) ->setContent(json_encode($data)) ->setContentType('application/json'); }
php
static function json( $data, $code = 200 ) { return (new Response()) ->setCode($code) ->setContent(json_encode($data)) ->setContentType('application/json'); }
[ "static", "function", "json", "(", "$", "data", ",", "$", "code", "=", "200", ")", "{", "return", "(", "new", "Response", "(", ")", ")", "->", "setCode", "(", "$", "code", ")", "->", "setContent", "(", "json_encode", "(", "$", "data", ")", ")", "->", "setContentType", "(", "'application/json'", ")", ";", "}" ]
Create Response object with JSON header + content @param array $data @param int $code HTTP code (optional) @return Response object
[ "Create", "Response", "object", "with", "JSON", "header", "+", "content" ]
958ba3e60d3f927adc40a543ec6d4f08d38cfd2c
https://github.com/cinnamonlab/framework/blob/958ba3e60d3f927adc40a543ec6d4f08d38cfd2c/src/Framework/Response.php#L17-L22
train
cinnamonlab/framework
src/Framework/Response.php
Response.setCode
function setCode( $code ) { $this->code = $code; $this->addHeader($this->getDefaultHeaderFromCode( $code )); return $this; }
php
function setCode( $code ) { $this->code = $code; $this->addHeader($this->getDefaultHeaderFromCode( $code )); return $this; }
[ "function", "setCode", "(", "$", "code", ")", "{", "$", "this", "->", "code", "=", "$", "code", ";", "$", "this", "->", "addHeader", "(", "$", "this", "->", "getDefaultHeaderFromCode", "(", "$", "code", ")", ")", ";", "return", "$", "this", ";", "}" ]
Set HTTP code and put on header @param $code @return $this
[ "Set", "HTTP", "code", "and", "put", "on", "header" ]
958ba3e60d3f927adc40a543ec6d4f08d38cfd2c
https://github.com/cinnamonlab/framework/blob/958ba3e60d3f927adc40a543ec6d4f08d38cfd2c/src/Framework/Response.php#L54-L58
train
shgysk8zer0/core_api
abstracts/file_io.php
File_IO.openFile
final public function openFile($filename, $use_include_path = false) { $this->getPathInfo($filename, $use_include_path); $this->fileResource = fopen( $this->dirname . DIRECTORY_SEPARATOR . $this->basename, self::FILE_MODE ); return flock($this->fileResource, LOCK_EX); }
php
final public function openFile($filename, $use_include_path = false) { $this->getPathInfo($filename, $use_include_path); $this->fileResource = fopen( $this->dirname . DIRECTORY_SEPARATOR . $this->basename, self::FILE_MODE ); return flock($this->fileResource, LOCK_EX); }
[ "final", "public", "function", "openFile", "(", "$", "filename", ",", "$", "use_include_path", "=", "false", ")", "{", "$", "this", "->", "getPathInfo", "(", "$", "filename", ",", "$", "use_include_path", ")", ";", "$", "this", "->", "fileResource", "=", "fopen", "(", "$", "this", "->", "dirname", ".", "DIRECTORY_SEPARATOR", ".", "$", "this", "->", "basename", ",", "self", "::", "FILE_MODE", ")", ";", "return", "flock", "(", "$", "this", "->", "fileResource", ",", "LOCK_EX", ")", ";", "}" ]
Opens the file in the specified mode designating read, write, create capabilities. Obtains exclusive lock on file, which is released when class is destroyed. @param string $filename Name/path of file to be working with @param bool $use_include_path If you want to search for the file in the include_path @return bool Whether or not lock was able to be obtained.
[ "Opens", "the", "file", "in", "the", "specified", "mode", "designating", "read", "write", "create", "capabilities", ".", "Obtains", "exclusive", "lock", "on", "file", "which", "is", "released", "when", "class", "is", "destroyed", "." ]
9e9b8baf761af874b95256ad2462e55fbb2b2e58
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/abstracts/file_io.php#L55-L63
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.getDifferenceYears
public final function getDifferenceYears( $dt = null, bool $abs = true ) : int { $dt = $dt ?: static::Now( $this->getTimezone() ); return (int) $this->diff( $dt, $abs )->format( '%r%y' ); }
php
public final function getDifferenceYears( $dt = null, bool $abs = true ) : int { $dt = $dt ?: static::Now( $this->getTimezone() ); return (int) $this->diff( $dt, $abs )->format( '%r%y' ); }
[ "public", "final", "function", "getDifferenceYears", "(", "$", "dt", "=", "null", ",", "bool", "$", "abs", "=", "true", ")", ":", "int", "{", "$", "dt", "=", "$", "dt", "?", ":", "static", "::", "Now", "(", "$", "this", "->", "getTimezone", "(", ")", ")", ";", "return", "(", "int", ")", "$", "this", "->", "diff", "(", "$", "dt", ",", "$", "abs", ")", "->", "format", "(", "'%r%y'", ")", ";", "}" ]
Get the difference in years between current date time and defined. If no other date time is defined Now is used. @param \Beluga\Date\DateTime|null $dt @param bool $abs Get the absolute of the difference @return int
[ "Get", "the", "difference", "in", "years", "between", "current", "date", "time", "and", "defined", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L549-L556
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.setISODate
public function setISODate( $year, $week, $day = null ) : DateTime { parent::setISODate( $year, $week, $day ); return $this; }
php
public function setISODate( $year, $week, $day = null ) : DateTime { parent::setISODate( $year, $week, $day ); return $this; }
[ "public", "function", "setISODate", "(", "$", "year", ",", "$", "week", ",", "$", "day", "=", "null", ")", ":", "DateTime", "{", "parent", "::", "setISODate", "(", "$", "year", ",", "$", "week", ",", "$", "day", ")", ";", "return", "$", "this", ";", "}" ]
Sets a date by ISO-8601 conform data. @param integer $year The year @param integer $week The Week number (Weeks begins at monday) @param integer $day The day @return \Beluga\Date\DateTime
[ "Sets", "a", "date", "by", "ISO", "-", "8601", "conform", "data", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L717-L725
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.setYear
public final function setYear( int $year = null ) : DateTime { if ( \is_null( $year ) ) { $year = static::CurrentYear(); } return $this->setDateParts( $year ); }
php
public final function setYear( int $year = null ) : DateTime { if ( \is_null( $year ) ) { $year = static::CurrentYear(); } return $this->setDateParts( $year ); }
[ "public", "final", "function", "setYear", "(", "int", "$", "year", "=", "null", ")", ":", "DateTime", "{", "if", "(", "\\", "is_null", "(", "$", "year", ")", ")", "{", "$", "year", "=", "static", "::", "CurrentYear", "(", ")", ";", "}", "return", "$", "this", "->", "setDateParts", "(", "$", "year", ")", ";", "}" ]
Changes the current defined year to defined value. @param integer $year The new year value. If the value NULL is used it means: Use the year of NOW() @return \Beluga\Date\DateTime
[ "Changes", "the", "current", "defined", "year", "to", "defined", "value", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L733-L744
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.setMonth
public final function setMonth( int $month = null ) : DateTime { if ( \is_null( $month ) ) { $month = static::CurrentMonth(); } return $this->setDateParts( null, $month ); }
php
public final function setMonth( int $month = null ) : DateTime { if ( \is_null( $month ) ) { $month = static::CurrentMonth(); } return $this->setDateParts( null, $month ); }
[ "public", "final", "function", "setMonth", "(", "int", "$", "month", "=", "null", ")", ":", "DateTime", "{", "if", "(", "\\", "is_null", "(", "$", "month", ")", ")", "{", "$", "month", "=", "static", "::", "CurrentMonth", "(", ")", ";", "}", "return", "$", "this", "->", "setDateParts", "(", "null", ",", "$", "month", ")", ";", "}" ]
Changes the current defined month to defined value. @param integer $month The new month value. If the value NULL is used it means: Use the month of NOW() @return \Beluga\Date\DateTime
[ "Changes", "the", "current", "defined", "month", "to", "defined", "value", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L752-L763
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.setDay
public final function setDay( int $day = null ) : DateTime { if ( \is_null( $day ) ) { $day = static::CurrentDay(); } return $this->setDateParts( null, null, $day ); }
php
public final function setDay( int $day = null ) : DateTime { if ( \is_null( $day ) ) { $day = static::CurrentDay(); } return $this->setDateParts( null, null, $day ); }
[ "public", "final", "function", "setDay", "(", "int", "$", "day", "=", "null", ")", ":", "DateTime", "{", "if", "(", "\\", "is_null", "(", "$", "day", ")", ")", "{", "$", "day", "=", "static", "::", "CurrentDay", "(", ")", ";", "}", "return", "$", "this", "->", "setDateParts", "(", "null", ",", "null", ",", "$", "day", ")", ";", "}" ]
Changes the current defined day to defined value. @param integer $day The new day value. If the value NULL is used it means: Use the day of NOW() @return \Beluga\Date\DateTime
[ "Changes", "the", "current", "defined", "day", "to", "defined", "value", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L771-L782
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.setHour
public final function setHour( int $hour = null ) : DateTime { if ( \is_null( $hour ) ) { $hour = static::CurrentHour(); } return $this->setTimeParts( $hour ); }
php
public final function setHour( int $hour = null ) : DateTime { if ( \is_null( $hour ) ) { $hour = static::CurrentHour(); } return $this->setTimeParts( $hour ); }
[ "public", "final", "function", "setHour", "(", "int", "$", "hour", "=", "null", ")", ":", "DateTime", "{", "if", "(", "\\", "is_null", "(", "$", "hour", ")", ")", "{", "$", "hour", "=", "static", "::", "CurrentHour", "(", ")", ";", "}", "return", "$", "this", "->", "setTimeParts", "(", "$", "hour", ")", ";", "}" ]
Changes the current defined hour to defined value. @param integer $hour The new hour value. If the value NULL is used it means: Use the hour of NOW() @return \Beluga\Date\DateTime
[ "Changes", "the", "current", "defined", "hour", "to", "defined", "value", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L790-L801
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.setMinute
public final function setMinute( int $minute = null ) : DateTime { if ( \is_null( $minute ) ) { $minute = static::CurrentMinute(); } return $this->setTimeParts( null, $minute ); }
php
public final function setMinute( int $minute = null ) : DateTime { if ( \is_null( $minute ) ) { $minute = static::CurrentMinute(); } return $this->setTimeParts( null, $minute ); }
[ "public", "final", "function", "setMinute", "(", "int", "$", "minute", "=", "null", ")", ":", "DateTime", "{", "if", "(", "\\", "is_null", "(", "$", "minute", ")", ")", "{", "$", "minute", "=", "static", "::", "CurrentMinute", "(", ")", ";", "}", "return", "$", "this", "->", "setTimeParts", "(", "null", ",", "$", "minute", ")", ";", "}" ]
Changes the current defined minute to defined value. @param integer $minute The new minute value. If the value NULL is used it means: Use the minute of NOW() @return \Beluga\Date\DateTime
[ "Changes", "the", "current", "defined", "minute", "to", "defined", "value", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L809-L820
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.setSecond
public final function setSecond( int $second = null ) : DateTime { if ( \is_null( $second ) ) { $second = static::CurrentSecond(); } return $this->setTimeParts( null, null, $second ); }
php
public final function setSecond( int $second = null ) : DateTime { if ( \is_null( $second ) ) { $second = static::CurrentSecond(); } return $this->setTimeParts( null, null, $second ); }
[ "public", "final", "function", "setSecond", "(", "int", "$", "second", "=", "null", ")", ":", "DateTime", "{", "if", "(", "\\", "is_null", "(", "$", "second", ")", ")", "{", "$", "second", "=", "static", "::", "CurrentSecond", "(", ")", ";", "}", "return", "$", "this", "->", "setTimeParts", "(", "null", ",", "null", ",", "$", "second", ")", ";", "}" ]
Changes the current defined second to defined value. @param integer $second The new second value. If the value NULL is used it means: Use the second of NOW() @return \Beluga\Date\DateTime
[ "Changes", "the", "current", "defined", "second", "to", "defined", "value", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L828-L839
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.addSeconds
public final function addSeconds( int $seconds = 1 ) : DateTime { return $this->move( new \DateInterval( 'PT' . \abs( $seconds ) . 'S' ), $seconds < 0 ); }
php
public final function addSeconds( int $seconds = 1 ) : DateTime { return $this->move( new \DateInterval( 'PT' . \abs( $seconds ) . 'S' ), $seconds < 0 ); }
[ "public", "final", "function", "addSeconds", "(", "int", "$", "seconds", "=", "1", ")", ":", "DateTime", "{", "return", "$", "this", "->", "move", "(", "new", "\\", "DateInterval", "(", "'PT'", ".", "\\", "abs", "(", "$", "seconds", ")", ".", "'S'", ")", ",", "$", "seconds", "<", "0", ")", ";", "}" ]
Adds the defined number of seconds. @param integer $seconds The seconds to add (use a negative value to subtract/remove the seconds) @return \Beluga\Date\DateTime Returns the current changed instance.
[ "Adds", "the", "defined", "number", "of", "seconds", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L885-L891
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.addMinutes
public final function addMinutes( int $minutes = 1 ) : DateTime { return $this->move( new \DateInterval( 'PT' . \abs( $minutes ) . 'M' ), $minutes < 0 ); }
php
public final function addMinutes( int $minutes = 1 ) : DateTime { return $this->move( new \DateInterval( 'PT' . \abs( $minutes ) . 'M' ), $minutes < 0 ); }
[ "public", "final", "function", "addMinutes", "(", "int", "$", "minutes", "=", "1", ")", ":", "DateTime", "{", "return", "$", "this", "->", "move", "(", "new", "\\", "DateInterval", "(", "'PT'", ".", "\\", "abs", "(", "$", "minutes", ")", ".", "'M'", ")", ",", "$", "minutes", "<", "0", ")", ";", "}" ]
Adds the defined number of minutes. @param integer $minutes The minutes to add (use a negative value to subtract/remove the minutes) @return \Beluga\Date\DateTime Returns the current changed instance.
[ "Adds", "the", "defined", "number", "of", "minutes", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L927-L933
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.addHours
public final function addHours( int $hours = 1 ) : DateTime { return $this->move( new \DateInterval( 'PT' . \abs( $hours ) . 'H' ), $hours < 0 ); }
php
public final function addHours( int $hours = 1 ) : DateTime { return $this->move( new \DateInterval( 'PT' . \abs( $hours ) . 'H' ), $hours < 0 ); }
[ "public", "final", "function", "addHours", "(", "int", "$", "hours", "=", "1", ")", ":", "DateTime", "{", "return", "$", "this", "->", "move", "(", "new", "\\", "DateInterval", "(", "'PT'", ".", "\\", "abs", "(", "$", "hours", ")", ".", "'H'", ")", ",", "$", "hours", "<", "0", ")", ";", "}" ]
Adds the defined number of hours. @param integer $hours The hours to add (use a negative value to subtract/remove the hours) @return \Beluga\Date\DateTime Returns the current changed instance.
[ "Adds", "the", "defined", "number", "of", "hours", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L955-L961
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.addDays
public final function addDays( int $days = 1 ) : DateTime { return $this->move( new \DateInterval( 'P' . \abs( $days ) . 'D' ), $days < 0 ); }
php
public final function addDays( int $days = 1 ) : DateTime { return $this->move( new \DateInterval( 'P' . \abs( $days ) . 'D' ), $days < 0 ); }
[ "public", "final", "function", "addDays", "(", "int", "$", "days", "=", "1", ")", ":", "DateTime", "{", "return", "$", "this", "->", "move", "(", "new", "\\", "DateInterval", "(", "'P'", ".", "\\", "abs", "(", "$", "days", ")", ".", "'D'", ")", ",", "$", "days", "<", "0", ")", ";", "}" ]
Adds the defined number of days. @param integer $days The days to add (use a negative value to subtract/remove the days) @return \Beluga\Date\DateTime Returns the current changed instance.
[ "Adds", "the", "defined", "number", "of", "days", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L969-L975
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.addWeeks
public final function addWeeks( int $weeks = 1 ) : DateTime { return $this->move( new \DateInterval( 'P' . \abs( $weeks ) . 'W' ), $weeks < 0 ); }
php
public final function addWeeks( int $weeks = 1 ) : DateTime { return $this->move( new \DateInterval( 'P' . \abs( $weeks ) . 'W' ), $weeks < 0 ); }
[ "public", "final", "function", "addWeeks", "(", "int", "$", "weeks", "=", "1", ")", ":", "DateTime", "{", "return", "$", "this", "->", "move", "(", "new", "\\", "DateInterval", "(", "'P'", ".", "\\", "abs", "(", "$", "weeks", ")", ".", "'W'", ")", ",", "$", "weeks", "<", "0", ")", ";", "}" ]
Adds the defined number of weeks. @param integer $weeks The weeks to add (use a negative value to subtract/remove the weeks) @return \Beluga\Date\DateTime Returns the current changed instance.
[ "Adds", "the", "defined", "number", "of", "weeks", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L983-L989
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.formatNamedDate
public final function formatNamedDate( bool $short = false ) : string { if ( $short ) { return \sprintf( '%s., %s. %s %d', $this->getShortWeekDayName(), $this->getDay(), $this->getShortMonthName(), $this->getYear() ); } return \sprintf( '%s, %s. %s %d', $this->getWeekDayName(), $this->getDay(), $this->getMonthName(), $this->getYear() ); }
php
public final function formatNamedDate( bool $short = false ) : string { if ( $short ) { return \sprintf( '%s., %s. %s %d', $this->getShortWeekDayName(), $this->getDay(), $this->getShortMonthName(), $this->getYear() ); } return \sprintf( '%s, %s. %s %d', $this->getWeekDayName(), $this->getDay(), $this->getMonthName(), $this->getYear() ); }
[ "public", "final", "function", "formatNamedDate", "(", "bool", "$", "short", "=", "false", ")", ":", "string", "{", "if", "(", "$", "short", ")", "{", "return", "\\", "sprintf", "(", "'%s., %s. %s %d'", ",", "$", "this", "->", "getShortWeekDayName", "(", ")", ",", "$", "this", "->", "getDay", "(", ")", ",", "$", "this", "->", "getShortMonthName", "(", ")", ",", "$", "this", "->", "getYear", "(", ")", ")", ";", "}", "return", "\\", "sprintf", "(", "'%s, %s. %s %d'", ",", "$", "this", "->", "getWeekDayName", "(", ")", ",", "$", "this", "->", "getDay", "(", ")", ",", "$", "this", "->", "getMonthName", "(", ")", ",", "$", "this", "->", "getYear", "(", ")", ")", ";", "}" ]
Formats the current instance to a named date, depending to current used locale. The output uses long names like "Montag, 20. Dezember 2030" or short names like "Mon, 20. Dec 2030" @param boolean $short Return names in short notation? @return string
[ "Formats", "the", "current", "instance", "to", "a", "named", "date", "depending", "to", "current", "used", "locale", ".", "The", "output", "uses", "long", "names", "like", "Montag", "20", ".", "Dezember", "2030", "or", "short", "names", "like", "Mon", "20", ".", "Dec", "2030" ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L1042-L1065
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.Parse
public static function Parse( $datetime, \DateTimeZone $timezone = null ) { if ( \is_null( $datetime ) ) { // NULL returns FALSE return false; } if ( $datetime instanceof DateTime ) { // Its already a \Beluga\DateTime => return it. return $datetime; } if ( $datetime instanceof \DateTimeInterface ) { // \DateTime values can be handled directly without some other requirements. return new DateTime( $datetime->format( 'y-m-d H:i:s' ), $datetime->getTimezone() ); } if ( is_array( $datetime ) || ( $datetime instanceof \stdClass ) ) { return false; } if ( TypeTool::IsInteger( $datetime ) ) { // Unix timestamp convert to DateTime string $datetime = \strftime( '%Y-%m-%d %H:%M:%S', \intval( $datetime ) ); } else if ( ! \is_string( $datetime ) ) { $type = new Type( $datetime ); if ( ! $type->hasAssociatedString() ) { // Not a string and not convertible to a string. return false; } // Getting the associated string value $datetime = $type->getStringValue(); } // $datetime is a string now! try { $dt = new DateTime( $datetime, $timezone ); return $dt; } catch ( \Throwable $ex ) { $replacements = array( '1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.', '10.', '11.', '12.' ); $ex = null; // Replace all month names and short month names. $datetime = \preg_replace( static::$monthNamesShortRegex, $replacements, \preg_replace( static::$monthNamesLongRegex, $replacements, $datetime ) ); // Replace every thing that's not an [0-9.:+/ -] $datetime = \preg_replace( '~\s{2,}~', ' ', \preg_replace( '~[^0-9.:+/-]+~', ' ', $datetime ) ); } try { $dt = new DateTime( \trim( $datetime ), $timezone ); return $dt; } catch ( \Throwable $ex ) { $ex = null; return false; } }
php
public static function Parse( $datetime, \DateTimeZone $timezone = null ) { if ( \is_null( $datetime ) ) { // NULL returns FALSE return false; } if ( $datetime instanceof DateTime ) { // Its already a \Beluga\DateTime => return it. return $datetime; } if ( $datetime instanceof \DateTimeInterface ) { // \DateTime values can be handled directly without some other requirements. return new DateTime( $datetime->format( 'y-m-d H:i:s' ), $datetime->getTimezone() ); } if ( is_array( $datetime ) || ( $datetime instanceof \stdClass ) ) { return false; } if ( TypeTool::IsInteger( $datetime ) ) { // Unix timestamp convert to DateTime string $datetime = \strftime( '%Y-%m-%d %H:%M:%S', \intval( $datetime ) ); } else if ( ! \is_string( $datetime ) ) { $type = new Type( $datetime ); if ( ! $type->hasAssociatedString() ) { // Not a string and not convertible to a string. return false; } // Getting the associated string value $datetime = $type->getStringValue(); } // $datetime is a string now! try { $dt = new DateTime( $datetime, $timezone ); return $dt; } catch ( \Throwable $ex ) { $replacements = array( '1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.', '10.', '11.', '12.' ); $ex = null; // Replace all month names and short month names. $datetime = \preg_replace( static::$monthNamesShortRegex, $replacements, \preg_replace( static::$monthNamesLongRegex, $replacements, $datetime ) ); // Replace every thing that's not an [0-9.:+/ -] $datetime = \preg_replace( '~\s{2,}~', ' ', \preg_replace( '~[^0-9.:+/-]+~', ' ', $datetime ) ); } try { $dt = new DateTime( \trim( $datetime ), $timezone ); return $dt; } catch ( \Throwable $ex ) { $ex = null; return false; } }
[ "public", "static", "function", "Parse", "(", "$", "datetime", ",", "\\", "DateTimeZone", "$", "timezone", "=", "null", ")", "{", "if", "(", "\\", "is_null", "(", "$", "datetime", ")", ")", "{", "// NULL returns FALSE", "return", "false", ";", "}", "if", "(", "$", "datetime", "instanceof", "DateTime", ")", "{", "// Its already a \\Beluga\\DateTime => return it.", "return", "$", "datetime", ";", "}", "if", "(", "$", "datetime", "instanceof", "\\", "DateTimeInterface", ")", "{", "// \\DateTime values can be handled directly without some other requirements.", "return", "new", "DateTime", "(", "$", "datetime", "->", "format", "(", "'y-m-d H:i:s'", ")", ",", "$", "datetime", "->", "getTimezone", "(", ")", ")", ";", "}", "if", "(", "is_array", "(", "$", "datetime", ")", "||", "(", "$", "datetime", "instanceof", "\\", "stdClass", ")", ")", "{", "return", "false", ";", "}", "if", "(", "TypeTool", "::", "IsInteger", "(", "$", "datetime", ")", ")", "{", "// Unix timestamp convert to DateTime string", "$", "datetime", "=", "\\", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ",", "\\", "intval", "(", "$", "datetime", ")", ")", ";", "}", "else", "if", "(", "!", "\\", "is_string", "(", "$", "datetime", ")", ")", "{", "$", "type", "=", "new", "Type", "(", "$", "datetime", ")", ";", "if", "(", "!", "$", "type", "->", "hasAssociatedString", "(", ")", ")", "{", "// Not a string and not convertible to a string.", "return", "false", ";", "}", "// Getting the associated string value", "$", "datetime", "=", "$", "type", "->", "getStringValue", "(", ")", ";", "}", "// $datetime is a string now!", "try", "{", "$", "dt", "=", "new", "DateTime", "(", "$", "datetime", ",", "$", "timezone", ")", ";", "return", "$", "dt", ";", "}", "catch", "(", "\\", "Throwable", "$", "ex", ")", "{", "$", "replacements", "=", "array", "(", "'1.'", ",", "'2.'", ",", "'3.'", ",", "'4.'", ",", "'5.'", ",", "'6.'", ",", "'7.'", ",", "'8.'", ",", "'9.'", ",", "'10.'", ",", "'11.'", ",", "'12.'", ")", ";", "$", "ex", "=", "null", ";", "// Replace all month names and short month names.", "$", "datetime", "=", "\\", "preg_replace", "(", "static", "::", "$", "monthNamesShortRegex", ",", "$", "replacements", ",", "\\", "preg_replace", "(", "static", "::", "$", "monthNamesLongRegex", ",", "$", "replacements", ",", "$", "datetime", ")", ")", ";", "// Replace every thing that's not an [0-9.:+/ -]", "$", "datetime", "=", "\\", "preg_replace", "(", "'~\\s{2,}~'", ",", "' '", ",", "\\", "preg_replace", "(", "'~[^0-9.:+/-]+~'", ",", "' '", ",", "$", "datetime", ")", ")", ";", "}", "try", "{", "$", "dt", "=", "new", "DateTime", "(", "\\", "trim", "(", "$", "datetime", ")", ",", "$", "timezone", ")", ";", "return", "$", "dt", ";", "}", "catch", "(", "\\", "Throwable", "$", "ex", ")", "{", "$", "ex", "=", "null", ";", "return", "false", ";", "}", "}" ]
Parses a value to a \Beluga\Date\DateTime instance. @param mixed $datetime The value to parse as DateTime. If can be a date(time) string, a unix timestamp , a object of type \DateTime or something that can be converted, by a string cast, to a valid date(time) string. @param \DateTimeZone $timezone An optional TimeZone @return \Beluga\Date\DateTime|bool Returns the created \Beluga\Date\DateTime instance, or boolean FALSE if parsing fails.
[ "Parses", "a", "value", "to", "a", "\\", "Beluga", "\\", "Date", "\\", "DateTime", "instance", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L1205-L1284
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.Create
public static function Create( int $year, int $month, int $day, int $hour = 0, int $minute = 0, int $second = 0 ) : DateTime { $dt = new DateTime(); $dt->setDate( $year, $month, $day ); $dt->setTime( $hour, $minute, $second ); return $dt; }
php
public static function Create( int $year, int $month, int $day, int $hour = 0, int $minute = 0, int $second = 0 ) : DateTime { $dt = new DateTime(); $dt->setDate( $year, $month, $day ); $dt->setTime( $hour, $minute, $second ); return $dt; }
[ "public", "static", "function", "Create", "(", "int", "$", "year", ",", "int", "$", "month", ",", "int", "$", "day", ",", "int", "$", "hour", "=", "0", ",", "int", "$", "minute", "=", "0", ",", "int", "$", "second", "=", "0", ")", ":", "DateTime", "{", "$", "dt", "=", "new", "DateTime", "(", ")", ";", "$", "dt", "->", "setDate", "(", "$", "year", ",", "$", "month", ",", "$", "day", ")", ";", "$", "dt", "->", "setTime", "(", "$", "hour", ",", "$", "minute", ",", "$", "second", ")", ";", "return", "$", "dt", ";", "}" ]
Init's a new instance. @param integer $year The year @param integer $month The month number (1-12) @param integer $day The day of month number (1-31 depending to leap year and month) @param integer $hour The Hour (0-23) @param integer $minute The Minute (0-59) @param integer $second The Second (0-59) @return \Beluga\Date\DateTime
[ "Init", "s", "a", "new", "instance", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L1297-L1306
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.FromDateTime
public static function FromDateTime( \DateTime $dt ) : DateTime { if ( $dt instanceof DateTime ) { return clone $dt; } return new DateTime( $dt->format('Y-m-d H:i:s.u'), $dt->getTimezone() ); }
php
public static function FromDateTime( \DateTime $dt ) : DateTime { if ( $dt instanceof DateTime ) { return clone $dt; } return new DateTime( $dt->format('Y-m-d H:i:s.u'), $dt->getTimezone() ); }
[ "public", "static", "function", "FromDateTime", "(", "\\", "DateTime", "$", "dt", ")", ":", "DateTime", "{", "if", "(", "$", "dt", "instanceof", "DateTime", ")", "{", "return", "clone", "$", "dt", ";", "}", "return", "new", "DateTime", "(", "$", "dt", "->", "format", "(", "'Y-m-d H:i:s.u'", ")", ",", "$", "dt", "->", "getTimezone", "(", ")", ")", ";", "}" ]
Create a DateTime instance from PHP \DateTime instance. @param \DateTime $dt @return \Beluga\Date\DateTime
[ "Create", "a", "DateTime", "instance", "from", "PHP", "\\", "DateTime", "instance", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L1314-L1324
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.FromFormat
public static function FromFormat( string $format, $time, \DateTimeZone $timezone = null ) : DateTime { if ( $timezone !== null ) { $dt = parent::createFromFormat( $format, $time, $timezone ); } else { $dt = parent::createFromFormat( $format, $time ); } if ( $dt instanceof \DateTime ) { return static::FromDateTime( $dt ); } throw new ArgumentError( 'format', $format, 'Date', \join( \PHP_EOL, parent::getLastErrors() ) ); }
php
public static function FromFormat( string $format, $time, \DateTimeZone $timezone = null ) : DateTime { if ( $timezone !== null ) { $dt = parent::createFromFormat( $format, $time, $timezone ); } else { $dt = parent::createFromFormat( $format, $time ); } if ( $dt instanceof \DateTime ) { return static::FromDateTime( $dt ); } throw new ArgumentError( 'format', $format, 'Date', \join( \PHP_EOL, parent::getLastErrors() ) ); }
[ "public", "static", "function", "FromFormat", "(", "string", "$", "format", ",", "$", "time", ",", "\\", "DateTimeZone", "$", "timezone", "=", "null", ")", ":", "DateTime", "{", "if", "(", "$", "timezone", "!==", "null", ")", "{", "$", "dt", "=", "parent", "::", "createFromFormat", "(", "$", "format", ",", "$", "time", ",", "$", "timezone", ")", ";", "}", "else", "{", "$", "dt", "=", "parent", "::", "createFromFormat", "(", "$", "format", ",", "$", "time", ")", ";", "}", "if", "(", "$", "dt", "instanceof", "\\", "DateTime", ")", "{", "return", "static", "::", "FromDateTime", "(", "$", "dt", ")", ";", "}", "throw", "new", "ArgumentError", "(", "'format'", ",", "$", "format", ",", "'Date'", ",", "\\", "join", "(", "\\", "PHP_EOL", ",", "parent", "::", "getLastErrors", "(", ")", ")", ")", ";", "}" ]
Create a DateTime instance from a specific format. @param string $format @param string $time @param \DateTimeZone $timezone @throws \Beluga\ArgumentError @return \Beluga\Date\DateTime
[ "Create", "a", "DateTime", "instance", "from", "a", "specific", "format", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L1340-L1363
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.Now
public static function Now( \DateTimeZone $timezone = null, bool $useDayStart = false, bool $useDayEnd = false ) : DateTime { $dt = new DateTime( 'now', $timezone ); if ( $useDayStart ) { $dt->setTime( 0, 0, 0 ); } else if ( $useDayEnd ) { $dt->setTime( 23, 59, 59 ); } return $dt; }
php
public static function Now( \DateTimeZone $timezone = null, bool $useDayStart = false, bool $useDayEnd = false ) : DateTime { $dt = new DateTime( 'now', $timezone ); if ( $useDayStart ) { $dt->setTime( 0, 0, 0 ); } else if ( $useDayEnd ) { $dt->setTime( 23, 59, 59 ); } return $dt; }
[ "public", "static", "function", "Now", "(", "\\", "DateTimeZone", "$", "timezone", "=", "null", ",", "bool", "$", "useDayStart", "=", "false", ",", "bool", "$", "useDayEnd", "=", "false", ")", ":", "DateTime", "{", "$", "dt", "=", "new", "DateTime", "(", "'now'", ",", "$", "timezone", ")", ";", "if", "(", "$", "useDayStart", ")", "{", "$", "dt", "->", "setTime", "(", "0", ",", "0", ",", "0", ")", ";", "}", "else", "if", "(", "$", "useDayEnd", ")", "{", "$", "dt", "->", "setTime", "(", "23", ",", "59", ",", "59", ")", ";", "}", "return", "$", "dt", ";", "}" ]
Init's a \Beluga\Date\DateTime with current DateTime and returns it. @param \DateTimeZone $timezone @param boolean $useDayStart Set 00:00:00 as time? (default=FALSE) @param boolean $useDayEnd Set 23:59:59 as time? (default=FALSE) @return \Beluga\Date\DateTime
[ "Init", "s", "a", "\\", "Beluga", "\\", "Date", "\\", "DateTime", "with", "current", "DateTime", "and", "returns", "it", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L1471-L1488
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.FromFile
public static function FromFile( string $file, bool $checkIfFileExists = false ) { if ( $checkIfFileExists && ! \file_exists( $file ) ) { return false; } try { return DateTime::Parse( \filemtime( $file ) ); } catch ( \Throwable $ex ) { $ex = null; return false; } }
php
public static function FromFile( string $file, bool $checkIfFileExists = false ) { if ( $checkIfFileExists && ! \file_exists( $file ) ) { return false; } try { return DateTime::Parse( \filemtime( $file ) ); } catch ( \Throwable $ex ) { $ex = null; return false; } }
[ "public", "static", "function", "FromFile", "(", "string", "$", "file", ",", "bool", "$", "checkIfFileExists", "=", "false", ")", "{", "if", "(", "$", "checkIfFileExists", "&&", "!", "\\", "file_exists", "(", "$", "file", ")", ")", "{", "return", "false", ";", "}", "try", "{", "return", "DateTime", "::", "Parse", "(", "\\", "filemtime", "(", "$", "file", ")", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "ex", ")", "{", "$", "ex", "=", "null", ";", "return", "false", ";", "}", "}" ]
Gets the last change DateTime of defined file. @param string $file Get the last change time from this file. @param boolean $checkIfFileExists Check if the file exists, before getting the datetime. (default=FALSE) @return \Beluga\Date\DateTime|bool Returns the DateTime, or boolean FALSE if does not exist or is not accessible by PHP.
[ "Gets", "the", "last", "change", "DateTime", "of", "defined", "file", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L1497-L1515
train
SagittariusX/Beluga.Date
src/Beluga/Date/DateTime.php
DateTime.GetDaysInMonth
public static function GetDaysInMonth( int $year, int $month ) : int { $dt = new \DateTime(); $dt->setDate( $year, $month, 2 ); $dt->setTime( 0, 0, 2 ); return \intval( $dt->format( 't' ) ); }
php
public static function GetDaysInMonth( int $year, int $month ) : int { $dt = new \DateTime(); $dt->setDate( $year, $month, 2 ); $dt->setTime( 0, 0, 2 ); return \intval( $dt->format( 't' ) ); }
[ "public", "static", "function", "GetDaysInMonth", "(", "int", "$", "year", ",", "int", "$", "month", ")", ":", "int", "{", "$", "dt", "=", "new", "\\", "DateTime", "(", ")", ";", "$", "dt", "->", "setDate", "(", "$", "year", ",", "$", "month", ",", "2", ")", ";", "$", "dt", "->", "setTime", "(", "0", ",", "0", ",", "2", ")", ";", "return", "\\", "intval", "(", "$", "dt", "->", "format", "(", "'t'", ")", ")", ";", "}" ]
Gets the days of the defined month in defined year. @param integer $year @param integer $month @return integer
[ "Gets", "the", "days", "of", "the", "defined", "month", "in", "defined", "year", "." ]
1bd28500e81eb5db8502e58506ebeb9268154884
https://github.com/SagittariusX/Beluga.Date/blob/1bd28500e81eb5db8502e58506ebeb9268154884/src/Beluga/Date/DateTime.php#L1524-L1533
train
ekyna/Table
Source/AbstractAdapter.php
AbstractAdapter.initializeFiltering
protected function initializeFiltering(ContextInterface $context) { $activeFilters = $context->getActiveFilters(); foreach ($activeFilters as $activeFilter) { $filterName = $activeFilter->getFilterName(); if ($this->table->hasFilter($filterName)) { $this->table->getFilter($filterName)->applyFilter($this, $activeFilter); } } }
php
protected function initializeFiltering(ContextInterface $context) { $activeFilters = $context->getActiveFilters(); foreach ($activeFilters as $activeFilter) { $filterName = $activeFilter->getFilterName(); if ($this->table->hasFilter($filterName)) { $this->table->getFilter($filterName)->applyFilter($this, $activeFilter); } } }
[ "protected", "function", "initializeFiltering", "(", "ContextInterface", "$", "context", ")", "{", "$", "activeFilters", "=", "$", "context", "->", "getActiveFilters", "(", ")", ";", "foreach", "(", "$", "activeFilters", "as", "$", "activeFilter", ")", "{", "$", "filterName", "=", "$", "activeFilter", "->", "getFilterName", "(", ")", ";", "if", "(", "$", "this", "->", "table", "->", "hasFilter", "(", "$", "filterName", ")", ")", "{", "$", "this", "->", "table", "->", "getFilter", "(", "$", "filterName", ")", "->", "applyFilter", "(", "$", "this", ",", "$", "activeFilter", ")", ";", "}", "}", "}" ]
Initializes filtering by applying all active filters through the related filter types. @param ContextInterface $context
[ "Initializes", "filtering", "by", "applying", "all", "active", "filters", "through", "the", "related", "filter", "types", "." ]
6f06e8fd8a3248d52f3a91f10508471344db311a
https://github.com/ekyna/Table/blob/6f06e8fd8a3248d52f3a91f10508471344db311a/Source/AbstractAdapter.php#L124-L134
train
ekyna/Table
Source/AbstractAdapter.php
AbstractAdapter.initializeSorting
protected function initializeSorting(ContextInterface $context) { if (null !== $activeSort = $context->getActiveSort()) { $columnName = $activeSort->getColumnName(); if ($this->table->hasColumn($columnName)) { $this->table->getColumn($columnName)->applySort($this, $activeSort); } } }
php
protected function initializeSorting(ContextInterface $context) { if (null !== $activeSort = $context->getActiveSort()) { $columnName = $activeSort->getColumnName(); if ($this->table->hasColumn($columnName)) { $this->table->getColumn($columnName)->applySort($this, $activeSort); } } }
[ "protected", "function", "initializeSorting", "(", "ContextInterface", "$", "context", ")", "{", "if", "(", "null", "!==", "$", "activeSort", "=", "$", "context", "->", "getActiveSort", "(", ")", ")", "{", "$", "columnName", "=", "$", "activeSort", "->", "getColumnName", "(", ")", ";", "if", "(", "$", "this", "->", "table", "->", "hasColumn", "(", "$", "columnName", ")", ")", "{", "$", "this", "->", "table", "->", "getColumn", "(", "$", "columnName", ")", "->", "applySort", "(", "$", "this", ",", "$", "activeSort", ")", ";", "}", "}", "}" ]
Initializes sorting by applying all active sorts through the related column types. @param ContextInterface $context
[ "Initializes", "sorting", "by", "applying", "all", "active", "sorts", "through", "the", "related", "column", "types", "." ]
6f06e8fd8a3248d52f3a91f10508471344db311a
https://github.com/ekyna/Table/blob/6f06e8fd8a3248d52f3a91f10508471344db311a/Source/AbstractAdapter.php#L141-L149
train
MatiasNAmendola/slimpower-jwt
src/RandomStringGenerator.php
RandomStringGenerator.generateWithCustomAlphabet
public static function generateWithCustomAlphabet($customAlphabet = '0123456789ABCDEF', $tokenLength = 32) { // Set initial alphabet. $generator = new RandomStringGenerator($customAlphabet); // Change alphabet whenever needed. //$generator->setAlphabet($customAlphabet); // Call method to generate random string. $token = $generator->generate($tokenLength); return $token; }
php
public static function generateWithCustomAlphabet($customAlphabet = '0123456789ABCDEF', $tokenLength = 32) { // Set initial alphabet. $generator = new RandomStringGenerator($customAlphabet); // Change alphabet whenever needed. //$generator->setAlphabet($customAlphabet); // Call method to generate random string. $token = $generator->generate($tokenLength); return $token; }
[ "public", "static", "function", "generateWithCustomAlphabet", "(", "$", "customAlphabet", "=", "'0123456789ABCDEF'", ",", "$", "tokenLength", "=", "32", ")", "{", "// Set initial alphabet.", "$", "generator", "=", "new", "RandomStringGenerator", "(", "$", "customAlphabet", ")", ";", "// Change alphabet whenever needed.", "//$generator->setAlphabet($customAlphabet);", "// Call method to generate random string.", "$", "token", "=", "$", "generator", "->", "generate", "(", "$", "tokenLength", ")", ";", "return", "$", "token", ";", "}" ]
Generate token with custom alphabet @param string $customAlphabet Set custom alphabet @param int $tokenLength Set token length. @return string
[ "Generate", "token", "with", "custom", "alphabet" ]
5afc151e8a37b06fe6cb6a44ff776e7ec9f40e98
https://github.com/MatiasNAmendola/slimpower-jwt/blob/5afc151e8a37b06fe6cb6a44ff776e7ec9f40e98/src/RandomStringGenerator.php#L85-L96
train
ndavison/groundwork-framework
src/Groundwork/Classes/Application.php
Application.init
public function init() { $this->register('request', function($app) { return new Request($app->config['baseurl']); }); $this->register('response', function($app) { return new Response(); }); $this->register('router', function($app) { return new Router(); }); // Register the app's IoC binds $app = $this; require $this->config['appdir'] . '/iocbinds.php'; // Register the app's routes $router = $this->get('router'); require $this->config['appdir'] . '/routes.php'; }
php
public function init() { $this->register('request', function($app) { return new Request($app->config['baseurl']); }); $this->register('response', function($app) { return new Response(); }); $this->register('router', function($app) { return new Router(); }); // Register the app's IoC binds $app = $this; require $this->config['appdir'] . '/iocbinds.php'; // Register the app's routes $router = $this->get('router'); require $this->config['appdir'] . '/routes.php'; }
[ "public", "function", "init", "(", ")", "{", "$", "this", "->", "register", "(", "'request'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "Request", "(", "$", "app", "->", "config", "[", "'baseurl'", "]", ")", ";", "}", ")", ";", "$", "this", "->", "register", "(", "'response'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "Response", "(", ")", ";", "}", ")", ";", "$", "this", "->", "register", "(", "'router'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "Router", "(", ")", ";", "}", ")", ";", "// Register the app's IoC binds", "$", "app", "=", "$", "this", ";", "require", "$", "this", "->", "config", "[", "'appdir'", "]", ".", "'/iocbinds.php'", ";", "// Register the app's routes", "$", "router", "=", "$", "this", "->", "get", "(", "'router'", ")", ";", "require", "$", "this", "->", "config", "[", "'appdir'", "]", ".", "'/routes.php'", ";", "}" ]
Initialise the IoC aliases and routes.
[ "Initialise", "the", "IoC", "aliases", "and", "routes", "." ]
c3d22a1410c8d8a07b4ca1f99a35a1181516cd6c
https://github.com/ndavison/groundwork-framework/blob/c3d22a1410c8d8a07b4ca1f99a35a1181516cd6c/src/Groundwork/Classes/Application.php#L30-L51
train
frogsystem/legacy-polls
src/Services/Routes.php
Routes.registerRoutes
public function registerRoutes(Map $map) { $map->attach('legacy.', '/', function (Map $map) { $map->get('polls', 'polls/', $this->controller(PollsController::class, 'polls'))->allows(['POST']); }); }
php
public function registerRoutes(Map $map) { $map->attach('legacy.', '/', function (Map $map) { $map->get('polls', 'polls/', $this->controller(PollsController::class, 'polls'))->allows(['POST']); }); }
[ "public", "function", "registerRoutes", "(", "Map", "$", "map", ")", "{", "$", "map", "->", "attach", "(", "'legacy.'", ",", "'/'", ",", "function", "(", "Map", "$", "map", ")", "{", "$", "map", "->", "get", "(", "'polls'", ",", "'polls/'", ",", "$", "this", "->", "controller", "(", "PollsController", "::", "class", ",", "'polls'", ")", ")", "->", "allows", "(", "[", "'POST'", "]", ")", ";", "}", ")", ";", "}" ]
Add the legacy route @param Map $map @return mixed|void
[ "Add", "the", "legacy", "route" ]
25f5f28ac6d0dda327e84b7e587f602da6995703
https://github.com/frogsystem/legacy-polls/blob/25f5f28ac6d0dda327e84b7e587f602da6995703/src/Services/Routes.php#L19-L24
train
SlaxWeb/Config
src/Container.php
Container.load
public function load( string $resourceName, bool $prependResourceName = false ) { switch ($this->_handler->load($resourceName, $prependResourceName)) { case Handler::CONFIG_PARSE_ERROR: throw new Exception\ConfigParseException( "Error parsing '{$resourceName}' configuration resource" ); case Handler::CONFIG_RESOURCE_NOT_FOUND: throw new Exception\ConfigResourceNotFoundException( "Error '{$resourceName}' configuration resource not found" ); } }
php
public function load( string $resourceName, bool $prependResourceName = false ) { switch ($this->_handler->load($resourceName, $prependResourceName)) { case Handler::CONFIG_PARSE_ERROR: throw new Exception\ConfigParseException( "Error parsing '{$resourceName}' configuration resource" ); case Handler::CONFIG_RESOURCE_NOT_FOUND: throw new Exception\ConfigResourceNotFoundException( "Error '{$resourceName}' configuration resource not found" ); } }
[ "public", "function", "load", "(", "string", "$", "resourceName", ",", "bool", "$", "prependResourceName", "=", "false", ")", "{", "switch", "(", "$", "this", "->", "_handler", "->", "load", "(", "$", "resourceName", ",", "$", "prependResourceName", ")", ")", "{", "case", "Handler", "::", "CONFIG_PARSE_ERROR", ":", "throw", "new", "Exception", "\\", "ConfigParseException", "(", "\"Error parsing '{$resourceName}' configuration resource\"", ")", ";", "case", "Handler", "::", "CONFIG_RESOURCE_NOT_FOUND", ":", "throw", "new", "Exception", "\\", "ConfigResourceNotFoundException", "(", "\"Error '{$resourceName}' configuration resource not found\"", ")", ";", "}", "}" ]
Load config resource Combine the received configuration resource name with the '_configLocation' protected property, and pass it to the config handler. @param string $resourceName Name of the configuration resource @param bool $prependResourceName If the resource name should be prepended to each config key @return void
[ "Load", "config", "resource" ]
92e75c3538d3903e00f5c52507bc0a322c4d1f11
https://github.com/SlaxWeb/Config/blob/92e75c3538d3903e00f5c52507bc0a322c4d1f11/src/Container.php#L115-L129
train
AdamB7586/menu-builder
src/Navigation.php
Navigation.setNavigationClass
public function setNavigationClass($class) { if(is_string($class) && !empty(trim($class))){ $this->menuElements['ul_class'] = $class; } if((is_string($class) && empty(trim($class))) || $class === false){ $this->menuElements['ul_class'] = ''; } return $this; }
php
public function setNavigationClass($class) { if(is_string($class) && !empty(trim($class))){ $this->menuElements['ul_class'] = $class; } if((is_string($class) && empty(trim($class))) || $class === false){ $this->menuElements['ul_class'] = ''; } return $this; }
[ "public", "function", "setNavigationClass", "(", "$", "class", ")", "{", "if", "(", "is_string", "(", "$", "class", ")", "&&", "!", "empty", "(", "trim", "(", "$", "class", ")", ")", ")", "{", "$", "this", "->", "menuElements", "[", "'ul_class'", "]", "=", "$", "class", ";", "}", "if", "(", "(", "is_string", "(", "$", "class", ")", "&&", "empty", "(", "trim", "(", "$", "class", ")", ")", ")", "||", "$", "class", "===", "false", ")", "{", "$", "this", "->", "menuElements", "[", "'ul_class'", "]", "=", "''", ";", "}", "return", "$", "this", ";", "}" ]
Set the main navigation UL class @param string|false $class This should be a string containing the class you want to set on the main UL element @return $this
[ "Set", "the", "main", "navigation", "UL", "class" ]
dbc192bca7d59475068c19d1a07a039e5f997ee4
https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Navigation.php#L94-L102
train
AdamB7586/menu-builder
src/Navigation.php
Navigation.setNavigationID
public function setNavigationID($id) { if(is_string($id) && !empty(trim($id))){ $this->menuElements['ul_id'] = $id; } if((is_string($id) && empty(trim($id))) || $id === false){ $this->menuElements['ul_id'] = ''; } return $this; }
php
public function setNavigationID($id) { if(is_string($id) && !empty(trim($id))){ $this->menuElements['ul_id'] = $id; } if((is_string($id) && empty(trim($id))) || $id === false){ $this->menuElements['ul_id'] = ''; } return $this; }
[ "public", "function", "setNavigationID", "(", "$", "id", ")", "{", "if", "(", "is_string", "(", "$", "id", ")", "&&", "!", "empty", "(", "trim", "(", "$", "id", ")", ")", ")", "{", "$", "this", "->", "menuElements", "[", "'ul_id'", "]", "=", "$", "id", ";", "}", "if", "(", "(", "is_string", "(", "$", "id", ")", "&&", "empty", "(", "trim", "(", "$", "id", ")", ")", ")", "||", "$", "id", "===", "false", ")", "{", "$", "this", "->", "menuElements", "[", "'ul_id'", "]", "=", "''", ";", "}", "return", "$", "this", ";", "}" ]
Set the main navigation ID element @param string $id This should be a string containing the id you want to set on the main UL element @return $this
[ "Set", "the", "main", "navigation", "ID", "element" ]
dbc192bca7d59475068c19d1a07a039e5f997ee4
https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Navigation.php#L117-L125
train
AdamB7586/menu-builder
src/Navigation.php
Navigation.setDefaultClass
public function setDefaultClass($class, $element = 'li'){ if(in_array($element, ['a', 'li', 'ul']) && ((is_string($class) && !empty(trim($class))) || is_bool($class))) { $this->menuElements[strtolower($element).'_default'] = $class; } elseif(in_array($element, $this->allowedElements)){ $this->menuElements[strtolower($element)] = $class; } return $this; }
php
public function setDefaultClass($class, $element = 'li'){ if(in_array($element, ['a', 'li', 'ul']) && ((is_string($class) && !empty(trim($class))) || is_bool($class))) { $this->menuElements[strtolower($element).'_default'] = $class; } elseif(in_array($element, $this->allowedElements)){ $this->menuElements[strtolower($element)] = $class; } return $this; }
[ "public", "function", "setDefaultClass", "(", "$", "class", ",", "$", "element", "=", "'li'", ")", "{", "if", "(", "in_array", "(", "$", "element", ",", "[", "'a'", ",", "'li'", ",", "'ul'", "]", ")", "&&", "(", "(", "is_string", "(", "$", "class", ")", "&&", "!", "empty", "(", "trim", "(", "$", "class", ")", ")", ")", "||", "is_bool", "(", "$", "class", ")", ")", ")", "{", "$", "this", "->", "menuElements", "[", "strtolower", "(", "$", "element", ")", ".", "'_default'", "]", "=", "$", "class", ";", "}", "elseif", "(", "in_array", "(", "$", "element", ",", "$", "this", "->", "allowedElements", ")", ")", "{", "$", "this", "->", "menuElements", "[", "strtolower", "(", "$", "element", ")", "]", "=", "$", "class", ";", "}", "return", "$", "this", ";", "}" ]
Change the default class assigned to all elements of a certain type in the menu @param string|boolean $class This should be the class you want to assign to all elements or false for no default @param string $element The element that you are changing the default for can be 'a', 'li' or 'ul' @return $this
[ "Change", "the", "default", "class", "assigned", "to", "all", "elements", "of", "a", "certain", "type", "in", "the", "menu" ]
dbc192bca7d59475068c19d1a07a039e5f997ee4
https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Navigation.php#L161-L169
train
AdamB7586/menu-builder
src/Navigation.php
Navigation.setCurrentURI
public function setCurrentURI($uri) { if(is_string($uri) && !empty(trim($uri))){ $this->currentURI = $uri; $this->currentArray = Levels::getCurrent($this->navigation, $this->currentURI); } else{ throw new InvalidArgumentException( '$uri must be a valid string when seting the current URI' ); } return $this; }
php
public function setCurrentURI($uri) { if(is_string($uri) && !empty(trim($uri))){ $this->currentURI = $uri; $this->currentArray = Levels::getCurrent($this->navigation, $this->currentURI); } else{ throw new InvalidArgumentException( '$uri must be a valid string when seting the current URI' ); } return $this; }
[ "public", "function", "setCurrentURI", "(", "$", "uri", ")", "{", "if", "(", "is_string", "(", "$", "uri", ")", "&&", "!", "empty", "(", "trim", "(", "$", "uri", ")", ")", ")", "{", "$", "this", "->", "currentURI", "=", "$", "uri", ";", "$", "this", "->", "currentArray", "=", "Levels", "::", "getCurrent", "(", "$", "this", "->", "navigation", ",", "$", "this", "->", "currentURI", ")", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "'$uri must be a valid string when seting the current URI'", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the current active URI @param string $uri This should be the string URI of the active link @return $this
[ "Sets", "the", "current", "active", "URI" ]
dbc192bca7d59475068c19d1a07a039e5f997ee4
https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Navigation.php#L176-L187
train
AdamB7586/menu-builder
src/Navigation.php
Navigation.hasLink
public function hasLink($link) { $found = false; array_walk_recursive($this->navigation, function($value, $key) use (&$found, $link) { if ($value == $link && $key === 'uri') { $found = true; } }); return $found; }
php
public function hasLink($link) { $found = false; array_walk_recursive($this->navigation, function($value, $key) use (&$found, $link) { if ($value == $link && $key === 'uri') { $found = true; } }); return $found; }
[ "public", "function", "hasLink", "(", "$", "link", ")", "{", "$", "found", "=", "false", ";", "array_walk_recursive", "(", "$", "this", "->", "navigation", ",", "function", "(", "$", "value", ",", "$", "key", ")", "use", "(", "&", "$", "found", ",", "$", "link", ")", "{", "if", "(", "$", "value", "==", "$", "link", "&&", "$", "key", "===", "'uri'", ")", "{", "$", "found", "=", "true", ";", "}", "}", ")", ";", "return", "$", "found", ";", "}" ]
Checks to see if a link exists within the current navigation array @param string $link The link you are checking to see if the exists in the array @return boolean If the link exists returns true else returns false
[ "Checks", "to", "see", "if", "a", "link", "exists", "within", "the", "current", "navigation", "array" ]
dbc192bca7d59475068c19d1a07a039e5f997ee4
https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Navigation.php#L277-L285
train
AdamB7586/menu-builder
src/Navigation.php
Navigation.hasLinks
public function hasLinks($array) { if(is_array($array)) { foreach($array as $link) { if($this->hasLink($link) === false) { return false; } } return true; } return false; }
php
public function hasLinks($array) { if(is_array($array)) { foreach($array as $link) { if($this->hasLink($link) === false) { return false; } } return true; } return false; }
[ "public", "function", "hasLinks", "(", "$", "array", ")", "{", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "foreach", "(", "$", "array", "as", "$", "link", ")", "{", "if", "(", "$", "this", "->", "hasLink", "(", "$", "link", ")", "===", "false", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks to see if an array of links exist within the current navigation array @param array $array an array containing the links @return boolean If all of the links exist within the current navigation array return true else returns false
[ "Checks", "to", "see", "if", "an", "array", "of", "links", "exist", "within", "the", "current", "navigation", "array" ]
dbc192bca7d59475068c19d1a07a039e5f997ee4
https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Navigation.php#L292-L302
train
AdamB7586/menu-builder
src/Navigation.php
Navigation.render
public function render() { return Menu::build($this->navigation, $this->menuElements, $this->currentArray, $this->getActiveClass(), $this->getStartLevel(), $this->getMaxLevels(), $this->caretElement, $this->dropdownLinkExtras); }
php
public function render() { return Menu::build($this->navigation, $this->menuElements, $this->currentArray, $this->getActiveClass(), $this->getStartLevel(), $this->getMaxLevels(), $this->caretElement, $this->dropdownLinkExtras); }
[ "public", "function", "render", "(", ")", "{", "return", "Menu", "::", "build", "(", "$", "this", "->", "navigation", ",", "$", "this", "->", "menuElements", ",", "$", "this", "->", "currentArray", ",", "$", "this", "->", "getActiveClass", "(", ")", ",", "$", "this", "->", "getStartLevel", "(", ")", ",", "$", "this", "->", "getMaxLevels", "(", ")", ",", "$", "this", "->", "caretElement", ",", "$", "this", "->", "dropdownLinkExtras", ")", ";", "}" ]
Returns the HTML navigation string @return string THe formatted menu item will be returned
[ "Returns", "the", "HTML", "navigation", "string" ]
dbc192bca7d59475068c19d1a07a039e5f997ee4
https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Navigation.php#L316-L318
train
AdamB7586/menu-builder
src/Navigation.php
Navigation.renderBreadcrumb
public function renderBreadcrumb($class = 'breadcrumb', $itemClass = 'breadcrumb-item', $list = true) { $breadcrumb = new Breadcrumb(); $breadcrumb->navArray = $this->navigation; return $breadcrumb->setBreacrumbLinks($this->currentArray)->createBreadcrumb($class, $itemClass, $list); }
php
public function renderBreadcrumb($class = 'breadcrumb', $itemClass = 'breadcrumb-item', $list = true) { $breadcrumb = new Breadcrumb(); $breadcrumb->navArray = $this->navigation; return $breadcrumb->setBreacrumbLinks($this->currentArray)->createBreadcrumb($class, $itemClass, $list); }
[ "public", "function", "renderBreadcrumb", "(", "$", "class", "=", "'breadcrumb'", ",", "$", "itemClass", "=", "'breadcrumb-item'", ",", "$", "list", "=", "true", ")", "{", "$", "breadcrumb", "=", "new", "Breadcrumb", "(", ")", ";", "$", "breadcrumb", "->", "navArray", "=", "$", "this", "->", "navigation", ";", "return", "$", "breadcrumb", "->", "setBreacrumbLinks", "(", "$", "this", "->", "currentArray", ")", "->", "createBreadcrumb", "(", "$", "class", ",", "$", "itemClass", ",", "$", "list", ")", ";", "}" ]
Renders a breadcrumb menu @param string $class The class to assign to the element @param string $itemClass The class to assign to each item @param boolean $list If the menu is a list set to true else set to false @return string
[ "Renders", "a", "breadcrumb", "menu" ]
dbc192bca7d59475068c19d1a07a039e5f997ee4
https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Navigation.php#L327-L331
train
narrowspark/arr
src/Arr/Arr.php
Arr.get
public static function get(array $array, $key = null, $default = null) { if ($key === null) { return $array; } if (isset($array[$key])) { return static::value($array[$key]); } foreach (explode('.', (string) $key) as $segment) { if (! array_key_exists($segment, $array)) { return static::value($default); } $array = $array[$segment]; } return $array; }
php
public static function get(array $array, $key = null, $default = null) { if ($key === null) { return $array; } if (isset($array[$key])) { return static::value($array[$key]); } foreach (explode('.', (string) $key) as $segment) { if (! array_key_exists($segment, $array)) { return static::value($default); } $array = $array[$segment]; } return $array; }
[ "public", "static", "function", "get", "(", "array", "$", "array", ",", "$", "key", "=", "null", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "key", "===", "null", ")", "{", "return", "$", "array", ";", "}", "if", "(", "isset", "(", "$", "array", "[", "$", "key", "]", ")", ")", "{", "return", "static", "::", "value", "(", "$", "array", "[", "$", "key", "]", ")", ";", "}", "foreach", "(", "explode", "(", "'.'", ",", "(", "string", ")", "$", "key", ")", "as", "$", "segment", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "segment", ",", "$", "array", ")", ")", "{", "return", "static", "::", "value", "(", "$", "default", ")", ";", "}", "$", "array", "=", "$", "array", "[", "$", "segment", "]", ";", "}", "return", "$", "array", ";", "}" ]
Get an item from an array using "dot" notation. If key dont exist, you get a default value back. @param array $array @param string|int|null $key @param mixed $default @return mixed
[ "Get", "an", "item", "from", "an", "array", "using", "dot", "notation", ".", "If", "key", "dont", "exist", "you", "get", "a", "default", "value", "back", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L94-L113
train
narrowspark/arr
src/Arr/Arr.php
Arr.add
public static function add(array $array, $key, $value): array { $target = static::get($array, $key, []); if (! is_array($target)) { $target = [$target]; } $target[] = $value; $array = static::set($array, $key, $target); return $array; }
php
public static function add(array $array, $key, $value): array { $target = static::get($array, $key, []); if (! is_array($target)) { $target = [$target]; } $target[] = $value; $array = static::set($array, $key, $target); return $array; }
[ "public", "static", "function", "add", "(", "array", "$", "array", ",", "$", "key", ",", "$", "value", ")", ":", "array", "{", "$", "target", "=", "static", "::", "get", "(", "$", "array", ",", "$", "key", ",", "[", "]", ")", ";", "if", "(", "!", "is_array", "(", "$", "target", ")", ")", "{", "$", "target", "=", "[", "$", "target", "]", ";", "}", "$", "target", "[", "]", "=", "$", "value", ";", "$", "array", "=", "static", "::", "set", "(", "$", "array", ",", "$", "key", ",", "$", "target", ")", ";", "return", "$", "array", ";", "}" ]
Add an element to the array at a specific location using the "dot" notation. @param array $array @param string[]|callable|null $key @param mixed $value @return array
[ "Add", "an", "element", "to", "the", "array", "at", "a", "specific", "location", "using", "the", "dot", "notation", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L125-L137
train
narrowspark/arr
src/Arr/Arr.php
Arr.any
public static function any(array $array, $keys): bool { foreach ((array) $keys as $key) { if (static::has($array, $key)) { return true; } } return false; }
php
public static function any(array $array, $keys): bool { foreach ((array) $keys as $key) { if (static::has($array, $key)) { return true; } } return false; }
[ "public", "static", "function", "any", "(", "array", "$", "array", ",", "$", "keys", ")", ":", "bool", "{", "foreach", "(", "(", "array", ")", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "static", "::", "has", "(", "$", "array", ",", "$", "key", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if any item or items exist in an array using "dot" notation. @param array $array @param string|array $keys @return bool
[ "Check", "if", "any", "item", "or", "items", "exist", "in", "an", "array", "using", "dot", "notation", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L147-L156
train
narrowspark/arr
src/Arr/Arr.php
Arr.update
public static function update(array $array, string $key, callable $callback) { $keys = explode('.', $key); $current = &$array; foreach ($keys as $key) { if (! isset($current[$key])) { return $array; } $current = &$current[$key]; } $current = $callback($current); return $array; }
php
public static function update(array $array, string $key, callable $callback) { $keys = explode('.', $key); $current = &$array; foreach ($keys as $key) { if (! isset($current[$key])) { return $array; } $current = &$current[$key]; } $current = $callback($current); return $array; }
[ "public", "static", "function", "update", "(", "array", "$", "array", ",", "string", "$", "key", ",", "callable", "$", "callback", ")", "{", "$", "keys", "=", "explode", "(", "'.'", ",", "$", "key", ")", ";", "$", "current", "=", "&", "$", "array", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "current", "[", "$", "key", "]", ")", ")", "{", "return", "$", "array", ";", "}", "$", "current", "=", "&", "$", "current", "[", "$", "key", "]", ";", "}", "$", "current", "=", "$", "callback", "(", "$", "current", ")", ";", "return", "$", "array", ";", "}" ]
Updates data at the given path. @param array $array @param sting $key @param callable $callback Callback to update the value. @return mixed Updated data.
[ "Updates", "data", "at", "the", "given", "path", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L227-L243
train
narrowspark/arr
src/Arr/Arr.php
Arr.closest
public static function closest(array $array, string $value) { sort($array); $closest = $array[0]; for ($i = 1, $j = count($array), $k = 0; $i < $j; $i++, $k++) { $middleValue = ((int) $array[$i] - (int) $array[$k]) / 2 + (int) $array[$k]; if ($value >= $middleValue) { $closest = $array[$i]; } } return static::value($closest); }
php
public static function closest(array $array, string $value) { sort($array); $closest = $array[0]; for ($i = 1, $j = count($array), $k = 0; $i < $j; $i++, $k++) { $middleValue = ((int) $array[$i] - (int) $array[$k]) / 2 + (int) $array[$k]; if ($value >= $middleValue) { $closest = $array[$i]; } } return static::value($closest); }
[ "public", "static", "function", "closest", "(", "array", "$", "array", ",", "string", "$", "value", ")", "{", "sort", "(", "$", "array", ")", ";", "$", "closest", "=", "$", "array", "[", "0", "]", ";", "for", "(", "$", "i", "=", "1", ",", "$", "j", "=", "count", "(", "$", "array", ")", ",", "$", "k", "=", "0", ";", "$", "i", "<", "$", "j", ";", "$", "i", "++", ",", "$", "k", "++", ")", "{", "$", "middleValue", "=", "(", "(", "int", ")", "$", "array", "[", "$", "i", "]", "-", "(", "int", ")", "$", "array", "[", "$", "k", "]", ")", "/", "2", "+", "(", "int", ")", "$", "array", "[", "$", "k", "]", ";", "if", "(", "$", "value", ">=", "$", "middleValue", ")", "{", "$", "closest", "=", "$", "array", "[", "$", "i", "]", ";", "}", "}", "return", "static", "::", "value", "(", "$", "closest", ")", ";", "}" ]
Return the closest found value from array. @param array $array @param string $value @return mixed
[ "Return", "the", "closest", "found", "value", "from", "array", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L395-L409
train
narrowspark/arr
src/Arr/Arr.php
Arr.every
public static function every(array $array, int $step, int $offset = 0): array { $new = []; $position = 0; foreach ($array as $key => $item) { if ($position % $step === $offset) { $new[] = $item; } ++$position; } return $new; }
php
public static function every(array $array, int $step, int $offset = 0): array { $new = []; $position = 0; foreach ($array as $key => $item) { if ($position % $step === $offset) { $new[] = $item; } ++$position; } return $new; }
[ "public", "static", "function", "every", "(", "array", "$", "array", ",", "int", "$", "step", ",", "int", "$", "offset", "=", "0", ")", ":", "array", "{", "$", "new", "=", "[", "]", ";", "$", "position", "=", "0", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "item", ")", "{", "if", "(", "$", "position", "%", "$", "step", "===", "$", "offset", ")", "{", "$", "new", "[", "]", "=", "$", "item", ";", "}", "++", "$", "position", ";", "}", "return", "$", "new", ";", "}" ]
Create a new array consisting of every n-th element. @param array $array @param int $step @param int $offset @return array
[ "Create", "a", "new", "array", "consisting", "of", "every", "n", "-", "th", "element", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L463-L478
train
narrowspark/arr
src/Arr/Arr.php
Arr.combine
public static function combine(array $array, callable $callback, bool $overwrite = true): array { $combined = []; foreach ($array as $key => $value) { $combinator = $callback($value, $key); // fix for hhvm #1871 bug if (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.10.0', '<=')) { $combinator->next(); } $index = $combinator->key(); if ($overwrite || ! isset($combined[$index])) { $combined[$index] = $combinator->current(); } } return $combined; }
php
public static function combine(array $array, callable $callback, bool $overwrite = true): array { $combined = []; foreach ($array as $key => $value) { $combinator = $callback($value, $key); // fix for hhvm #1871 bug if (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.10.0', '<=')) { $combinator->next(); } $index = $combinator->key(); if ($overwrite || ! isset($combined[$index])) { $combined[$index] = $combinator->current(); } } return $combined; }
[ "public", "static", "function", "combine", "(", "array", "$", "array", ",", "callable", "$", "callback", ",", "bool", "$", "overwrite", "=", "true", ")", ":", "array", "{", "$", "combined", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "combinator", "=", "$", "callback", "(", "$", "value", ",", "$", "key", ")", ";", "// fix for hhvm #1871 bug", "if", "(", "defined", "(", "'HHVM_VERSION'", ")", "&&", "version_compare", "(", "HHVM_VERSION", ",", "'3.10.0'", ",", "'<='", ")", ")", "{", "$", "combinator", "->", "next", "(", ")", ";", "}", "$", "index", "=", "$", "combinator", "->", "key", "(", ")", ";", "if", "(", "$", "overwrite", "||", "!", "isset", "(", "$", "combined", "[", "$", "index", "]", ")", ")", "{", "$", "combined", "[", "$", "index", "]", "=", "$", "combinator", "->", "current", "(", ")", ";", "}", "}", "return", "$", "combined", ";", "}" ]
Indexes an array depending on the values it contains. @param array $array @param callable $callback Function to combine values. @param bool $overwrite Should duplicate keys be overwritten? @return array Indexed values.
[ "Indexes", "an", "array", "depending", "on", "the", "values", "it", "contains", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L489-L509
train
narrowspark/arr
src/Arr/Arr.php
Arr.collapse
public static function collapse(array $array): array { $newArray = []; foreach ($array as $key => $value) { if (is_array($value)) { // strip any manually added '.' if (preg_match('/\./', (string) $key)) { $key = substr($key, 0, -2); } self::recurseCollapse($value, $newArray, (array) $key); } else { $newArray[$key] = $value; } } return $newArray; }
php
public static function collapse(array $array): array { $newArray = []; foreach ($array as $key => $value) { if (is_array($value)) { // strip any manually added '.' if (preg_match('/\./', (string) $key)) { $key = substr($key, 0, -2); } self::recurseCollapse($value, $newArray, (array) $key); } else { $newArray[$key] = $value; } } return $newArray; }
[ "public", "static", "function", "collapse", "(", "array", "$", "array", ")", ":", "array", "{", "$", "newArray", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "// strip any manually added '.'", "if", "(", "preg_match", "(", "'/\\./'", ",", "(", "string", ")", "$", "key", ")", ")", "{", "$", "key", "=", "substr", "(", "$", "key", ",", "0", ",", "-", "2", ")", ";", "}", "self", "::", "recurseCollapse", "(", "$", "value", ",", "$", "newArray", ",", "(", "array", ")", "$", "key", ")", ";", "}", "else", "{", "$", "newArray", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "newArray", ";", "}" ]
Collapse a nested array down to an array of flat key=>value pairs. @param array $array @return array
[ "Collapse", "a", "nested", "array", "down", "to", "an", "array", "of", "flat", "key", "=", ">", "value", "pairs", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L518-L536
train
narrowspark/arr
src/Arr/Arr.php
Arr.reindex
public static function reindex(array $array, array $map, bool $unmapped = true): array { $reindexed = $unmapped ? $array : []; foreach ($map as $from => $to) { if (isset($array[$from])) { $reindexed[$to] = $array[$from]; } } return $reindexed; }
php
public static function reindex(array $array, array $map, bool $unmapped = true): array { $reindexed = $unmapped ? $array : []; foreach ($map as $from => $to) { if (isset($array[$from])) { $reindexed[$to] = $array[$from]; } } return $reindexed; }
[ "public", "static", "function", "reindex", "(", "array", "$", "array", ",", "array", "$", "map", ",", "bool", "$", "unmapped", "=", "true", ")", ":", "array", "{", "$", "reindexed", "=", "$", "unmapped", "?", "$", "array", ":", "[", "]", ";", "foreach", "(", "$", "map", "as", "$", "from", "=>", "$", "to", ")", "{", "if", "(", "isset", "(", "$", "array", "[", "$", "from", "]", ")", ")", "{", "$", "reindexed", "[", "$", "to", "]", "=", "$", "array", "[", "$", "from", "]", ";", "}", "}", "return", "$", "reindexed", ";", "}" ]
Reindexes a list of values. @param array $array @param array $map An map of correspondances of the form ['currentIndex' => 'newIndex']. @param bool $unmapped Whether or not to keep keys that are not remapped. @return array
[ "Reindexes", "a", "list", "of", "values", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L598-L611
train
narrowspark/arr
src/Arr/Arr.php
Arr.extend
public static function extend(): array { $merged = []; foreach (func_get_args() as $array) { foreach ($array as $key => $value) { if (is_array($value) && static::has($merged, $key) && is_array($merged[$key])) { $merged[$key] = static::extend($merged[$key], $value); } else { $merged[$key] = $value; } } } return $merged; }
php
public static function extend(): array { $merged = []; foreach (func_get_args() as $array) { foreach ($array as $key => $value) { if (is_array($value) && static::has($merged, $key) && is_array($merged[$key])) { $merged[$key] = static::extend($merged[$key], $value); } else { $merged[$key] = $value; } } } return $merged; }
[ "public", "static", "function", "extend", "(", ")", ":", "array", "{", "$", "merged", "=", "[", "]", ";", "foreach", "(", "func_get_args", "(", ")", "as", "$", "array", ")", "{", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "static", "::", "has", "(", "$", "merged", ",", "$", "key", ")", "&&", "is_array", "(", "$", "merged", "[", "$", "key", "]", ")", ")", "{", "$", "merged", "[", "$", "key", "]", "=", "static", "::", "extend", "(", "$", "merged", "[", "$", "key", "]", ",", "$", "value", ")", ";", "}", "else", "{", "$", "merged", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "}", "return", "$", "merged", ";", "}" ]
Extend one array with another. @return array
[ "Extend", "one", "array", "with", "another", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L674-L689
train
narrowspark/arr
src/Arr/Arr.php
Arr.asHierarchy
public static function asHierarchy(array $array): array { $hierarchy = []; foreach ($array as $key => $value) { $segments = explode('.', (string) $key); $valueSegment = array_pop($segments); $branch = &$hierarchy; foreach ($segments as $segment) { if (! isset($branch[$segment])) { $branch[$segment] = []; } $branch = &$branch[$segment]; } $branch[$valueSegment] = $value; } return $hierarchy; }
php
public static function asHierarchy(array $array): array { $hierarchy = []; foreach ($array as $key => $value) { $segments = explode('.', (string) $key); $valueSegment = array_pop($segments); $branch = &$hierarchy; foreach ($segments as $segment) { if (! isset($branch[$segment])) { $branch[$segment] = []; } $branch = &$branch[$segment]; } $branch[$valueSegment] = $value; } return $hierarchy; }
[ "public", "static", "function", "asHierarchy", "(", "array", "$", "array", ")", ":", "array", "{", "$", "hierarchy", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "segments", "=", "explode", "(", "'.'", ",", "(", "string", ")", "$", "key", ")", ";", "$", "valueSegment", "=", "array_pop", "(", "$", "segments", ")", ";", "$", "branch", "=", "&", "$", "hierarchy", ";", "foreach", "(", "$", "segments", "as", "$", "segment", ")", "{", "if", "(", "!", "isset", "(", "$", "branch", "[", "$", "segment", "]", ")", ")", "{", "$", "branch", "[", "$", "segment", "]", "=", "[", "]", ";", "}", "$", "branch", "=", "&", "$", "branch", "[", "$", "segment", "]", ";", "}", "$", "branch", "[", "$", "valueSegment", "]", "=", "$", "value", ";", "}", "return", "$", "hierarchy", ";", "}" ]
Transforms a 1-dimensional array into a multi-dimensional one, exploding keys according to a separator. @param array $array @return array
[ "Transforms", "a", "1", "-", "dimensional", "array", "into", "a", "multi", "-", "dimensional", "one", "exploding", "keys", "according", "to", "a", "separator", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L699-L720
train
narrowspark/arr
src/Arr/Arr.php
Arr.groupBy
public static function groupBy(array $array, callable $callback = null): array { $callback = $callback ?: function ($value) { return $value; }; return array_reduce( $array, function ($buckets, $value) use ($callback) { $key = $callback($value); if (! array_key_exists($key, $buckets)) { $buckets[$key] = []; } $buckets[$key][] = $value; return $buckets; }, [] ); }
php
public static function groupBy(array $array, callable $callback = null): array { $callback = $callback ?: function ($value) { return $value; }; return array_reduce( $array, function ($buckets, $value) use ($callback) { $key = $callback($value); if (! array_key_exists($key, $buckets)) { $buckets[$key] = []; } $buckets[$key][] = $value; return $buckets; }, [] ); }
[ "public", "static", "function", "groupBy", "(", "array", "$", "array", ",", "callable", "$", "callback", "=", "null", ")", ":", "array", "{", "$", "callback", "=", "$", "callback", "?", ":", "function", "(", "$", "value", ")", "{", "return", "$", "value", ";", "}", ";", "return", "array_reduce", "(", "$", "array", ",", "function", "(", "$", "buckets", ",", "$", "value", ")", "use", "(", "$", "callback", ")", "{", "$", "key", "=", "$", "callback", "(", "$", "value", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "buckets", ")", ")", "{", "$", "buckets", "[", "$", "key", "]", "=", "[", "]", ";", "}", "$", "buckets", "[", "$", "key", "]", "[", "]", "=", "$", "value", ";", "return", "$", "buckets", ";", "}", ",", "[", "]", ")", ";", "}" ]
Separates elements from an array into groups. The function maps an element to the key that will be used for grouping. If no function is passed, the element itself will be used as key. @param array $array @param callable|null $callback @return array
[ "Separates", "elements", "from", "an", "array", "into", "groups", ".", "The", "function", "maps", "an", "element", "to", "the", "key", "that", "will", "be", "used", "for", "grouping", ".", "If", "no", "function", "is", "passed", "the", "element", "itself", "will", "be", "used", "as", "key", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L732-L753
train
narrowspark/arr
src/Arr/Arr.php
Arr.flatten
public static function flatten(array $array, string $separator = null, string $prepend = ''): array { $flattened = []; foreach ($array as $key => $value) { if (is_array($value)) { $flattened = array_merge($flattened, static::flatten($value, $separator, $prepend . $key . $separator)); } else { $flattened[$prepend . $key] = $value; } } return $flattened; }
php
public static function flatten(array $array, string $separator = null, string $prepend = ''): array { $flattened = []; foreach ($array as $key => $value) { if (is_array($value)) { $flattened = array_merge($flattened, static::flatten($value, $separator, $prepend . $key . $separator)); } else { $flattened[$prepend . $key] = $value; } } return $flattened; }
[ "public", "static", "function", "flatten", "(", "array", "$", "array", ",", "string", "$", "separator", "=", "null", ",", "string", "$", "prepend", "=", "''", ")", ":", "array", "{", "$", "flattened", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "flattened", "=", "array_merge", "(", "$", "flattened", ",", "static", "::", "flatten", "(", "$", "value", ",", "$", "separator", ",", "$", "prepend", ".", "$", "key", ".", "$", "separator", ")", ")", ";", "}", "else", "{", "$", "flattened", "[", "$", "prepend", ".", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "flattened", ";", "}" ]
Flatten a nested array to a separated key. @param array $array @param string|null $separator @param string $prepend @return array
[ "Flatten", "a", "nested", "array", "to", "a", "separated", "key", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L822-L835
train
narrowspark/arr
src/Arr/Arr.php
Arr.expand
public static function expand(array $array, string $prepend = ''): array { $results = []; if ($prepend) { $prepend .= '.'; } foreach ($array as $key => $value) { if ($prepend) { $pos = strpos($key, $prepend); if ($pos === 0) { $key = substr($key, strlen($prepend)); } } $results = static::set($results, $key, $value); } return $results; }
php
public static function expand(array $array, string $prepend = ''): array { $results = []; if ($prepend) { $prepend .= '.'; } foreach ($array as $key => $value) { if ($prepend) { $pos = strpos($key, $prepend); if ($pos === 0) { $key = substr($key, strlen($prepend)); } } $results = static::set($results, $key, $value); } return $results; }
[ "public", "static", "function", "expand", "(", "array", "$", "array", ",", "string", "$", "prepend", "=", "''", ")", ":", "array", "{", "$", "results", "=", "[", "]", ";", "if", "(", "$", "prepend", ")", "{", "$", "prepend", ".=", "'.'", ";", "}", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "prepend", ")", "{", "$", "pos", "=", "strpos", "(", "$", "key", ",", "$", "prepend", ")", ";", "if", "(", "$", "pos", "===", "0", ")", "{", "$", "key", "=", "substr", "(", "$", "key", ",", "strlen", "(", "$", "prepend", ")", ")", ";", "}", "}", "$", "results", "=", "static", "::", "set", "(", "$", "results", ",", "$", "key", ",", "$", "value", ")", ";", "}", "return", "$", "results", ";", "}" ]
Expand a flattened array with dots to a multi-dimensional associative array. @param array $array @param string $prepend @return array
[ "Expand", "a", "flattened", "array", "with", "dots", "to", "a", "multi", "-", "dimensional", "associative", "array", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L845-L866
train
narrowspark/arr
src/Arr/Arr.php
Arr.extendDistinct
public static function extendDistinct() { $merged = []; foreach (func_get_args() as $array) { foreach ($array as $key => $value) { if (is_array($value) && static::has($merged, $key) && is_array($merged[$key])) { if (static::isAssoc($value) && static::isAssoc($merged[$key])) { $merged[$key] = static::extendDistinct($merged[$key], $value); continue; } } $merged[$key] = $value; } } return $merged; }
php
public static function extendDistinct() { $merged = []; foreach (func_get_args() as $array) { foreach ($array as $key => $value) { if (is_array($value) && static::has($merged, $key) && is_array($merged[$key])) { if (static::isAssoc($value) && static::isAssoc($merged[$key])) { $merged[$key] = static::extendDistinct($merged[$key], $value); continue; } } $merged[$key] = $value; } } return $merged; }
[ "public", "static", "function", "extendDistinct", "(", ")", "{", "$", "merged", "=", "[", "]", ";", "foreach", "(", "func_get_args", "(", ")", "as", "$", "array", ")", "{", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "static", "::", "has", "(", "$", "merged", ",", "$", "key", ")", "&&", "is_array", "(", "$", "merged", "[", "$", "key", "]", ")", ")", "{", "if", "(", "static", "::", "isAssoc", "(", "$", "value", ")", "&&", "static", "::", "isAssoc", "(", "$", "merged", "[", "$", "key", "]", ")", ")", "{", "$", "merged", "[", "$", "key", "]", "=", "static", "::", "extendDistinct", "(", "$", "merged", "[", "$", "key", "]", ",", "$", "value", ")", ";", "continue", ";", "}", "}", "$", "merged", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "merged", ";", "}" ]
Extend one array with another. Non associative arrays will not be merged but rather replaced. @return array
[ "Extend", "one", "array", "with", "another", ".", "Non", "associative", "arrays", "will", "not", "be", "merged", "but", "rather", "replaced", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L902-L921
train
narrowspark/arr
src/Arr/Arr.php
Arr.sort
public static function sort( array $array, callable $callback, int $options = SORT_REGULAR, bool $descending = false ): array { $results = []; // First we will loop through the items and get the comparator from a callback // function which we were given. Then, we will sort the returned values and // and grab the corresponding values for the sorted keys from this array. foreach ($array as $key => $value) { $results[$key] = $callback($value, $key); } $descending ? arsort($results, $options) : asort($results, $options); // Once we have sorted all of the keys in the array, we will loop through them // and grab the corresponding model so we can set the underlying items list // to the sorted version. Then we'll just return the collection instance. foreach (array_keys($results) as $key) { $results[$key] = $array[$key]; } return $results; }
php
public static function sort( array $array, callable $callback, int $options = SORT_REGULAR, bool $descending = false ): array { $results = []; // First we will loop through the items and get the comparator from a callback // function which we were given. Then, we will sort the returned values and // and grab the corresponding values for the sorted keys from this array. foreach ($array as $key => $value) { $results[$key] = $callback($value, $key); } $descending ? arsort($results, $options) : asort($results, $options); // Once we have sorted all of the keys in the array, we will loop through them // and grab the corresponding model so we can set the underlying items list // to the sorted version. Then we'll just return the collection instance. foreach (array_keys($results) as $key) { $results[$key] = $array[$key]; } return $results; }
[ "public", "static", "function", "sort", "(", "array", "$", "array", ",", "callable", "$", "callback", ",", "int", "$", "options", "=", "SORT_REGULAR", ",", "bool", "$", "descending", "=", "false", ")", ":", "array", "{", "$", "results", "=", "[", "]", ";", "// First we will loop through the items and get the comparator from a callback", "// function which we were given. Then, we will sort the returned values and", "// and grab the corresponding values for the sorted keys from this array.", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "results", "[", "$", "key", "]", "=", "$", "callback", "(", "$", "value", ",", "$", "key", ")", ";", "}", "$", "descending", "?", "arsort", "(", "$", "results", ",", "$", "options", ")", ":", "asort", "(", "$", "results", ",", "$", "options", ")", ";", "// Once we have sorted all of the keys in the array, we will loop through them", "// and grab the corresponding model so we can set the underlying items list", "// to the sorted version. Then we'll just return the collection instance.", "foreach", "(", "array_keys", "(", "$", "results", ")", "as", "$", "key", ")", "{", "$", "results", "[", "$", "key", "]", "=", "$", "array", "[", "$", "key", "]", ";", "}", "return", "$", "results", ";", "}" ]
Sort the array using the given callback. @param array $array @param callable $callback @param int $options @param bool $descending @return array
[ "Sort", "the", "array", "using", "the", "given", "callback", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L933-L958
train
narrowspark/arr
src/Arr/Arr.php
Arr.map
public static function map(array $array, callable $callback) { $newArray = []; foreach ($array as $key => $item) { $result = $callback($item, $key); $newArray = is_array($result) ? array_replace_recursive($array, $result) : array_merge_recursive($array, (array) $result); } return $newArray; }
php
public static function map(array $array, callable $callback) { $newArray = []; foreach ($array as $key => $item) { $result = $callback($item, $key); $newArray = is_array($result) ? array_replace_recursive($array, $result) : array_merge_recursive($array, (array) $result); } return $newArray; }
[ "public", "static", "function", "map", "(", "array", "$", "array", ",", "callable", "$", "callback", ")", "{", "$", "newArray", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "item", ")", "{", "$", "result", "=", "$", "callback", "(", "$", "item", ",", "$", "key", ")", ";", "$", "newArray", "=", "is_array", "(", "$", "result", ")", "?", "array_replace_recursive", "(", "$", "array", ",", "$", "result", ")", ":", "array_merge_recursive", "(", "$", "array", ",", "(", "array", ")", "$", "result", ")", ";", "}", "return", "$", "newArray", ";", "}" ]
Applies the callback to the elements of the given arrays @param array $array @param callable $callback @return array
[ "Applies", "the", "callback", "to", "the", "elements", "of", "the", "given", "arrays" ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L1024-L1037
train
narrowspark/arr
src/Arr/Arr.php
Arr.all
public static function all(array $array, callable $predicate) { foreach ($array as $key => $value) { if (! $predicate($value, $key, $array)) { return false; } } return true; }
php
public static function all(array $array, callable $predicate) { foreach ($array as $key => $value) { if (! $predicate($value, $key, $array)) { return false; } } return true; }
[ "public", "static", "function", "all", "(", "array", "$", "array", ",", "callable", "$", "predicate", ")", "{", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "$", "predicate", "(", "$", "value", ",", "$", "key", ",", "$", "array", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns whether every element of the array satisfies the given predicate or not. Works with Iterators too. @param array $array @param callable $predicate @return bool
[ "Returns", "whether", "every", "element", "of", "the", "array", "satisfies", "the", "given", "predicate", "or", "not", ".", "Works", "with", "Iterators", "too", "." ]
0429f3509d99c020fc80c44a7ad0ecf6d0bfc053
https://github.com/narrowspark/arr/blob/0429f3509d99c020fc80c44a7ad0ecf6d0bfc053/src/Arr/Arr.php#L1061-L1070
train
Wedeto/FileFormats
src/JSON/Writer.php
Writer.writeJSON
public static function writeJSON($obj, $buf = null) { $output = json_encode($obj); if ($output === false && json_last_error() === JSON_ERROR_UTF8) { $obj_fixed = Encoding::fixUTF8($obj); $output = json_encode($obj_fixed); if ($output === false && json_last_error() === JSON_ERROR_UTF8) { // @codeCoverageIgnoreStart // The input has to be extremely weird to trigger this, so // in practice it shouldn't happen. $rep = WF::str($obj); throw new IOException("Invalid encoding: " . $rep); // @codeCoverageIgnoreEnd } } if (is_resource($buf)) { fwrite($buf, $output); return ""; } return $output; }
php
public static function writeJSON($obj, $buf = null) { $output = json_encode($obj); if ($output === false && json_last_error() === JSON_ERROR_UTF8) { $obj_fixed = Encoding::fixUTF8($obj); $output = json_encode($obj_fixed); if ($output === false && json_last_error() === JSON_ERROR_UTF8) { // @codeCoverageIgnoreStart // The input has to be extremely weird to trigger this, so // in practice it shouldn't happen. $rep = WF::str($obj); throw new IOException("Invalid encoding: " . $rep); // @codeCoverageIgnoreEnd } } if (is_resource($buf)) { fwrite($buf, $output); return ""; } return $output; }
[ "public", "static", "function", "writeJSON", "(", "$", "obj", ",", "$", "buf", "=", "null", ")", "{", "$", "output", "=", "json_encode", "(", "$", "obj", ")", ";", "if", "(", "$", "output", "===", "false", "&&", "json_last_error", "(", ")", "===", "JSON_ERROR_UTF8", ")", "{", "$", "obj_fixed", "=", "Encoding", "::", "fixUTF8", "(", "$", "obj", ")", ";", "$", "output", "=", "json_encode", "(", "$", "obj_fixed", ")", ";", "if", "(", "$", "output", "===", "false", "&&", "json_last_error", "(", ")", "===", "JSON_ERROR_UTF8", ")", "{", "// @codeCoverageIgnoreStart", "// The input has to be extremely weird to trigger this, so", "// in practice it shouldn't happen. ", "$", "rep", "=", "WF", "::", "str", "(", "$", "obj", ")", ";", "throw", "new", "IOException", "(", "\"Invalid encoding: \"", ".", "$", "rep", ")", ";", "// @codeCoverageIgnoreEnd", "}", "}", "if", "(", "is_resource", "(", "$", "buf", ")", ")", "{", "fwrite", "(", "$", "buf", ",", "$", "output", ")", ";", "return", "\"\"", ";", "}", "return", "$", "output", ";", "}" ]
Encode the specified entity, catching UTF8 errors. @param mixed $obj The data to output @param resource $buf The buffer to write to. If this is specified, nothing is returned. @return string The JSON encoded data if no buffer was specified.
[ "Encode", "the", "specified", "entity", "catching", "UTF8", "errors", "." ]
65b71fbd38a2ee6b504622aca4f4047ce9d31e9f
https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/JSON/Writer.php#L80-L106
train
Wedeto/FileFormats
src/JSON/Writer.php
Writer.pprintJSON
public static function pprintJSON($obj, $indent = 0, $json_array = null, $buf = null) { if (!is_object($obj) && !is_array($obj)) return self::writeJSON($obj, $buf); // Make sure objects are traversable, or otherwise convert it to array if (method_exists($obj, "jsonSerialize")) { $obj = $obj->jsonSerialize(); } elseif (!WF::is_array_like($obj)) { // Extract properties and mark as non-array $obj = get_object_vars($obj); $json_array = false; } if ($json_array === null) $array = WF::is_numeric_array($obj); else $array = (bool)$json_array; // Open a memory buffer when no buffer is provided $return_buf = false; if ($buf === null) { $buf = fopen("php://memory", "rw"); $return_buf = true; } // Write opening bracket if (count($obj) > 0) { fwrite($buf, $array ? "[\n" : "{\n"); // Write properties $indent += 4; $tot = count($obj); $cur = 0; foreach ($obj as $key => $sub) { // Keys need to be string, otherwise they will not be quoted if (is_numeric($key) && !$array) $key = (string)$key; $ending = (++$cur < $tot ? ",\n" : "\n"); fwrite($buf, str_repeat(' ', $indent)); if (!$array) { self::writeJSON($key, $buf); fwrite($buf, ': '); } if (WF::is_array_like($sub) || is_object($sub)) self::pprintJSON($sub, $indent, null, $buf); else self::writeJSON($sub, $buf); fwrite($buf, $ending); } // Write closing bracket fwrite($buf, str_repeat(' ', $indent - 4) . ($array ? ']' : '}')); } else fwrite($buf, $array ? "[]" : "{}"); if (!$return_buf) return; // Get buffer contents and return it rewind($buf); $json = stream_get_contents($buf); fclose($buf); return $json; }
php
public static function pprintJSON($obj, $indent = 0, $json_array = null, $buf = null) { if (!is_object($obj) && !is_array($obj)) return self::writeJSON($obj, $buf); // Make sure objects are traversable, or otherwise convert it to array if (method_exists($obj, "jsonSerialize")) { $obj = $obj->jsonSerialize(); } elseif (!WF::is_array_like($obj)) { // Extract properties and mark as non-array $obj = get_object_vars($obj); $json_array = false; } if ($json_array === null) $array = WF::is_numeric_array($obj); else $array = (bool)$json_array; // Open a memory buffer when no buffer is provided $return_buf = false; if ($buf === null) { $buf = fopen("php://memory", "rw"); $return_buf = true; } // Write opening bracket if (count($obj) > 0) { fwrite($buf, $array ? "[\n" : "{\n"); // Write properties $indent += 4; $tot = count($obj); $cur = 0; foreach ($obj as $key => $sub) { // Keys need to be string, otherwise they will not be quoted if (is_numeric($key) && !$array) $key = (string)$key; $ending = (++$cur < $tot ? ",\n" : "\n"); fwrite($buf, str_repeat(' ', $indent)); if (!$array) { self::writeJSON($key, $buf); fwrite($buf, ': '); } if (WF::is_array_like($sub) || is_object($sub)) self::pprintJSON($sub, $indent, null, $buf); else self::writeJSON($sub, $buf); fwrite($buf, $ending); } // Write closing bracket fwrite($buf, str_repeat(' ', $indent - 4) . ($array ? ']' : '}')); } else fwrite($buf, $array ? "[]" : "{}"); if (!$return_buf) return; // Get buffer contents and return it rewind($buf); $json = stream_get_contents($buf); fclose($buf); return $json; }
[ "public", "static", "function", "pprintJSON", "(", "$", "obj", ",", "$", "indent", "=", "0", ",", "$", "json_array", "=", "null", ",", "$", "buf", "=", "null", ")", "{", "if", "(", "!", "is_object", "(", "$", "obj", ")", "&&", "!", "is_array", "(", "$", "obj", ")", ")", "return", "self", "::", "writeJSON", "(", "$", "obj", ",", "$", "buf", ")", ";", "// Make sure objects are traversable, or otherwise convert it to array", "if", "(", "method_exists", "(", "$", "obj", ",", "\"jsonSerialize\"", ")", ")", "{", "$", "obj", "=", "$", "obj", "->", "jsonSerialize", "(", ")", ";", "}", "elseif", "(", "!", "WF", "::", "is_array_like", "(", "$", "obj", ")", ")", "{", "// Extract properties and mark as non-array", "$", "obj", "=", "get_object_vars", "(", "$", "obj", ")", ";", "$", "json_array", "=", "false", ";", "}", "if", "(", "$", "json_array", "===", "null", ")", "$", "array", "=", "WF", "::", "is_numeric_array", "(", "$", "obj", ")", ";", "else", "$", "array", "=", "(", "bool", ")", "$", "json_array", ";", "// Open a memory buffer when no buffer is provided", "$", "return_buf", "=", "false", ";", "if", "(", "$", "buf", "===", "null", ")", "{", "$", "buf", "=", "fopen", "(", "\"php://memory\"", ",", "\"rw\"", ")", ";", "$", "return_buf", "=", "true", ";", "}", "// Write opening bracket", "if", "(", "count", "(", "$", "obj", ")", ">", "0", ")", "{", "fwrite", "(", "$", "buf", ",", "$", "array", "?", "\"[\\n\"", ":", "\"{\\n\"", ")", ";", "// Write properties", "$", "indent", "+=", "4", ";", "$", "tot", "=", "count", "(", "$", "obj", ")", ";", "$", "cur", "=", "0", ";", "foreach", "(", "$", "obj", "as", "$", "key", "=>", "$", "sub", ")", "{", "// Keys need to be string, otherwise they will not be quoted", "if", "(", "is_numeric", "(", "$", "key", ")", "&&", "!", "$", "array", ")", "$", "key", "=", "(", "string", ")", "$", "key", ";", "$", "ending", "=", "(", "++", "$", "cur", "<", "$", "tot", "?", "\",\\n\"", ":", "\"\\n\"", ")", ";", "fwrite", "(", "$", "buf", ",", "str_repeat", "(", "' '", ",", "$", "indent", ")", ")", ";", "if", "(", "!", "$", "array", ")", "{", "self", "::", "writeJSON", "(", "$", "key", ",", "$", "buf", ")", ";", "fwrite", "(", "$", "buf", ",", "': '", ")", ";", "}", "if", "(", "WF", "::", "is_array_like", "(", "$", "sub", ")", "||", "is_object", "(", "$", "sub", ")", ")", "self", "::", "pprintJSON", "(", "$", "sub", ",", "$", "indent", ",", "null", ",", "$", "buf", ")", ";", "else", "self", "::", "writeJSON", "(", "$", "sub", ",", "$", "buf", ")", ";", "fwrite", "(", "$", "buf", ",", "$", "ending", ")", ";", "}", "// Write closing bracket", "fwrite", "(", "$", "buf", ",", "str_repeat", "(", "' '", ",", "$", "indent", "-", "4", ")", ".", "(", "$", "array", "?", "']'", ":", "'}'", ")", ")", ";", "}", "else", "fwrite", "(", "$", "buf", ",", "$", "array", "?", "\"[]\"", ":", "\"{}\"", ")", ";", "if", "(", "!", "$", "return_buf", ")", "return", ";", "// Get buffer contents and return it", "rewind", "(", "$", "buf", ")", ";", "$", "json", "=", "stream_get_contents", "(", "$", "buf", ")", ";", "fclose", "(", "$", "buf", ")", ";", "return", "$", "json", ";", "}" ]
PrettyPrint the specified output. @param JSONSerializable $obj The data to output @param bool $json_array When set to true, output will be formatted as a JSON array, rather than an object. If this is set to null the keys will be examined to auto-detect the proper value. @param resource $buf The buffer to write to. If this is specified, nothing is returned. @return string the JSON encoded, formatted data, if no buffer is specified.
[ "PrettyPrint", "the", "specified", "output", "." ]
65b71fbd38a2ee6b504622aca4f4047ce9d31e9f
https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/JSON/Writer.php#L120-L195
train
as3io/As3ModlrBundle
DependencyInjection/ServiceLoader/MetadataDrivers.php
MetadataDrivers.createFileLocator
private function createFileLocator($modelDir, $mixinDir, $embedDir) { $definition = new Definition( Utility::getLibraryClass('Metadata\Driver\FileLocator'), [$modelDir, $mixinDir, $embedDir] ); $definition->setPublic(false); return $definition; }
php
private function createFileLocator($modelDir, $mixinDir, $embedDir) { $definition = new Definition( Utility::getLibraryClass('Metadata\Driver\FileLocator'), [$modelDir, $mixinDir, $embedDir] ); $definition->setPublic(false); return $definition; }
[ "private", "function", "createFileLocator", "(", "$", "modelDir", ",", "$", "mixinDir", ",", "$", "embedDir", ")", "{", "$", "definition", "=", "new", "Definition", "(", "Utility", "::", "getLibraryClass", "(", "'Metadata\\Driver\\FileLocator'", ")", ",", "[", "$", "modelDir", ",", "$", "mixinDir", ",", "$", "embedDir", "]", ")", ";", "$", "definition", "->", "setPublic", "(", "false", ")", ";", "return", "$", "definition", ";", "}" ]
Creates the file locator service definition. @param string $modelDir @param string $mixinDir @param string $embedDir @return Definition
[ "Creates", "the", "file", "locator", "service", "definition", "." ]
7ce2abb7390c7eaf4081c5b7e00b96e7001774a4
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoader/MetadataDrivers.php#L25-L33
train
as3io/As3ModlrBundle
DependencyInjection/ServiceLoader/MetadataDrivers.php
MetadataDrivers.createYmlDriver
private function createYmlDriver($driverName, array $driverConfig, ContainerBuilder $container) { // Definition directories list($modelDir, $mixinDir, $embedDir) = $this->getDefinitionDirs($driverConfig, $container); // Set the directories to the dirs container parameter. Utility::appendParameter('dirs', sprintf('%s.model_dir', $driverName), $modelDir, $container); Utility::appendParameter('dirs', sprintf('%s.mixin_dir', $driverName), $mixinDir, $container); Utility::appendParameter('dirs', sprintf('%s.embed_dir', $driverName), $embedDir, $container); // File locator $locatorName = sprintf('%s.file_locator', $driverName); $locatorDef = $this->createFileLocator($modelDir, $mixinDir, $embedDir); $container->setDefinition($locatorName, $locatorDef); // Driver return new Definition( Utility::getLibraryClass('Metadata\Driver\YamlFileDriver'), [ new Reference($locatorName), new Reference(Utility::getAliasedName('storage_manager')), ] ); }
php
private function createYmlDriver($driverName, array $driverConfig, ContainerBuilder $container) { // Definition directories list($modelDir, $mixinDir, $embedDir) = $this->getDefinitionDirs($driverConfig, $container); // Set the directories to the dirs container parameter. Utility::appendParameter('dirs', sprintf('%s.model_dir', $driverName), $modelDir, $container); Utility::appendParameter('dirs', sprintf('%s.mixin_dir', $driverName), $mixinDir, $container); Utility::appendParameter('dirs', sprintf('%s.embed_dir', $driverName), $embedDir, $container); // File locator $locatorName = sprintf('%s.file_locator', $driverName); $locatorDef = $this->createFileLocator($modelDir, $mixinDir, $embedDir); $container->setDefinition($locatorName, $locatorDef); // Driver return new Definition( Utility::getLibraryClass('Metadata\Driver\YamlFileDriver'), [ new Reference($locatorName), new Reference(Utility::getAliasedName('storage_manager')), ] ); }
[ "private", "function", "createYmlDriver", "(", "$", "driverName", ",", "array", "$", "driverConfig", ",", "ContainerBuilder", "$", "container", ")", "{", "// Definition directories", "list", "(", "$", "modelDir", ",", "$", "mixinDir", ",", "$", "embedDir", ")", "=", "$", "this", "->", "getDefinitionDirs", "(", "$", "driverConfig", ",", "$", "container", ")", ";", "// Set the directories to the dirs container parameter.", "Utility", "::", "appendParameter", "(", "'dirs'", ",", "sprintf", "(", "'%s.model_dir'", ",", "$", "driverName", ")", ",", "$", "modelDir", ",", "$", "container", ")", ";", "Utility", "::", "appendParameter", "(", "'dirs'", ",", "sprintf", "(", "'%s.mixin_dir'", ",", "$", "driverName", ")", ",", "$", "mixinDir", ",", "$", "container", ")", ";", "Utility", "::", "appendParameter", "(", "'dirs'", ",", "sprintf", "(", "'%s.embed_dir'", ",", "$", "driverName", ")", ",", "$", "embedDir", ",", "$", "container", ")", ";", "// File locator", "$", "locatorName", "=", "sprintf", "(", "'%s.file_locator'", ",", "$", "driverName", ")", ";", "$", "locatorDef", "=", "$", "this", "->", "createFileLocator", "(", "$", "modelDir", ",", "$", "mixinDir", ",", "$", "embedDir", ")", ";", "$", "container", "->", "setDefinition", "(", "$", "locatorName", ",", "$", "locatorDef", ")", ";", "// Driver", "return", "new", "Definition", "(", "Utility", "::", "getLibraryClass", "(", "'Metadata\\Driver\\YamlFileDriver'", ")", ",", "[", "new", "Reference", "(", "$", "locatorName", ")", ",", "new", "Reference", "(", "Utility", "::", "getAliasedName", "(", "'storage_manager'", ")", ")", ",", "]", ")", ";", "}" ]
Creates the YAML metadata driver service definition. @param string $driverName @param array $driverConfig @param ContainerBuilder $container @return Definition
[ "Creates", "the", "YAML", "metadata", "driver", "service", "definition", "." ]
7ce2abb7390c7eaf4081c5b7e00b96e7001774a4
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoader/MetadataDrivers.php#L43-L66
train
as3io/As3ModlrBundle
DependencyInjection/ServiceLoader/MetadataDrivers.php
MetadataDrivers.getDefinitionDir
private function getDefinitionDir($type, array $driverConfig, ContainerBuilder $container) { $defaultDir = sprintf('%s/Resources/As3ModlrBundle', $container->getParameter('kernel.root_dir')); $folder = sprintf('%ss', $type); $key = sprintf('%s_dir', $type); return isset($driverConfig['parameters'][$key]) ? Utility::locateResource($driverConfig['parameters'][$key], $container) : sprintf('%s/%s', $defaultDir, $folder) ; }
php
private function getDefinitionDir($type, array $driverConfig, ContainerBuilder $container) { $defaultDir = sprintf('%s/Resources/As3ModlrBundle', $container->getParameter('kernel.root_dir')); $folder = sprintf('%ss', $type); $key = sprintf('%s_dir', $type); return isset($driverConfig['parameters'][$key]) ? Utility::locateResource($driverConfig['parameters'][$key], $container) : sprintf('%s/%s', $defaultDir, $folder) ; }
[ "private", "function", "getDefinitionDir", "(", "$", "type", ",", "array", "$", "driverConfig", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "defaultDir", "=", "sprintf", "(", "'%s/Resources/As3ModlrBundle'", ",", "$", "container", "->", "getParameter", "(", "'kernel.root_dir'", ")", ")", ";", "$", "folder", "=", "sprintf", "(", "'%ss'", ",", "$", "type", ")", ";", "$", "key", "=", "sprintf", "(", "'%s_dir'", ",", "$", "type", ")", ";", "return", "isset", "(", "$", "driverConfig", "[", "'parameters'", "]", "[", "$", "key", "]", ")", "?", "Utility", "::", "locateResource", "(", "$", "driverConfig", "[", "'parameters'", "]", "[", "$", "key", "]", ",", "$", "container", ")", ":", "sprintf", "(", "'%s/%s'", ",", "$", "defaultDir", ",", "$", "folder", ")", ";", "}" ]
Gets the directory for a definition type. @param string $type @param array $driverConfig @param ContainerBuilder $container @return string
[ "Gets", "the", "directory", "for", "a", "definition", "type", "." ]
7ce2abb7390c7eaf4081c5b7e00b96e7001774a4
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoader/MetadataDrivers.php#L76-L87
train