repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
cubicmushroom/valueobjects
src/Money/Currency.php
Currency.sameValueAs
public function sameValueAs(ValueObjectInterface $currency) { if (false === Util::classEquals($this, $currency)) { return false; } return $this->getCode()->toNative() == $currency->getCode()->toNative(); }
php
public function sameValueAs(ValueObjectInterface $currency) { if (false === Util::classEquals($this, $currency)) { return false; } return $this->getCode()->toNative() == $currency->getCode()->toNative(); }
[ "public", "function", "sameValueAs", "(", "ValueObjectInterface", "$", "currency", ")", "{", "if", "(", "false", "===", "Util", "::", "classEquals", "(", "$", "this", ",", "$", "currency", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "getCode", "(", ")", "->", "toNative", "(", ")", "==", "$", "currency", "->", "getCode", "(", ")", "->", "toNative", "(", ")", ";", "}" ]
Tells whether two Currency are equal by comparing their names @param ValueObjectInterface $currency @return bool
[ "Tells", "whether", "two", "Currency", "are", "equal", "by", "comparing", "their", "names" ]
4554239ab75d65eeb9773219aa5b07e9fbfabb92
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/Money/Currency.php#L42-L49
train
as3io/As3ModlrBundle
DependencyInjection/ServiceLoader/MetadataCache.php
MetadataCache.createBundleCacheWarmer
private function createBundleCacheWarmer($warmerName) { $definition = new Definition( Utility::getBundleClass('CacheWarmer\MetadataWarmer'), [new Reference($warmerName)] ); $definition->setPublic(false); $definition->addTag('kernel.cache_warmer'); return $definition; }
php
private function createBundleCacheWarmer($warmerName) { $definition = new Definition( Utility::getBundleClass('CacheWarmer\MetadataWarmer'), [new Reference($warmerName)] ); $definition->setPublic(false); $definition->addTag('kernel.cache_warmer'); return $definition; }
[ "private", "function", "createBundleCacheWarmer", "(", "$", "warmerName", ")", "{", "$", "definition", "=", "new", "Definition", "(", "Utility", "::", "getBundleClass", "(", "'CacheWarmer\\MetadataWarmer'", ")", ",", "[", "new", "Reference", "(", "$", "warmerName", ")", "]", ")", ";", "$", "definition", "->", "setPublic", "(", "false", ")", ";", "$", "definition", "->", "addTag", "(", "'kernel.cache_warmer'", ")", ";", "return", "$", "definition", ";", "}" ]
Creates the bundle cache warmer definition. @param string $warmerName @return Definition
[ "Creates", "the", "bundle", "cache", "warmer", "definition", "." ]
7ce2abb7390c7eaf4081c5b7e00b96e7001774a4
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoader/MetadataCache.php#L23-L32
train
as3io/As3ModlrBundle
DependencyInjection/ServiceLoader/MetadataCache.php
MetadataCache.createCacheClearCommand
private function createCacheClearCommand($warmerName) { $definition = new Definition( Utility::getBundleClass('Command\Metadata\ClearCacheCommand'), [new Reference($warmerName)] ); $definition->addTag('console.command'); return $definition; }
php
private function createCacheClearCommand($warmerName) { $definition = new Definition( Utility::getBundleClass('Command\Metadata\ClearCacheCommand'), [new Reference($warmerName)] ); $definition->addTag('console.command'); return $definition; }
[ "private", "function", "createCacheClearCommand", "(", "$", "warmerName", ")", "{", "$", "definition", "=", "new", "Definition", "(", "Utility", "::", "getBundleClass", "(", "'Command\\Metadata\\ClearCacheCommand'", ")", ",", "[", "new", "Reference", "(", "$", "warmerName", ")", "]", ")", ";", "$", "definition", "->", "addTag", "(", "'console.command'", ")", ";", "return", "$", "definition", ";", "}" ]
Creates the cache clear command definition. @param string $warmerName @return Definition
[ "Creates", "the", "cache", "clear", "command", "definition", "." ]
7ce2abb7390c7eaf4081c5b7e00b96e7001774a4
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoader/MetadataCache.php#L40-L48
train
as3io/As3ModlrBundle
DependencyInjection/ServiceLoader/MetadataCache.php
MetadataCache.createFileCache
private function createFileCache($subClassName, array $cacheConfig, ContainerBuilder $container) { $cacheDir = $this->getFileCacheDir($cacheConfig, $container); Utility::appendParameter('dirs', 'metadata_cache_dir', $cacheDir, $container); return new Definition( Utility::getLibraryClass($subClassName), [$cacheDir] ); }
php
private function createFileCache($subClassName, array $cacheConfig, ContainerBuilder $container) { $cacheDir = $this->getFileCacheDir($cacheConfig, $container); Utility::appendParameter('dirs', 'metadata_cache_dir', $cacheDir, $container); return new Definition( Utility::getLibraryClass($subClassName), [$cacheDir] ); }
[ "private", "function", "createFileCache", "(", "$", "subClassName", ",", "array", "$", "cacheConfig", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "cacheDir", "=", "$", "this", "->", "getFileCacheDir", "(", "$", "cacheConfig", ",", "$", "container", ")", ";", "Utility", "::", "appendParameter", "(", "'dirs'", ",", "'metadata_cache_dir'", ",", "$", "cacheDir", ",", "$", "container", ")", ";", "return", "new", "Definition", "(", "Utility", "::", "getLibraryClass", "(", "$", "subClassName", ")", ",", "[", "$", "cacheDir", "]", ")", ";", "}" ]
Creates a file cache service definition. @param string $subClassName @param array $cacheConfig @param ContainerBuilder $container @return Definition
[ "Creates", "a", "file", "cache", "service", "definition", "." ]
7ce2abb7390c7eaf4081c5b7e00b96e7001774a4
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoader/MetadataCache.php#L73-L82
train
as3io/As3ModlrBundle
DependencyInjection/ServiceLoader/MetadataCache.php
MetadataCache.getFileCacheDir
private function getFileCacheDir(array $cacheConfig, ContainerBuilder $container) { $dir = sprintf('%s/as3_modlr', $container->getParameter('kernel.cache_dir')); if (isset($cacheConfig['parameters']['dir'])) { $dir = $cacheConfig['parameters']['dir']; } return $dir; }
php
private function getFileCacheDir(array $cacheConfig, ContainerBuilder $container) { $dir = sprintf('%s/as3_modlr', $container->getParameter('kernel.cache_dir')); if (isset($cacheConfig['parameters']['dir'])) { $dir = $cacheConfig['parameters']['dir']; } return $dir; }
[ "private", "function", "getFileCacheDir", "(", "array", "$", "cacheConfig", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "dir", "=", "sprintf", "(", "'%s/as3_modlr'", ",", "$", "container", "->", "getParameter", "(", "'kernel.cache_dir'", ")", ")", ";", "if", "(", "isset", "(", "$", "cacheConfig", "[", "'parameters'", "]", "[", "'dir'", "]", ")", ")", "{", "$", "dir", "=", "$", "cacheConfig", "[", "'parameters'", "]", "[", "'dir'", "]", ";", "}", "return", "$", "dir", ";", "}" ]
Gets the file cache directory. @param array $cacheConfig @param ContainerBuilder $container @return string
[ "Gets", "the", "file", "cache", "directory", "." ]
7ce2abb7390c7eaf4081c5b7e00b96e7001774a4
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoader/MetadataCache.php#L105-L112
train
as3io/As3ModlrBundle
DependencyInjection/ServiceLoader/MetadataCache.php
MetadataCache.loadCacheWarming
private function loadCacheWarming(ContainerBuilder $container) { // Root cache warmer $warmerName = Utility::getAliasedName('metadata.cache.warmer'); $definition = $this->createCacheWarmer($container); $container->setDefinition($warmerName, $definition); // Bundle wrapped cache warmer $definition = $this->createBundleCacheWarmer($warmerName); $container->setDefinition(Utility::getAliasedName('bundle.cache.warmer'), $definition); // Cache clear command $definition = $this->createCacheClearCommand($warmerName); $container->setDefinition(Utility::getAliasedName('command.metadata.cache_clear'), $definition); return $this; }
php
private function loadCacheWarming(ContainerBuilder $container) { // Root cache warmer $warmerName = Utility::getAliasedName('metadata.cache.warmer'); $definition = $this->createCacheWarmer($container); $container->setDefinition($warmerName, $definition); // Bundle wrapped cache warmer $definition = $this->createBundleCacheWarmer($warmerName); $container->setDefinition(Utility::getAliasedName('bundle.cache.warmer'), $definition); // Cache clear command $definition = $this->createCacheClearCommand($warmerName); $container->setDefinition(Utility::getAliasedName('command.metadata.cache_clear'), $definition); return $this; }
[ "private", "function", "loadCacheWarming", "(", "ContainerBuilder", "$", "container", ")", "{", "// Root cache warmer", "$", "warmerName", "=", "Utility", "::", "getAliasedName", "(", "'metadata.cache.warmer'", ")", ";", "$", "definition", "=", "$", "this", "->", "createCacheWarmer", "(", "$", "container", ")", ";", "$", "container", "->", "setDefinition", "(", "$", "warmerName", ",", "$", "definition", ")", ";", "// Bundle wrapped cache warmer", "$", "definition", "=", "$", "this", "->", "createBundleCacheWarmer", "(", "$", "warmerName", ")", ";", "$", "container", "->", "setDefinition", "(", "Utility", "::", "getAliasedName", "(", "'bundle.cache.warmer'", ")", ",", "$", "definition", ")", ";", "// Cache clear command", "$", "definition", "=", "$", "this", "->", "createCacheClearCommand", "(", "$", "warmerName", ")", ";", "$", "container", "->", "setDefinition", "(", "Utility", "::", "getAliasedName", "(", "'command.metadata.cache_clear'", ")", ",", "$", "definition", ")", ";", "return", "$", "this", ";", "}" ]
Loads cache warming services. @param ContainerBuilder $container @return self
[ "Loads", "cache", "warming", "services", "." ]
7ce2abb7390c7eaf4081c5b7e00b96e7001774a4
https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoader/MetadataCache.php#L160-L176
train
modulusphp/support
Config.php
Config.has
public static function has(string $key) : bool { $expect = explode('.', $key); $config = Config::all(); foreach($expect as $setting) { if (!isset($config[$setting])) return false; $config = $config[$setting]; } return true; }
php
public static function has(string $key) : bool { $expect = explode('.', $key); $config = Config::all(); foreach($expect as $setting) { if (!isset($config[$setting])) return false; $config = $config[$setting]; } return true; }
[ "public", "static", "function", "has", "(", "string", "$", "key", ")", ":", "bool", "{", "$", "expect", "=", "explode", "(", "'.'", ",", "$", "key", ")", ";", "$", "config", "=", "Config", "::", "all", "(", ")", ";", "foreach", "(", "$", "expect", "as", "$", "setting", ")", "{", "if", "(", "!", "isset", "(", "$", "config", "[", "$", "setting", "]", ")", ")", "return", "false", ";", "$", "config", "=", "$", "config", "[", "$", "setting", "]", ";", "}", "return", "true", ";", "}" ]
Check if setting exists @param string $key @return bool
[ "Check", "if", "setting", "exists" ]
b5c5b48dcbeb379e6cd1f29159dc8cdacef3adab
https://github.com/modulusphp/support/blob/b5c5b48dcbeb379e6cd1f29159dc8cdacef3adab/Config.php#L22-L33
train
fulgurio/LightCMSBundle
Utils/MediaLibrary.php
MediaLibrary.getUniqFilename
private function getUniqFilename($path, $filename, $counter = 0) { if (($pos = mb_strrpos($filename, '.')) == FALSE) { $file = $filename; $extension = ''; } else { $file = mb_substr($filename, 0, $pos); $extension = mb_substr($filename, $pos); } $postfix = $counter > 0 ? $this->slugSuffixSeparator . $counter : ''; if (file_exists($path . '/' . $file . $postfix . $extension)) { return $this->getUniqFilename($path, $filename, $counter + 1); } return $file . $postfix . $extension; }
php
private function getUniqFilename($path, $filename, $counter = 0) { if (($pos = mb_strrpos($filename, '.')) == FALSE) { $file = $filename; $extension = ''; } else { $file = mb_substr($filename, 0, $pos); $extension = mb_substr($filename, $pos); } $postfix = $counter > 0 ? $this->slugSuffixSeparator . $counter : ''; if (file_exists($path . '/' . $file . $postfix . $extension)) { return $this->getUniqFilename($path, $filename, $counter + 1); } return $file . $postfix . $extension; }
[ "private", "function", "getUniqFilename", "(", "$", "path", ",", "$", "filename", ",", "$", "counter", "=", "0", ")", "{", "if", "(", "(", "$", "pos", "=", "mb_strrpos", "(", "$", "filename", ",", "'.'", ")", ")", "==", "FALSE", ")", "{", "$", "file", "=", "$", "filename", ";", "$", "extension", "=", "''", ";", "}", "else", "{", "$", "file", "=", "mb_substr", "(", "$", "filename", ",", "0", ",", "$", "pos", ")", ";", "$", "extension", "=", "mb_substr", "(", "$", "filename", ",", "$", "pos", ")", ";", "}", "$", "postfix", "=", "$", "counter", ">", "0", "?", "$", "this", "->", "slugSuffixSeparator", ".", "$", "counter", ":", "''", ";", "if", "(", "file_exists", "(", "$", "path", ".", "'/'", ".", "$", "file", ".", "$", "postfix", ".", "$", "extension", ")", ")", "{", "return", "$", "this", "->", "getUniqFilename", "(", "$", "path", ",", "$", "filename", ",", "$", "counter", "+", "1", ")", ";", "}", "return", "$", "file", ".", "$", "postfix", ".", "$", "extension", ";", "}" ]
Get uniq name for upload @param string $path @param string $filename @param number $counter @return string
[ "Get", "uniq", "name", "for", "upload" ]
66319af52b97b6552b7c391ee370538263f42d10
https://github.com/fulgurio/LightCMSBundle/blob/66319af52b97b6552b7c391ee370538263f42d10/Utils/MediaLibrary.php#L93-L111
train
ScaraMVC/Framework
src/Scara/Routing/RouteLoader.php
RouteLoader.getRequestedRoute
public function getRequestedRoute($basepath) { if ($basepath == '/') { $url = strtolower($_SERVER['REQUEST_URI']); } else { $url = explode($basepath, strtolower($_SERVER['REQUEST_URI']))[1]; } return $this->_router->getRoute($url); }
php
public function getRequestedRoute($basepath) { if ($basepath == '/') { $url = strtolower($_SERVER['REQUEST_URI']); } else { $url = explode($basepath, strtolower($_SERVER['REQUEST_URI']))[1]; } return $this->_router->getRoute($url); }
[ "public", "function", "getRequestedRoute", "(", "$", "basepath", ")", "{", "if", "(", "$", "basepath", "==", "'/'", ")", "{", "$", "url", "=", "strtolower", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ";", "}", "else", "{", "$", "url", "=", "explode", "(", "$", "basepath", ",", "strtolower", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ")", "[", "1", "]", ";", "}", "return", "$", "this", "->", "_router", "->", "getRoute", "(", "$", "url", ")", ";", "}" ]
Gets the requested route for the controller. @param string $basepath - Application's base path @return array
[ "Gets", "the", "requested", "route", "for", "the", "controller", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Routing/RouteLoader.php#L37-L46
train
Linkvalue-Interne/MajoraFrameworkExtraBundle
src/Majora/Framework/Domain/Action/ActionFactory.php
ActionFactory.createAction
public function createAction($name) { if (!$this->actions->containsKey($name)) { throw new \InvalidArgumentException(sprintf( 'Any action registered under "%s" name, only ["%s"] are.', $name, implode('","', $this->actions->getKeys()) )); } return clone $this->actions->get($name); }
php
public function createAction($name) { if (!$this->actions->containsKey($name)) { throw new \InvalidArgumentException(sprintf( 'Any action registered under "%s" name, only ["%s"] are.', $name, implode('","', $this->actions->getKeys()) )); } return clone $this->actions->get($name); }
[ "public", "function", "createAction", "(", "$", "name", ")", "{", "if", "(", "!", "$", "this", "->", "actions", "->", "containsKey", "(", "$", "name", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Any action registered under \"%s\" name, only [\"%s\"] are.'", ",", "$", "name", ",", "implode", "(", "'\",\"'", ",", "$", "this", "->", "actions", "->", "getKeys", "(", ")", ")", ")", ")", ";", "}", "return", "clone", "$", "this", "->", "actions", "->", "get", "(", "$", "name", ")", ";", "}" ]
Creates and return a new action under given name @param string $name @return ActionInterface
[ "Creates", "and", "return", "a", "new", "action", "under", "given", "name" ]
6f368380cfc39d27fafb0844e9a53b4d86d7c034
https://github.com/Linkvalue-Interne/MajoraFrameworkExtraBundle/blob/6f368380cfc39d27fafb0844e9a53b4d86d7c034/src/Majora/Framework/Domain/Action/ActionFactory.php#L49-L60
train
staticka/staticka
src/Helper/ViewHelper.php
ViewHelper.render
public function render($template, array $data = array()) { $data = array_merge($data, $this->website->helpers()); $data['config'] = $this->website; $renderer = $this->website->renderer(); return $renderer->render($template, $data); }
php
public function render($template, array $data = array()) { $data = array_merge($data, $this->website->helpers()); $data['config'] = $this->website; $renderer = $this->website->renderer(); return $renderer->render($template, $data); }
[ "public", "function", "render", "(", "$", "template", ",", "array", "$", "data", "=", "array", "(", ")", ")", "{", "$", "data", "=", "array_merge", "(", "$", "data", ",", "$", "this", "->", "website", "->", "helpers", "(", ")", ")", ";", "$", "data", "[", "'config'", "]", "=", "$", "this", "->", "website", ";", "$", "renderer", "=", "$", "this", "->", "website", "->", "renderer", "(", ")", ";", "return", "$", "renderer", "->", "render", "(", "$", "template", ",", "$", "data", ")", ";", "}" ]
Renders the partial template. @param string $template @param array $data @return string
[ "Renders", "the", "partial", "template", "." ]
6e3b814c391ed03b0bd409803e11579bae677ce4
https://github.com/staticka/staticka/blob/6e3b814c391ed03b0bd409803e11579bae677ce4/src/Helper/ViewHelper.php#L37-L46
train
Linkvalue-Interne/MajoraFrameworkExtraBundle
src/Majora/Bundle/FrameworkExtraBundle/Event/ClockSubscriber.php
ClockSubscriber.onKernelRequest
public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); if (!$strMockedDate = $request->query->get($this->mockParamName)) { return; } $this->mock($strMockedDate); }
php
public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); if (!$strMockedDate = $request->query->get($this->mockParamName)) { return; } $this->mock($strMockedDate); }
[ "public", "function", "onKernelRequest", "(", "GetResponseEvent", "$", "event", ")", "{", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";", "if", "(", "!", "$", "strMockedDate", "=", "$", "request", "->", "query", "->", "get", "(", "$", "this", "->", "mockParamName", ")", ")", "{", "return", ";", "}", "$", "this", "->", "mock", "(", "$", "strMockedDate", ")", ";", "}" ]
kernel request event handler
[ "kernel", "request", "event", "handler" ]
6f368380cfc39d27fafb0844e9a53b4d86d7c034
https://github.com/Linkvalue-Interne/MajoraFrameworkExtraBundle/blob/6f368380cfc39d27fafb0844e9a53b4d86d7c034/src/Majora/Bundle/FrameworkExtraBundle/Event/ClockSubscriber.php#L47-L55
train
Linkvalue-Interne/MajoraFrameworkExtraBundle
src/Majora/Bundle/FrameworkExtraBundle/Event/ClockSubscriber.php
ClockSubscriber.onConsoleCommand
public function onConsoleCommand(ConsoleCommandEvent $event) { $input = $event->getInput(); if (!$input->hasOption($this->mockParamName)) { return; } $this->mock($input->getOption($this->mockParamName)); }
php
public function onConsoleCommand(ConsoleCommandEvent $event) { $input = $event->getInput(); if (!$input->hasOption($this->mockParamName)) { return; } $this->mock($input->getOption($this->mockParamName)); }
[ "public", "function", "onConsoleCommand", "(", "ConsoleCommandEvent", "$", "event", ")", "{", "$", "input", "=", "$", "event", "->", "getInput", "(", ")", ";", "if", "(", "!", "$", "input", "->", "hasOption", "(", "$", "this", "->", "mockParamName", ")", ")", "{", "return", ";", "}", "$", "this", "->", "mock", "(", "$", "input", "->", "getOption", "(", "$", "this", "->", "mockParamName", ")", ")", ";", "}" ]
console command event handler
[ "console", "command", "event", "handler" ]
6f368380cfc39d27fafb0844e9a53b4d86d7c034
https://github.com/Linkvalue-Interne/MajoraFrameworkExtraBundle/blob/6f368380cfc39d27fafb0844e9a53b4d86d7c034/src/Majora/Bundle/FrameworkExtraBundle/Event/ClockSubscriber.php#L60-L68
train
cubicmushroom/valueobjects
src/DateTime/DateTimeWithTimeZone.php
DateTimeWithTimeZone.sameValueAs
public function sameValueAs(ValueObjectInterface $dateTimeWithTimeZone) { if (false === Util::classEquals($this, $dateTimeWithTimeZone)) { return false; } return $this->getDateTime()->sameValueAs($dateTimeWithTimeZone->getDateTime()) && $this->getTimeZone()->sameValueAs($dateTimeWithTimeZone->getTimeZone()); }
php
public function sameValueAs(ValueObjectInterface $dateTimeWithTimeZone) { if (false === Util::classEquals($this, $dateTimeWithTimeZone)) { return false; } return $this->getDateTime()->sameValueAs($dateTimeWithTimeZone->getDateTime()) && $this->getTimeZone()->sameValueAs($dateTimeWithTimeZone->getTimeZone()); }
[ "public", "function", "sameValueAs", "(", "ValueObjectInterface", "$", "dateTimeWithTimeZone", ")", "{", "if", "(", "false", "===", "Util", "::", "classEquals", "(", "$", "this", ",", "$", "dateTimeWithTimeZone", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "getDateTime", "(", ")", "->", "sameValueAs", "(", "$", "dateTimeWithTimeZone", "->", "getDateTime", "(", ")", ")", "&&", "$", "this", "->", "getTimeZone", "(", ")", "->", "sameValueAs", "(", "$", "dateTimeWithTimeZone", "->", "getTimeZone", "(", ")", ")", ";", "}" ]
Tells whether two DateTimeWithTimeZone are equal by comparing their values @param ValueObjectInterface $dateTimeWithTimeZone @return bool
[ "Tells", "whether", "two", "DateTimeWithTimeZone", "are", "equal", "by", "comparing", "their", "values" ]
4554239ab75d65eeb9773219aa5b07e9fbfabb92
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/DateTime/DateTimeWithTimeZone.php#L83-L91
train
cubicmushroom/valueobjects
src/DateTime/DateTimeWithTimeZone.php
DateTimeWithTimeZone.sameTimestampAs
public function sameTimestampAs(ValueObjectInterface $dateTimeWithTimeZone) { if (false === Util::classEquals($this, $dateTimeWithTimeZone)) { return false; } return $this->toNativeDateTime() == $dateTimeWithTimeZone->toNativeDateTime(); }
php
public function sameTimestampAs(ValueObjectInterface $dateTimeWithTimeZone) { if (false === Util::classEquals($this, $dateTimeWithTimeZone)) { return false; } return $this->toNativeDateTime() == $dateTimeWithTimeZone->toNativeDateTime(); }
[ "public", "function", "sameTimestampAs", "(", "ValueObjectInterface", "$", "dateTimeWithTimeZone", ")", "{", "if", "(", "false", "===", "Util", "::", "classEquals", "(", "$", "this", ",", "$", "dateTimeWithTimeZone", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "toNativeDateTime", "(", ")", "==", "$", "dateTimeWithTimeZone", "->", "toNativeDateTime", "(", ")", ";", "}" ]
Tells whether two DateTimeWithTimeZone represents the same timestamp @param ValueObjectInterface $dateTimeWithTimeZone @return bool
[ "Tells", "whether", "two", "DateTimeWithTimeZone", "represents", "the", "same", "timestamp" ]
4554239ab75d65eeb9773219aa5b07e9fbfabb92
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/DateTime/DateTimeWithTimeZone.php#L100-L107
train
cubicmushroom/valueobjects
src/DateTime/DateTimeWithTimeZone.php
DateTimeWithTimeZone.toNativeDateTime
public function toNativeDateTime() { $date = $this->getDateTime()->getDate(); $time = $this->getDateTime()->getTime(); $year = $date->getYear()->toNative(); $month = $date->getMonth()->getNumericValue(); $day = $date->getDay()->toNative(); $hour = $time->getHour()->toNative(); $minute = $time->getMinute()->toNative(); $second = $time->getSecond()->toNative(); $timezone = $this->getTimeZone()->toNativeDateTimeZone(); $dateTime = new \DateTime(); $dateTime->setTimezone($timezone); $dateTime->setDate($year, $month, $day); $dateTime->setTime($hour, $minute, $second); return $dateTime; }
php
public function toNativeDateTime() { $date = $this->getDateTime()->getDate(); $time = $this->getDateTime()->getTime(); $year = $date->getYear()->toNative(); $month = $date->getMonth()->getNumericValue(); $day = $date->getDay()->toNative(); $hour = $time->getHour()->toNative(); $minute = $time->getMinute()->toNative(); $second = $time->getSecond()->toNative(); $timezone = $this->getTimeZone()->toNativeDateTimeZone(); $dateTime = new \DateTime(); $dateTime->setTimezone($timezone); $dateTime->setDate($year, $month, $day); $dateTime->setTime($hour, $minute, $second); return $dateTime; }
[ "public", "function", "toNativeDateTime", "(", ")", "{", "$", "date", "=", "$", "this", "->", "getDateTime", "(", ")", "->", "getDate", "(", ")", ";", "$", "time", "=", "$", "this", "->", "getDateTime", "(", ")", "->", "getTime", "(", ")", ";", "$", "year", "=", "$", "date", "->", "getYear", "(", ")", "->", "toNative", "(", ")", ";", "$", "month", "=", "$", "date", "->", "getMonth", "(", ")", "->", "getNumericValue", "(", ")", ";", "$", "day", "=", "$", "date", "->", "getDay", "(", ")", "->", "toNative", "(", ")", ";", "$", "hour", "=", "$", "time", "->", "getHour", "(", ")", "->", "toNative", "(", ")", ";", "$", "minute", "=", "$", "time", "->", "getMinute", "(", ")", "->", "toNative", "(", ")", ";", "$", "second", "=", "$", "time", "->", "getSecond", "(", ")", "->", "toNative", "(", ")", ";", "$", "timezone", "=", "$", "this", "->", "getTimeZone", "(", ")", "->", "toNativeDateTimeZone", "(", ")", ";", "$", "dateTime", "=", "new", "\\", "DateTime", "(", ")", ";", "$", "dateTime", "->", "setTimezone", "(", "$", "timezone", ")", ";", "$", "dateTime", "->", "setDate", "(", "$", "year", ",", "$", "month", ",", "$", "day", ")", ";", "$", "dateTime", "->", "setTime", "(", "$", "hour", ",", "$", "minute", ",", "$", "second", ")", ";", "return", "$", "dateTime", ";", "}" ]
Returns a native PHP \DateTime version of the current DateTimeWithTimeZone @return \DateTime
[ "Returns", "a", "native", "PHP", "\\", "DateTime", "version", "of", "the", "current", "DateTimeWithTimeZone" ]
4554239ab75d65eeb9773219aa5b07e9fbfabb92
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/DateTime/DateTimeWithTimeZone.php#L134-L152
train
seyfer/ZendPsrLogger
src/ZendPsrLogger/Logger.php
Logger.log
public function log($level, $message, array $context = []) { if (isset($this->psrToZendPriorityMap[$level])) { $level = $this->psrToZendPriorityMap[$level]; } $this->externalLogger ->log($level, $message, $this->getExtraWithContextMerged($context)); }
php
public function log($level, $message, array $context = []) { if (isset($this->psrToZendPriorityMap[$level])) { $level = $this->psrToZendPriorityMap[$level]; } $this->externalLogger ->log($level, $message, $this->getExtraWithContextMerged($context)); }
[ "public", "function", "log", "(", "$", "level", ",", "$", "message", ",", "array", "$", "context", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "psrToZendPriorityMap", "[", "$", "level", "]", ")", ")", "{", "$", "level", "=", "$", "this", "->", "psrToZendPriorityMap", "[", "$", "level", "]", ";", "}", "$", "this", "->", "externalLogger", "->", "log", "(", "$", "level", ",", "$", "message", ",", "$", "this", "->", "getExtraWithContextMerged", "(", "$", "context", ")", ")", ";", "}" ]
main log function @param $level @param $message @param array $context @return null|void
[ "main", "log", "function" ]
aafd57012bbdc144083362cb7e621c9d7e13aabf
https://github.com/seyfer/ZendPsrLogger/blob/aafd57012bbdc144083362cb7e621c9d7e13aabf/src/ZendPsrLogger/Logger.php#L104-L113
train
seyfer/ZendPsrLogger
src/ZendPsrLogger/Logger.php
Logger.getExtraWithContextMerged
private function getExtraWithContextMerged(array $context = []) { $extra = $this->getExtra(); if (!empty($context)) { $extra = array_merge($extra, $context); } return $extra; }
php
private function getExtraWithContextMerged(array $context = []) { $extra = $this->getExtra(); if (!empty($context)) { $extra = array_merge($extra, $context); } return $extra; }
[ "private", "function", "getExtraWithContextMerged", "(", "array", "$", "context", "=", "[", "]", ")", "{", "$", "extra", "=", "$", "this", "->", "getExtra", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "context", ")", ")", "{", "$", "extra", "=", "array_merge", "(", "$", "extra", ",", "$", "context", ")", ";", "}", "return", "$", "extra", ";", "}" ]
merge extra with current context @param array $context @return array
[ "merge", "extra", "with", "current", "context" ]
aafd57012bbdc144083362cb7e621c9d7e13aabf
https://github.com/seyfer/ZendPsrLogger/blob/aafd57012bbdc144083362cb7e621c9d7e13aabf/src/ZendPsrLogger/Logger.php#L120-L128
train
mwyatt/core
src/Helper.php
Helper.slugify
public static function slugify($slug) { $slug = preg_replace('/\xE3\x80\x80/', ' ', $slug); $slug = str_replace('-', ' ', $slug); $slug = preg_replace('#[:\#\*"@+=;!><&\.%()\]\/\'\\\\|\[]#', "\x20", $slug); $slug = str_replace('?', '', $slug); $slug = trim(mb_strtolower($slug, 'UTF-8')); $slug = preg_replace('#\x20+#', '-', $slug); return $slug; }
php
public static function slugify($slug) { $slug = preg_replace('/\xE3\x80\x80/', ' ', $slug); $slug = str_replace('-', ' ', $slug); $slug = preg_replace('#[:\#\*"@+=;!><&\.%()\]\/\'\\\\|\[]#', "\x20", $slug); $slug = str_replace('?', '', $slug); $slug = trim(mb_strtolower($slug, 'UTF-8')); $slug = preg_replace('#\x20+#', '-', $slug); return $slug; }
[ "public", "static", "function", "slugify", "(", "$", "slug", ")", "{", "$", "slug", "=", "preg_replace", "(", "'/\\xE3\\x80\\x80/'", ",", "' '", ",", "$", "slug", ")", ";", "$", "slug", "=", "str_replace", "(", "'-'", ",", "' '", ",", "$", "slug", ")", ";", "$", "slug", "=", "preg_replace", "(", "'#[:\\#\\*\"@+=;!><&\\.%()\\]\\/\\'\\\\\\\\|\\[]#'", ",", "\"\\x20\"", ",", "$", "slug", ")", ";", "$", "slug", "=", "str_replace", "(", "'?'", ",", "''", ",", "$", "slug", ")", ";", "$", "slug", "=", "trim", "(", "mb_strtolower", "(", "$", "slug", ",", "'UTF-8'", ")", ")", ";", "$", "slug", "=", "preg_replace", "(", "'#\\x20+#'", ",", "'-'", ",", "$", "slug", ")", ";", "return", "$", "slug", ";", "}" ]
better than urlfriendly because & becomes 'amp' then when making urls it can be translated? @param string $slug @return string foo-bar
[ "better", "than", "urlfriendly", "because", "&", "becomes", "amp", "then", "when", "making", "urls", "it", "can", "be", "translated?" ]
8ea9d67cc84fe6aff17a469c703d5492dbcd93ed
https://github.com/mwyatt/core/blob/8ea9d67cc84fe6aff17a469c703d5492dbcd93ed/src/Helper.php#L67-L76
train
mwyatt/core
src/Helper.php
Helper.calcAverage
public static function calcAverage($small, $big) { $average = 0; if ($big != 0) { $x = 0; $y = 0; $average = 0; $x = $small / $big; $y = $x * 100; // $average = round($y); // converts to 65% $average = number_format((float)$y, 2, '.', ''); } return $average; }
php
public static function calcAverage($small, $big) { $average = 0; if ($big != 0) { $x = 0; $y = 0; $average = 0; $x = $small / $big; $y = $x * 100; // $average = round($y); // converts to 65% $average = number_format((float)$y, 2, '.', ''); } return $average; }
[ "public", "static", "function", "calcAverage", "(", "$", "small", ",", "$", "big", ")", "{", "$", "average", "=", "0", ";", "if", "(", "$", "big", "!=", "0", ")", "{", "$", "x", "=", "0", ";", "$", "y", "=", "0", ";", "$", "average", "=", "0", ";", "$", "x", "=", "$", "small", "/", "$", "big", ";", "$", "y", "=", "$", "x", "*", "100", ";", "// $average = round($y); // converts to 65%", "$", "average", "=", "number_format", "(", "(", "float", ")", "$", "y", ",", "2", ",", "'.'", ",", "''", ")", ";", "}", "return", "$", "average", ";", "}" ]
calculates the average 0 to 100 @param int $small @param int $big @return int
[ "calculates", "the", "average", "0", "to", "100" ]
8ea9d67cc84fe6aff17a469c703d5492dbcd93ed
https://github.com/mwyatt/core/blob/8ea9d67cc84fe6aff17a469c703d5492dbcd93ed/src/Helper.php#L96-L109
train
gplcart/device
controllers/Settings.php
Settings.getFrontendThemesSettings
protected function getFrontendThemesSettings() { $themes = $this->module->getByType('theme', true); unset($themes[$this->theme_backend]); return $themes; }
php
protected function getFrontendThemesSettings() { $themes = $this->module->getByType('theme', true); unset($themes[$this->theme_backend]); return $themes; }
[ "protected", "function", "getFrontendThemesSettings", "(", ")", "{", "$", "themes", "=", "$", "this", "->", "module", "->", "getByType", "(", "'theme'", ",", "true", ")", ";", "unset", "(", "$", "themes", "[", "$", "this", "->", "theme_backend", "]", ")", ";", "return", "$", "themes", ";", "}" ]
Returns an array of frontend themes
[ "Returns", "an", "array", "of", "frontend", "themes" ]
288fcbd50cc3a2c7aa74cc0c3410135dcc9b2881
https://github.com/gplcart/device/blob/288fcbd50cc3a2c7aa74cc0c3410135dcc9b2881/controllers/Settings.php#L39-L44
train
Wedeto/Log
src/LoggerFactory.php
LoggerFactory.getLogger
public static function getLogger(array $context = array()) { $str = \Wedeto\Util\Functions::str($context); if (self::$logger_factory === null) return new NullLogger(); return self::$logger_factory->get(array($context['class'] ?? "Wedeto.UndefinedLogger")); }
php
public static function getLogger(array $context = array()) { $str = \Wedeto\Util\Functions::str($context); if (self::$logger_factory === null) return new NullLogger(); return self::$logger_factory->get(array($context['class'] ?? "Wedeto.UndefinedLogger")); }
[ "public", "static", "function", "getLogger", "(", "array", "$", "context", "=", "array", "(", ")", ")", "{", "$", "str", "=", "\\", "Wedeto", "\\", "Util", "\\", "Functions", "::", "str", "(", "$", "context", ")", ";", "if", "(", "self", "::", "$", "logger_factory", "===", "null", ")", "return", "new", "NullLogger", "(", ")", ";", "return", "self", "::", "$", "logger_factory", "->", "get", "(", "array", "(", "$", "context", "[", "'class'", "]", "??", "\"Wedeto.UndefinedLogger\"", ")", ")", ";", "}" ]
This function is subscribed to the Wedeto.Util.GetLogger hook to obtain their logger.
[ "This", "function", "is", "subscribed", "to", "the", "Wedeto", ".", "Util", ".", "GetLogger", "hook", "to", "obtain", "their", "logger", "." ]
88252c5052089fdcc5dae466d1ad5889bb2b735f
https://github.com/Wedeto/Log/blob/88252c5052089fdcc5dae466d1ad5889bb2b735f/src/LoggerFactory.php#L50-L57
train
Wedeto/HTTP
src/Response/Error.php
Error.getResponse
public function getResponse() { if (empty($this->response)) $this->response = new StringResponse(WF::str($this->getPrevious() ?? $this), "text/plain"); return $this->response; }
php
public function getResponse() { if (empty($this->response)) $this->response = new StringResponse(WF::str($this->getPrevious() ?? $this), "text/plain"); return $this->response; }
[ "public", "function", "getResponse", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "response", ")", ")", "$", "this", "->", "response", "=", "new", "StringResponse", "(", "WF", "::", "str", "(", "$", "this", "->", "getPrevious", "(", ")", "??", "$", "this", ")", ",", "\"text/plain\"", ")", ";", "return", "$", "this", "->", "response", ";", "}" ]
Get the formatted response, representing this error
[ "Get", "the", "formatted", "response", "representing", "this", "error" ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Response/Error.php#L68-L74
train
jfadich/json-property
src/JsonManager.php
JsonManager.getJsonProperty
public function getJsonProperty($property, $key = null, $default = null) { $instance = $this->getJsonInstance($property); if ( $key !== null ) { return $instance->get( $key, $default ); } return $instance; }
php
public function getJsonProperty($property, $key = null, $default = null) { $instance = $this->getJsonInstance($property); if ( $key !== null ) { return $instance->get( $key, $default ); } return $instance; }
[ "public", "function", "getJsonProperty", "(", "$", "property", ",", "$", "key", "=", "null", ",", "$", "default", "=", "null", ")", "{", "$", "instance", "=", "$", "this", "->", "getJsonInstance", "(", "$", "property", ")", ";", "if", "(", "$", "key", "!==", "null", ")", "{", "return", "$", "instance", "->", "get", "(", "$", "key", ",", "$", "default", ")", ";", "}", "return", "$", "instance", ";", "}" ]
Get instance for given property. If a key is given return the value or default. @param $property @param string $key @param mixed $default @return JsonProperty @throws JsonPropertyException
[ "Get", "instance", "for", "given", "property", ".", "If", "a", "key", "is", "given", "return", "the", "value", "or", "default", "." ]
3c11ac731a7bc206529058a94047eeafa5827b15
https://github.com/jfadich/json-property/blob/3c11ac731a7bc206529058a94047eeafa5827b15/src/JsonManager.php#L58-L67
train
jfadich/json-property
src/JsonManager.php
JsonManager.isJsonProperty
public function isJsonProperty($property, $throwException = false) { if(is_string($property) && in_array($property, $this->properties)) return true; if($throwException) throw new JsonPropertyException("Requested property '{$property}' is not a valid for '".get_class($this)."'."); return false; }
php
public function isJsonProperty($property, $throwException = false) { if(is_string($property) && in_array($property, $this->properties)) return true; if($throwException) throw new JsonPropertyException("Requested property '{$property}' is not a valid for '".get_class($this)."'."); return false; }
[ "public", "function", "isJsonProperty", "(", "$", "property", ",", "$", "throwException", "=", "false", ")", "{", "if", "(", "is_string", "(", "$", "property", ")", "&&", "in_array", "(", "$", "property", ",", "$", "this", "->", "properties", ")", ")", "return", "true", ";", "if", "(", "$", "throwException", ")", "throw", "new", "JsonPropertyException", "(", "\"Requested property '{$property}' is not a valid for '\"", ".", "get_class", "(", "$", "this", ")", ".", "\"'.\"", ")", ";", "return", "false", ";", "}" ]
Check if requested property is bound to the model @param string $property @param bool $throwException @return bool @throws JsonPropertyException
[ "Check", "if", "requested", "property", "is", "bound", "to", "the", "model" ]
3c11ac731a7bc206529058a94047eeafa5827b15
https://github.com/jfadich/json-property/blob/3c11ac731a7bc206529058a94047eeafa5827b15/src/JsonManager.php#L77-L86
train
jfadich/json-property
src/JsonManager.php
JsonManager.getJsonInstance
private function getJsonInstance($property) { if(!$this->isJsonProperty($property)) throw new JsonPropertyException("Requested property '{$property}' is not a valid for '".get_class($this->model)."'."); if(!array_key_exists($property, $this->jsonInstances)) $this->jsonInstances[$property] = new JsonProperty( $this->model, $property ); return $this->jsonInstances[$property]; }
php
private function getJsonInstance($property) { if(!$this->isJsonProperty($property)) throw new JsonPropertyException("Requested property '{$property}' is not a valid for '".get_class($this->model)."'."); if(!array_key_exists($property, $this->jsonInstances)) $this->jsonInstances[$property] = new JsonProperty( $this->model, $property ); return $this->jsonInstances[$property]; }
[ "private", "function", "getJsonInstance", "(", "$", "property", ")", "{", "if", "(", "!", "$", "this", "->", "isJsonProperty", "(", "$", "property", ")", ")", "throw", "new", "JsonPropertyException", "(", "\"Requested property '{$property}' is not a valid for '\"", ".", "get_class", "(", "$", "this", "->", "model", ")", ".", "\"'.\"", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "property", ",", "$", "this", "->", "jsonInstances", ")", ")", "$", "this", "->", "jsonInstances", "[", "$", "property", "]", "=", "new", "JsonProperty", "(", "$", "this", "->", "model", ",", "$", "property", ")", ";", "return", "$", "this", "->", "jsonInstances", "[", "$", "property", "]", ";", "}" ]
Instantiate the JsonProperty object, or return the existing instance @param string $property @return JsonProperty @throws JsonPropertyException
[ "Instantiate", "the", "JsonProperty", "object", "or", "return", "the", "existing", "instance" ]
3c11ac731a7bc206529058a94047eeafa5827b15
https://github.com/jfadich/json-property/blob/3c11ac731a7bc206529058a94047eeafa5827b15/src/JsonManager.php#L95-L104
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.buildConfig
private function buildConfig(Request $request) { $config = array( 'mode' => $request->query->get('mode', 'browse'), ); if (null !== $types = $request->query->get('types', array())) { // TODO validate types $config['types'] = $types; } return $config; }
php
private function buildConfig(Request $request) { $config = array( 'mode' => $request->query->get('mode', 'browse'), ); if (null !== $types = $request->query->get('types', array())) { // TODO validate types $config['types'] = $types; } return $config; }
[ "private", "function", "buildConfig", "(", "Request", "$", "request", ")", "{", "$", "config", "=", "array", "(", "'mode'", "=>", "$", "request", "->", "query", "->", "get", "(", "'mode'", ",", "'browse'", ")", ",", ")", ";", "if", "(", "null", "!==", "$", "types", "=", "$", "request", "->", "query", "->", "get", "(", "'types'", ",", "array", "(", ")", ")", ")", "{", "// TODO validate types", "$", "config", "[", "'types'", "]", "=", "$", "types", ";", "}", "return", "$", "config", ";", "}" ]
Builds the browser config. @param Request $request @return array
[ "Builds", "the", "browser", "config", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L86-L96
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.listAction
public function listAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $root = $this->getFolderRepository()->findRoot(); if (null !== $id = $request->query->get('folderId')) { if (!$this->activateFolderById($id, $root)) { $root->setActive(true); } } else { $root->setActive(true); } $folders = $this->get('jms_serializer')->serialize( array($root), 'json', SerializationContext::create()->setGroups(array('Manager')) ); $response = new Response($folders); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
php
public function listAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $root = $this->getFolderRepository()->findRoot(); if (null !== $id = $request->query->get('folderId')) { if (!$this->activateFolderById($id, $root)) { $root->setActive(true); } } else { $root->setActive(true); } $folders = $this->get('jms_serializer')->serialize( array($root), 'json', SerializationContext::create()->setGroups(array('Manager')) ); $response = new Response($folders); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
[ "public", "function", "listAction", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "$", "root", "=", "$", "this", "->", "getFolderRepository", "(", ")", "->", "findRoot", "(", ")", ";", "if", "(", "null", "!==", "$", "id", "=", "$", "request", "->", "query", "->", "get", "(", "'folderId'", ")", ")", "{", "if", "(", "!", "$", "this", "->", "activateFolderById", "(", "$", "id", ",", "$", "root", ")", ")", "{", "$", "root", "->", "setActive", "(", "true", ")", ";", "}", "}", "else", "{", "$", "root", "->", "setActive", "(", "true", ")", ";", "}", "$", "folders", "=", "$", "this", "->", "get", "(", "'jms_serializer'", ")", "->", "serialize", "(", "array", "(", "$", "root", ")", ",", "'json'", ",", "SerializationContext", "::", "create", "(", ")", "->", "setGroups", "(", "array", "(", "'Manager'", ")", ")", ")", ";", "$", "response", "=", "new", "Response", "(", "$", "folders", ")", ";", "$", "response", "->", "headers", "->", "add", "(", "array", "(", "'Content-Type'", "=>", "'application/json'", ")", ")", ";", "return", "$", "response", ";", "}" ]
Lists the children folders. @param Request $request @return Response
[ "Lists", "the", "children", "folders", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L105-L130
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.activateFolderById
private function activateFolderById($id, FolderInterface $folder) { foreach ($folder->getChildren() as $child) { if ($child->getId() == $id) { $child->setActive(true); return true; } if ($this->activateFolderById($id, $child)) { return true; } } return false; }
php
private function activateFolderById($id, FolderInterface $folder) { foreach ($folder->getChildren() as $child) { if ($child->getId() == $id) { $child->setActive(true); return true; } if ($this->activateFolderById($id, $child)) { return true; } } return false; }
[ "private", "function", "activateFolderById", "(", "$", "id", ",", "FolderInterface", "$", "folder", ")", "{", "foreach", "(", "$", "folder", "->", "getChildren", "(", ")", "as", "$", "child", ")", "{", "if", "(", "$", "child", "->", "getId", "(", ")", "==", "$", "id", ")", "{", "$", "child", "->", "setActive", "(", "true", ")", ";", "return", "true", ";", "}", "if", "(", "$", "this", "->", "activateFolderById", "(", "$", "id", ",", "$", "child", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Activate the folder by id. @param int $id @param FolderInterface $folder @return bool
[ "Activate", "the", "folder", "by", "id", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L140-L152
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.createAction
public function createAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $refFolder = $this->findFolderById($request->attributes->get('id')); $repo = $this->getFolderRepository(); $newFolder = $repo->createNew(); $newFolder->setName('New folder'); $mode = strtolower($request->request->get('mode')); if (!in_array($mode, array('child', 'after'))) { $response = new Response(json_encode(array( 'error' => true, 'message' => 'Unexpected creation mode.', ), JSON_FORCE_OBJECT)); } else { if ($mode === 'after') { $repo->persistAsNextSiblingOf($newFolder, $refFolder); } else { $repo->persistAsFirstChildOf($newFolder, $refFolder); } if (true !== $message = $this->validateFolder($newFolder)) { $response = new Response(json_encode(array( 'error' => true, 'message' => $message, ), JSON_FORCE_OBJECT)); } else { $this->getEntityManager()->flush(); $data = $this->get('jms_serializer')->serialize( $newFolder, 'json', SerializationContext::create()->setGroups(array('Manager')) ); $response = new Response(sprintf('{"node":%s}', $data)); } } $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
php
public function createAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $refFolder = $this->findFolderById($request->attributes->get('id')); $repo = $this->getFolderRepository(); $newFolder = $repo->createNew(); $newFolder->setName('New folder'); $mode = strtolower($request->request->get('mode')); if (!in_array($mode, array('child', 'after'))) { $response = new Response(json_encode(array( 'error' => true, 'message' => 'Unexpected creation mode.', ), JSON_FORCE_OBJECT)); } else { if ($mode === 'after') { $repo->persistAsNextSiblingOf($newFolder, $refFolder); } else { $repo->persistAsFirstChildOf($newFolder, $refFolder); } if (true !== $message = $this->validateFolder($newFolder)) { $response = new Response(json_encode(array( 'error' => true, 'message' => $message, ), JSON_FORCE_OBJECT)); } else { $this->getEntityManager()->flush(); $data = $this->get('jms_serializer')->serialize( $newFolder, 'json', SerializationContext::create()->setGroups(array('Manager')) ); $response = new Response(sprintf('{"node":%s}', $data)); } } $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
[ "public", "function", "createAction", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "$", "refFolder", "=", "$", "this", "->", "findFolderById", "(", "$", "request", "->", "attributes", "->", "get", "(", "'id'", ")", ")", ";", "$", "repo", "=", "$", "this", "->", "getFolderRepository", "(", ")", ";", "$", "newFolder", "=", "$", "repo", "->", "createNew", "(", ")", ";", "$", "newFolder", "->", "setName", "(", "'New folder'", ")", ";", "$", "mode", "=", "strtolower", "(", "$", "request", "->", "request", "->", "get", "(", "'mode'", ")", ")", ";", "if", "(", "!", "in_array", "(", "$", "mode", ",", "array", "(", "'child'", ",", "'after'", ")", ")", ")", "{", "$", "response", "=", "new", "Response", "(", "json_encode", "(", "array", "(", "'error'", "=>", "true", ",", "'message'", "=>", "'Unexpected creation mode.'", ",", ")", ",", "JSON_FORCE_OBJECT", ")", ")", ";", "}", "else", "{", "if", "(", "$", "mode", "===", "'after'", ")", "{", "$", "repo", "->", "persistAsNextSiblingOf", "(", "$", "newFolder", ",", "$", "refFolder", ")", ";", "}", "else", "{", "$", "repo", "->", "persistAsFirstChildOf", "(", "$", "newFolder", ",", "$", "refFolder", ")", ";", "}", "if", "(", "true", "!==", "$", "message", "=", "$", "this", "->", "validateFolder", "(", "$", "newFolder", ")", ")", "{", "$", "response", "=", "new", "Response", "(", "json_encode", "(", "array", "(", "'error'", "=>", "true", ",", "'message'", "=>", "$", "message", ",", ")", ",", "JSON_FORCE_OBJECT", ")", ")", ";", "}", "else", "{", "$", "this", "->", "getEntityManager", "(", ")", "->", "flush", "(", ")", ";", "$", "data", "=", "$", "this", "->", "get", "(", "'jms_serializer'", ")", "->", "serialize", "(", "$", "newFolder", ",", "'json'", ",", "SerializationContext", "::", "create", "(", ")", "->", "setGroups", "(", "array", "(", "'Manager'", ")", ")", ")", ";", "$", "response", "=", "new", "Response", "(", "sprintf", "(", "'{\"node\":%s}'", ",", "$", "data", ")", ")", ";", "}", "}", "$", "response", "->", "headers", "->", "add", "(", "array", "(", "'Content-Type'", "=>", "'application/json'", ")", ")", ";", "return", "$", "response", ";", "}" ]
Creates the folder. @param Request $request @return Response
[ "Creates", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L161-L204
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.renameAction
public function renameAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); $folder->setName($request->request->get('name')); if (true !== $message = $this->validateFolder($folder)) { $result = array( 'error' => true, 'message' => $message, ); } else { $this->persistFolder($folder); $result = array( 'name' => $folder->getName(), ); } $response = new Response(json_encode($result, JSON_FORCE_OBJECT)); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
php
public function renameAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); $folder->setName($request->request->get('name')); if (true !== $message = $this->validateFolder($folder)) { $result = array( 'error' => true, 'message' => $message, ); } else { $this->persistFolder($folder); $result = array( 'name' => $folder->getName(), ); } $response = new Response(json_encode($result, JSON_FORCE_OBJECT)); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
[ "public", "function", "renameAction", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "$", "folder", "=", "$", "this", "->", "findFolderById", "(", "$", "request", "->", "attributes", "->", "get", "(", "'id'", ")", ")", ";", "$", "folder", "->", "setName", "(", "$", "request", "->", "request", "->", "get", "(", "'name'", ")", ")", ";", "if", "(", "true", "!==", "$", "message", "=", "$", "this", "->", "validateFolder", "(", "$", "folder", ")", ")", "{", "$", "result", "=", "array", "(", "'error'", "=>", "true", ",", "'message'", "=>", "$", "message", ",", ")", ";", "}", "else", "{", "$", "this", "->", "persistFolder", "(", "$", "folder", ")", ";", "$", "result", "=", "array", "(", "'name'", "=>", "$", "folder", "->", "getName", "(", ")", ",", ")", ";", "}", "$", "response", "=", "new", "Response", "(", "json_encode", "(", "$", "result", ",", "JSON_FORCE_OBJECT", ")", ")", ";", "$", "response", "->", "headers", "->", "add", "(", "array", "(", "'Content-Type'", "=>", "'application/json'", ")", ")", ";", "return", "$", "response", ";", "}" ]
Renames the folder. @param Request $request @return Response
[ "Renames", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L213-L238
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.deleteAction
public function deleteAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); $result = array(); try { $this->removeFolder($folder); } catch (DBALException $e) { $result = array( 'error' => true, 'message' => 'Ce dossier n\'est pas vide.', ); } $response = new Response(json_encode($result, JSON_FORCE_OBJECT)); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
php
public function deleteAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); $result = array(); try { $this->removeFolder($folder); } catch (DBALException $e) { $result = array( 'error' => true, 'message' => 'Ce dossier n\'est pas vide.', ); } $response = new Response(json_encode($result, JSON_FORCE_OBJECT)); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
[ "public", "function", "deleteAction", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "$", "folder", "=", "$", "this", "->", "findFolderById", "(", "$", "request", "->", "attributes", "->", "get", "(", "'id'", ")", ")", ";", "$", "result", "=", "array", "(", ")", ";", "try", "{", "$", "this", "->", "removeFolder", "(", "$", "folder", ")", ";", "}", "catch", "(", "DBALException", "$", "e", ")", "{", "$", "result", "=", "array", "(", "'error'", "=>", "true", ",", "'message'", "=>", "'Ce dossier n\\'est pas vide.'", ",", ")", ";", "}", "$", "response", "=", "new", "Response", "(", "json_encode", "(", "$", "result", ",", "JSON_FORCE_OBJECT", ")", ")", ";", "$", "response", "->", "headers", "->", "add", "(", "array", "(", "'Content-Type'", "=>", "'application/json'", ")", ")", ";", "return", "$", "response", ";", "}" ]
Deletes the folder. @param Request $request @return Response
[ "Deletes", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L247-L268
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.moveAction
public function moveAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); $result = []; $mode = $request->request->get('mode'); if (!in_array($mode, array('before', 'after', 'over'))) { $result = array( 'error' => true, 'message' => 'Unexpected creation mode.', ); } else { $reference = $this->findFolderById($request->request->get('reference')); if ($mode === 'before') { $this->getFolderRepository()->persistAsPrevSiblingOf($folder, $reference); } elseif ($mode === 'after') { $this->getFolderRepository()->persistAsNextSiblingOf($folder, $reference); } elseif ($mode === 'over') { $this->getFolderRepository()->persistAsLastChildOf($folder, $reference); } $this->getEntityManager()->flush(); } $response = new Response(json_encode($result, JSON_FORCE_OBJECT)); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
php
public function moveAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); $result = []; $mode = $request->request->get('mode'); if (!in_array($mode, array('before', 'after', 'over'))) { $result = array( 'error' => true, 'message' => 'Unexpected creation mode.', ); } else { $reference = $this->findFolderById($request->request->get('reference')); if ($mode === 'before') { $this->getFolderRepository()->persistAsPrevSiblingOf($folder, $reference); } elseif ($mode === 'after') { $this->getFolderRepository()->persistAsNextSiblingOf($folder, $reference); } elseif ($mode === 'over') { $this->getFolderRepository()->persistAsLastChildOf($folder, $reference); } $this->getEntityManager()->flush(); } $response = new Response(json_encode($result, JSON_FORCE_OBJECT)); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
[ "public", "function", "moveAction", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "$", "folder", "=", "$", "this", "->", "findFolderById", "(", "$", "request", "->", "attributes", "->", "get", "(", "'id'", ")", ")", ";", "$", "result", "=", "[", "]", ";", "$", "mode", "=", "$", "request", "->", "request", "->", "get", "(", "'mode'", ")", ";", "if", "(", "!", "in_array", "(", "$", "mode", ",", "array", "(", "'before'", ",", "'after'", ",", "'over'", ")", ")", ")", "{", "$", "result", "=", "array", "(", "'error'", "=>", "true", ",", "'message'", "=>", "'Unexpected creation mode.'", ",", ")", ";", "}", "else", "{", "$", "reference", "=", "$", "this", "->", "findFolderById", "(", "$", "request", "->", "request", "->", "get", "(", "'reference'", ")", ")", ";", "if", "(", "$", "mode", "===", "'before'", ")", "{", "$", "this", "->", "getFolderRepository", "(", ")", "->", "persistAsPrevSiblingOf", "(", "$", "folder", ",", "$", "reference", ")", ";", "}", "elseif", "(", "$", "mode", "===", "'after'", ")", "{", "$", "this", "->", "getFolderRepository", "(", ")", "->", "persistAsNextSiblingOf", "(", "$", "folder", ",", "$", "reference", ")", ";", "}", "elseif", "(", "$", "mode", "===", "'over'", ")", "{", "$", "this", "->", "getFolderRepository", "(", ")", "->", "persistAsLastChildOf", "(", "$", "folder", ",", "$", "reference", ")", ";", "}", "$", "this", "->", "getEntityManager", "(", ")", "->", "flush", "(", ")", ";", "}", "$", "response", "=", "new", "Response", "(", "json_encode", "(", "$", "result", ",", "JSON_FORCE_OBJECT", ")", ")", ";", "$", "response", "->", "headers", "->", "add", "(", "array", "(", "'Content-Type'", "=>", "'application/json'", ")", ")", ";", "return", "$", "response", ";", "}" ]
Moves the folder. @param Request $request @return Response
[ "Moves", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L277-L309
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.listMediaAction
public function listMediaAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); $medias = $this ->get('ekyna_media.browser') ->setFolder($folder) ->findMedias((array)$request->query->get('types')); $data = array('medias' => $medias); $response = new Response($this->get('jms_serializer')->serialize( $data, 'json', SerializationContext::create()->setGroups(array('Manager')) )); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
php
public function listMediaAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); $medias = $this ->get('ekyna_media.browser') ->setFolder($folder) ->findMedias((array)$request->query->get('types')); $data = array('medias' => $medias); $response = new Response($this->get('jms_serializer')->serialize( $data, 'json', SerializationContext::create()->setGroups(array('Manager')) )); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
[ "public", "function", "listMediaAction", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "$", "folder", "=", "$", "this", "->", "findFolderById", "(", "$", "request", "->", "attributes", "->", "get", "(", "'id'", ")", ")", ";", "$", "medias", "=", "$", "this", "->", "get", "(", "'ekyna_media.browser'", ")", "->", "setFolder", "(", "$", "folder", ")", "->", "findMedias", "(", "(", "array", ")", "$", "request", "->", "query", "->", "get", "(", "'types'", ")", ")", ";", "$", "data", "=", "array", "(", "'medias'", "=>", "$", "medias", ")", ";", "$", "response", "=", "new", "Response", "(", "$", "this", "->", "get", "(", "'jms_serializer'", ")", "->", "serialize", "(", "$", "data", ",", "'json'", ",", "SerializationContext", "::", "create", "(", ")", "->", "setGroups", "(", "array", "(", "'Manager'", ")", ")", ")", ")", ";", "$", "response", "->", "headers", "->", "add", "(", "array", "(", "'Content-Type'", "=>", "'application/json'", ")", ")", ";", "return", "$", "response", ";", "}" ]
Lists the medias by folder. @param Request $request @return Response
[ "Lists", "the", "medias", "by", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L318-L341
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.moveMediaAction
public function moveMediaAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); /** @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $media */ $media = $this->get('ekyna_media.media.repository')->find($request->attributes->get('mediaId')); if (null === $media) { throw new NotFoundHttpException('Media not found.'); } if ($folder === $media->getFolder()) { $result = array('success' => true); } else { $media->setFolder($folder); $event = $this->get('ekyna_media.media.operator')->update($media); if (!$event->hasErrors()) { $result = array('success' => true); } else { $result = array('success' => false); } } $response = new Response(json_encode($result)); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
php
public function moveMediaAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folder = $this->findFolderById($request->attributes->get('id')); /** @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $media */ $media = $this->get('ekyna_media.media.repository')->find($request->attributes->get('mediaId')); if (null === $media) { throw new NotFoundHttpException('Media not found.'); } if ($folder === $media->getFolder()) { $result = array('success' => true); } else { $media->setFolder($folder); $event = $this->get('ekyna_media.media.operator')->update($media); if (!$event->hasErrors()) { $result = array('success' => true); } else { $result = array('success' => false); } } $response = new Response(json_encode($result)); $response->headers->add(array('Content-Type' => 'application/json')); return $response; }
[ "public", "function", "moveMediaAction", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "$", "folder", "=", "$", "this", "->", "findFolderById", "(", "$", "request", "->", "attributes", "->", "get", "(", "'id'", ")", ")", ";", "/** @var \\Ekyna\\Bundle\\MediaBundle\\Model\\MediaInterface $media */", "$", "media", "=", "$", "this", "->", "get", "(", "'ekyna_media.media.repository'", ")", "->", "find", "(", "$", "request", "->", "attributes", "->", "get", "(", "'mediaId'", ")", ")", ";", "if", "(", "null", "===", "$", "media", ")", "{", "throw", "new", "NotFoundHttpException", "(", "'Media not found.'", ")", ";", "}", "if", "(", "$", "folder", "===", "$", "media", "->", "getFolder", "(", ")", ")", "{", "$", "result", "=", "array", "(", "'success'", "=>", "true", ")", ";", "}", "else", "{", "$", "media", "->", "setFolder", "(", "$", "folder", ")", ";", "$", "event", "=", "$", "this", "->", "get", "(", "'ekyna_media.media.operator'", ")", "->", "update", "(", "$", "media", ")", ";", "if", "(", "!", "$", "event", "->", "hasErrors", "(", ")", ")", "{", "$", "result", "=", "array", "(", "'success'", "=>", "true", ")", ";", "}", "else", "{", "$", "result", "=", "array", "(", "'success'", "=>", "false", ")", ";", "}", "}", "$", "response", "=", "new", "Response", "(", "json_encode", "(", "$", "result", ")", ")", ";", "$", "response", "->", "headers", "->", "add", "(", "array", "(", "'Content-Type'", "=>", "'application/json'", ")", ")", ";", "return", "$", "response", ";", "}" ]
Moves the media to the folder. @param Request $request @return Response
[ "Moves", "the", "media", "to", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L350-L379
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.createMediaAction
public function createMediaAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folderId = $request->attributes->get('id'); $folder = $this->findFolderById($folderId); $upload = new MediaUpload(); $form = $this->createForm('ekyna_media_upload', $upload, array( 'action' => $this->generateUrl( 'ekyna_media_browser_admin_create_media', array('id' => $folderId) ), 'method' => 'POST', 'attr' => array( 'class' => 'form-horizontal form-with-tabs', ), 'folder' => $folder, )); $modal = $this->createModal(); $modal->setTitle('ekyna_media.upload.title'); $modal->setVars(array( 'form_template' => 'EkynaMediaBundle:Manager:upload.html.twig', )); $success = false; $form->handleRequest($request); if ($form->isValid()) { $success = true; // TODO use ResourceManager foreach ($upload->getMedias() as $media) { $event = $this->get('ekyna_media.media.operator')->create($media); if ($event->hasErrors()) { $success = false; break; } } } if ($success) { $modal->setContent(array('success' => true)); } else { $modal->setContent($form->createView()); } return $this->get('ekyna_core.modal')->render($modal); }
php
public function createMediaAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $folderId = $request->attributes->get('id'); $folder = $this->findFolderById($folderId); $upload = new MediaUpload(); $form = $this->createForm('ekyna_media_upload', $upload, array( 'action' => $this->generateUrl( 'ekyna_media_browser_admin_create_media', array('id' => $folderId) ), 'method' => 'POST', 'attr' => array( 'class' => 'form-horizontal form-with-tabs', ), 'folder' => $folder, )); $modal = $this->createModal(); $modal->setTitle('ekyna_media.upload.title'); $modal->setVars(array( 'form_template' => 'EkynaMediaBundle:Manager:upload.html.twig', )); $success = false; $form->handleRequest($request); if ($form->isValid()) { $success = true; // TODO use ResourceManager foreach ($upload->getMedias() as $media) { $event = $this->get('ekyna_media.media.operator')->create($media); if ($event->hasErrors()) { $success = false; break; } } } if ($success) { $modal->setContent(array('success' => true)); } else { $modal->setContent($form->createView()); } return $this->get('ekyna_core.modal')->render($modal); }
[ "public", "function", "createMediaAction", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "$", "folderId", "=", "$", "request", "->", "attributes", "->", "get", "(", "'id'", ")", ";", "$", "folder", "=", "$", "this", "->", "findFolderById", "(", "$", "folderId", ")", ";", "$", "upload", "=", "new", "MediaUpload", "(", ")", ";", "$", "form", "=", "$", "this", "->", "createForm", "(", "'ekyna_media_upload'", ",", "$", "upload", ",", "array", "(", "'action'", "=>", "$", "this", "->", "generateUrl", "(", "'ekyna_media_browser_admin_create_media'", ",", "array", "(", "'id'", "=>", "$", "folderId", ")", ")", ",", "'method'", "=>", "'POST'", ",", "'attr'", "=>", "array", "(", "'class'", "=>", "'form-horizontal form-with-tabs'", ",", ")", ",", "'folder'", "=>", "$", "folder", ",", ")", ")", ";", "$", "modal", "=", "$", "this", "->", "createModal", "(", ")", ";", "$", "modal", "->", "setTitle", "(", "'ekyna_media.upload.title'", ")", ";", "$", "modal", "->", "setVars", "(", "array", "(", "'form_template'", "=>", "'EkynaMediaBundle:Manager:upload.html.twig'", ",", ")", ")", ";", "$", "success", "=", "false", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "if", "(", "$", "form", "->", "isValid", "(", ")", ")", "{", "$", "success", "=", "true", ";", "// TODO use ResourceManager", "foreach", "(", "$", "upload", "->", "getMedias", "(", ")", "as", "$", "media", ")", "{", "$", "event", "=", "$", "this", "->", "get", "(", "'ekyna_media.media.operator'", ")", "->", "create", "(", "$", "media", ")", ";", "if", "(", "$", "event", "->", "hasErrors", "(", ")", ")", "{", "$", "success", "=", "false", ";", "break", ";", "}", "}", "}", "if", "(", "$", "success", ")", "{", "$", "modal", "->", "setContent", "(", "array", "(", "'success'", "=>", "true", ")", ")", ";", "}", "else", "{", "$", "modal", "->", "setContent", "(", "$", "form", "->", "createView", "(", ")", ")", ";", "}", "return", "$", "this", "->", "get", "(", "'ekyna_core.modal'", ")", "->", "render", "(", "$", "modal", ")", ";", "}" ]
Creates the media into the folder. @param Request $request @return Response
[ "Creates", "the", "media", "into", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L388-L437
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.importMediaAction
public function importMediaAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $modal = $this->createModal(); $modal->setTitle('ekyna_media.import.title'); $folderId = $request->attributes->get('id'); $folder = $this->findFolderById($folderId); $import = new MediaImport($folder); $flow = $this->get('ekyna_media.import_media.form_flow'); $flow->bind($import); $form = $flow->createForm(); if ($flow->isValid($form)) { $flow->saveCurrentStepData($form); if ($flow->nextStep()) { $form = $flow->createForm(); } else { // TODO use ResourceManager $operator = $this->get('ekyna_media.media.operator'); foreach ($import->getMedias() as $media) { $event = $operator->create($media); if ($event->isPropagationStopped()) { $this->addFlash(sprintf('Failed to create "%s" media.', $media->getPath()), 'danger'); } } $modal->setContent(array('success' => true)); return $this->get('ekyna_core.modal')->render($modal); } } $modal->setContent($form->createView()); return $this->get('ekyna_core.modal')->render($modal); }
php
public function importMediaAction(Request $request) { if (!$request->isXmlHttpRequest()) { throw new NotFoundHttpException(); } $modal = $this->createModal(); $modal->setTitle('ekyna_media.import.title'); $folderId = $request->attributes->get('id'); $folder = $this->findFolderById($folderId); $import = new MediaImport($folder); $flow = $this->get('ekyna_media.import_media.form_flow'); $flow->bind($import); $form = $flow->createForm(); if ($flow->isValid($form)) { $flow->saveCurrentStepData($form); if ($flow->nextStep()) { $form = $flow->createForm(); } else { // TODO use ResourceManager $operator = $this->get('ekyna_media.media.operator'); foreach ($import->getMedias() as $media) { $event = $operator->create($media); if ($event->isPropagationStopped()) { $this->addFlash(sprintf('Failed to create "%s" media.', $media->getPath()), 'danger'); } } $modal->setContent(array('success' => true)); return $this->get('ekyna_core.modal')->render($modal); } } $modal->setContent($form->createView()); return $this->get('ekyna_core.modal')->render($modal); }
[ "public", "function", "importMediaAction", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "$", "modal", "=", "$", "this", "->", "createModal", "(", ")", ";", "$", "modal", "->", "setTitle", "(", "'ekyna_media.import.title'", ")", ";", "$", "folderId", "=", "$", "request", "->", "attributes", "->", "get", "(", "'id'", ")", ";", "$", "folder", "=", "$", "this", "->", "findFolderById", "(", "$", "folderId", ")", ";", "$", "import", "=", "new", "MediaImport", "(", "$", "folder", ")", ";", "$", "flow", "=", "$", "this", "->", "get", "(", "'ekyna_media.import_media.form_flow'", ")", ";", "$", "flow", "->", "bind", "(", "$", "import", ")", ";", "$", "form", "=", "$", "flow", "->", "createForm", "(", ")", ";", "if", "(", "$", "flow", "->", "isValid", "(", "$", "form", ")", ")", "{", "$", "flow", "->", "saveCurrentStepData", "(", "$", "form", ")", ";", "if", "(", "$", "flow", "->", "nextStep", "(", ")", ")", "{", "$", "form", "=", "$", "flow", "->", "createForm", "(", ")", ";", "}", "else", "{", "// TODO use ResourceManager", "$", "operator", "=", "$", "this", "->", "get", "(", "'ekyna_media.media.operator'", ")", ";", "foreach", "(", "$", "import", "->", "getMedias", "(", ")", "as", "$", "media", ")", "{", "$", "event", "=", "$", "operator", "->", "create", "(", "$", "media", ")", ";", "if", "(", "$", "event", "->", "isPropagationStopped", "(", ")", ")", "{", "$", "this", "->", "addFlash", "(", "sprintf", "(", "'Failed to create \"%s\" media.'", ",", "$", "media", "->", "getPath", "(", ")", ")", ",", "'danger'", ")", ";", "}", "}", "$", "modal", "->", "setContent", "(", "array", "(", "'success'", "=>", "true", ")", ")", ";", "return", "$", "this", "->", "get", "(", "'ekyna_core.modal'", ")", "->", "render", "(", "$", "modal", ")", ";", "}", "}", "$", "modal", "->", "setContent", "(", "$", "form", "->", "createView", "(", ")", ")", ";", "return", "$", "this", "->", "get", "(", "'ekyna_core.modal'", ")", "->", "render", "(", "$", "modal", ")", ";", "}" ]
Imports the media into the folder. @param Request $request @return Response
[ "Imports", "the", "media", "into", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L446-L487
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.persistFolder
private function persistFolder(FolderInterface $folder) { $em = $this->getEntityManager(); $em->persist($folder); $em->flush(); }
php
private function persistFolder(FolderInterface $folder) { $em = $this->getEntityManager(); $em->persist($folder); $em->flush(); }
[ "private", "function", "persistFolder", "(", "FolderInterface", "$", "folder", ")", "{", "$", "em", "=", "$", "this", "->", "getEntityManager", "(", ")", ";", "$", "em", "->", "persist", "(", "$", "folder", ")", ";", "$", "em", "->", "flush", "(", ")", ";", "}" ]
Persists the folder. @param FolderInterface $folder
[ "Persists", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L524-L529
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.removeFolder
private function removeFolder(FolderInterface $folder) { $em = $this->getEntityManager(); $em->remove($folder); $em->flush(); }
php
private function removeFolder(FolderInterface $folder) { $em = $this->getEntityManager(); $em->remove($folder); $em->flush(); }
[ "private", "function", "removeFolder", "(", "FolderInterface", "$", "folder", ")", "{", "$", "em", "=", "$", "this", "->", "getEntityManager", "(", ")", ";", "$", "em", "->", "remove", "(", "$", "folder", ")", ";", "$", "em", "->", "flush", "(", ")", ";", "}" ]
Removes the folder. @param FolderInterface $folder
[ "Removes", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L536-L541
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.validateFolder
private function validateFolder(FolderInterface $folder) { $errorList = $this->get('validator')->validate($folder); if ($errorList->count()) { return $errorList->get(0)->getMessage(); } return true; }
php
private function validateFolder(FolderInterface $folder) { $errorList = $this->get('validator')->validate($folder); if ($errorList->count()) { return $errorList->get(0)->getMessage(); } return true; }
[ "private", "function", "validateFolder", "(", "FolderInterface", "$", "folder", ")", "{", "$", "errorList", "=", "$", "this", "->", "get", "(", "'validator'", ")", "->", "validate", "(", "$", "folder", ")", ";", "if", "(", "$", "errorList", "->", "count", "(", ")", ")", "{", "return", "$", "errorList", "->", "get", "(", "0", ")", "->", "getMessage", "(", ")", ";", "}", "return", "true", ";", "}" ]
Validates the folder. @param FolderInterface $folder @return true|string
[ "Validates", "the", "folder", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L560-L567
train
ekyna/MediaBundle
Controller/Admin/BrowserController.php
BrowserController.findFolderById
private function findFolderById($id) { $folder = $this->getFolderRepository()->find($id); if (null === $folder) { throw new NotFoundHttpException('Folder not found.'); } return $folder; }
php
private function findFolderById($id) { $folder = $this->getFolderRepository()->find($id); if (null === $folder) { throw new NotFoundHttpException('Folder not found.'); } return $folder; }
[ "private", "function", "findFolderById", "(", "$", "id", ")", "{", "$", "folder", "=", "$", "this", "->", "getFolderRepository", "(", ")", "->", "find", "(", "$", "id", ")", ";", "if", "(", "null", "===", "$", "folder", ")", "{", "throw", "new", "NotFoundHttpException", "(", "'Folder not found.'", ")", ";", "}", "return", "$", "folder", ";", "}" ]
Returns the folder by id. @param integer $id @return FolderInterface
[ "Returns", "the", "folder", "by", "id", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/Admin/BrowserController.php#L576-L583
train
praxigento/mobi_mod_pv
Service/Sale/Save.php
Save.exec
public function exec(ARequest $request) { $result = new AResponse(); $orderId = $request->getSaleOrderId(); $datePaid = $request->getSaleOrderDatePaid(); $items = $request->getOrderItems(); /* for all items get PV data by warehouse */ $orderTotal = 0; foreach ($items as $item) { $prodId = $item->getProductId(); $stockId = $item->getStockId(); $itemId = $item->getItemId(); $pv = $this->daoStockItem->getPvByProductAndStock($prodId, $stockId); $qty = $item->getQuantity(); $total = $pv * $qty; $eItem = new \Praxigento\Pv\Repo\Data\Sale\Item(); $eItem->setItemRef($itemId); $eItem->setSubtotal($total); $eItem->setDiscount(0); $eItem->setTotal($total); $this->daoSaleItem->replace($eItem); $orderTotal += $total; } /* save order data */ $eOrder = new \Praxigento\Pv\Repo\Data\Sale(); $eOrder->setSaleRef($orderId); $eOrder->setSubtotal($orderTotal); $eOrder->setDiscount(0); $eOrder->setTotal($orderTotal); $eOrder->setDatePaid($datePaid); $this->daoSale->replace($eOrder); $result->markSucceed(); return $result; }
php
public function exec(ARequest $request) { $result = new AResponse(); $orderId = $request->getSaleOrderId(); $datePaid = $request->getSaleOrderDatePaid(); $items = $request->getOrderItems(); /* for all items get PV data by warehouse */ $orderTotal = 0; foreach ($items as $item) { $prodId = $item->getProductId(); $stockId = $item->getStockId(); $itemId = $item->getItemId(); $pv = $this->daoStockItem->getPvByProductAndStock($prodId, $stockId); $qty = $item->getQuantity(); $total = $pv * $qty; $eItem = new \Praxigento\Pv\Repo\Data\Sale\Item(); $eItem->setItemRef($itemId); $eItem->setSubtotal($total); $eItem->setDiscount(0); $eItem->setTotal($total); $this->daoSaleItem->replace($eItem); $orderTotal += $total; } /* save order data */ $eOrder = new \Praxigento\Pv\Repo\Data\Sale(); $eOrder->setSaleRef($orderId); $eOrder->setSubtotal($orderTotal); $eOrder->setDiscount(0); $eOrder->setTotal($orderTotal); $eOrder->setDatePaid($datePaid); $this->daoSale->replace($eOrder); $result->markSucceed(); return $result; }
[ "public", "function", "exec", "(", "ARequest", "$", "request", ")", "{", "$", "result", "=", "new", "AResponse", "(", ")", ";", "$", "orderId", "=", "$", "request", "->", "getSaleOrderId", "(", ")", ";", "$", "datePaid", "=", "$", "request", "->", "getSaleOrderDatePaid", "(", ")", ";", "$", "items", "=", "$", "request", "->", "getOrderItems", "(", ")", ";", "/* for all items get PV data by warehouse */", "$", "orderTotal", "=", "0", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "prodId", "=", "$", "item", "->", "getProductId", "(", ")", ";", "$", "stockId", "=", "$", "item", "->", "getStockId", "(", ")", ";", "$", "itemId", "=", "$", "item", "->", "getItemId", "(", ")", ";", "$", "pv", "=", "$", "this", "->", "daoStockItem", "->", "getPvByProductAndStock", "(", "$", "prodId", ",", "$", "stockId", ")", ";", "$", "qty", "=", "$", "item", "->", "getQuantity", "(", ")", ";", "$", "total", "=", "$", "pv", "*", "$", "qty", ";", "$", "eItem", "=", "new", "\\", "Praxigento", "\\", "Pv", "\\", "Repo", "\\", "Data", "\\", "Sale", "\\", "Item", "(", ")", ";", "$", "eItem", "->", "setItemRef", "(", "$", "itemId", ")", ";", "$", "eItem", "->", "setSubtotal", "(", "$", "total", ")", ";", "$", "eItem", "->", "setDiscount", "(", "0", ")", ";", "$", "eItem", "->", "setTotal", "(", "$", "total", ")", ";", "$", "this", "->", "daoSaleItem", "->", "replace", "(", "$", "eItem", ")", ";", "$", "orderTotal", "+=", "$", "total", ";", "}", "/* save order data */", "$", "eOrder", "=", "new", "\\", "Praxigento", "\\", "Pv", "\\", "Repo", "\\", "Data", "\\", "Sale", "(", ")", ";", "$", "eOrder", "->", "setSaleRef", "(", "$", "orderId", ")", ";", "$", "eOrder", "->", "setSubtotal", "(", "$", "orderTotal", ")", ";", "$", "eOrder", "->", "setDiscount", "(", "0", ")", ";", "$", "eOrder", "->", "setTotal", "(", "$", "orderTotal", ")", ";", "$", "eOrder", "->", "setDatePaid", "(", "$", "datePaid", ")", ";", "$", "this", "->", "daoSale", "->", "replace", "(", "$", "eOrder", ")", ";", "$", "result", "->", "markSucceed", "(", ")", ";", "return", "$", "result", ";", "}" ]
Save PV data on sale order save. @param ARequest $request @return AResponse
[ "Save", "PV", "data", "on", "sale", "order", "save", "." ]
d1540b7e94264527006e8b9fa68904a72a63928e
https://github.com/praxigento/mobi_mod_pv/blob/d1540b7e94264527006e8b9fa68904a72a63928e/Service/Sale/Save.php#L36-L70
train
smalldb/smalldb-rest
class/Application.php
Application.createSmalldb
public static function createSmalldb($config) { // Create Smalldb backend without context $smalldb = new \Smalldb\StateMachine\JsonDirBackend($config['smalldb'], null, 'smalldb'); // Initialize database connection & query builder $flupdo = \Smalldb\Flupdo\Flupdo::createInstanceFromConfig($config['flupdo']); // Initialize authenticator if (!isset($config['auth']['class'])) { throw new InvalidArgumentException('Authenticator not defined. Please set auth.class option.'); } $auth_class = $config['auth']['class']; $auth = new $auth_class($config['auth'], $smalldb); // Set Smalldb context $smalldb->setContext(array( 'database' => $flupdo, 'auth' => $auth, )); // Kick up Auth $auth->checkSession(); return $smalldb; }
php
public static function createSmalldb($config) { // Create Smalldb backend without context $smalldb = new \Smalldb\StateMachine\JsonDirBackend($config['smalldb'], null, 'smalldb'); // Initialize database connection & query builder $flupdo = \Smalldb\Flupdo\Flupdo::createInstanceFromConfig($config['flupdo']); // Initialize authenticator if (!isset($config['auth']['class'])) { throw new InvalidArgumentException('Authenticator not defined. Please set auth.class option.'); } $auth_class = $config['auth']['class']; $auth = new $auth_class($config['auth'], $smalldb); // Set Smalldb context $smalldb->setContext(array( 'database' => $flupdo, 'auth' => $auth, )); // Kick up Auth $auth->checkSession(); return $smalldb; }
[ "public", "static", "function", "createSmalldb", "(", "$", "config", ")", "{", "// Create Smalldb backend without context", "$", "smalldb", "=", "new", "\\", "Smalldb", "\\", "StateMachine", "\\", "JsonDirBackend", "(", "$", "config", "[", "'smalldb'", "]", ",", "null", ",", "'smalldb'", ")", ";", "// Initialize database connection & query builder", "$", "flupdo", "=", "\\", "Smalldb", "\\", "Flupdo", "\\", "Flupdo", "::", "createInstanceFromConfig", "(", "$", "config", "[", "'flupdo'", "]", ")", ";", "// Initialize authenticator", "if", "(", "!", "isset", "(", "$", "config", "[", "'auth'", "]", "[", "'class'", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Authenticator not defined. Please set auth.class option.'", ")", ";", "}", "$", "auth_class", "=", "$", "config", "[", "'auth'", "]", "[", "'class'", "]", ";", "$", "auth", "=", "new", "$", "auth_class", "(", "$", "config", "[", "'auth'", "]", ",", "$", "smalldb", ")", ";", "// Set Smalldb context", "$", "smalldb", "->", "setContext", "(", "array", "(", "'database'", "=>", "$", "flupdo", ",", "'auth'", "=>", "$", "auth", ",", ")", ")", ";", "// Kick up Auth", "$", "auth", "->", "checkSession", "(", ")", ";", "return", "$", "smalldb", ";", "}" ]
Create and initialize Smalldb, including Flupdo and Auth objects
[ "Create", "and", "initialize", "Smalldb", "including", "Flupdo", "and", "Auth", "objects" ]
ff393ee39060b4524d41835921e86ed40af006fe
https://github.com/smalldb/smalldb-rest/blob/ff393ee39060b4524d41835921e86ed40af006fe/class/Application.php#L136-L161
train
smalldb/smalldb-rest
class/Application.php
Application.renderStateMachine
public static function renderStateMachine(\Smalldb\StateMachine\AbstractBackend $smalldb, $machine, $format) { $dot = $smalldb->getMachine($machine)->exportDot(); if ($format == 'dot') { header('Content-Type: text/plain; encoding=utf8'); echo $dot; } else if ($format == 'png' || $format == 'pdf' || $format == 'svg') { $image = FALSE; // Check cache $dot_hash = md5($dot).'_'.$format; if (function_exists('apcu_fetch')) { $image = apcu_fetch($dot_hash); } if ($image === FALSE) { // Render diagram using Graphviz $p = proc_open('dot -T'.$format, [ ['pipe', 'r'], ['pipe', 'wb'], ['file', 'php://stdout', 'a'] ], $fp); fwrite($fp[0], $dot); fclose($fp[0]); $image = stream_get_contents($fp[1]); fclose($fp[1]); $err = proc_close($p); if ($err != 0) { // Failed - drop corrupt image data $image = FALSE; } else if (function_exists('apcu_store')) { // Store image in cache apcu_store($dot_hash, $image, 3600); } } if ($image) { // Send image switch ($format) { case 'png': header('Content-Type: image/png'); break; case 'svg': header('Content-Type: image/svg+xml'); break; case 'pdf': header('Content-Type: application/pdf'); break; } echo $image; } } else { throw new \InvalidArgumentException('Unknown format'); } }
php
public static function renderStateMachine(\Smalldb\StateMachine\AbstractBackend $smalldb, $machine, $format) { $dot = $smalldb->getMachine($machine)->exportDot(); if ($format == 'dot') { header('Content-Type: text/plain; encoding=utf8'); echo $dot; } else if ($format == 'png' || $format == 'pdf' || $format == 'svg') { $image = FALSE; // Check cache $dot_hash = md5($dot).'_'.$format; if (function_exists('apcu_fetch')) { $image = apcu_fetch($dot_hash); } if ($image === FALSE) { // Render diagram using Graphviz $p = proc_open('dot -T'.$format, [ ['pipe', 'r'], ['pipe', 'wb'], ['file', 'php://stdout', 'a'] ], $fp); fwrite($fp[0], $dot); fclose($fp[0]); $image = stream_get_contents($fp[1]); fclose($fp[1]); $err = proc_close($p); if ($err != 0) { // Failed - drop corrupt image data $image = FALSE; } else if (function_exists('apcu_store')) { // Store image in cache apcu_store($dot_hash, $image, 3600); } } if ($image) { // Send image switch ($format) { case 'png': header('Content-Type: image/png'); break; case 'svg': header('Content-Type: image/svg+xml'); break; case 'pdf': header('Content-Type: application/pdf'); break; } echo $image; } } else { throw new \InvalidArgumentException('Unknown format'); } }
[ "public", "static", "function", "renderStateMachine", "(", "\\", "Smalldb", "\\", "StateMachine", "\\", "AbstractBackend", "$", "smalldb", ",", "$", "machine", ",", "$", "format", ")", "{", "$", "dot", "=", "$", "smalldb", "->", "getMachine", "(", "$", "machine", ")", "->", "exportDot", "(", ")", ";", "if", "(", "$", "format", "==", "'dot'", ")", "{", "header", "(", "'Content-Type: text/plain; encoding=utf8'", ")", ";", "echo", "$", "dot", ";", "}", "else", "if", "(", "$", "format", "==", "'png'", "||", "$", "format", "==", "'pdf'", "||", "$", "format", "==", "'svg'", ")", "{", "$", "image", "=", "FALSE", ";", "// Check cache", "$", "dot_hash", "=", "md5", "(", "$", "dot", ")", ".", "'_'", ".", "$", "format", ";", "if", "(", "function_exists", "(", "'apcu_fetch'", ")", ")", "{", "$", "image", "=", "apcu_fetch", "(", "$", "dot_hash", ")", ";", "}", "if", "(", "$", "image", "===", "FALSE", ")", "{", "// Render diagram using Graphviz", "$", "p", "=", "proc_open", "(", "'dot -T'", ".", "$", "format", ",", "[", "[", "'pipe'", ",", "'r'", "]", ",", "[", "'pipe'", ",", "'wb'", "]", ",", "[", "'file'", ",", "'php://stdout'", ",", "'a'", "]", "]", ",", "$", "fp", ")", ";", "fwrite", "(", "$", "fp", "[", "0", "]", ",", "$", "dot", ")", ";", "fclose", "(", "$", "fp", "[", "0", "]", ")", ";", "$", "image", "=", "stream_get_contents", "(", "$", "fp", "[", "1", "]", ")", ";", "fclose", "(", "$", "fp", "[", "1", "]", ")", ";", "$", "err", "=", "proc_close", "(", "$", "p", ")", ";", "if", "(", "$", "err", "!=", "0", ")", "{", "// Failed - drop corrupt image data", "$", "image", "=", "FALSE", ";", "}", "else", "if", "(", "function_exists", "(", "'apcu_store'", ")", ")", "{", "// Store image in cache", "apcu_store", "(", "$", "dot_hash", ",", "$", "image", ",", "3600", ")", ";", "}", "}", "if", "(", "$", "image", ")", "{", "// Send image", "switch", "(", "$", "format", ")", "{", "case", "'png'", ":", "header", "(", "'Content-Type: image/png'", ")", ";", "break", ";", "case", "'svg'", ":", "header", "(", "'Content-Type: image/svg+xml'", ")", ";", "break", ";", "case", "'pdf'", ":", "header", "(", "'Content-Type: application/pdf'", ")", ";", "break", ";", "}", "echo", "$", "image", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unknown format'", ")", ";", "}", "}" ]
Render state diagram
[ "Render", "state", "diagram" ]
ff393ee39060b4524d41835921e86ed40af006fe
https://github.com/smalldb/smalldb-rest/blob/ff393ee39060b4524d41835921e86ed40af006fe/class/Application.php#L186-L234
train
lightwerk/SurfTasks
Classes/Lightwerk/SurfTasks/Task/Database/AbstractTask.php
AbstractTask.getMysqlArguments
protected function getMysqlArguments($credentials, $appendDatabase = true) { $arguments = []; $database = ''; foreach ($this->databaseArguments as $key) { if (empty($credentials[$key])) { continue; } $value = escapeshellarg($credentials[$key]); if ($key === 'database') { $database = $value; } else { $arguments[$key] = '--' . $key . '=' . $value; } } if ($appendDatabase === true) { return implode(' ', $arguments) . ' ' . $database; } else { return implode(' ', $arguments); } }
php
protected function getMysqlArguments($credentials, $appendDatabase = true) { $arguments = []; $database = ''; foreach ($this->databaseArguments as $key) { if (empty($credentials[$key])) { continue; } $value = escapeshellarg($credentials[$key]); if ($key === 'database') { $database = $value; } else { $arguments[$key] = '--' . $key . '=' . $value; } } if ($appendDatabase === true) { return implode(' ', $arguments) . ' ' . $database; } else { return implode(' ', $arguments); } }
[ "protected", "function", "getMysqlArguments", "(", "$", "credentials", ",", "$", "appendDatabase", "=", "true", ")", "{", "$", "arguments", "=", "[", "]", ";", "$", "database", "=", "''", ";", "foreach", "(", "$", "this", "->", "databaseArguments", "as", "$", "key", ")", "{", "if", "(", "empty", "(", "$", "credentials", "[", "$", "key", "]", ")", ")", "{", "continue", ";", "}", "$", "value", "=", "escapeshellarg", "(", "$", "credentials", "[", "$", "key", "]", ")", ";", "if", "(", "$", "key", "===", "'database'", ")", "{", "$", "database", "=", "$", "value", ";", "}", "else", "{", "$", "arguments", "[", "$", "key", "]", "=", "'--'", ".", "$", "key", ".", "'='", ".", "$", "value", ";", "}", "}", "if", "(", "$", "appendDatabase", "===", "true", ")", "{", "return", "implode", "(", "' '", ",", "$", "arguments", ")", ".", "' '", ".", "$", "database", ";", "}", "else", "{", "return", "implode", "(", "' '", ",", "$", "arguments", ")", ";", "}", "}" ]
Returns MySQL Arguments. @param array $credentials @param bool $appendDatabase @return string
[ "Returns", "MySQL", "Arguments", "." ]
8a6e4c85e42c762ad6515778c3fc7e19052cd9d1
https://github.com/lightwerk/SurfTasks/blob/8a6e4c85e42c762ad6515778c3fc7e19052cd9d1/Classes/Lightwerk/SurfTasks/Task/Database/AbstractTask.php#L158-L178
train
sndsgd/sndsgd-event
src/Event.php
Event.split
public static function split($event) { if (!is_string($event)) { throw new InvalidArgumentException( "invalid value provided for 'event'; expecting an event name ". "or event name and namespace as string" ); } list($type, $namespace) = array_pad(explode('.', $event, 2), 2, null); return [ ($type === '') ? null : $type, ($namespace === '') ? null : $namespace ]; }
php
public static function split($event) { if (!is_string($event)) { throw new InvalidArgumentException( "invalid value provided for 'event'; expecting an event name ". "or event name and namespace as string" ); } list($type, $namespace) = array_pad(explode('.', $event, 2), 2, null); return [ ($type === '') ? null : $type, ($namespace === '') ? null : $namespace ]; }
[ "public", "static", "function", "split", "(", "$", "event", ")", "{", "if", "(", "!", "is_string", "(", "$", "event", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"invalid value provided for 'event'; expecting an event name \"", ".", "\"or event name and namespace as string\"", ")", ";", "}", "list", "(", "$", "type", ",", "$", "namespace", ")", "=", "array_pad", "(", "explode", "(", "'.'", ",", "$", "event", ",", "2", ")", ",", "2", ",", "null", ")", ";", "return", "[", "(", "$", "type", "===", "''", ")", "?", "null", ":", "$", "type", ",", "(", "$", "namespace", "===", "''", ")", "?", "null", ":", "$", "namespace", "]", ";", "}" ]
Split an event in the type and namespace portions @param string $event The type/namespace combo for an event @return array.<string|null>
[ "Split", "an", "event", "in", "the", "type", "and", "namespace", "portions" ]
531bd348fd77db6a27346aa6dfec43e99ecd3eef
https://github.com/sndsgd/sndsgd-event/blob/531bd348fd77db6a27346aa6dfec43e99ecd3eef/src/Event.php#L24-L38
train
dms-org/common.structure
src/Table/Form/Builder/TableColumnFieldDefiner.php
TableColumnFieldDefiner.withPredefinedColumnValues
public function withPredefinedColumnValues(FieldBuilderBase $field, array $columnValues) : TableRowFieldDefiner { $this->fieldBuilder->attr(TableType::ATTR_PREDEFINED_COLUMNS, array_values($columnValues)); return $this->withColumnKeyAs($field); }
php
public function withPredefinedColumnValues(FieldBuilderBase $field, array $columnValues) : TableRowFieldDefiner { $this->fieldBuilder->attr(TableType::ATTR_PREDEFINED_COLUMNS, array_values($columnValues)); return $this->withColumnKeyAs($field); }
[ "public", "function", "withPredefinedColumnValues", "(", "FieldBuilderBase", "$", "field", ",", "array", "$", "columnValues", ")", ":", "TableRowFieldDefiner", "{", "$", "this", "->", "fieldBuilder", "->", "attr", "(", "TableType", "::", "ATTR_PREDEFINED_COLUMNS", ",", "array_values", "(", "$", "columnValues", ")", ")", ";", "return", "$", "this", "->", "withColumnKeyAs", "(", "$", "field", ")", ";", "}" ]
Defines the columns as predefined set of values. @param FieldBuilderBase $field @param array $columnValues @return TableRowFieldDefiner
[ "Defines", "the", "columns", "as", "predefined", "set", "of", "values", "." ]
23f122182f60df5ec847047a81a39c8aab019ff1
https://github.com/dms-org/common.structure/blob/23f122182f60df5ec847047a81a39c8aab019ff1/src/Table/Form/Builder/TableColumnFieldDefiner.php#L46-L50
train
dms-org/common.structure
src/Table/Form/Builder/TableColumnFieldDefiner.php
TableColumnFieldDefiner.withColumnKeyAsField
public function withColumnKeyAsField(IField $field) : TableRowFieldDefiner { return new TableRowFieldDefiner($this->fieldBuilder, $this->cellClassName, $field); }
php
public function withColumnKeyAsField(IField $field) : TableRowFieldDefiner { return new TableRowFieldDefiner($this->fieldBuilder, $this->cellClassName, $field); }
[ "public", "function", "withColumnKeyAsField", "(", "IField", "$", "field", ")", ":", "TableRowFieldDefiner", "{", "return", "new", "TableRowFieldDefiner", "(", "$", "this", "->", "fieldBuilder", ",", "$", "this", "->", "cellClassName", ",", "$", "field", ")", ";", "}" ]
Defines the column field for the table. @param IField $field @return TableRowFieldDefiner
[ "Defines", "the", "column", "field", "for", "the", "table", "." ]
23f122182f60df5ec847047a81a39c8aab019ff1
https://github.com/dms-org/common.structure/blob/23f122182f60df5ec847047a81a39c8aab019ff1/src/Table/Form/Builder/TableColumnFieldDefiner.php#L71-L74
train
comodojo/foundation
src/Comodojo/Foundation/Utils/ArrayOps.php
ArrayOps.circularDiffKeys
public static function circularDiffKeys(array $left, array $right) { return [ // only in left array_diff_key($left, $right), // common keys array_intersect_key($left, $right), // only in right array_diff_key($right, $left) ]; }
php
public static function circularDiffKeys(array $left, array $right) { return [ // only in left array_diff_key($left, $right), // common keys array_intersect_key($left, $right), // only in right array_diff_key($right, $left) ]; }
[ "public", "static", "function", "circularDiffKeys", "(", "array", "$", "left", ",", "array", "$", "right", ")", "{", "return", "[", "// only in left", "array_diff_key", "(", "$", "left", ",", "$", "right", ")", ",", "// common keys", "array_intersect_key", "(", "$", "left", ",", "$", "right", ")", ",", "// only in right", "array_diff_key", "(", "$", "right", ",", "$", "left", ")", "]", ";", "}" ]
Perform a circular diff between two arrays using keys. This method returns an array containing: [ [keys in $left array but not in $right], [keys in both %left and $right], [keys in $right but not in $left], ] @param array $left @param array $right @return array
[ "Perform", "a", "circular", "diff", "between", "two", "arrays", "using", "keys", "." ]
21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a
https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Utils/ArrayOps.php#L35-L46
train
comodojo/foundation
src/Comodojo/Foundation/Utils/ArrayOps.php
ArrayOps.replaceStrict
public static function replaceStrict(array $source, array ...$replace) { $replacements = []; foreach ($replace as $items) { $replacements[] = array_intersect_key($items, $source); } return array_merge($source, ...$replacements); }
php
public static function replaceStrict(array $source, array ...$replace) { $replacements = []; foreach ($replace as $items) { $replacements[] = array_intersect_key($items, $source); } return array_merge($source, ...$replacements); }
[ "public", "static", "function", "replaceStrict", "(", "array", "$", "source", ",", "array", "...", "$", "replace", ")", "{", "$", "replacements", "=", "[", "]", ";", "foreach", "(", "$", "replace", "as", "$", "items", ")", "{", "$", "replacements", "[", "]", "=", "array_intersect_key", "(", "$", "items", ",", "$", "source", ")", ";", "}", "return", "array_merge", "(", "$", "source", ",", "...", "$", "replacements", ")", ";", "}" ]
Replace items only if relative keys are actually defined in source array @param array $source @param array $replace @return array
[ "Replace", "items", "only", "if", "relative", "keys", "are", "actually", "defined", "in", "source", "array" ]
21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a
https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Utils/ArrayOps.php#L68-L78
train
wb-crowdfusion/crowdfusion
system/core/classes/nodedb/utils/MetaUtils.php
MetaUtils.validateMeta
public static function validateMeta(array &$array) { foreach ($array as $key => $tag) { if (!($tag instanceof Meta)) { $newtag = new Meta($tag); $array[$key] = $newtag; } } }
php
public static function validateMeta(array &$array) { foreach ($array as $key => $tag) { if (!($tag instanceof Meta)) { $newtag = new Meta($tag); $array[$key] = $newtag; } } }
[ "public", "static", "function", "validateMeta", "(", "array", "&", "$", "array", ")", "{", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "tag", ")", "{", "if", "(", "!", "(", "$", "tag", "instanceof", "Meta", ")", ")", "{", "$", "newtag", "=", "new", "Meta", "(", "$", "tag", ")", ";", "$", "array", "[", "$", "key", "]", "=", "$", "newtag", ";", "}", "}", "}" ]
Validates that the given array contains all valid Meta entries @param array &$array An array of strings or Meta objects @return void @throws Exception if any items are invalid.
[ "Validates", "that", "the", "given", "array", "contains", "all", "valid", "Meta", "entries" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/nodedb/utils/MetaUtils.php#L36-L45
train
wb-crowdfusion/crowdfusion
system/core/classes/nodedb/utils/MetaUtils.php
MetaUtils.truncateToMax
public static function truncateToMax($obj, $metaName, $string, $ellipsis = false) { switch (true) { case $obj instanceof Element: case $obj instanceof Aspect: break; case $obj instanceof NodeRef: case $obj instanceof Node: $obj = $obj->Element; break; default: throw new Exception(__CLASS__ . '::' . __FUNCTION__ . ": Expected first argument to be instance of Element, Aspect, Node or NodeRef"); } $metaValidationArray = $obj->Schema->getMetaDef($metaName)->Validation->toArray(); $max = $metaValidationArray['max']; $maxBytes = max($max, 255); $truncated = false; if (strlen($string) > $maxBytes) { $truncated = true; $string = StringUtils::utf8SafeTruncate($string, $maxBytes - ($ellipsis ? 3 : 0)); } if ($max < 255 && StringUtils::charCount($string) > $max) { $truncated = true; $string = StringUtils::utf8Substr($string, 0, $max - ($ellipsis ? 1 : 0)); } return $string . (($truncated && $ellipsis) ? "\xe2\x80\xa6" : ''); }
php
public static function truncateToMax($obj, $metaName, $string, $ellipsis = false) { switch (true) { case $obj instanceof Element: case $obj instanceof Aspect: break; case $obj instanceof NodeRef: case $obj instanceof Node: $obj = $obj->Element; break; default: throw new Exception(__CLASS__ . '::' . __FUNCTION__ . ": Expected first argument to be instance of Element, Aspect, Node or NodeRef"); } $metaValidationArray = $obj->Schema->getMetaDef($metaName)->Validation->toArray(); $max = $metaValidationArray['max']; $maxBytes = max($max, 255); $truncated = false; if (strlen($string) > $maxBytes) { $truncated = true; $string = StringUtils::utf8SafeTruncate($string, $maxBytes - ($ellipsis ? 3 : 0)); } if ($max < 255 && StringUtils::charCount($string) > $max) { $truncated = true; $string = StringUtils::utf8Substr($string, 0, $max - ($ellipsis ? 1 : 0)); } return $string . (($truncated && $ellipsis) ? "\xe2\x80\xa6" : ''); }
[ "public", "static", "function", "truncateToMax", "(", "$", "obj", ",", "$", "metaName", ",", "$", "string", ",", "$", "ellipsis", "=", "false", ")", "{", "switch", "(", "true", ")", "{", "case", "$", "obj", "instanceof", "Element", ":", "case", "$", "obj", "instanceof", "Aspect", ":", "break", ";", "case", "$", "obj", "instanceof", "NodeRef", ":", "case", "$", "obj", "instanceof", "Node", ":", "$", "obj", "=", "$", "obj", "->", "Element", ";", "break", ";", "default", ":", "throw", "new", "Exception", "(", "__CLASS__", ".", "'::'", ".", "__FUNCTION__", ".", "\": Expected first argument to be instance of Element, Aspect, Node or NodeRef\"", ")", ";", "}", "$", "metaValidationArray", "=", "$", "obj", "->", "Schema", "->", "getMetaDef", "(", "$", "metaName", ")", "->", "Validation", "->", "toArray", "(", ")", ";", "$", "max", "=", "$", "metaValidationArray", "[", "'max'", "]", ";", "$", "maxBytes", "=", "max", "(", "$", "max", ",", "255", ")", ";", "$", "truncated", "=", "false", ";", "if", "(", "strlen", "(", "$", "string", ")", ">", "$", "maxBytes", ")", "{", "$", "truncated", "=", "true", ";", "$", "string", "=", "StringUtils", "::", "utf8SafeTruncate", "(", "$", "string", ",", "$", "maxBytes", "-", "(", "$", "ellipsis", "?", "3", ":", "0", ")", ")", ";", "}", "if", "(", "$", "max", "<", "255", "&&", "StringUtils", "::", "charCount", "(", "$", "string", ")", ">", "$", "max", ")", "{", "$", "truncated", "=", "true", ";", "$", "string", "=", "StringUtils", "::", "utf8Substr", "(", "$", "string", ",", "0", ",", "$", "max", "-", "(", "$", "ellipsis", "?", "1", ":", "0", ")", ")", ";", "}", "return", "$", "string", ".", "(", "(", "$", "truncated", "&&", "$", "ellipsis", ")", "?", "\"\\xe2\\x80\\xa6\"", ":", "''", ")", ";", "}" ]
Returns a string truncated to fit inside a meta. @param mixed $obj - object that has the schema (Node | NodeRef | Element | Aspect) @param string $metaName @param string $string - string to be truncated @param bool $ellipsis - if set, output is appended with three dots @return string
[ "Returns", "a", "string", "truncated", "to", "fit", "inside", "a", "meta", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/nodedb/utils/MetaUtils.php#L164-L195
train
OUTRAGElib/objectlist
lib/ObjectListPopulationTrait.php
ObjectListPopulationTrait.populateObjectList
public final function populateObjectList($input, $deep = true) { if($this instanceof ArrayAccess == false) throw new Exception("Cannot set properties on objects that are not children of 'ArrayAccess'"); if(!is_array($input)) { if($input instanceof Traversable && method_exists($input, "toArray")) $input = $input->toArray(); elseif($input instanceof Traversable) $input = iterator_to_array($input); else $input = []; } if($deep) { foreach($input as $key => $value) { if(is_null($value) || is_scalar($value)) $this[$key] = $value; else $this[$key] = (new static())->populateObjectList($value, $deep); } } else { foreach($input as $key => $value) { # if we're not in deep mode then all we're doing is going through # each of the items and tacking them onto the stack, or something $this[$key] = $value; } } return $this; }
php
public final function populateObjectList($input, $deep = true) { if($this instanceof ArrayAccess == false) throw new Exception("Cannot set properties on objects that are not children of 'ArrayAccess'"); if(!is_array($input)) { if($input instanceof Traversable && method_exists($input, "toArray")) $input = $input->toArray(); elseif($input instanceof Traversable) $input = iterator_to_array($input); else $input = []; } if($deep) { foreach($input as $key => $value) { if(is_null($value) || is_scalar($value)) $this[$key] = $value; else $this[$key] = (new static())->populateObjectList($value, $deep); } } else { foreach($input as $key => $value) { # if we're not in deep mode then all we're doing is going through # each of the items and tacking them onto the stack, or something $this[$key] = $value; } } return $this; }
[ "public", "final", "function", "populateObjectList", "(", "$", "input", ",", "$", "deep", "=", "true", ")", "{", "if", "(", "$", "this", "instanceof", "ArrayAccess", "==", "false", ")", "throw", "new", "Exception", "(", "\"Cannot set properties on objects that are not children of 'ArrayAccess'\"", ")", ";", "if", "(", "!", "is_array", "(", "$", "input", ")", ")", "{", "if", "(", "$", "input", "instanceof", "Traversable", "&&", "method_exists", "(", "$", "input", ",", "\"toArray\"", ")", ")", "$", "input", "=", "$", "input", "->", "toArray", "(", ")", ";", "elseif", "(", "$", "input", "instanceof", "Traversable", ")", "$", "input", "=", "iterator_to_array", "(", "$", "input", ")", ";", "else", "$", "input", "=", "[", "]", ";", "}", "if", "(", "$", "deep", ")", "{", "foreach", "(", "$", "input", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_null", "(", "$", "value", ")", "||", "is_scalar", "(", "$", "value", ")", ")", "$", "this", "[", "$", "key", "]", "=", "$", "value", ";", "else", "$", "this", "[", "$", "key", "]", "=", "(", "new", "static", "(", ")", ")", "->", "populateObjectList", "(", "$", "value", ",", "$", "deep", ")", ";", "}", "}", "else", "{", "foreach", "(", "$", "input", "as", "$", "key", "=>", "$", "value", ")", "{", "# if we're not in deep mode then all we're doing is going through", "# each of the items and tacking them onto the stack, or something", "$", "this", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "this", ";", "}" ]
Populate an object list from, well, anything really
[ "Populate", "an", "object", "list", "from", "well", "anything", "really" ]
8ac3f9fd99992c58a3f537325e02ba2337f9ee55
https://github.com/OUTRAGElib/objectlist/blob/8ac3f9fd99992c58a3f537325e02ba2337f9ee55/lib/ObjectListPopulationTrait.php#L15-L51
train
OUTRAGElib/objectlist
lib/ObjectListPopulationTrait.php
ObjectListPopulationTrait.populateWithReference
public final function populateWithReference(array &$input) { if($this instanceof ObjectList == false) throw new Exception("Cannot set list to reference on non-supported object types"); $this->list = &$input; return $this; }
php
public final function populateWithReference(array &$input) { if($this instanceof ObjectList == false) throw new Exception("Cannot set list to reference on non-supported object types"); $this->list = &$input; return $this; }
[ "public", "final", "function", "populateWithReference", "(", "array", "&", "$", "input", ")", "{", "if", "(", "$", "this", "instanceof", "ObjectList", "==", "false", ")", "throw", "new", "Exception", "(", "\"Cannot set list to reference on non-supported object types\"", ")", ";", "$", "this", "->", "list", "=", "&", "$", "input", ";", "return", "$", "this", ";", "}" ]
Populate this object with a reference
[ "Populate", "this", "object", "with", "a", "reference" ]
8ac3f9fd99992c58a3f537325e02ba2337f9ee55
https://github.com/OUTRAGElib/objectlist/blob/8ac3f9fd99992c58a3f537325e02ba2337f9ee55/lib/ObjectListPopulationTrait.php#L57-L65
train
bandama-framework/bandama-framework
src/foundation/database/QueryBuilder.php
QueryBuilder.getQuery
public function getQuery() { $query = 'SELECT '.implode(', ', $this->fields) .' FROM '.implode(', ', $this->from); if (count($this->conditions) > 0) { $query = $query.' WHERE '.implode(' AND ', $this->conditions); } $query = rtrim($query).';'; return $query; }
php
public function getQuery() { $query = 'SELECT '.implode(', ', $this->fields) .' FROM '.implode(', ', $this->from); if (count($this->conditions) > 0) { $query = $query.' WHERE '.implode(' AND ', $this->conditions); } $query = rtrim($query).';'; return $query; }
[ "public", "function", "getQuery", "(", ")", "{", "$", "query", "=", "'SELECT '", ".", "implode", "(", "', '", ",", "$", "this", "->", "fields", ")", ".", "' FROM '", ".", "implode", "(", "', '", ",", "$", "this", "->", "from", ")", ";", "if", "(", "count", "(", "$", "this", "->", "conditions", ")", ">", "0", ")", "{", "$", "query", "=", "$", "query", ".", "' WHERE '", ".", "implode", "(", "' AND '", ",", "$", "this", "->", "conditions", ")", ";", "}", "$", "query", "=", "rtrim", "(", "$", "query", ")", ".", "';'", ";", "return", "$", "query", ";", "}" ]
Build query to generate a string @return string
[ "Build", "query", "to", "generate", "a", "string" ]
234ed703baf9e31268941c9d5f6d5e004cc53066
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/database/QueryBuilder.php#L81-L90
train
pdscopes/php-arrays
src/ArrDots.php
ArrDots.explode
public static function explode($array) { $results = []; foreach ($array as $key => $value) { static::set($results, $key, $value); } return $results; }
php
public static function explode($array) { $results = []; foreach ($array as $key => $value) { static::set($results, $key, $value); } return $results; }
[ "public", "static", "function", "explode", "(", "$", "array", ")", "{", "$", "results", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "static", "::", "set", "(", "$", "results", ",", "$", "key", ",", "$", "value", ")", ";", "}", "return", "$", "results", ";", "}" ]
Explode a single level dots array into a multi-dimensional associative array. @param array $array @return array
[ "Explode", "a", "single", "level", "dots", "array", "into", "a", "multi", "-", "dimensional", "associative", "array", "." ]
4648ef6d34a63682f4cb367716ba7c205b60ae1f
https://github.com/pdscopes/php-arrays/blob/4648ef6d34a63682f4cb367716ba7c205b60ae1f/src/ArrDots.php#L45-L54
train
pdscopes/php-arrays
src/ArrDots.php
ArrDots.collate
public static function collate($array, $key, $wildcard = null) { // If no wildcard set or the wildcard is not in the key if (null === $wildcard || strpos($key, $wildcard) === false) { return static::has($array, $key) ? [$key => static::get($array, $key)] : []; } $pattern = ''; $segments = explode('.', $key); while (($segment = array_shift($segments)) !== null) { // If we have run out of arrays to look into, stop looking if (!Arr::accessible($array)) { return []; } // If this segment is a wildcard if ($segment === $wildcard) { $values = []; foreach (array_keys($array) as $attr) { $subKey = implode('.', array_merge([$attr], $segments)); foreach (static::collate($array, $subKey, $wildcard) as $attrKey => $value) { $values[$pattern . $attrKey] = $value; } } return $values; } if (Arr::exists($array, $segment)) { $array = $array[$segment]; } else { return []; } $pattern .= $segment . '.'; } return [$key => $array]; }
php
public static function collate($array, $key, $wildcard = null) { // If no wildcard set or the wildcard is not in the key if (null === $wildcard || strpos($key, $wildcard) === false) { return static::has($array, $key) ? [$key => static::get($array, $key)] : []; } $pattern = ''; $segments = explode('.', $key); while (($segment = array_shift($segments)) !== null) { // If we have run out of arrays to look into, stop looking if (!Arr::accessible($array)) { return []; } // If this segment is a wildcard if ($segment === $wildcard) { $values = []; foreach (array_keys($array) as $attr) { $subKey = implode('.', array_merge([$attr], $segments)); foreach (static::collate($array, $subKey, $wildcard) as $attrKey => $value) { $values[$pattern . $attrKey] = $value; } } return $values; } if (Arr::exists($array, $segment)) { $array = $array[$segment]; } else { return []; } $pattern .= $segment . '.'; } return [$key => $array]; }
[ "public", "static", "function", "collate", "(", "$", "array", ",", "$", "key", ",", "$", "wildcard", "=", "null", ")", "{", "// If no wildcard set or the wildcard is not in the key", "if", "(", "null", "===", "$", "wildcard", "||", "strpos", "(", "$", "key", ",", "$", "wildcard", ")", "===", "false", ")", "{", "return", "static", "::", "has", "(", "$", "array", ",", "$", "key", ")", "?", "[", "$", "key", "=>", "static", "::", "get", "(", "$", "array", ",", "$", "key", ")", "]", ":", "[", "]", ";", "}", "$", "pattern", "=", "''", ";", "$", "segments", "=", "explode", "(", "'.'", ",", "$", "key", ")", ";", "while", "(", "(", "$", "segment", "=", "array_shift", "(", "$", "segments", ")", ")", "!==", "null", ")", "{", "// If we have run out of arrays to look into, stop looking", "if", "(", "!", "Arr", "::", "accessible", "(", "$", "array", ")", ")", "{", "return", "[", "]", ";", "}", "// If this segment is a wildcard", "if", "(", "$", "segment", "===", "$", "wildcard", ")", "{", "$", "values", "=", "[", "]", ";", "foreach", "(", "array_keys", "(", "$", "array", ")", "as", "$", "attr", ")", "{", "$", "subKey", "=", "implode", "(", "'.'", ",", "array_merge", "(", "[", "$", "attr", "]", ",", "$", "segments", ")", ")", ";", "foreach", "(", "static", "::", "collate", "(", "$", "array", ",", "$", "subKey", ",", "$", "wildcard", ")", "as", "$", "attrKey", "=>", "$", "value", ")", "{", "$", "values", "[", "$", "pattern", ".", "$", "attrKey", "]", "=", "$", "value", ";", "}", "}", "return", "$", "values", ";", "}", "if", "(", "Arr", "::", "exists", "(", "$", "array", ",", "$", "segment", ")", ")", "{", "$", "array", "=", "$", "array", "[", "$", "segment", "]", ";", "}", "else", "{", "return", "[", "]", ";", "}", "$", "pattern", ".=", "$", "segment", ".", "'.'", ";", "}", "return", "[", "$", "key", "=>", "$", "array", "]", ";", "}" ]
Get all items from a multi-dimensional associative array using "dots" notation and return a flattened "dots" notation array. @param ArrayAccess|array $array @param string $key @param null|string $wildcard @return array|mixed[]
[ "Get", "all", "items", "from", "a", "multi", "-", "dimensional", "associative", "array", "using", "dots", "notation", "and", "return", "a", "flattened", "dots", "notation", "array", "." ]
4648ef6d34a63682f4cb367716ba7c205b60ae1f
https://github.com/pdscopes/php-arrays/blob/4648ef6d34a63682f4cb367716ba7c205b60ae1f/src/ArrDots.php#L178-L215
train
pdscopes/php-arrays
src/ArrDots.php
ArrDots.has
public static function has($array, $keys, $wildcard = null) { // If the keys are null or the array is not accessible if (null === $keys || empty($array) || !Arr::accessible($array)) { return false; } // Check that every key exists in $array $originalArray = $array; foreach ((array) $keys as $key) { $array = $originalArray; // If the array has the key carry on if (Arr::exists($array, $key)) { continue; } // Break up the key into segments and drill into the array $segments = explode('.', $key); foreach ($segments as $k => $segment) { // If the segment is a wildcard if ($segment === $wildcard && !empty($array)) { // If this is the last segment then the array has the key if ($k + 1 === count($segments)) { break; } // If we are still considering an array, drill into every possibility if (Arr::accessible($array)) { // Check that at least one possibility contains the (sub)key $subKey = implode('.', array_slice($segments, $k + 1)); $found = array_reduce($array, function ($f, $item) use ($subKey, $wildcard) { return $f || static::has($item, $subKey, $wildcard); }, false); if (!$found) { return false; } else { break; } } } // Otherwise continue to drill into $array if (!empty($array) && Arr::accessible($array) && Arr::exists($array, $segment)) { $array = $array[$segment]; continue; } return false; } } return true; }
php
public static function has($array, $keys, $wildcard = null) { // If the keys are null or the array is not accessible if (null === $keys || empty($array) || !Arr::accessible($array)) { return false; } // Check that every key exists in $array $originalArray = $array; foreach ((array) $keys as $key) { $array = $originalArray; // If the array has the key carry on if (Arr::exists($array, $key)) { continue; } // Break up the key into segments and drill into the array $segments = explode('.', $key); foreach ($segments as $k => $segment) { // If the segment is a wildcard if ($segment === $wildcard && !empty($array)) { // If this is the last segment then the array has the key if ($k + 1 === count($segments)) { break; } // If we are still considering an array, drill into every possibility if (Arr::accessible($array)) { // Check that at least one possibility contains the (sub)key $subKey = implode('.', array_slice($segments, $k + 1)); $found = array_reduce($array, function ($f, $item) use ($subKey, $wildcard) { return $f || static::has($item, $subKey, $wildcard); }, false); if (!$found) { return false; } else { break; } } } // Otherwise continue to drill into $array if (!empty($array) && Arr::accessible($array) && Arr::exists($array, $segment)) { $array = $array[$segment]; continue; } return false; } } return true; }
[ "public", "static", "function", "has", "(", "$", "array", ",", "$", "keys", ",", "$", "wildcard", "=", "null", ")", "{", "// If the keys are null or the array is not accessible", "if", "(", "null", "===", "$", "keys", "||", "empty", "(", "$", "array", ")", "||", "!", "Arr", "::", "accessible", "(", "$", "array", ")", ")", "{", "return", "false", ";", "}", "// Check that every key exists in $array", "$", "originalArray", "=", "$", "array", ";", "foreach", "(", "(", "array", ")", "$", "keys", "as", "$", "key", ")", "{", "$", "array", "=", "$", "originalArray", ";", "// If the array has the key carry on", "if", "(", "Arr", "::", "exists", "(", "$", "array", ",", "$", "key", ")", ")", "{", "continue", ";", "}", "// Break up the key into segments and drill into the array", "$", "segments", "=", "explode", "(", "'.'", ",", "$", "key", ")", ";", "foreach", "(", "$", "segments", "as", "$", "k", "=>", "$", "segment", ")", "{", "// If the segment is a wildcard", "if", "(", "$", "segment", "===", "$", "wildcard", "&&", "!", "empty", "(", "$", "array", ")", ")", "{", "// If this is the last segment then the array has the key", "if", "(", "$", "k", "+", "1", "===", "count", "(", "$", "segments", ")", ")", "{", "break", ";", "}", "// If we are still considering an array, drill into every possibility", "if", "(", "Arr", "::", "accessible", "(", "$", "array", ")", ")", "{", "// Check that at least one possibility contains the (sub)key", "$", "subKey", "=", "implode", "(", "'.'", ",", "array_slice", "(", "$", "segments", ",", "$", "k", "+", "1", ")", ")", ";", "$", "found", "=", "array_reduce", "(", "$", "array", ",", "function", "(", "$", "f", ",", "$", "item", ")", "use", "(", "$", "subKey", ",", "$", "wildcard", ")", "{", "return", "$", "f", "||", "static", "::", "has", "(", "$", "item", ",", "$", "subKey", ",", "$", "wildcard", ")", ";", "}", ",", "false", ")", ";", "if", "(", "!", "$", "found", ")", "{", "return", "false", ";", "}", "else", "{", "break", ";", "}", "}", "}", "// Otherwise continue to drill into $array", "if", "(", "!", "empty", "(", "$", "array", ")", "&&", "Arr", "::", "accessible", "(", "$", "array", ")", "&&", "Arr", "::", "exists", "(", "$", "array", ",", "$", "segment", ")", ")", "{", "$", "array", "=", "$", "array", "[", "$", "segment", "]", ";", "continue", ";", "}", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Determine if an item or items exist in an multi-dimensional associative array using "dots" notation. @param ArrayAccess|array $array @param string|string[] $keys @param null|string $wildcard @return bool
[ "Determine", "if", "an", "item", "or", "items", "exist", "in", "an", "multi", "-", "dimensional", "associative", "array", "using", "dots", "notation", "." ]
4648ef6d34a63682f4cb367716ba7c205b60ae1f
https://github.com/pdscopes/php-arrays/blob/4648ef6d34a63682f4cb367716ba7c205b60ae1f/src/ArrDots.php#L226-L276
train
phossa/phossa-route
src/Phossa/Route/Context/Request.php
Request.parseUrl
protected function parseUrl( /*# string */ $httpMethod, /*# string */ $url ) { $this->server = $_SERVER; $server = &$this->server; // set http method if ($httpMethod) { $server['REQUEST_METHOD'] = $httpMethod; } elseif (!isset($server['REQUEST_METHOD'])) { $server['REQUEST_METHOD'] = 'GET'; } // parse url if (empty($url)) { $this->request = $_REQUEST; } else { $parts = (array) parse_url($url); // scheme if (isset($parts['scheme'])) { $scheme = strtolower($parts['scheme']); $server['HTTPS'] = 'https' === $scheme ? $scheme : ''; } // host if (isset($parts['host'])) { $server['HTTP_HOST'] = $parts['host']; } // port if (isset($parts['port'])) { $server['SERVER_PORT'] = $parts['port']; } // fix query $this->fixUrlQuery($parts); // fix path $this->fixUrlPath($parts); } // normalize $server['PATH_INFO'] = '/' . trim($server['PATH_INFO'], '/'); return $this; }
php
protected function parseUrl( /*# string */ $httpMethod, /*# string */ $url ) { $this->server = $_SERVER; $server = &$this->server; // set http method if ($httpMethod) { $server['REQUEST_METHOD'] = $httpMethod; } elseif (!isset($server['REQUEST_METHOD'])) { $server['REQUEST_METHOD'] = 'GET'; } // parse url if (empty($url)) { $this->request = $_REQUEST; } else { $parts = (array) parse_url($url); // scheme if (isset($parts['scheme'])) { $scheme = strtolower($parts['scheme']); $server['HTTPS'] = 'https' === $scheme ? $scheme : ''; } // host if (isset($parts['host'])) { $server['HTTP_HOST'] = $parts['host']; } // port if (isset($parts['port'])) { $server['SERVER_PORT'] = $parts['port']; } // fix query $this->fixUrlQuery($parts); // fix path $this->fixUrlPath($parts); } // normalize $server['PATH_INFO'] = '/' . trim($server['PATH_INFO'], '/'); return $this; }
[ "protected", "function", "parseUrl", "(", "/*# string */", "$", "httpMethod", ",", "/*# string */", "$", "url", ")", "{", "$", "this", "->", "server", "=", "$", "_SERVER", ";", "$", "server", "=", "&", "$", "this", "->", "server", ";", "// set http method", "if", "(", "$", "httpMethod", ")", "{", "$", "server", "[", "'REQUEST_METHOD'", "]", "=", "$", "httpMethod", ";", "}", "elseif", "(", "!", "isset", "(", "$", "server", "[", "'REQUEST_METHOD'", "]", ")", ")", "{", "$", "server", "[", "'REQUEST_METHOD'", "]", "=", "'GET'", ";", "}", "// parse url", "if", "(", "empty", "(", "$", "url", ")", ")", "{", "$", "this", "->", "request", "=", "$", "_REQUEST", ";", "}", "else", "{", "$", "parts", "=", "(", "array", ")", "parse_url", "(", "$", "url", ")", ";", "// scheme", "if", "(", "isset", "(", "$", "parts", "[", "'scheme'", "]", ")", ")", "{", "$", "scheme", "=", "strtolower", "(", "$", "parts", "[", "'scheme'", "]", ")", ";", "$", "server", "[", "'HTTPS'", "]", "=", "'https'", "===", "$", "scheme", "?", "$", "scheme", ":", "''", ";", "}", "// host", "if", "(", "isset", "(", "$", "parts", "[", "'host'", "]", ")", ")", "{", "$", "server", "[", "'HTTP_HOST'", "]", "=", "$", "parts", "[", "'host'", "]", ";", "}", "// port", "if", "(", "isset", "(", "$", "parts", "[", "'port'", "]", ")", ")", "{", "$", "server", "[", "'SERVER_PORT'", "]", "=", "$", "parts", "[", "'port'", "]", ";", "}", "// fix query", "$", "this", "->", "fixUrlQuery", "(", "$", "parts", ")", ";", "// fix path", "$", "this", "->", "fixUrlPath", "(", "$", "parts", ")", ";", "}", "// normalize", "$", "server", "[", "'PATH_INFO'", "]", "=", "'/'", ".", "trim", "(", "$", "server", "[", "'PATH_INFO'", "]", ",", "'/'", ")", ";", "return", "$", "this", ";", "}" ]
Parse a given URL @param string $httpMethod HTTP method @param string $url URL @return status @access protected
[ "Parse", "a", "given", "URL" ]
fdcc1c814b8b1692a60d433d3c085e6c7a923acc
https://github.com/phossa/phossa-route/blob/fdcc1c814b8b1692a60d433d3c085e6c7a923acc/src/Phossa/Route/Context/Request.php#L127-L174
train
ZFury/framework
library/Media/File.php
File.getAudios
public function getAudios() { $qb = $this->entityManager->createQueryBuilder(); $qb->select('f') ->from('\Media\Entity\File', 'f') ->innerJoin('\Media\Entity\ObjectFile', 'obf', Join::WITH, 'f.id = obf.fileId') ->where('f.type = :type') ->andWhere('obf.entityName = :name') ->andWhere('obf.objectId = :id') ->setParameter('type', \Media\Entity\File::AUDIO_FILETYPE) ->setParameter('name', $this->getEntityName()) ->setParameter('id', $this->getId()); return $qb->getQuery()->getResult(); }
php
public function getAudios() { $qb = $this->entityManager->createQueryBuilder(); $qb->select('f') ->from('\Media\Entity\File', 'f') ->innerJoin('\Media\Entity\ObjectFile', 'obf', Join::WITH, 'f.id = obf.fileId') ->where('f.type = :type') ->andWhere('obf.entityName = :name') ->andWhere('obf.objectId = :id') ->setParameter('type', \Media\Entity\File::AUDIO_FILETYPE) ->setParameter('name', $this->getEntityName()) ->setParameter('id', $this->getId()); return $qb->getQuery()->getResult(); }
[ "public", "function", "getAudios", "(", ")", "{", "$", "qb", "=", "$", "this", "->", "entityManager", "->", "createQueryBuilder", "(", ")", ";", "$", "qb", "->", "select", "(", "'f'", ")", "->", "from", "(", "'\\Media\\Entity\\File'", ",", "'f'", ")", "->", "innerJoin", "(", "'\\Media\\Entity\\ObjectFile'", ",", "'obf'", ",", "Join", "::", "WITH", ",", "'f.id = obf.fileId'", ")", "->", "where", "(", "'f.type = :type'", ")", "->", "andWhere", "(", "'obf.entityName = :name'", ")", "->", "andWhere", "(", "'obf.objectId = :id'", ")", "->", "setParameter", "(", "'type'", ",", "\\", "Media", "\\", "Entity", "\\", "File", "::", "AUDIO_FILETYPE", ")", "->", "setParameter", "(", "'name'", ",", "$", "this", "->", "getEntityName", "(", ")", ")", "->", "setParameter", "(", "'id'", ",", "$", "this", "->", "getId", "(", ")", ")", ";", "return", "$", "qb", "->", "getQuery", "(", ")", "->", "getResult", "(", ")", ";", "}" ]
Returns an array of ids @return mixed
[ "Returns", "an", "array", "of", "ids" ]
eee4ca2a64d2d65490777b08be56c4c9b67bc892
https://github.com/ZFury/framework/blob/eee4ca2a64d2d65490777b08be56c4c9b67bc892/library/Media/File.php#L49-L63
train
tonis-io-legacy/tonis
src/App.php
App.router
public function router() { return new Router\Router($this->routeMap, new Router\Resolver\Container($this->container)); }
php
public function router() { return new Router\Router($this->routeMap, new Router\Resolver\Container($this->container)); }
[ "public", "function", "router", "(", ")", "{", "return", "new", "Router", "\\", "Router", "(", "$", "this", "->", "routeMap", ",", "new", "Router", "\\", "Resolver", "\\", "Container", "(", "$", "this", "->", "container", ")", ")", ";", "}" ]
Routers are middleware and can be added to Tonis. e.g., $router = $app->router(); $router->get(...) $app->add($router); @return Router\Router
[ "Routers", "are", "middleware", "and", "can", "be", "added", "to", "Tonis", "." ]
8371a277a94232433d882aaf37a85cd469daf501
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/App.php#L88-L91
train
tonis-io-legacy/tonis
src/App.php
App.decorateRequest
private function decorateRequest(ServerRequestInterface $request) { if ($request instanceof Http\Request) { return $request; } return new Http\Request($this, $request); }
php
private function decorateRequest(ServerRequestInterface $request) { if ($request instanceof Http\Request) { return $request; } return new Http\Request($this, $request); }
[ "private", "function", "decorateRequest", "(", "ServerRequestInterface", "$", "request", ")", "{", "if", "(", "$", "request", "instanceof", "Http", "\\", "Request", ")", "{", "return", "$", "request", ";", "}", "return", "new", "Http", "\\", "Request", "(", "$", "this", ",", "$", "request", ")", ";", "}" ]
Decorates a request to add this app to it. @param ServerRequestInterface $request @return ServerRequestInterface|Http\Request
[ "Decorates", "a", "request", "to", "add", "this", "app", "to", "it", "." ]
8371a277a94232433d882aaf37a85cd469daf501
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/App.php#L250-L257
train
tonis-io-legacy/tonis
src/App.php
App.decorateResponse
private function decorateResponse(ResponseInterface $response) { if ($response instanceof Http\Response) { return $response; } return new Http\Response($this, $response); }
php
private function decorateResponse(ResponseInterface $response) { if ($response instanceof Http\Response) { return $response; } return new Http\Response($this, $response); }
[ "private", "function", "decorateResponse", "(", "ResponseInterface", "$", "response", ")", "{", "if", "(", "$", "response", "instanceof", "Http", "\\", "Response", ")", "{", "return", "$", "response", ";", "}", "return", "new", "Http", "\\", "Response", "(", "$", "this", ",", "$", "response", ")", ";", "}" ]
Decorates a response to add this app to it. @param ResponseInterface $response @return ResponseInterface|Http\Response
[ "Decorates", "a", "response", "to", "add", "this", "app", "to", "it", "." ]
8371a277a94232433d882aaf37a85cd469daf501
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/App.php#L265-L272
train
fiiSoft/fiisoft-basics
src/Tools/Validation/SpecificationValidator.php
SpecificationValidator.normalizeSpecification
private function normalizeSpecification(array $input) { $output = []; $mayBeChildless = null; foreach ($input as $key => $spec) { if ($key === 'attributes') { if (!is_array($spec)) { throw new LogicException('Value under key '.$key.' have to be an array'); } $output[$key] = []; foreach ($spec as $attrName => $attrSpec) { if (is_string($attrName)) { if (!is_array($attrSpec)) { throw new LogicException('Attribute specification have to be an array'); } if (!empty($attrSpec['maxLength']) && (!is_int($attrSpec['maxLength']) || $attrSpec['maxLength'] < 1) ) { throw new LogicException('Attribute constraint "maxLength" has to be an integer >= 1'); } if (!empty($attrSpec['enum']) && !is_array($attrSpec['enum'])) { throw new LogicException('Attribute constraint "enum" has to be an array'); } $output[$key][$attrName] = array_merge($this->defaultAttrSpec, $attrSpec); } else { $output[$key][$attrSpec] = $this->defaultAttrSpec; } } } elseif ($key === 'children') { $output[$key] = []; foreach ($input[$key] as $childKey => $child) { if (is_string($childKey)) { if (!is_array($child)) { throw new LogicException('Invalid child specification for key '.$childKey); } $output[$key][$childKey] = array_merge( $this->defaultChildSpec, $this->normalizeSpecification($child) ); if ($mayBeChildless !== false) { $mayBeChildless = $output[$key][$childKey]['mayBeChildless']; } } else { $output[$key][$child] = $this->defaultChildSpec; if ($mayBeChildless !== false) { $mayBeChildless = $output[$key][$child]['mayBeChildless']; } } } } else { $output[$key] = $spec; } } if (!isset($output['mayBeChildless'])) { if ($mayBeChildless !== null) { $output['mayBeChildless'] = $mayBeChildless; } elseif (isset($this->defaultChildSpec['mayBeChildless'])) { $output['mayBeChildless'] = $this->defaultChildSpec['mayBeChildless']; } } return $output; }
php
private function normalizeSpecification(array $input) { $output = []; $mayBeChildless = null; foreach ($input as $key => $spec) { if ($key === 'attributes') { if (!is_array($spec)) { throw new LogicException('Value under key '.$key.' have to be an array'); } $output[$key] = []; foreach ($spec as $attrName => $attrSpec) { if (is_string($attrName)) { if (!is_array($attrSpec)) { throw new LogicException('Attribute specification have to be an array'); } if (!empty($attrSpec['maxLength']) && (!is_int($attrSpec['maxLength']) || $attrSpec['maxLength'] < 1) ) { throw new LogicException('Attribute constraint "maxLength" has to be an integer >= 1'); } if (!empty($attrSpec['enum']) && !is_array($attrSpec['enum'])) { throw new LogicException('Attribute constraint "enum" has to be an array'); } $output[$key][$attrName] = array_merge($this->defaultAttrSpec, $attrSpec); } else { $output[$key][$attrSpec] = $this->defaultAttrSpec; } } } elseif ($key === 'children') { $output[$key] = []; foreach ($input[$key] as $childKey => $child) { if (is_string($childKey)) { if (!is_array($child)) { throw new LogicException('Invalid child specification for key '.$childKey); } $output[$key][$childKey] = array_merge( $this->defaultChildSpec, $this->normalizeSpecification($child) ); if ($mayBeChildless !== false) { $mayBeChildless = $output[$key][$childKey]['mayBeChildless']; } } else { $output[$key][$child] = $this->defaultChildSpec; if ($mayBeChildless !== false) { $mayBeChildless = $output[$key][$child]['mayBeChildless']; } } } } else { $output[$key] = $spec; } } if (!isset($output['mayBeChildless'])) { if ($mayBeChildless !== null) { $output['mayBeChildless'] = $mayBeChildless; } elseif (isset($this->defaultChildSpec['mayBeChildless'])) { $output['mayBeChildless'] = $this->defaultChildSpec['mayBeChildless']; } } return $output; }
[ "private", "function", "normalizeSpecification", "(", "array", "$", "input", ")", "{", "$", "output", "=", "[", "]", ";", "$", "mayBeChildless", "=", "null", ";", "foreach", "(", "$", "input", "as", "$", "key", "=>", "$", "spec", ")", "{", "if", "(", "$", "key", "===", "'attributes'", ")", "{", "if", "(", "!", "is_array", "(", "$", "spec", ")", ")", "{", "throw", "new", "LogicException", "(", "'Value under key '", ".", "$", "key", ".", "' have to be an array'", ")", ";", "}", "$", "output", "[", "$", "key", "]", "=", "[", "]", ";", "foreach", "(", "$", "spec", "as", "$", "attrName", "=>", "$", "attrSpec", ")", "{", "if", "(", "is_string", "(", "$", "attrName", ")", ")", "{", "if", "(", "!", "is_array", "(", "$", "attrSpec", ")", ")", "{", "throw", "new", "LogicException", "(", "'Attribute specification have to be an array'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "attrSpec", "[", "'maxLength'", "]", ")", "&&", "(", "!", "is_int", "(", "$", "attrSpec", "[", "'maxLength'", "]", ")", "||", "$", "attrSpec", "[", "'maxLength'", "]", "<", "1", ")", ")", "{", "throw", "new", "LogicException", "(", "'Attribute constraint \"maxLength\" has to be an integer >= 1'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "attrSpec", "[", "'enum'", "]", ")", "&&", "!", "is_array", "(", "$", "attrSpec", "[", "'enum'", "]", ")", ")", "{", "throw", "new", "LogicException", "(", "'Attribute constraint \"enum\" has to be an array'", ")", ";", "}", "$", "output", "[", "$", "key", "]", "[", "$", "attrName", "]", "=", "array_merge", "(", "$", "this", "->", "defaultAttrSpec", ",", "$", "attrSpec", ")", ";", "}", "else", "{", "$", "output", "[", "$", "key", "]", "[", "$", "attrSpec", "]", "=", "$", "this", "->", "defaultAttrSpec", ";", "}", "}", "}", "elseif", "(", "$", "key", "===", "'children'", ")", "{", "$", "output", "[", "$", "key", "]", "=", "[", "]", ";", "foreach", "(", "$", "input", "[", "$", "key", "]", "as", "$", "childKey", "=>", "$", "child", ")", "{", "if", "(", "is_string", "(", "$", "childKey", ")", ")", "{", "if", "(", "!", "is_array", "(", "$", "child", ")", ")", "{", "throw", "new", "LogicException", "(", "'Invalid child specification for key '", ".", "$", "childKey", ")", ";", "}", "$", "output", "[", "$", "key", "]", "[", "$", "childKey", "]", "=", "array_merge", "(", "$", "this", "->", "defaultChildSpec", ",", "$", "this", "->", "normalizeSpecification", "(", "$", "child", ")", ")", ";", "if", "(", "$", "mayBeChildless", "!==", "false", ")", "{", "$", "mayBeChildless", "=", "$", "output", "[", "$", "key", "]", "[", "$", "childKey", "]", "[", "'mayBeChildless'", "]", ";", "}", "}", "else", "{", "$", "output", "[", "$", "key", "]", "[", "$", "child", "]", "=", "$", "this", "->", "defaultChildSpec", ";", "if", "(", "$", "mayBeChildless", "!==", "false", ")", "{", "$", "mayBeChildless", "=", "$", "output", "[", "$", "key", "]", "[", "$", "child", "]", "[", "'mayBeChildless'", "]", ";", "}", "}", "}", "}", "else", "{", "$", "output", "[", "$", "key", "]", "=", "$", "spec", ";", "}", "}", "if", "(", "!", "isset", "(", "$", "output", "[", "'mayBeChildless'", "]", ")", ")", "{", "if", "(", "$", "mayBeChildless", "!==", "null", ")", "{", "$", "output", "[", "'mayBeChildless'", "]", "=", "$", "mayBeChildless", ";", "}", "elseif", "(", "isset", "(", "$", "this", "->", "defaultChildSpec", "[", "'mayBeChildless'", "]", ")", ")", "{", "$", "output", "[", "'mayBeChildless'", "]", "=", "$", "this", "->", "defaultChildSpec", "[", "'mayBeChildless'", "]", ";", "}", "}", "return", "$", "output", ";", "}" ]
Convert simplified specification to full form used in validation. @param array $input specification @throws LogicException @return array normalized specification
[ "Convert", "simplified", "specification", "to", "full", "form", "used", "in", "validation", "." ]
cf0e56a9abf646fae075f16e65eced282601c193
https://github.com/fiiSoft/fiisoft-basics/blob/cf0e56a9abf646fae075f16e65eced282601c193/src/Tools/Validation/SpecificationValidator.php#L251-L320
train
linguisticteam/xml-sitemap
src/sitemap.php
XMLSitemap.getXML
public function getXML( $version = '1.0', $encoding = 'UTF-8', $willFormatOutput = true ) { if (is_null( self::$instance )) { self::$instance = new \DOMDocument( $version, $encoding ); self::$instance->formatOutput = $willFormatOutput; } return self::$instance; }
php
public function getXML( $version = '1.0', $encoding = 'UTF-8', $willFormatOutput = true ) { if (is_null( self::$instance )) { self::$instance = new \DOMDocument( $version, $encoding ); self::$instance->formatOutput = $willFormatOutput; } return self::$instance; }
[ "public", "function", "getXML", "(", "$", "version", "=", "'1.0'", ",", "$", "encoding", "=", "'UTF-8'", ",", "$", "willFormatOutput", "=", "true", ")", "{", "if", "(", "is_null", "(", "self", "::", "$", "instance", ")", ")", "{", "self", "::", "$", "instance", "=", "new", "\\", "DOMDocument", "(", "$", "version", ",", "$", "encoding", ")", ";", "self", "::", "$", "instance", "->", "formatOutput", "=", "$", "willFormatOutput", ";", "}", "return", "self", "::", "$", "instance", ";", "}" ]
Creates the instance of DOMDocument all classes will be working with. @param string $version @param string $encoding @param bool $willFormatOutput @return \DOMDocument
[ "Creates", "the", "instance", "of", "DOMDocument", "all", "classes", "will", "be", "working", "with", "." ]
b600a31ad9c1c136fa6f3d3b6a394002121d42f0
https://github.com/linguisticteam/xml-sitemap/blob/b600a31ad9c1c136fa6f3d3b6a394002121d42f0/src/sitemap.php#L39-L47
train
linguisticteam/xml-sitemap
src/sitemap.php
XMLSitemap.addChild
protected function addChild( $attribute, $value = null, $escape = false ) { if ( ! empty( $value )) { if ($escape === true) { $node = $this->XML->createElement( $attribute ); $node->appendChild( new \DOMCdataSection( $value ) ); } else { $node = $this->XML->createElement( $attribute, $value ); } $this->mainNode->appendChild( $node ); } }
php
protected function addChild( $attribute, $value = null, $escape = false ) { if ( ! empty( $value )) { if ($escape === true) { $node = $this->XML->createElement( $attribute ); $node->appendChild( new \DOMCdataSection( $value ) ); } else { $node = $this->XML->createElement( $attribute, $value ); } $this->mainNode->appendChild( $node ); } }
[ "protected", "function", "addChild", "(", "$", "attribute", ",", "$", "value", "=", "null", ",", "$", "escape", "=", "false", ")", "{", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "if", "(", "$", "escape", "===", "true", ")", "{", "$", "node", "=", "$", "this", "->", "XML", "->", "createElement", "(", "$", "attribute", ")", ";", "$", "node", "->", "appendChild", "(", "new", "\\", "DOMCdataSection", "(", "$", "value", ")", ")", ";", "}", "else", "{", "$", "node", "=", "$", "this", "->", "XML", "->", "createElement", "(", "$", "attribute", ",", "$", "value", ")", ";", "}", "$", "this", "->", "mainNode", "->", "appendChild", "(", "$", "node", ")", ";", "}", "}" ]
Adds a child node to the main node that each inherited class creates when it instantiates itself. @param $attribute @param null $value @param bool $escape Whether to escape the value, we usually escape any field that might contain special characters to avoid using special char handler methods
[ "Adds", "a", "child", "node", "to", "the", "main", "node", "that", "each", "inherited", "class", "creates", "when", "it", "instantiates", "itself", "." ]
b600a31ad9c1c136fa6f3d3b6a394002121d42f0
https://github.com/linguisticteam/xml-sitemap/blob/b600a31ad9c1c136fa6f3d3b6a394002121d42f0/src/sitemap.php#L77-L88
train
linguisticteam/xml-sitemap
src/sitemap.php
XMLSitemap.addStylesheet
public function addStylesheet( $url ) { $this->XML->appendChild( $this->XML->createProcessingInstruction( 'xml-stylesheet', sprintf( 'type="text/xsl" href="%s"', $url ) ) ); }
php
public function addStylesheet( $url ) { $this->XML->appendChild( $this->XML->createProcessingInstruction( 'xml-stylesheet', sprintf( 'type="text/xsl" href="%s"', $url ) ) ); }
[ "public", "function", "addStylesheet", "(", "$", "url", ")", "{", "$", "this", "->", "XML", "->", "appendChild", "(", "$", "this", "->", "XML", "->", "createProcessingInstruction", "(", "'xml-stylesheet'", ",", "sprintf", "(", "'type=\"text/xsl\" href=\"%s\"'", ",", "$", "url", ")", ")", ")", ";", "}" ]
Adds the XSL stylesheet to our document @param $url
[ "Adds", "the", "XSL", "stylesheet", "to", "our", "document" ]
b600a31ad9c1c136fa6f3d3b6a394002121d42f0
https://github.com/linguisticteam/xml-sitemap/blob/b600a31ad9c1c136fa6f3d3b6a394002121d42f0/src/sitemap.php#L105-L109
train
linguisticteam/xml-sitemap
src/sitemap.php
XMLSitemap.addExtraNamespaces
protected function addExtraNamespaces( $nodeset ) { $this->addNamespace( 'hasImages', $nodeset, 'xmlns:image', "http://www.google.com/schemas/sitemap-image/1.1" ); $this->addNamespace( 'hasVideos', $nodeset, 'xmlns:video', "http://www.google.com/schemas/sitemap-video/1.1" ); $this->addNamespace( 'hasMobile', $nodeset, 'xmlns:mobile', "http://www.google.com/schemas/sitemap-mobile/1.0" ); $this->addNamespace( 'hasNews', $nodeset, 'xmlns:news', "http://www.google.com/schemas/sitemap-news/0.9" ); }
php
protected function addExtraNamespaces( $nodeset ) { $this->addNamespace( 'hasImages', $nodeset, 'xmlns:image', "http://www.google.com/schemas/sitemap-image/1.1" ); $this->addNamespace( 'hasVideos', $nodeset, 'xmlns:video', "http://www.google.com/schemas/sitemap-video/1.1" ); $this->addNamespace( 'hasMobile', $nodeset, 'xmlns:mobile', "http://www.google.com/schemas/sitemap-mobile/1.0" ); $this->addNamespace( 'hasNews', $nodeset, 'xmlns:news', "http://www.google.com/schemas/sitemap-news/0.9" ); }
[ "protected", "function", "addExtraNamespaces", "(", "$", "nodeset", ")", "{", "$", "this", "->", "addNamespace", "(", "'hasImages'", ",", "$", "nodeset", ",", "'xmlns:image'", ",", "\"http://www.google.com/schemas/sitemap-image/1.1\"", ")", ";", "$", "this", "->", "addNamespace", "(", "'hasVideos'", ",", "$", "nodeset", ",", "'xmlns:video'", ",", "\"http://www.google.com/schemas/sitemap-video/1.1\"", ")", ";", "$", "this", "->", "addNamespace", "(", "'hasMobile'", ",", "$", "nodeset", ",", "'xmlns:mobile'", ",", "\"http://www.google.com/schemas/sitemap-mobile/1.0\"", ")", ";", "$", "this", "->", "addNamespace", "(", "'hasNews'", ",", "$", "nodeset", ",", "'xmlns:news'", ",", "\"http://www.google.com/schemas/sitemap-news/0.9\"", ")", ";", "}" ]
If we add nodes with special namespaces, we setup a boolean in our iterator classes that switch to true so we can add the appropriate namespaces to our document. Ex: an image is added to the document, we set "hasImages" to true so that it's evaluated to true here and the image namespace is added. @param \DOMElement $nodeset
[ "If", "we", "add", "nodes", "with", "special", "namespaces", "we", "setup", "a", "boolean", "in", "our", "iterator", "classes", "that", "switch", "to", "true", "so", "we", "can", "add", "the", "appropriate", "namespaces", "to", "our", "document", "." ]
b600a31ad9c1c136fa6f3d3b6a394002121d42f0
https://github.com/linguisticteam/xml-sitemap/blob/b600a31ad9c1c136fa6f3d3b6a394002121d42f0/src/sitemap.php#L125-L132
train
bytic/debugbar
src/DebugBarServiceProvider.php
DebugBarServiceProvider.registerMiddleware
protected function registerMiddleware($middleware) { /** @var Kernel $kernel */ $kernel = $this->getContainer()->get(KernelInterface::class); $kernel->prependMiddleware($middleware); }
php
protected function registerMiddleware($middleware) { /** @var Kernel $kernel */ $kernel = $this->getContainer()->get(KernelInterface::class); $kernel->prependMiddleware($middleware); }
[ "protected", "function", "registerMiddleware", "(", "$", "middleware", ")", "{", "/** @var Kernel $kernel */", "$", "kernel", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "KernelInterface", "::", "class", ")", ";", "$", "kernel", "->", "prependMiddleware", "(", "$", "middleware", ")", ";", "}" ]
Register the Debugbar Middleware @param string $middleware
[ "Register", "the", "Debugbar", "Middleware" ]
3199ade9a8fff866bffc39712bdf78d2dd214e4b
https://github.com/bytic/debugbar/blob/3199ade9a8fff866bffc39712bdf78d2dd214e4b/src/DebugBarServiceProvider.php#L81-L86
train
anime-db/catalog-bundle
src/Controller/UpdateController.php
UpdateController.getPlugin
protected function getPlugin($plugin) { try { list($vendor, $package) = explode('/', $plugin); return $this->get('anime_db.api.client')->getPlugin($vendor, $package); } catch (\RuntimeException $e) { return; } }
php
protected function getPlugin($plugin) { try { list($vendor, $package) = explode('/', $plugin); return $this->get('anime_db.api.client')->getPlugin($vendor, $package); } catch (\RuntimeException $e) { return; } }
[ "protected", "function", "getPlugin", "(", "$", "plugin", ")", "{", "try", "{", "list", "(", "$", "vendor", ",", "$", "package", ")", "=", "explode", "(", "'/'", ",", "$", "plugin", ")", ";", "return", "$", "this", "->", "get", "(", "'anime_db.api.client'", ")", "->", "getPlugin", "(", "$", "vendor", ",", "$", "package", ")", ";", "}", "catch", "(", "\\", "RuntimeException", "$", "e", ")", "{", "return", ";", "}", "}" ]
Get plugin. @param string $plugin @return array|null
[ "Get", "plugin", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Controller/UpdateController.php#L106-L115
train
anime-db/catalog-bundle
src/Controller/UpdateController.php
UpdateController.executeAction
public function executeAction() { // update for Windows XP does not work if (strpos(php_uname('v'), 'Windows XP') !== false) { $this->redirect($this->generateUrl('update')); } // execute update file_put_contents($this->container->getParameter('kernel.root_dir').'/../web/update.log', ''); $this->get('anime_db.command') ->send('php app/console animedb:update --env=prod --no-ansi >web/update.log 2>&1'); return $this->render('AnimeDbCatalogBundle:Update:execute.html.twig', [ 'log_file' => '/update.log', 'end_message' => self::END_MESSAGE, ]); }
php
public function executeAction() { // update for Windows XP does not work if (strpos(php_uname('v'), 'Windows XP') !== false) { $this->redirect($this->generateUrl('update')); } // execute update file_put_contents($this->container->getParameter('kernel.root_dir').'/../web/update.log', ''); $this->get('anime_db.command') ->send('php app/console animedb:update --env=prod --no-ansi >web/update.log 2>&1'); return $this->render('AnimeDbCatalogBundle:Update:execute.html.twig', [ 'log_file' => '/update.log', 'end_message' => self::END_MESSAGE, ]); }
[ "public", "function", "executeAction", "(", ")", "{", "// update for Windows XP does not work", "if", "(", "strpos", "(", "php_uname", "(", "'v'", ")", ",", "'Windows XP'", ")", "!==", "false", ")", "{", "$", "this", "->", "redirect", "(", "$", "this", "->", "generateUrl", "(", "'update'", ")", ")", ";", "}", "// execute update", "file_put_contents", "(", "$", "this", "->", "container", "->", "getParameter", "(", "'kernel.root_dir'", ")", ".", "'/../web/update.log'", ",", "''", ")", ";", "$", "this", "->", "get", "(", "'anime_db.command'", ")", "->", "send", "(", "'php app/console animedb:update --env=prod --no-ansi >web/update.log 2>&1'", ")", ";", "return", "$", "this", "->", "render", "(", "'AnimeDbCatalogBundle:Update:execute.html.twig'", ",", "[", "'log_file'", "=>", "'/update.log'", ",", "'end_message'", "=>", "self", "::", "END_MESSAGE", ",", "]", ")", ";", "}" ]
Execute update application. @return Response
[ "Execute", "update", "application", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Controller/UpdateController.php#L122-L138
train
modulusphp/support
Obj.php
Obj.old
public static function old($value, $fallback = '') { return Variable::has('form.old') ? (isset(Variable::get('form.old')[$value]) ? Variable::get('form.old')[$value] : $fallback) : $fallback; }
php
public static function old($value, $fallback = '') { return Variable::has('form.old') ? (isset(Variable::get('form.old')[$value]) ? Variable::get('form.old')[$value] : $fallback) : $fallback; }
[ "public", "static", "function", "old", "(", "$", "value", ",", "$", "fallback", "=", "''", ")", "{", "return", "Variable", "::", "has", "(", "'form.old'", ")", "?", "(", "isset", "(", "Variable", "::", "get", "(", "'form.old'", ")", "[", "$", "value", "]", ")", "?", "Variable", "::", "get", "(", "'form.old'", ")", "[", "$", "value", "]", ":", "$", "fallback", ")", ":", "$", "fallback", ";", "}" ]
Get old value or fallback @param mixed $value @param mixed $fallback @return void
[ "Get", "old", "value", "or", "fallback" ]
b5c5b48dcbeb379e6cd1f29159dc8cdacef3adab
https://github.com/modulusphp/support/blob/b5c5b48dcbeb379e6cd1f29159dc8cdacef3adab/Obj.php#L34-L37
train
modulusphp/support
Obj.php
Obj.is_base64
public static function is_base64(string $string) : bool { if (base64_encode(base64_decode($string, true)) === $string) return true; return false; }
php
public static function is_base64(string $string) : bool { if (base64_encode(base64_decode($string, true)) === $string) return true; return false; }
[ "public", "static", "function", "is_base64", "(", "string", "$", "string", ")", ":", "bool", "{", "if", "(", "base64_encode", "(", "base64_decode", "(", "$", "string", ",", "true", ")", ")", "===", "$", "string", ")", "return", "true", ";", "return", "false", ";", "}" ]
Check if string is base64 or not @param string $string @return bool
[ "Check", "if", "string", "is", "base64", "or", "not" ]
b5c5b48dcbeb379e6cd1f29159dc8cdacef3adab
https://github.com/modulusphp/support/blob/b5c5b48dcbeb379e6cd1f29159dc8cdacef3adab/Obj.php#L101-L105
train
railken/amethyst-authentication
src/Http/Controllers/App/AuthController.php
AuthController.getProvider
public function getProvider($name, $request) { $class = isset($this->providers[$name]) ? $this->providers[$name] : null; if (!$class) { return null; } return new $class($request, $request->input('client_id'), $request->input('client_secret'), $request->input('redirect_url')); }
php
public function getProvider($name, $request) { $class = isset($this->providers[$name]) ? $this->providers[$name] : null; if (!$class) { return null; } return new $class($request, $request->input('client_id'), $request->input('client_secret'), $request->input('redirect_url')); }
[ "public", "function", "getProvider", "(", "$", "name", ",", "$", "request", ")", "{", "$", "class", "=", "isset", "(", "$", "this", "->", "providers", "[", "$", "name", "]", ")", "?", "$", "this", "->", "providers", "[", "$", "name", "]", ":", "null", ";", "if", "(", "!", "$", "class", ")", "{", "return", "null", ";", "}", "return", "new", "$", "class", "(", "$", "request", ",", "$", "request", "->", "input", "(", "'client_id'", ")", ",", "$", "request", "->", "input", "(", "'client_secret'", ")", ",", "$", "request", "->", "input", "(", "'redirect_url'", ")", ")", ";", "}" ]
Get provider. @param string $name @param Request $request @return \Laravel\Socialite\Two\AbstractProvider|null
[ "Get", "provider", "." ]
59f28ddffa41a5f7fae4d5504eacf7c664e54b46
https://github.com/railken/amethyst-authentication/blob/59f28ddffa41a5f7fae4d5504eacf7c664e54b46/src/Http/Controllers/App/AuthController.php#L56-L65
train
railken/amethyst-authentication
src/Http/Controllers/App/AuthController.php
AuthController.signIn
public function signIn(Request $request) { $oauth_client = DB::table('oauth_clients')->where('password_client', 1)->first(); if (!$oauth_client) { return $this->response([ 'code' => 'CLIENT_NOT_FOUND', ], Response::HTTP_BAD_REQUEST); } $request->request->add([ 'username' => $request->input('username'), 'password' => $request->input('password'), 'scope' => '*', 'grant_type' => 'password', 'client_id' => $oauth_client->id, 'client_secret' => $oauth_client->secret, ]); $request = Request::create('/oauth/token', 'POST', []); $response = Route::dispatch($request); $body = json_decode($response->getContent()); if ($response->getStatusCode() === 200) { return $this->response(['data' => $body], Response::HTTP_OK); } if ($response->getStatusCode() === 401) { return $this->response(['errors' => ['code' => 'NOT_VALID', 'message' => $body->error]], Response::HTTP_UNAUTHORIZED); } if ($response->getStatusCode() === 400) { return $this->response(['errors' => ['code' => 'BAD_REQUEST', 'message' => $body->message]], Response::HTTP_BAD_REQUEST); } }
php
public function signIn(Request $request) { $oauth_client = DB::table('oauth_clients')->where('password_client', 1)->first(); if (!$oauth_client) { return $this->response([ 'code' => 'CLIENT_NOT_FOUND', ], Response::HTTP_BAD_REQUEST); } $request->request->add([ 'username' => $request->input('username'), 'password' => $request->input('password'), 'scope' => '*', 'grant_type' => 'password', 'client_id' => $oauth_client->id, 'client_secret' => $oauth_client->secret, ]); $request = Request::create('/oauth/token', 'POST', []); $response = Route::dispatch($request); $body = json_decode($response->getContent()); if ($response->getStatusCode() === 200) { return $this->response(['data' => $body], Response::HTTP_OK); } if ($response->getStatusCode() === 401) { return $this->response(['errors' => ['code' => 'NOT_VALID', 'message' => $body->error]], Response::HTTP_UNAUTHORIZED); } if ($response->getStatusCode() === 400) { return $this->response(['errors' => ['code' => 'BAD_REQUEST', 'message' => $body->message]], Response::HTTP_BAD_REQUEST); } }
[ "public", "function", "signIn", "(", "Request", "$", "request", ")", "{", "$", "oauth_client", "=", "DB", "::", "table", "(", "'oauth_clients'", ")", "->", "where", "(", "'password_client'", ",", "1", ")", "->", "first", "(", ")", ";", "if", "(", "!", "$", "oauth_client", ")", "{", "return", "$", "this", "->", "response", "(", "[", "'code'", "=>", "'CLIENT_NOT_FOUND'", ",", "]", ",", "Response", "::", "HTTP_BAD_REQUEST", ")", ";", "}", "$", "request", "->", "request", "->", "add", "(", "[", "'username'", "=>", "$", "request", "->", "input", "(", "'username'", ")", ",", "'password'", "=>", "$", "request", "->", "input", "(", "'password'", ")", ",", "'scope'", "=>", "'*'", ",", "'grant_type'", "=>", "'password'", ",", "'client_id'", "=>", "$", "oauth_client", "->", "id", ",", "'client_secret'", "=>", "$", "oauth_client", "->", "secret", ",", "]", ")", ";", "$", "request", "=", "Request", "::", "create", "(", "'/oauth/token'", ",", "'POST'", ",", "[", "]", ")", ";", "$", "response", "=", "Route", "::", "dispatch", "(", "$", "request", ")", ";", "$", "body", "=", "json_decode", "(", "$", "response", "->", "getContent", "(", ")", ")", ";", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "===", "200", ")", "{", "return", "$", "this", "->", "response", "(", "[", "'data'", "=>", "$", "body", "]", ",", "Response", "::", "HTTP_OK", ")", ";", "}", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "===", "401", ")", "{", "return", "$", "this", "->", "response", "(", "[", "'errors'", "=>", "[", "'code'", "=>", "'NOT_VALID'", ",", "'message'", "=>", "$", "body", "->", "error", "]", "]", ",", "Response", "::", "HTTP_UNAUTHORIZED", ")", ";", "}", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "===", "400", ")", "{", "return", "$", "this", "->", "response", "(", "[", "'errors'", "=>", "[", "'code'", "=>", "'BAD_REQUEST'", ",", "'message'", "=>", "$", "body", "->", "message", "]", "]", ",", "Response", "::", "HTTP_BAD_REQUEST", ")", ";", "}", "}" ]
Sign in a user. @param \Illuminate\Http\Request $request @return \Symfony\Component\HttpFoundation\Response
[ "Sign", "in", "a", "user", "." ]
59f28ddffa41a5f7fae4d5504eacf7c664e54b46
https://github.com/railken/amethyst-authentication/blob/59f28ddffa41a5f7fae4d5504eacf7c664e54b46/src/Http/Controllers/App/AuthController.php#L74-L109
train
railken/amethyst-authentication
src/Http/Controllers/App/AuthController.php
AuthController.signInWithProvider
public function signInWithProvider($provider_name, Request $request) { $provider = $this->getProvider($provider_name, $request); if (!$provider) { return $this->response(['errors' => [ 'code' => 'PROVIDER_NOT_FOUND', 'message' => 'No provider found', ]], Response::HTTP_BAD_REQUEST); } $provider->stateless(); if ($request->input('code') !== null) { try { return $this->authenticateByCode($provider, $request->input('code')); } catch (\Exception $e) { return $this->response([ 'code' => 'CODE_NOT_VALID', 'message' => 'Code invalid or expired'.$e->getMessage(), ], Response::HTTP_BAD_REQUEST); } } }
php
public function signInWithProvider($provider_name, Request $request) { $provider = $this->getProvider($provider_name, $request); if (!$provider) { return $this->response(['errors' => [ 'code' => 'PROVIDER_NOT_FOUND', 'message' => 'No provider found', ]], Response::HTTP_BAD_REQUEST); } $provider->stateless(); if ($request->input('code') !== null) { try { return $this->authenticateByCode($provider, $request->input('code')); } catch (\Exception $e) { return $this->response([ 'code' => 'CODE_NOT_VALID', 'message' => 'Code invalid or expired'.$e->getMessage(), ], Response::HTTP_BAD_REQUEST); } } }
[ "public", "function", "signInWithProvider", "(", "$", "provider_name", ",", "Request", "$", "request", ")", "{", "$", "provider", "=", "$", "this", "->", "getProvider", "(", "$", "provider_name", ",", "$", "request", ")", ";", "if", "(", "!", "$", "provider", ")", "{", "return", "$", "this", "->", "response", "(", "[", "'errors'", "=>", "[", "'code'", "=>", "'PROVIDER_NOT_FOUND'", ",", "'message'", "=>", "'No provider found'", ",", "]", "]", ",", "Response", "::", "HTTP_BAD_REQUEST", ")", ";", "}", "$", "provider", "->", "stateless", "(", ")", ";", "if", "(", "$", "request", "->", "input", "(", "'code'", ")", "!==", "null", ")", "{", "try", "{", "return", "$", "this", "->", "authenticateByCode", "(", "$", "provider", ",", "$", "request", "->", "input", "(", "'code'", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "$", "this", "->", "response", "(", "[", "'code'", "=>", "'CODE_NOT_VALID'", ",", "'message'", "=>", "'Code invalid or expired'", ".", "$", "e", "->", "getMessage", "(", ")", ",", "]", ",", "Response", "::", "HTTP_BAD_REQUEST", ")", ";", "}", "}", "}" ]
Request token and generate a new one. @param string $provider_name @param Request $request @return \Symfony\Component\HttpFoundation\Response
[ "Request", "token", "and", "generate", "a", "new", "one", "." ]
59f28ddffa41a5f7fae4d5504eacf7c664e54b46
https://github.com/railken/amethyst-authentication/blob/59f28ddffa41a5f7fae4d5504eacf7c664e54b46/src/Http/Controllers/App/AuthController.php#L119-L142
train
railken/amethyst-authentication
src/Http/Controllers/App/AuthController.php
AuthController.authenticateByCode
public function authenticateByCode($provider, string $code) { $provider_user = $provider->user(); /** @var \Railken\Amethyst\Repositories\UserRepository */ $repository = $this->manager->getRepository(); $user = $repository->findOneByEmail($provider_user->getEmail()); if (!$user) { $result = $this->manager->create([ 'name' => $provider_user->getNickname() ? $provider_user->getNickname() : $provider_user->getName(), 'role' => 'user', 'password' => str_random(32), 'email' => $provider_user->getEmail(), ]); if (!$result->ok()) { return $this->response(['errors' => $result->getSimpleErrors()], Response::HTTP_BAD_REQUEST); } $user = $result->getResource(); } $token = Container::getInstance()->make(\Laravel\Passport\PersonalAccessTokenFactory::class)->make( $user->getKey(), 'login', [] ); return $this->response([ 'token_type' => 'Bearer', 'expires_in' => 0, 'access_token' => $token->accessToken, ], Response::HTTP_OK); }
php
public function authenticateByCode($provider, string $code) { $provider_user = $provider->user(); /** @var \Railken\Amethyst\Repositories\UserRepository */ $repository = $this->manager->getRepository(); $user = $repository->findOneByEmail($provider_user->getEmail()); if (!$user) { $result = $this->manager->create([ 'name' => $provider_user->getNickname() ? $provider_user->getNickname() : $provider_user->getName(), 'role' => 'user', 'password' => str_random(32), 'email' => $provider_user->getEmail(), ]); if (!$result->ok()) { return $this->response(['errors' => $result->getSimpleErrors()], Response::HTTP_BAD_REQUEST); } $user = $result->getResource(); } $token = Container::getInstance()->make(\Laravel\Passport\PersonalAccessTokenFactory::class)->make( $user->getKey(), 'login', [] ); return $this->response([ 'token_type' => 'Bearer', 'expires_in' => 0, 'access_token' => $token->accessToken, ], Response::HTTP_OK); }
[ "public", "function", "authenticateByCode", "(", "$", "provider", ",", "string", "$", "code", ")", "{", "$", "provider_user", "=", "$", "provider", "->", "user", "(", ")", ";", "/** @var \\Railken\\Amethyst\\Repositories\\UserRepository */", "$", "repository", "=", "$", "this", "->", "manager", "->", "getRepository", "(", ")", ";", "$", "user", "=", "$", "repository", "->", "findOneByEmail", "(", "$", "provider_user", "->", "getEmail", "(", ")", ")", ";", "if", "(", "!", "$", "user", ")", "{", "$", "result", "=", "$", "this", "->", "manager", "->", "create", "(", "[", "'name'", "=>", "$", "provider_user", "->", "getNickname", "(", ")", "?", "$", "provider_user", "->", "getNickname", "(", ")", ":", "$", "provider_user", "->", "getName", "(", ")", ",", "'role'", "=>", "'user'", ",", "'password'", "=>", "str_random", "(", "32", ")", ",", "'email'", "=>", "$", "provider_user", "->", "getEmail", "(", ")", ",", "]", ")", ";", "if", "(", "!", "$", "result", "->", "ok", "(", ")", ")", "{", "return", "$", "this", "->", "response", "(", "[", "'errors'", "=>", "$", "result", "->", "getSimpleErrors", "(", ")", "]", ",", "Response", "::", "HTTP_BAD_REQUEST", ")", ";", "}", "$", "user", "=", "$", "result", "->", "getResource", "(", ")", ";", "}", "$", "token", "=", "Container", "::", "getInstance", "(", ")", "->", "make", "(", "\\", "Laravel", "\\", "Passport", "\\", "PersonalAccessTokenFactory", "::", "class", ")", "->", "make", "(", "$", "user", "->", "getKey", "(", ")", ",", "'login'", ",", "[", "]", ")", ";", "return", "$", "this", "->", "response", "(", "[", "'token_type'", "=>", "'Bearer'", ",", "'expires_in'", "=>", "0", ",", "'access_token'", "=>", "$", "token", "->", "accessToken", ",", "]", ",", "Response", "::", "HTTP_OK", ")", ";", "}" ]
Authenticate a user by the "code" of oauth2. @param \Laravel\Socialite\Two\AbstractProvider $provider @param string $code @return \Symfony\Component\HttpFoundation\Response
[ "Authenticate", "a", "user", "by", "the", "code", "of", "oauth2", "." ]
59f28ddffa41a5f7fae4d5504eacf7c664e54b46
https://github.com/railken/amethyst-authentication/blob/59f28ddffa41a5f7fae4d5504eacf7c664e54b46/src/Http/Controllers/App/AuthController.php#L152-L187
train
smtech/obsolete__oauth-negotiator
OAuthNegotiator.php
OAuthNegotiator.constructIdentityToken
private function constructIdentityToken() { if (isset($_REQUEST[self::CODE])) { $this->requestToken($_REQUEST[self::CODE], self::IDENTITY_TOKEN); $_SESSION[self::SESSION][self::IS_API_TOKEN] = false; $_SESSION[self::SESSION][self::STATE] = self::NEGOTIATION_COMPLETE; header("Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}"); exit; } elseif (isset($_REQUEST[self::ERROR])) { $_SESSION[self::SESSION][self::STATE] = self::NEGOTIATION_FAILED; $_SESSION[self::SESSION][self::ERROR] = $_REQUEST[self::ERROR]; header("Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}?error={$_REQUEST[self::ERROR]}"); exit; } else { throw new OAuthNegotiator_Exception( 'Unexpected OAuth response', OAuthNegotiator_Exception::CODE_RESPONSE ); } }
php
private function constructIdentityToken() { if (isset($_REQUEST[self::CODE])) { $this->requestToken($_REQUEST[self::CODE], self::IDENTITY_TOKEN); $_SESSION[self::SESSION][self::IS_API_TOKEN] = false; $_SESSION[self::SESSION][self::STATE] = self::NEGOTIATION_COMPLETE; header("Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}"); exit; } elseif (isset($_REQUEST[self::ERROR])) { $_SESSION[self::SESSION][self::STATE] = self::NEGOTIATION_FAILED; $_SESSION[self::SESSION][self::ERROR] = $_REQUEST[self::ERROR]; header("Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}?error={$_REQUEST[self::ERROR]}"); exit; } else { throw new OAuthNegotiator_Exception( 'Unexpected OAuth response', OAuthNegotiator_Exception::CODE_RESPONSE ); } }
[ "private", "function", "constructIdentityToken", "(", ")", "{", "if", "(", "isset", "(", "$", "_REQUEST", "[", "self", "::", "CODE", "]", ")", ")", "{", "$", "this", "->", "requestToken", "(", "$", "_REQUEST", "[", "self", "::", "CODE", "]", ",", "self", "::", "IDENTITY_TOKEN", ")", ";", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "IS_API_TOKEN", "]", "=", "false", ";", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "STATE", "]", "=", "self", "::", "NEGOTIATION_COMPLETE", ";", "header", "(", "\"Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}\"", ")", ";", "exit", ";", "}", "elseif", "(", "isset", "(", "$", "_REQUEST", "[", "self", "::", "ERROR", "]", ")", ")", "{", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "STATE", "]", "=", "self", "::", "NEGOTIATION_FAILED", ";", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "ERROR", "]", "=", "$", "_REQUEST", "[", "self", "::", "ERROR", "]", ";", "header", "(", "\"Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}?error={$_REQUEST[self::ERROR]}\"", ")", ";", "exit", ";", "}", "else", "{", "throw", "new", "OAuthNegotiator_Exception", "(", "'Unexpected OAuth response'", ",", "OAuthNegotiator_Exception", "::", "CODE_RESPONSE", ")", ";", "}", "}" ]
Construct an OAuthNegotiator to use an access code to request an identity token @return void @throws OAuthNegotiator_Exception CODE_RESPONSE if the prior request for an authorization token resulted in neither an authorization code or an erro (weird!)
[ "Construct", "an", "OAuthNegotiator", "to", "use", "an", "access", "code", "to", "request", "an", "identity", "token" ]
f29099100cb931582058139cbedc5d1e65a8255a
https://github.com/smtech/obsolete__oauth-negotiator/blob/f29099100cb931582058139cbedc5d1e65a8255a/OAuthNegotiator.php#L243-L261
train
smtech/obsolete__oauth-negotiator
OAuthNegotiator.php
OAuthNegotiator.constructAPIToken
private function constructAPIToken() { if (isset($_REQUEST[self::CODE])) { $this->requestToken($_REQUEST[self::CODE], self::API_TOKEN); $_SESSION[self::SESSION][self::IS_API_TOKEN] = true; $_SESSION[self::SESSION][self::STATE] = self::NEGOTIATION_COMPLETE; header ("Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}"); exit; } elseif (isset($_REQUEST[self::ERROR])) { $_SESSION[self::SESSION][self::STATE] = self::NEGOTIATION_FAILED; $_SESSION[self::SESSION][self::ERROR] = $_REQUEST[self::ERROR]; header("Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}?error={$_REQUEST[self::ERROR]}"); exit; } else { throw new OAuthNegotiator_Exception( 'Unexpected OAuth response', OAuthNegotiator_Exception::CODE_RESPONSE ); } }
php
private function constructAPIToken() { if (isset($_REQUEST[self::CODE])) { $this->requestToken($_REQUEST[self::CODE], self::API_TOKEN); $_SESSION[self::SESSION][self::IS_API_TOKEN] = true; $_SESSION[self::SESSION][self::STATE] = self::NEGOTIATION_COMPLETE; header ("Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}"); exit; } elseif (isset($_REQUEST[self::ERROR])) { $_SESSION[self::SESSION][self::STATE] = self::NEGOTIATION_FAILED; $_SESSION[self::SESSION][self::ERROR] = $_REQUEST[self::ERROR]; header("Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}?error={$_REQUEST[self::ERROR]}"); exit; } else { throw new OAuthNegotiator_Exception( 'Unexpected OAuth response', OAuthNegotiator_Exception::CODE_RESPONSE ); } }
[ "private", "function", "constructAPIToken", "(", ")", "{", "if", "(", "isset", "(", "$", "_REQUEST", "[", "self", "::", "CODE", "]", ")", ")", "{", "$", "this", "->", "requestToken", "(", "$", "_REQUEST", "[", "self", "::", "CODE", "]", ",", "self", "::", "API_TOKEN", ")", ";", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "IS_API_TOKEN", "]", "=", "true", ";", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "STATE", "]", "=", "self", "::", "NEGOTIATION_COMPLETE", ";", "header", "(", "\"Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}\"", ")", ";", "exit", ";", "}", "elseif", "(", "isset", "(", "$", "_REQUEST", "[", "self", "::", "ERROR", "]", ")", ")", "{", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "STATE", "]", "=", "self", "::", "NEGOTIATION_FAILED", ";", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "ERROR", "]", "=", "$", "_REQUEST", "[", "self", "::", "ERROR", "]", ";", "header", "(", "\"Location: {$_SESSION[self::SESSION][self::LANDING_PAGE]}?error={$_REQUEST[self::ERROR]}\"", ")", ";", "exit", ";", "}", "else", "{", "throw", "new", "OAuthNegotiator_Exception", "(", "'Unexpected OAuth response'", ",", "OAuthNegotiator_Exception", "::", "CODE_RESPONSE", ")", ";", "}", "}" ]
Construct an OAuthNegotiator to use an access code to request an API Token with matching user profile @return void @throws OAuthNegotiator_Exception CODE_RESPONSE if the prior request for an authorization token resulted in neither an authorization code or an error (weird!) @throws OAuthNegotatior_Exception USER_RESPONSE if a user profile cannot be acquired to match the API access token (i.e. the OAuth server is probably not a Canvas instance)
[ "Construct", "an", "OAuthNegotiator", "to", "use", "an", "access", "code", "to", "request", "an", "API", "Token", "with", "matching", "user", "profile" ]
f29099100cb931582058139cbedc5d1e65a8255a
https://github.com/smtech/obsolete__oauth-negotiator/blob/f29099100cb931582058139cbedc5d1e65a8255a/OAuthNegotiator.php#L271-L290
train
smtech/obsolete__oauth-negotiator
OAuthNegotiator.php
OAuthNegotiator.constructNegotiationReporter
private function constructNegotiationReporter() { switch ($_SESSION[self::SESSION][self::STATE]) { case self::NEGOTIATION_COMPLETE: case self::NEGOTIATION_FAILED: { $this->ready = true; $this->apiUrl = (isset($_SESSION[self::SESSION][self::API_URL]) ? $_SESSION[self::SESSION][self::API_URL] : null); $this->token = (isset($_SESSION[self::SESSION][self::TOKEN]) ? $_SESSION[self::SESSION][self::TOKEN] : null); $this->isApiToken = (isset($_SESSION[self::SESSION][self::IS_API_TOKEN]) ? $_SESSION[self::SESSION][self::IS_API_TOKEN] : false); $this->user = (isset($_SESSION[self::SESSION][self::USER]) ? $_SESSION[self::SESSION][self::USER] : null); $this->error = (isset($_SESSION[self::SESSION][self::ERROR]) ? $_SESSION[self::SESSION][self::ERROR] : null); unset($_SESSION[self::SESSION]); $_SESSION[self::SESSION][self::STATE] = $state; break; } default: { $this->ready = false; } } }
php
private function constructNegotiationReporter() { switch ($_SESSION[self::SESSION][self::STATE]) { case self::NEGOTIATION_COMPLETE: case self::NEGOTIATION_FAILED: { $this->ready = true; $this->apiUrl = (isset($_SESSION[self::SESSION][self::API_URL]) ? $_SESSION[self::SESSION][self::API_URL] : null); $this->token = (isset($_SESSION[self::SESSION][self::TOKEN]) ? $_SESSION[self::SESSION][self::TOKEN] : null); $this->isApiToken = (isset($_SESSION[self::SESSION][self::IS_API_TOKEN]) ? $_SESSION[self::SESSION][self::IS_API_TOKEN] : false); $this->user = (isset($_SESSION[self::SESSION][self::USER]) ? $_SESSION[self::SESSION][self::USER] : null); $this->error = (isset($_SESSION[self::SESSION][self::ERROR]) ? $_SESSION[self::SESSION][self::ERROR] : null); unset($_SESSION[self::SESSION]); $_SESSION[self::SESSION][self::STATE] = $state; break; } default: { $this->ready = false; } } }
[ "private", "function", "constructNegotiationReporter", "(", ")", "{", "switch", "(", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "STATE", "]", ")", "{", "case", "self", "::", "NEGOTIATION_COMPLETE", ":", "case", "self", "::", "NEGOTIATION_FAILED", ":", "{", "$", "this", "->", "ready", "=", "true", ";", "$", "this", "->", "apiUrl", "=", "(", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "API_URL", "]", ")", "?", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "API_URL", "]", ":", "null", ")", ";", "$", "this", "->", "token", "=", "(", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "TOKEN", "]", ")", "?", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "TOKEN", "]", ":", "null", ")", ";", "$", "this", "->", "isApiToken", "=", "(", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "IS_API_TOKEN", "]", ")", "?", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "IS_API_TOKEN", "]", ":", "false", ")", ";", "$", "this", "->", "user", "=", "(", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "USER", "]", ")", "?", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "USER", "]", ":", "null", ")", ";", "$", "this", "->", "error", "=", "(", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "ERROR", "]", ")", "?", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "ERROR", "]", ":", "null", ")", ";", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION", "]", ")", ";", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "STATE", "]", "=", "$", "state", ";", "break", ";", "}", "default", ":", "{", "$", "this", "->", "ready", "=", "false", ";", "}", "}", "}" ]
Prepare to report on the results of the OAuth negotiation @return void
[ "Prepare", "to", "report", "on", "the", "results", "of", "the", "OAuth", "negotiation" ]
f29099100cb931582058139cbedc5d1e65a8255a
https://github.com/smtech/obsolete__oauth-negotiator/blob/f29099100cb931582058139cbedc5d1e65a8255a/OAuthNegotiator.php#L297-L315
train
smtech/obsolete__oauth-negotiator
OAuthNegotiator.php
OAuthNegotiator.requestAuthorizationCode
private function requestAuthorizationCode($responseType, $scopes, $purpose) { $_SESSION[self::SESSION][self::STATE] = self::$SCOPES[$scopes][self::CODE_REQUESTED]; if ($scopes === self::IDENTITY_TOKEN) { header( "Location: {$_SESSION[self::SESSION][self::OAUTH_ENDPOINT]}/auth?" . http_build_query( array( self::CLIENT_ID => $_SESSION[self::SESSION][self::CLIENT_ID], self::RESPONSE_TYPE => $responseType, self::REDIRECT_URI => $_SESSION[self::SESSION][self::REDIRECT_URI], self::STATE => self::$SCOPES[$scopes][self::CODE_PROVIDED], self::SCOPES => $scopes, self::PURPOSE => $purpose ) ) ); } else { header( "Location: {$_SESSION[self::SESSION][self::OAUTH_ENDPOINT]}/auth?" . http_build_query( array( self::CLIENT_ID => $_SESSION[self::SESSION][self::CLIENT_ID], self::RESPONSE_TYPE => $responseType, self::REDIRECT_URI => $_SESSION[self::SESSION][self::REDIRECT_URI], self::STATE => self::$SCOPES[$scopes][self::CODE_PROVIDED], self::PURPOSE => $purpose ) ) ); } exit; }
php
private function requestAuthorizationCode($responseType, $scopes, $purpose) { $_SESSION[self::SESSION][self::STATE] = self::$SCOPES[$scopes][self::CODE_REQUESTED]; if ($scopes === self::IDENTITY_TOKEN) { header( "Location: {$_SESSION[self::SESSION][self::OAUTH_ENDPOINT]}/auth?" . http_build_query( array( self::CLIENT_ID => $_SESSION[self::SESSION][self::CLIENT_ID], self::RESPONSE_TYPE => $responseType, self::REDIRECT_URI => $_SESSION[self::SESSION][self::REDIRECT_URI], self::STATE => self::$SCOPES[$scopes][self::CODE_PROVIDED], self::SCOPES => $scopes, self::PURPOSE => $purpose ) ) ); } else { header( "Location: {$_SESSION[self::SESSION][self::OAUTH_ENDPOINT]}/auth?" . http_build_query( array( self::CLIENT_ID => $_SESSION[self::SESSION][self::CLIENT_ID], self::RESPONSE_TYPE => $responseType, self::REDIRECT_URI => $_SESSION[self::SESSION][self::REDIRECT_URI], self::STATE => self::$SCOPES[$scopes][self::CODE_PROVIDED], self::PURPOSE => $purpose ) ) ); } exit; }
[ "private", "function", "requestAuthorizationCode", "(", "$", "responseType", ",", "$", "scopes", ",", "$", "purpose", ")", "{", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "STATE", "]", "=", "self", "::", "$", "SCOPES", "[", "$", "scopes", "]", "[", "self", "::", "CODE_REQUESTED", "]", ";", "if", "(", "$", "scopes", "===", "self", "::", "IDENTITY_TOKEN", ")", "{", "header", "(", "\"Location: {$_SESSION[self::SESSION][self::OAUTH_ENDPOINT]}/auth?\"", ".", "http_build_query", "(", "array", "(", "self", "::", "CLIENT_ID", "=>", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "CLIENT_ID", "]", ",", "self", "::", "RESPONSE_TYPE", "=>", "$", "responseType", ",", "self", "::", "REDIRECT_URI", "=>", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "REDIRECT_URI", "]", ",", "self", "::", "STATE", "=>", "self", "::", "$", "SCOPES", "[", "$", "scopes", "]", "[", "self", "::", "CODE_PROVIDED", "]", ",", "self", "::", "SCOPES", "=>", "$", "scopes", ",", "self", "::", "PURPOSE", "=>", "$", "purpose", ")", ")", ")", ";", "}", "else", "{", "header", "(", "\"Location: {$_SESSION[self::SESSION][self::OAUTH_ENDPOINT]}/auth?\"", ".", "http_build_query", "(", "array", "(", "self", "::", "CLIENT_ID", "=>", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "CLIENT_ID", "]", ",", "self", "::", "RESPONSE_TYPE", "=>", "$", "responseType", ",", "self", "::", "REDIRECT_URI", "=>", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "REDIRECT_URI", "]", ",", "self", "::", "STATE", "=>", "self", "::", "$", "SCOPES", "[", "$", "scopes", "]", "[", "self", "::", "CODE_PROVIDED", "]", ",", "self", "::", "PURPOSE", "=>", "$", "purpose", ")", ")", ")", ";", "}", "exit", ";", "}" ]
Request an authorization code from the OAuth server @param string $responseType Always 'code' @param string $scopes The type of token for which we need an authorization code (IDENTITY_TOKEN|API_TOKEN) @param string $purpose User-readable description of the purpose for which this token will be used @return void
[ "Request", "an", "authorization", "code", "from", "the", "OAuth", "server" ]
f29099100cb931582058139cbedc5d1e65a8255a
https://github.com/smtech/obsolete__oauth-negotiator/blob/f29099100cb931582058139cbedc5d1e65a8255a/OAuthNegotiator.php#L390-L419
train
smtech/obsolete__oauth-negotiator
OAuthNegotiator.php
OAuthNegotiator.requestToken
private function requestToken($code, $tokenType) { $authApi = new PestJSON("{$_SESSION[self::SESSION][self::OAUTH_ENDPOINT]}"); try { $response = $authApi->post('token', array( self::CLIENT_ID => $_SESSION[self::SESSION][self::CLIENT_ID], self::REDIRECT_URI => $_SESSION[self::SESSION][self::REDIRECT_URI], self::STATE => self::$SCOPES[$tokenType][self::TOKEN_PROVIDED], self::CLIENT_SECRET => $_SESSION[self::SESSION][self::CLIENT_SECRET], self::CODE => $code, ) ); } catch (Pest_ServerError $e) { echo $e->getMessage(); exit; } if ($response) { if (isset($response['access_token'])) { $_SESSION[self::SESSION][self::TOKEN] = $response['access_token']; return true; } else { throw new OAuthNegotiator_Exception( 'Access token not received', OAuthNegotiator_Exception::TOKEN_RESPONSE ); } } else { throw new OAuthNegotiator_Exception( 'Unexpected OAuth response', OAuthNegotiator_Exception::TOKEN_RESPONSE ); } }
php
private function requestToken($code, $tokenType) { $authApi = new PestJSON("{$_SESSION[self::SESSION][self::OAUTH_ENDPOINT]}"); try { $response = $authApi->post('token', array( self::CLIENT_ID => $_SESSION[self::SESSION][self::CLIENT_ID], self::REDIRECT_URI => $_SESSION[self::SESSION][self::REDIRECT_URI], self::STATE => self::$SCOPES[$tokenType][self::TOKEN_PROVIDED], self::CLIENT_SECRET => $_SESSION[self::SESSION][self::CLIENT_SECRET], self::CODE => $code, ) ); } catch (Pest_ServerError $e) { echo $e->getMessage(); exit; } if ($response) { if (isset($response['access_token'])) { $_SESSION[self::SESSION][self::TOKEN] = $response['access_token']; return true; } else { throw new OAuthNegotiator_Exception( 'Access token not received', OAuthNegotiator_Exception::TOKEN_RESPONSE ); } } else { throw new OAuthNegotiator_Exception( 'Unexpected OAuth response', OAuthNegotiator_Exception::TOKEN_RESPONSE ); } }
[ "private", "function", "requestToken", "(", "$", "code", ",", "$", "tokenType", ")", "{", "$", "authApi", "=", "new", "PestJSON", "(", "\"{$_SESSION[self::SESSION][self::OAUTH_ENDPOINT]}\"", ")", ";", "try", "{", "$", "response", "=", "$", "authApi", "->", "post", "(", "'token'", ",", "array", "(", "self", "::", "CLIENT_ID", "=>", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "CLIENT_ID", "]", ",", "self", "::", "REDIRECT_URI", "=>", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "REDIRECT_URI", "]", ",", "self", "::", "STATE", "=>", "self", "::", "$", "SCOPES", "[", "$", "tokenType", "]", "[", "self", "::", "TOKEN_PROVIDED", "]", ",", "self", "::", "CLIENT_SECRET", "=>", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "CLIENT_SECRET", "]", ",", "self", "::", "CODE", "=>", "$", "code", ",", ")", ")", ";", "}", "catch", "(", "Pest_ServerError", "$", "e", ")", "{", "echo", "$", "e", "->", "getMessage", "(", ")", ";", "exit", ";", "}", "if", "(", "$", "response", ")", "{", "if", "(", "isset", "(", "$", "response", "[", "'access_token'", "]", ")", ")", "{", "$", "_SESSION", "[", "self", "::", "SESSION", "]", "[", "self", "::", "TOKEN", "]", "=", "$", "response", "[", "'access_token'", "]", ";", "return", "true", ";", "}", "else", "{", "throw", "new", "OAuthNegotiator_Exception", "(", "'Access token not received'", ",", "OAuthNegotiator_Exception", "::", "TOKEN_RESPONSE", ")", ";", "}", "}", "else", "{", "throw", "new", "OAuthNegotiator_Exception", "(", "'Unexpected OAuth response'", ",", "OAuthNegotiator_Exception", "::", "TOKEN_RESPONSE", ")", ";", "}", "}" ]
Request a token from the OAuth server @param string $code An authorization code provided by the OAuth server @param string $tokenType Type of token being requested (IDENTITY_TOKEN|API_TOKEN) @return void Updates session variables @throws OAuthNegotiator_Exception TOKEN_RESPONSE if a token no token is received or on any other uanticipated response from the OAuth server
[ "Request", "a", "token", "from", "the", "OAuth", "server" ]
f29099100cb931582058139cbedc5d1e65a8255a
https://github.com/smtech/obsolete__oauth-negotiator/blob/f29099100cb931582058139cbedc5d1e65a8255a/OAuthNegotiator.php#L431-L463
train
FuzeWorks/Core
src/FuzeWorks/Router.php
Router.addRoute
public function addRoute($route, $callable, $prepend = true) { if ($prepend) { $this->routes = array($route => $callable) + $this->routes; } else { $this->routes[$route] = $callable; } $this->logger->log('Route added at '.($prepend ? 'top' : 'bottom').': "'.$route.'"'); }
php
public function addRoute($route, $callable, $prepend = true) { if ($prepend) { $this->routes = array($route => $callable) + $this->routes; } else { $this->routes[$route] = $callable; } $this->logger->log('Route added at '.($prepend ? 'top' : 'bottom').': "'.$route.'"'); }
[ "public", "function", "addRoute", "(", "$", "route", ",", "$", "callable", ",", "$", "prepend", "=", "true", ")", "{", "if", "(", "$", "prepend", ")", "{", "$", "this", "->", "routes", "=", "array", "(", "$", "route", "=>", "$", "callable", ")", "+", "$", "this", "->", "routes", ";", "}", "else", "{", "$", "this", "->", "routes", "[", "$", "route", "]", "=", "$", "callable", ";", "}", "$", "this", "->", "logger", "->", "log", "(", "'Route added at '", ".", "(", "$", "prepend", "?", "'top'", ":", "'bottom'", ")", ".", "': \"'", ".", "$", "route", ".", "'\"'", ")", ";", "}" ]
Add a route to the Router's routing table The route consists of 2 parts: the route and data. The route is a regex string which will later be matched upon Router::route(). The data can be multiple things. First it can be a string, which will later be processed and turned into a callable. If the string is like 'controller/method' then the contoller 'Controller' will be loaded and the method 'method' will be called. The data can also be a callable. That callable will be called with all the regex that match the route. The callable is expected to return a string just like above. You can also provide an array. If you have an array like this: array('callable' => array('Class', 'method')) then your callable shall be used instead of the defaultCallabele. @param string $route This is a RegEx of the route, Every capture group will be a match, passed on to a callable @param mixed $data Can be multiple things. See description above @param bool $prepend Whether or not to insert at the beginning of the routing table @return void
[ "Add", "a", "route", "to", "the", "Router", "s", "routing", "table" ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Router.php#L282-L291
train
FuzeWorks/Core
src/FuzeWorks/Router.php
Router.route
public function route($performLoading = true): bool { // Turn the segment array into a URI string $uri = implode('/', $this->uri->segments); // Fire the event to notify our modules $event = Events::fireEvent('routerRouteEvent', $this->routes, $performLoading, $uri); // The event has been cancelled if ($event->isCancelled()) { return false; } // Assign everything to the object to make it accessible, but let modules check it first $routes = $event->routes; $performLoading = $event->performLoading; // If a cached page should be loaded, do so and stop loading a routed page if ($performLoading === true && $event->cacheOverride === false && $this->output->_display_cache() === true) { return true; } // Check the custom routes foreach ($routes as $route => $value) { // Match the path against the routes if (preg_match('#^'.$route.'$#', $event->path, $matches)) { $this->logger->log('Route matched: '.$route); // Save the matches $this->matches = $matches; // Are we using callbacks or another method? if ( is_array($value)) { // Maybe there is a real callable which should be called in the future if ( isset($value['callable']) ) { $this->callable = $value['callable']; } // If the callable is satisfied, break away if (!$performLoading || $this->loadCallable($matches, $route)) { return true; } // Otherwise try other routes continue; } elseif ( is_callable($value) ) { // Prepare the callable array_shift($matches); // Retrieve the path that should be loaded $value = call_user_func_array($value, $matches); } elseif (strpos($value, '$') !== FALSE && strpos($route, '(') !== FALSE) { $value = preg_replace('#^'.$route.'$#', $value, $event->path); } if ($performLoading === true) { // Now run the defaultRouter for when something is not a callable $this->routeDefault(explode('/', $value), $route); return true; } return false; } } // If we got this far it means we didn't encounter a // matching route so we'll set the site default route $this->matches = array(); if ($performLoading === true) { $this->routeDefault(array_values($this->uri->segments), '.*$'); return true; } return false; }
php
public function route($performLoading = true): bool { // Turn the segment array into a URI string $uri = implode('/', $this->uri->segments); // Fire the event to notify our modules $event = Events::fireEvent('routerRouteEvent', $this->routes, $performLoading, $uri); // The event has been cancelled if ($event->isCancelled()) { return false; } // Assign everything to the object to make it accessible, but let modules check it first $routes = $event->routes; $performLoading = $event->performLoading; // If a cached page should be loaded, do so and stop loading a routed page if ($performLoading === true && $event->cacheOverride === false && $this->output->_display_cache() === true) { return true; } // Check the custom routes foreach ($routes as $route => $value) { // Match the path against the routes if (preg_match('#^'.$route.'$#', $event->path, $matches)) { $this->logger->log('Route matched: '.$route); // Save the matches $this->matches = $matches; // Are we using callbacks or another method? if ( is_array($value)) { // Maybe there is a real callable which should be called in the future if ( isset($value['callable']) ) { $this->callable = $value['callable']; } // If the callable is satisfied, break away if (!$performLoading || $this->loadCallable($matches, $route)) { return true; } // Otherwise try other routes continue; } elseif ( is_callable($value) ) { // Prepare the callable array_shift($matches); // Retrieve the path that should be loaded $value = call_user_func_array($value, $matches); } elseif (strpos($value, '$') !== FALSE && strpos($route, '(') !== FALSE) { $value = preg_replace('#^'.$route.'$#', $value, $event->path); } if ($performLoading === true) { // Now run the defaultRouter for when something is not a callable $this->routeDefault(explode('/', $value), $route); return true; } return false; } } // If we got this far it means we didn't encounter a // matching route so we'll set the site default route $this->matches = array(); if ($performLoading === true) { $this->routeDefault(array_values($this->uri->segments), '.*$'); return true; } return false; }
[ "public", "function", "route", "(", "$", "performLoading", "=", "true", ")", ":", "bool", "{", "// Turn the segment array into a URI string", "$", "uri", "=", "implode", "(", "'/'", ",", "$", "this", "->", "uri", "->", "segments", ")", ";", "// Fire the event to notify our modules", "$", "event", "=", "Events", "::", "fireEvent", "(", "'routerRouteEvent'", ",", "$", "this", "->", "routes", ",", "$", "performLoading", ",", "$", "uri", ")", ";", "// The event has been cancelled", "if", "(", "$", "event", "->", "isCancelled", "(", ")", ")", "{", "return", "false", ";", "}", "// Assign everything to the object to make it accessible, but let modules check it first", "$", "routes", "=", "$", "event", "->", "routes", ";", "$", "performLoading", "=", "$", "event", "->", "performLoading", ";", "// If a cached page should be loaded, do so and stop loading a routed page", "if", "(", "$", "performLoading", "===", "true", "&&", "$", "event", "->", "cacheOverride", "===", "false", "&&", "$", "this", "->", "output", "->", "_display_cache", "(", ")", "===", "true", ")", "{", "return", "true", ";", "}", "// Check the custom routes", "foreach", "(", "$", "routes", "as", "$", "route", "=>", "$", "value", ")", "{", "// Match the path against the routes", "if", "(", "preg_match", "(", "'#^'", ".", "$", "route", ".", "'$#'", ",", "$", "event", "->", "path", ",", "$", "matches", ")", ")", "{", "$", "this", "->", "logger", "->", "log", "(", "'Route matched: '", ".", "$", "route", ")", ";", "// Save the matches", "$", "this", "->", "matches", "=", "$", "matches", ";", "// Are we using callbacks or another method?", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "// Maybe there is a real callable which should be called in the future", "if", "(", "isset", "(", "$", "value", "[", "'callable'", "]", ")", ")", "{", "$", "this", "->", "callable", "=", "$", "value", "[", "'callable'", "]", ";", "}", "// If the callable is satisfied, break away", "if", "(", "!", "$", "performLoading", "||", "$", "this", "->", "loadCallable", "(", "$", "matches", ",", "$", "route", ")", ")", "{", "return", "true", ";", "}", "// Otherwise try other routes", "continue", ";", "}", "elseif", "(", "is_callable", "(", "$", "value", ")", ")", "{", "// Prepare the callable", "array_shift", "(", "$", "matches", ")", ";", "// Retrieve the path that should be loaded", "$", "value", "=", "call_user_func_array", "(", "$", "value", ",", "$", "matches", ")", ";", "}", "elseif", "(", "strpos", "(", "$", "value", ",", "'$'", ")", "!==", "FALSE", "&&", "strpos", "(", "$", "route", ",", "'('", ")", "!==", "FALSE", ")", "{", "$", "value", "=", "preg_replace", "(", "'#^'", ".", "$", "route", ".", "'$#'", ",", "$", "value", ",", "$", "event", "->", "path", ")", ";", "}", "if", "(", "$", "performLoading", "===", "true", ")", "{", "// Now run the defaultRouter for when something is not a callable", "$", "this", "->", "routeDefault", "(", "explode", "(", "'/'", ",", "$", "value", ")", ",", "$", "route", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", "}", "// If we got this far it means we didn't encounter a", "// matching route so we'll set the site default route", "$", "this", "->", "matches", "=", "array", "(", ")", ";", "if", "(", "$", "performLoading", "===", "true", ")", "{", "$", "this", "->", "routeDefault", "(", "array_values", "(", "$", "this", "->", "uri", "->", "segments", ")", ",", "'.*$'", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Extracts the routing path from the URL using the routing table. Determines what should be loaded and what data matches the route regex. @param bool $performLoading Immediate process the route after it has been determined
[ "Extracts", "the", "routing", "path", "from", "the", "URL", "using", "the", "routing", "table", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Router.php#L312-L398
train
FuzeWorks/Core
src/FuzeWorks/Router.php
Router.routeDefault
protected function routeDefault($segments = array(), $route) { // If we don't have any segments left - try the default controller; // WARNING: Directories get shifted out of the segments array! if (empty($segments)) { $segments[0] = $this->config->routing->default_controller; } if ($this->config->routing->translate_uri_dashes === true) { $segments[0] = str_replace('-', '_', $segments[0]); if (isset($segments[1])) { $segments[1] = str_replace('-', '_', $segments[1]); } } // Prepare the values for loading $controller = $segments[0]; $function = (isset($segments[1]) ? $segments[1] : $this->config->routing->default_function); // And prepare the Router URI array_unshift($segments, null); unset($segments[0]); $this->uri->rsegments = $segments; // Now create a matches array $matches = array( 'controller' => $controller, 'function' => $function, 'parameters' => array_slice($this->uri->rsegments, 2) ); // And finally load the callable $this->callable = array('\FuzeWorks\Router', 'defaultCallable'); $this->loadCallable($matches, $route); }
php
protected function routeDefault($segments = array(), $route) { // If we don't have any segments left - try the default controller; // WARNING: Directories get shifted out of the segments array! if (empty($segments)) { $segments[0] = $this->config->routing->default_controller; } if ($this->config->routing->translate_uri_dashes === true) { $segments[0] = str_replace('-', '_', $segments[0]); if (isset($segments[1])) { $segments[1] = str_replace('-', '_', $segments[1]); } } // Prepare the values for loading $controller = $segments[0]; $function = (isset($segments[1]) ? $segments[1] : $this->config->routing->default_function); // And prepare the Router URI array_unshift($segments, null); unset($segments[0]); $this->uri->rsegments = $segments; // Now create a matches array $matches = array( 'controller' => $controller, 'function' => $function, 'parameters' => array_slice($this->uri->rsegments, 2) ); // And finally load the callable $this->callable = array('\FuzeWorks\Router', 'defaultCallable'); $this->loadCallable($matches, $route); }
[ "protected", "function", "routeDefault", "(", "$", "segments", "=", "array", "(", ")", ",", "$", "route", ")", "{", "// If we don't have any segments left - try the default controller;", "// WARNING: Directories get shifted out of the segments array!", "if", "(", "empty", "(", "$", "segments", ")", ")", "{", "$", "segments", "[", "0", "]", "=", "$", "this", "->", "config", "->", "routing", "->", "default_controller", ";", "}", "if", "(", "$", "this", "->", "config", "->", "routing", "->", "translate_uri_dashes", "===", "true", ")", "{", "$", "segments", "[", "0", "]", "=", "str_replace", "(", "'-'", ",", "'_'", ",", "$", "segments", "[", "0", "]", ")", ";", "if", "(", "isset", "(", "$", "segments", "[", "1", "]", ")", ")", "{", "$", "segments", "[", "1", "]", "=", "str_replace", "(", "'-'", ",", "'_'", ",", "$", "segments", "[", "1", "]", ")", ";", "}", "}", "// Prepare the values for loading", "$", "controller", "=", "$", "segments", "[", "0", "]", ";", "$", "function", "=", "(", "isset", "(", "$", "segments", "[", "1", "]", ")", "?", "$", "segments", "[", "1", "]", ":", "$", "this", "->", "config", "->", "routing", "->", "default_function", ")", ";", "// And prepare the Router URI", "array_unshift", "(", "$", "segments", ",", "null", ")", ";", "unset", "(", "$", "segments", "[", "0", "]", ")", ";", "$", "this", "->", "uri", "->", "rsegments", "=", "$", "segments", ";", "// Now create a matches array", "$", "matches", "=", "array", "(", "'controller'", "=>", "$", "controller", ",", "'function'", "=>", "$", "function", ",", "'parameters'", "=>", "array_slice", "(", "$", "this", "->", "uri", "->", "rsegments", ",", "2", ")", ")", ";", "// And finally load the callable", "$", "this", "->", "callable", "=", "array", "(", "'\\FuzeWorks\\Router'", ",", "'defaultCallable'", ")", ";", "$", "this", "->", "loadCallable", "(", "$", "matches", ",", "$", "route", ")", ";", "}" ]
Converts a routing string into parameters for the defaultCallable. @param array $segments Segments of the controller,method,parameters to open @param string @route The route which was matched @return void
[ "Converts", "a", "routing", "string", "into", "parameters", "for", "the", "defaultCallable", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Router.php#L407-L444
train
FuzeWorks/Core
src/FuzeWorks/Router.php
Router.loadCallable
public function loadCallable($matches = array(), $route): bool { $this->logger->newLevel('Loading callable'); // Fire the event to notify our modules $event = Events::fireEvent('routerLoadCallableEvent', $this->callable, $matches, $route); // The event has been cancelled if ($event->isCancelled()) { return false; } // Prepare the arguments and add the route $args = $event->matches; $args['route'] = $event->route; if (!is_callable($event->callable)) { if (isset($event->callable['controller'])) { // Reset the arguments and fetch from custom callable $args = array(); $args['controller'] = isset($event->callable['controller']) ? $event->callable['controller'] : (isset($matches['controller']) ? $matches['controller'] : null); $args['function'] = isset($event->callable['function']) ? $event->callable['function'] : (isset($matches['function']) ? $matches['function'] : null); $args['parameters'] = isset($event->callable['parameters']) ? $event->callable['parameters'] : (isset($matches['parameters']) ? explode('/', $matches['parameters']) : null); $this->callable = array('\FuzeWorks\Router', 'defaultCallable'); } else { $this->logger->log('The given callable is not callable!', E_ERROR); $this->logger->http_error(500); $this->logger->stopLevel(); return true; } } else { $this->callable = $event->callable; } // And log the input to the logger $this->logger->newLevel('Calling callable'); foreach ($args as $key => $value) { $this->logger->log($key.': '.var_export($value, true).''); } $this->logger->stopLevel(); $skip = call_user_func_array($this->callable, array($args)) === true; if (!$skip) { $this->logger->log('Callable not satisfied, skipping to next callable'); } $this->logger->stopLevel(); return $skip; }
php
public function loadCallable($matches = array(), $route): bool { $this->logger->newLevel('Loading callable'); // Fire the event to notify our modules $event = Events::fireEvent('routerLoadCallableEvent', $this->callable, $matches, $route); // The event has been cancelled if ($event->isCancelled()) { return false; } // Prepare the arguments and add the route $args = $event->matches; $args['route'] = $event->route; if (!is_callable($event->callable)) { if (isset($event->callable['controller'])) { // Reset the arguments and fetch from custom callable $args = array(); $args['controller'] = isset($event->callable['controller']) ? $event->callable['controller'] : (isset($matches['controller']) ? $matches['controller'] : null); $args['function'] = isset($event->callable['function']) ? $event->callable['function'] : (isset($matches['function']) ? $matches['function'] : null); $args['parameters'] = isset($event->callable['parameters']) ? $event->callable['parameters'] : (isset($matches['parameters']) ? explode('/', $matches['parameters']) : null); $this->callable = array('\FuzeWorks\Router', 'defaultCallable'); } else { $this->logger->log('The given callable is not callable!', E_ERROR); $this->logger->http_error(500); $this->logger->stopLevel(); return true; } } else { $this->callable = $event->callable; } // And log the input to the logger $this->logger->newLevel('Calling callable'); foreach ($args as $key => $value) { $this->logger->log($key.': '.var_export($value, true).''); } $this->logger->stopLevel(); $skip = call_user_func_array($this->callable, array($args)) === true; if (!$skip) { $this->logger->log('Callable not satisfied, skipping to next callable'); } $this->logger->stopLevel(); return $skip; }
[ "public", "function", "loadCallable", "(", "$", "matches", "=", "array", "(", ")", ",", "$", "route", ")", ":", "bool", "{", "$", "this", "->", "logger", "->", "newLevel", "(", "'Loading callable'", ")", ";", "// Fire the event to notify our modules", "$", "event", "=", "Events", "::", "fireEvent", "(", "'routerLoadCallableEvent'", ",", "$", "this", "->", "callable", ",", "$", "matches", ",", "$", "route", ")", ";", "// The event has been cancelled", "if", "(", "$", "event", "->", "isCancelled", "(", ")", ")", "{", "return", "false", ";", "}", "// Prepare the arguments and add the route", "$", "args", "=", "$", "event", "->", "matches", ";", "$", "args", "[", "'route'", "]", "=", "$", "event", "->", "route", ";", "if", "(", "!", "is_callable", "(", "$", "event", "->", "callable", ")", ")", "{", "if", "(", "isset", "(", "$", "event", "->", "callable", "[", "'controller'", "]", ")", ")", "{", "// Reset the arguments and fetch from custom callable", "$", "args", "=", "array", "(", ")", ";", "$", "args", "[", "'controller'", "]", "=", "isset", "(", "$", "event", "->", "callable", "[", "'controller'", "]", ")", "?", "$", "event", "->", "callable", "[", "'controller'", "]", ":", "(", "isset", "(", "$", "matches", "[", "'controller'", "]", ")", "?", "$", "matches", "[", "'controller'", "]", ":", "null", ")", ";", "$", "args", "[", "'function'", "]", "=", "isset", "(", "$", "event", "->", "callable", "[", "'function'", "]", ")", "?", "$", "event", "->", "callable", "[", "'function'", "]", ":", "(", "isset", "(", "$", "matches", "[", "'function'", "]", ")", "?", "$", "matches", "[", "'function'", "]", ":", "null", ")", ";", "$", "args", "[", "'parameters'", "]", "=", "isset", "(", "$", "event", "->", "callable", "[", "'parameters'", "]", ")", "?", "$", "event", "->", "callable", "[", "'parameters'", "]", ":", "(", "isset", "(", "$", "matches", "[", "'parameters'", "]", ")", "?", "explode", "(", "'/'", ",", "$", "matches", "[", "'parameters'", "]", ")", ":", "null", ")", ";", "$", "this", "->", "callable", "=", "array", "(", "'\\FuzeWorks\\Router'", ",", "'defaultCallable'", ")", ";", "}", "else", "{", "$", "this", "->", "logger", "->", "log", "(", "'The given callable is not callable!'", ",", "E_ERROR", ")", ";", "$", "this", "->", "logger", "->", "http_error", "(", "500", ")", ";", "$", "this", "->", "logger", "->", "stopLevel", "(", ")", ";", "return", "true", ";", "}", "}", "else", "{", "$", "this", "->", "callable", "=", "$", "event", "->", "callable", ";", "}", "// And log the input to the logger", "$", "this", "->", "logger", "->", "newLevel", "(", "'Calling callable'", ")", ";", "foreach", "(", "$", "args", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "logger", "->", "log", "(", "$", "key", ".", "': '", ".", "var_export", "(", "$", "value", ",", "true", ")", ".", "''", ")", ";", "}", "$", "this", "->", "logger", "->", "stopLevel", "(", ")", ";", "$", "skip", "=", "call_user_func_array", "(", "$", "this", "->", "callable", ",", "array", "(", "$", "args", ")", ")", "===", "true", ";", "if", "(", "!", "$", "skip", ")", "{", "$", "this", "->", "logger", "->", "log", "(", "'Callable not satisfied, skipping to next callable'", ")", ";", "}", "$", "this", "->", "logger", "->", "stopLevel", "(", ")", ";", "return", "$", "skip", ";", "}" ]
Load the callable to which the route matched. First it checks if it is possible to call the callable. If not, the default callable gets selected and a controller, function and parameters get selected. Then the arguments get prepared and finally the callable is called. @param array Preg matches with the routing path @param string The route that matched @return bool Whether or not the callable was satisfied
[ "Load", "the", "callable", "to", "which", "the", "route", "matched", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Router.php#L458-L510
train
FuzeWorks/Core
src/FuzeWorks/Router.php
Router.defaultCallable
public function defaultCallable($arguments = array()): bool { $this->logger->log('Default callable called!'); $controller = $arguments['controller']; $function = $arguments['function']; $parameters = empty($arguments['parameters']) ? null : $arguments['parameters']; // Construct file paths and classes $class = '\Application\Controller\\'.ucfirst($controller); $directory = $this->controller_directory; $file = $directory . DS . strtolower('controller.'.$controller.'.php'); $event = Events::fireEvent('routerLoadControllerEvent', $file, $directory, $class, $controller, $function, $parameters ); // Cancel if requested to do so if ($event->isCancelled()) { return false; } // Check if the file exists if (file_exists($event->file)) { if (!class_exists($event->className)) { $this->logger->log('Loading controller '.$event->className.' from file: '.$event->file); require $event->file; } // Get the path the controller should know about $path = implode('/', $this->uri->rsegments); // And create the controller $this->callable = new $event->className($path); // If the controller does not want a function to be loaded, provide a halt parameter. if (isset($this->callable->halt)) { return false; } // Check if method exists or if there is a caller function if (method_exists($this->callable, $event->function) || method_exists($this->callable, '__call')) { // Run the routerCallMethodEvent $methodEvent = Events::fireEvent('routerCallMethodEvent'); if ($methodEvent->isCancelled()) { return false; } // Execute the function on the controller $this->output->append_output($this->callable->{$event->function}($event->parameters)); return true; } else { // Function could not be found $this->logger->log('Could not find function '.$event->function.' on controller '.$event->className); $this->logger->http_error(404); } } else { // Controller could not be found $this->logger->log('Could not find controller '.$event->className); $this->logger->http_error(404); } return false; }
php
public function defaultCallable($arguments = array()): bool { $this->logger->log('Default callable called!'); $controller = $arguments['controller']; $function = $arguments['function']; $parameters = empty($arguments['parameters']) ? null : $arguments['parameters']; // Construct file paths and classes $class = '\Application\Controller\\'.ucfirst($controller); $directory = $this->controller_directory; $file = $directory . DS . strtolower('controller.'.$controller.'.php'); $event = Events::fireEvent('routerLoadControllerEvent', $file, $directory, $class, $controller, $function, $parameters ); // Cancel if requested to do so if ($event->isCancelled()) { return false; } // Check if the file exists if (file_exists($event->file)) { if (!class_exists($event->className)) { $this->logger->log('Loading controller '.$event->className.' from file: '.$event->file); require $event->file; } // Get the path the controller should know about $path = implode('/', $this->uri->rsegments); // And create the controller $this->callable = new $event->className($path); // If the controller does not want a function to be loaded, provide a halt parameter. if (isset($this->callable->halt)) { return false; } // Check if method exists or if there is a caller function if (method_exists($this->callable, $event->function) || method_exists($this->callable, '__call')) { // Run the routerCallMethodEvent $methodEvent = Events::fireEvent('routerCallMethodEvent'); if ($methodEvent->isCancelled()) { return false; } // Execute the function on the controller $this->output->append_output($this->callable->{$event->function}($event->parameters)); return true; } else { // Function could not be found $this->logger->log('Could not find function '.$event->function.' on controller '.$event->className); $this->logger->http_error(404); } } else { // Controller could not be found $this->logger->log('Could not find controller '.$event->className); $this->logger->http_error(404); } return false; }
[ "public", "function", "defaultCallable", "(", "$", "arguments", "=", "array", "(", ")", ")", ":", "bool", "{", "$", "this", "->", "logger", "->", "log", "(", "'Default callable called!'", ")", ";", "$", "controller", "=", "$", "arguments", "[", "'controller'", "]", ";", "$", "function", "=", "$", "arguments", "[", "'function'", "]", ";", "$", "parameters", "=", "empty", "(", "$", "arguments", "[", "'parameters'", "]", ")", "?", "null", ":", "$", "arguments", "[", "'parameters'", "]", ";", "// Construct file paths and classes", "$", "class", "=", "'\\Application\\Controller\\\\'", ".", "ucfirst", "(", "$", "controller", ")", ";", "$", "directory", "=", "$", "this", "->", "controller_directory", ";", "$", "file", "=", "$", "directory", ".", "DS", ".", "strtolower", "(", "'controller.'", ".", "$", "controller", ".", "'.php'", ")", ";", "$", "event", "=", "Events", "::", "fireEvent", "(", "'routerLoadControllerEvent'", ",", "$", "file", ",", "$", "directory", ",", "$", "class", ",", "$", "controller", ",", "$", "function", ",", "$", "parameters", ")", ";", "// Cancel if requested to do so", "if", "(", "$", "event", "->", "isCancelled", "(", ")", ")", "{", "return", "false", ";", "}", "// Check if the file exists", "if", "(", "file_exists", "(", "$", "event", "->", "file", ")", ")", "{", "if", "(", "!", "class_exists", "(", "$", "event", "->", "className", ")", ")", "{", "$", "this", "->", "logger", "->", "log", "(", "'Loading controller '", ".", "$", "event", "->", "className", ".", "' from file: '", ".", "$", "event", "->", "file", ")", ";", "require", "$", "event", "->", "file", ";", "}", "// Get the path the controller should know about", "$", "path", "=", "implode", "(", "'/'", ",", "$", "this", "->", "uri", "->", "rsegments", ")", ";", "// And create the controller", "$", "this", "->", "callable", "=", "new", "$", "event", "->", "className", "(", "$", "path", ")", ";", "// If the controller does not want a function to be loaded, provide a halt parameter.", "if", "(", "isset", "(", "$", "this", "->", "callable", "->", "halt", ")", ")", "{", "return", "false", ";", "}", "// Check if method exists or if there is a caller function", "if", "(", "method_exists", "(", "$", "this", "->", "callable", ",", "$", "event", "->", "function", ")", "||", "method_exists", "(", "$", "this", "->", "callable", ",", "'__call'", ")", ")", "{", "// Run the routerCallMethodEvent", "$", "methodEvent", "=", "Events", "::", "fireEvent", "(", "'routerCallMethodEvent'", ")", ";", "if", "(", "$", "methodEvent", "->", "isCancelled", "(", ")", ")", "{", "return", "false", ";", "}", "// Execute the function on the controller", "$", "this", "->", "output", "->", "append_output", "(", "$", "this", "->", "callable", "->", "{", "$", "event", "->", "function", "}", "(", "$", "event", "->", "parameters", ")", ")", ";", "return", "true", ";", "}", "else", "{", "// Function could not be found", "$", "this", "->", "logger", "->", "log", "(", "'Could not find function '", ".", "$", "event", "->", "function", ".", "' on controller '", ".", "$", "event", "->", "className", ")", ";", "$", "this", "->", "logger", "->", "http_error", "(", "404", ")", ";", "}", "}", "else", "{", "// Controller could not be found", "$", "this", "->", "logger", "->", "log", "(", "'Could not find controller '", ".", "$", "event", "->", "className", ")", ";", "$", "this", "->", "logger", "->", "http_error", "(", "404", ")", ";", "}", "return", "false", ";", "}" ]
The default callable. This callable will do the 'old skool' routing. It will load the controllers from the controller-directory in the application-directory.
[ "The", "default", "callable", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Router.php#L518-L587
train
codeup-berlin/interop-mvc
src/Middleware/Stack/Server/ArraySelfDelegate.php
ArraySelfDelegate.withMiddleware
public function withMiddleware(MiddlewareInterface $middleware) { if (!($middleware instanceof ServerMiddlewareInterface)) { throw new \InvalidArgumentException('ServerMiddlewareInterface request expected.'); } foreach ($this->middlewares as $m) { if ($m === $middleware) { return $this; } } $this->middlewares[] = $middleware; // breaking **** immutability by intention ^^~> return $this; }
php
public function withMiddleware(MiddlewareInterface $middleware) { if (!($middleware instanceof ServerMiddlewareInterface)) { throw new \InvalidArgumentException('ServerMiddlewareInterface request expected.'); } foreach ($this->middlewares as $m) { if ($m === $middleware) { return $this; } } $this->middlewares[] = $middleware; // breaking **** immutability by intention ^^~> return $this; }
[ "public", "function", "withMiddleware", "(", "MiddlewareInterface", "$", "middleware", ")", "{", "if", "(", "!", "(", "$", "middleware", "instanceof", "ServerMiddlewareInterface", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'ServerMiddlewareInterface request expected.'", ")", ";", "}", "foreach", "(", "$", "this", "->", "middlewares", "as", "$", "m", ")", "{", "if", "(", "$", "m", "===", "$", "middleware", ")", "{", "return", "$", "this", ";", "}", "}", "$", "this", "->", "middlewares", "[", "]", "=", "$", "middleware", ";", "// breaking **** immutability by intention ^^~>", "return", "$", "this", ";", "}" ]
Return an instance with the specified middleware added to the stack. This method MUST be implemented in such a way as to retain the immutability of the stack, and MUST return an instance that contains the specified middleware. @param MiddlewareInterface $middleware @return self
[ "Return", "an", "instance", "with", "the", "specified", "middleware", "added", "to", "the", "stack", ".", "This", "method", "MUST", "be", "implemented", "in", "such", "a", "way", "as", "to", "retain", "the", "immutability", "of", "the", "stack", "and", "MUST", "return", "an", "instance", "that", "contains", "the", "specified", "middleware", "." ]
b21818b7d060f3934d1225fb0d9fbefdf21a9894
https://github.com/codeup-berlin/interop-mvc/blob/b21818b7d060f3934d1225fb0d9fbefdf21a9894/src/Middleware/Stack/Server/ArraySelfDelegate.php#L47-L61
train
codeup-berlin/interop-mvc
src/Middleware/Stack/Server/ArraySelfDelegate.php
ArraySelfDelegate.withoutMiddleware
public function withoutMiddleware(MiddlewareInterface $middleware) { if (!($middleware instanceof ServerMiddlewareInterface)) { throw new \InvalidArgumentException('ServerMiddlewareInterface request expected.'); } foreach ($this->middlewares as $k => $m) { if ($m === $middleware) { unset($this->middlewares[$k]); break; } } // breaking **** immutability by intention ^^~> return $this; }
php
public function withoutMiddleware(MiddlewareInterface $middleware) { if (!($middleware instanceof ServerMiddlewareInterface)) { throw new \InvalidArgumentException('ServerMiddlewareInterface request expected.'); } foreach ($this->middlewares as $k => $m) { if ($m === $middleware) { unset($this->middlewares[$k]); break; } } // breaking **** immutability by intention ^^~> return $this; }
[ "public", "function", "withoutMiddleware", "(", "MiddlewareInterface", "$", "middleware", ")", "{", "if", "(", "!", "(", "$", "middleware", "instanceof", "ServerMiddlewareInterface", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'ServerMiddlewareInterface request expected.'", ")", ";", "}", "foreach", "(", "$", "this", "->", "middlewares", "as", "$", "k", "=>", "$", "m", ")", "{", "if", "(", "$", "m", "===", "$", "middleware", ")", "{", "unset", "(", "$", "this", "->", "middlewares", "[", "$", "k", "]", ")", ";", "break", ";", "}", "}", "// breaking **** immutability by intention ^^~>", "return", "$", "this", ";", "}" ]
Return an instance without the specified middleware. This method MUST be implemented in such a way as to retain the immutability of the stack, and MUST return an instance that does not contain the specified middleware. @param MiddlewareInterface $middleware @return self
[ "Return", "an", "instance", "without", "the", "specified", "middleware", ".", "This", "method", "MUST", "be", "implemented", "in", "such", "a", "way", "as", "to", "retain", "the", "immutability", "of", "the", "stack", "and", "MUST", "return", "an", "instance", "that", "does", "not", "contain", "the", "specified", "middleware", "." ]
b21818b7d060f3934d1225fb0d9fbefdf21a9894
https://github.com/codeup-berlin/interop-mvc/blob/b21818b7d060f3934d1225fb0d9fbefdf21a9894/src/Middleware/Stack/Server/ArraySelfDelegate.php#L72-L86
train
codeup-berlin/interop-mvc
src/Middleware/Stack/Server/ArraySelfDelegate.php
ArraySelfDelegate.process
public function process(RequestInterface $request) { if ($this->processingStack !== null) { throw new \RuntimeException('Middleware stack is already processing.'); } if (!count($this->middlewares)) { throw new \RuntimeException('Middleware stack is empty.'); } if (!($request instanceof ServerRequestInterface)) { throw new \InvalidArgumentException('ServerRequest request expected.'); } $this->processingStack = array_reverse($this->middlewares); /** @var ServerMiddlewareInterface $middleware */ $middleware = array_shift($this->processingStack); return $middleware->process($request, $this); }
php
public function process(RequestInterface $request) { if ($this->processingStack !== null) { throw new \RuntimeException('Middleware stack is already processing.'); } if (!count($this->middlewares)) { throw new \RuntimeException('Middleware stack is empty.'); } if (!($request instanceof ServerRequestInterface)) { throw new \InvalidArgumentException('ServerRequest request expected.'); } $this->processingStack = array_reverse($this->middlewares); /** @var ServerMiddlewareInterface $middleware */ $middleware = array_shift($this->processingStack); return $middleware->process($request, $this); }
[ "public", "function", "process", "(", "RequestInterface", "$", "request", ")", "{", "if", "(", "$", "this", "->", "processingStack", "!==", "null", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Middleware stack is already processing.'", ")", ";", "}", "if", "(", "!", "count", "(", "$", "this", "->", "middlewares", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Middleware stack is empty.'", ")", ";", "}", "if", "(", "!", "(", "$", "request", "instanceof", "ServerRequestInterface", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'ServerRequest request expected.'", ")", ";", "}", "$", "this", "->", "processingStack", "=", "array_reverse", "(", "$", "this", "->", "middlewares", ")", ";", "/** @var ServerMiddlewareInterface $middleware */", "$", "middleware", "=", "array_shift", "(", "$", "this", "->", "processingStack", ")", ";", "return", "$", "middleware", "->", "process", "(", "$", "request", ",", "$", "this", ")", ";", "}" ]
Process the request through middleware and return the response. This method MUST be implemented in such a way as to allow the same stack to be reused for processing multiple requests in sequence. @param RequestInterface $request @return ResponseInterface
[ "Process", "the", "request", "through", "middleware", "and", "return", "the", "response", ".", "This", "method", "MUST", "be", "implemented", "in", "such", "a", "way", "as", "to", "allow", "the", "same", "stack", "to", "be", "reused", "for", "processing", "multiple", "requests", "in", "sequence", "." ]
b21818b7d060f3934d1225fb0d9fbefdf21a9894
https://github.com/codeup-berlin/interop-mvc/blob/b21818b7d060f3934d1225fb0d9fbefdf21a9894/src/Middleware/Stack/Server/ArraySelfDelegate.php#L96-L111
train
climphp/Clim
Clim/Container.php
Container.registerDefaultServices
public static function registerDefaultServices(ContainerInterface $container) { if (!$container->has('argv')) { $container['argv'] = $_SERVER['argv']; } if (!$container->has('Debug')) { $container['Debug'] = function (ContainerInterface $c) { return new DebugMiddleware($c); }; } if (!$container->has('Database')) { $container['Database'] = function (ContainerInterface $c) { return new DatabaseMiddleware($c); }; } if (!$container->has('Console')) { $container['Console'] = function (ContainerInterface $c) { return new ConsoleMiddleware($c); }; } if (!$container->has('callableResolver')) { /** * Instance of \Slim\Interfaces\CallableResolverInterface * * @param ContainerInterface $c * * @return CallableResolver */ $container['callableResolver'] = function (ContainerInterface $c) { return new CallableResolver($c); }; } }
php
public static function registerDefaultServices(ContainerInterface $container) { if (!$container->has('argv')) { $container['argv'] = $_SERVER['argv']; } if (!$container->has('Debug')) { $container['Debug'] = function (ContainerInterface $c) { return new DebugMiddleware($c); }; } if (!$container->has('Database')) { $container['Database'] = function (ContainerInterface $c) { return new DatabaseMiddleware($c); }; } if (!$container->has('Console')) { $container['Console'] = function (ContainerInterface $c) { return new ConsoleMiddleware($c); }; } if (!$container->has('callableResolver')) { /** * Instance of \Slim\Interfaces\CallableResolverInterface * * @param ContainerInterface $c * * @return CallableResolver */ $container['callableResolver'] = function (ContainerInterface $c) { return new CallableResolver($c); }; } }
[ "public", "static", "function", "registerDefaultServices", "(", "ContainerInterface", "$", "container", ")", "{", "if", "(", "!", "$", "container", "->", "has", "(", "'argv'", ")", ")", "{", "$", "container", "[", "'argv'", "]", "=", "$", "_SERVER", "[", "'argv'", "]", ";", "}", "if", "(", "!", "$", "container", "->", "has", "(", "'Debug'", ")", ")", "{", "$", "container", "[", "'Debug'", "]", "=", "function", "(", "ContainerInterface", "$", "c", ")", "{", "return", "new", "DebugMiddleware", "(", "$", "c", ")", ";", "}", ";", "}", "if", "(", "!", "$", "container", "->", "has", "(", "'Database'", ")", ")", "{", "$", "container", "[", "'Database'", "]", "=", "function", "(", "ContainerInterface", "$", "c", ")", "{", "return", "new", "DatabaseMiddleware", "(", "$", "c", ")", ";", "}", ";", "}", "if", "(", "!", "$", "container", "->", "has", "(", "'Console'", ")", ")", "{", "$", "container", "[", "'Console'", "]", "=", "function", "(", "ContainerInterface", "$", "c", ")", "{", "return", "new", "ConsoleMiddleware", "(", "$", "c", ")", ";", "}", ";", "}", "if", "(", "!", "$", "container", "->", "has", "(", "'callableResolver'", ")", ")", "{", "/**\n * Instance of \\Slim\\Interfaces\\CallableResolverInterface\n *\n * @param ContainerInterface $c\n *\n * @return CallableResolver\n */", "$", "container", "[", "'callableResolver'", "]", "=", "function", "(", "ContainerInterface", "$", "c", ")", "{", "return", "new", "CallableResolver", "(", "$", "c", ")", ";", "}", ";", "}", "}" ]
This function registers the default services that Clim needs to work. All services are shared - that is, they are registered such that the same instance is returned on subsequent calls. @return void
[ "This", "function", "registers", "the", "default", "services", "that", "Clim", "needs", "to", "work", "." ]
d2d09a82e1b7a0b8d454e585e6db421ff02ec8e4
https://github.com/climphp/Clim/blob/d2d09a82e1b7a0b8d454e585e6db421ff02ec8e4/Clim/Container.php#L54-L90
train
eliasis-framework/complement
src/Traits/ComplementState.php
ComplementState.setState
public function setState($state) { $this->complement['state'] = $state; $this->states['state'] = $state; $this->setStates(); return $state; }
php
public function setState($state) { $this->complement['state'] = $state; $this->states['state'] = $state; $this->setStates(); return $state; }
[ "public", "function", "setState", "(", "$", "state", ")", "{", "$", "this", "->", "complement", "[", "'state'", "]", "=", "$", "state", ";", "$", "this", "->", "states", "[", "'state'", "]", "=", "$", "state", ";", "$", "this", "->", "setStates", "(", ")", ";", "return", "$", "state", ";", "}" ]
Set complement state. @param string $state → complement state @return string → state
[ "Set", "complement", "state", "." ]
d50e92cf01600ff4573bf1761c312069044748c3
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Traits/ComplementState.php#L84-L91
train
eliasis-framework/complement
src/Traits/ComplementState.php
ComplementState.changeState
public function changeState() { $this->getStates(); $actualState = $this->getState(); $newState = self::$statesHandler[$actualState]['state']; $action = self::$statesHandler[$actualState]['action']; $this->setState($newState); $this->doAction($action); return $newState; }
php
public function changeState() { $this->getStates(); $actualState = $this->getState(); $newState = self::$statesHandler[$actualState]['state']; $action = self::$statesHandler[$actualState]['action']; $this->setState($newState); $this->doAction($action); return $newState; }
[ "public", "function", "changeState", "(", ")", "{", "$", "this", "->", "getStates", "(", ")", ";", "$", "actualState", "=", "$", "this", "->", "getState", "(", ")", ";", "$", "newState", "=", "self", "::", "$", "statesHandler", "[", "$", "actualState", "]", "[", "'state'", "]", ";", "$", "action", "=", "self", "::", "$", "statesHandler", "[", "$", "actualState", "]", "[", "'action'", "]", ";", "$", "this", "->", "setState", "(", "$", "newState", ")", ";", "$", "this", "->", "doAction", "(", "$", "action", ")", ";", "return", "$", "newState", ";", "}" ]
Change complement state. @uses \Eliasis\Complement\Traits\ComplementAction::doAction() @return string → new state
[ "Change", "complement", "state", "." ]
d50e92cf01600ff4573bf1761c312069044748c3
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Traits/ComplementState.php#L100-L112
train
eliasis-framework/complement
src/Traits/ComplementState.php
ComplementState.getState
public function getState() { if (isset($this->states['state'])) { return $this->states['state']; } elseif (isset($this->complement['state'])) { return $this->complement['state']; } $type = self::getType(); return self::$defaultStates[$type]; }
php
public function getState() { if (isset($this->states['state'])) { return $this->states['state']; } elseif (isset($this->complement['state'])) { return $this->complement['state']; } $type = self::getType(); return self::$defaultStates[$type]; }
[ "public", "function", "getState", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "states", "[", "'state'", "]", ")", ")", "{", "return", "$", "this", "->", "states", "[", "'state'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "this", "->", "complement", "[", "'state'", "]", ")", ")", "{", "return", "$", "this", "->", "complement", "[", "'state'", "]", ";", "}", "$", "type", "=", "self", "::", "getType", "(", ")", ";", "return", "self", "::", "$", "defaultStates", "[", "$", "type", "]", ";", "}" ]
Get complement state. @uses \Eliasis\Framework\App::complements() @uses \Eliasis\Complement\Traits\ComplementHandler::getType() @return string → complement state
[ "Get", "complement", "state", "." ]
d50e92cf01600ff4573bf1761c312069044748c3
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Traits/ComplementState.php#L122-L133
train
eliasis-framework/complement
src/Traits/ComplementState.php
ComplementState.getStates
public function getStates() { $appID = App::getCurrentID(); $complementID = self::getCurrentID(); $states = $this->getStatesFromFile(); if (isset($states[$appID][$complementID])) { return $this->states = $states[$appID][$complementID]; } return $this->states = []; }
php
public function getStates() { $appID = App::getCurrentID(); $complementID = self::getCurrentID(); $states = $this->getStatesFromFile(); if (isset($states[$appID][$complementID])) { return $this->states = $states[$appID][$complementID]; } return $this->states = []; }
[ "public", "function", "getStates", "(", ")", "{", "$", "appID", "=", "App", "::", "getCurrentID", "(", ")", ";", "$", "complementID", "=", "self", "::", "getCurrentID", "(", ")", ";", "$", "states", "=", "$", "this", "->", "getStatesFromFile", "(", ")", ";", "if", "(", "isset", "(", "$", "states", "[", "$", "appID", "]", "[", "$", "complementID", "]", ")", ")", "{", "return", "$", "this", "->", "states", "=", "$", "states", "[", "$", "appID", "]", "[", "$", "complementID", "]", ";", "}", "return", "$", "this", "->", "states", "=", "[", "]", ";", "}" ]
Get complements states. @uses \Eliasis\Framework\App::getCurrentID() @uses \Eliasis\Complement\Complement::getCurrentID() @return array → complements states
[ "Get", "complements", "states", "." ]
d50e92cf01600ff4573bf1761c312069044748c3
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Traits/ComplementState.php#L143-L154
train
eliasis-framework/complement
src/Traits/ComplementState.php
ComplementState.setStates
private function setStates() { $appID = App::getCurrentID(); $complementID = self::getCurrentID(); if (! is_null($this->states)) { $states = $this->getStatesFromFile(); if ($this->stateChanged($states)) { $file = $this->getStatesFilePath(); $states[$appID][$complementID] = $this->states; Json::arrayToFile($states, $file); Hook::doAction('Eliasis/Complement/after_set_states', $states); } } }
php
private function setStates() { $appID = App::getCurrentID(); $complementID = self::getCurrentID(); if (! is_null($this->states)) { $states = $this->getStatesFromFile(); if ($this->stateChanged($states)) { $file = $this->getStatesFilePath(); $states[$appID][$complementID] = $this->states; Json::arrayToFile($states, $file); Hook::doAction('Eliasis/Complement/after_set_states', $states); } } }
[ "private", "function", "setStates", "(", ")", "{", "$", "appID", "=", "App", "::", "getCurrentID", "(", ")", ";", "$", "complementID", "=", "self", "::", "getCurrentID", "(", ")", ";", "if", "(", "!", "is_null", "(", "$", "this", "->", "states", ")", ")", "{", "$", "states", "=", "$", "this", "->", "getStatesFromFile", "(", ")", ";", "if", "(", "$", "this", "->", "stateChanged", "(", "$", "states", ")", ")", "{", "$", "file", "=", "$", "this", "->", "getStatesFilePath", "(", ")", ";", "$", "states", "[", "$", "appID", "]", "[", "$", "complementID", "]", "=", "$", "this", "->", "states", ";", "Json", "::", "arrayToFile", "(", "$", "states", ",", "$", "file", ")", ";", "Hook", "::", "doAction", "(", "'Eliasis/Complement/after_set_states'", ",", "$", "states", ")", ";", "}", "}", "}" ]
Set complements states. @uses \Eliasis\Framework\App::getCurrentID() @uses \Eliasis\Complement\Complement::getCurrentID() @uses \Josantonius\Json\Json::arrayToFile() @uses \Josantonius\Hook\Hook::doAction()
[ "Set", "complements", "states", "." ]
d50e92cf01600ff4573bf1761c312069044748c3
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Traits/ComplementState.php#L164-L179
train
eliasis-framework/complement
src/Traits/ComplementState.php
ComplementState.stateChanged
private function stateChanged($states) { $appID = App::getCurrentID(); $complementID = self::getCurrentID(); if (isset($states[$appID][$complementID])) { $actualStates = $states[$appID][$complementID]; if (! count(array_diff_assoc($actualStates, $this->states))) { return false; } } return true; }
php
private function stateChanged($states) { $appID = App::getCurrentID(); $complementID = self::getCurrentID(); if (isset($states[$appID][$complementID])) { $actualStates = $states[$appID][$complementID]; if (! count(array_diff_assoc($actualStates, $this->states))) { return false; } } return true; }
[ "private", "function", "stateChanged", "(", "$", "states", ")", "{", "$", "appID", "=", "App", "::", "getCurrentID", "(", ")", ";", "$", "complementID", "=", "self", "::", "getCurrentID", "(", ")", ";", "if", "(", "isset", "(", "$", "states", "[", "$", "appID", "]", "[", "$", "complementID", "]", ")", ")", "{", "$", "actualStates", "=", "$", "states", "[", "$", "appID", "]", "[", "$", "complementID", "]", ";", "if", "(", "!", "count", "(", "array_diff_assoc", "(", "$", "actualStates", ",", "$", "this", "->", "states", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if complement state has changed. @param string $states → complement states @uses \Eliasis\Framework\App::getCurrentID() @uses \Eliasis\Complement\Complement::getCurrentID() @return bool
[ "Check", "if", "complement", "state", "has", "changed", "." ]
d50e92cf01600ff4573bf1761c312069044748c3
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Traits/ComplementState.php#L191-L205
train
eliasis-framework/complement
src/Traits/ComplementState.php
ComplementState.getStatesFilePath
private function getStatesFilePath() { $type = self::getType(); $complementType = self::getType('strtoupper'); return App::$complementType() . '.' . $type . '-states.json'; }
php
private function getStatesFilePath() { $type = self::getType(); $complementType = self::getType('strtoupper'); return App::$complementType() . '.' . $type . '-states.json'; }
[ "private", "function", "getStatesFilePath", "(", ")", "{", "$", "type", "=", "self", "::", "getType", "(", ")", ";", "$", "complementType", "=", "self", "::", "getType", "(", "'strtoupper'", ")", ";", "return", "App", "::", "$", "complementType", "(", ")", ".", "'.'", ".", "$", "type", ".", "'-states.json'", ";", "}" ]
Get complements file path. @uses \Eliasis\Framework\App::COMPLEMENT() @uses \Eliasis\Complement\Traits\ComplementHandler::getType() @return string → complements file path
[ "Get", "complements", "file", "path", "." ]
d50e92cf01600ff4573bf1761c312069044748c3
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Traits/ComplementState.php#L227-L233
train
squareproton/Bond
src/Bond/RecordManager/Response.php
Response.rollback
public function rollback( $transaction ) { $status = $this->getStatus( $transaction); if( count($status) !== 1 ) { throw new \LogicException("You can't rollback more than 1 transaction"); } list( $transaction, $transactionStatus ) = each( $status ); // rollback things which were attempted foreach( $transactionStatus as $key => $taskStatus ) { if( $taskStatus === self::SUCCESS ) { $this->status[$transaction][$key] = self::ROLLEDBACK; } } }
php
public function rollback( $transaction ) { $status = $this->getStatus( $transaction); if( count($status) !== 1 ) { throw new \LogicException("You can't rollback more than 1 transaction"); } list( $transaction, $transactionStatus ) = each( $status ); // rollback things which were attempted foreach( $transactionStatus as $key => $taskStatus ) { if( $taskStatus === self::SUCCESS ) { $this->status[$transaction][$key] = self::ROLLEDBACK; } } }
[ "public", "function", "rollback", "(", "$", "transaction", ")", "{", "$", "status", "=", "$", "this", "->", "getStatus", "(", "$", "transaction", ")", ";", "if", "(", "count", "(", "$", "status", ")", "!==", "1", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"You can't rollback more than 1 transaction\"", ")", ";", "}", "list", "(", "$", "transaction", ",", "$", "transactionStatus", ")", "=", "each", "(", "$", "status", ")", ";", "// rollback things which were attempted", "foreach", "(", "$", "transactionStatus", "as", "$", "key", "=>", "$", "taskStatus", ")", "{", "if", "(", "$", "taskStatus", "===", "self", "::", "SUCCESS", ")", "{", "$", "this", "->", "status", "[", "$", "transaction", "]", "[", "$", "key", "]", "=", "self", "::", "ROLLEDBACK", ";", "}", "}", "}" ]
Rollback a named transaction @param <type> $transaction
[ "Rollback", "a", "named", "transaction" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/RecordManager/Response.php#L83-L99
train
squareproton/Bond
src/Bond/RecordManager/Response.php
Response.isSuccess
public function isSuccess( $transaction = RecordManager::TRANSACTIONS_ALL ) { $output = true; foreach( $this->getStatus($transaction) as $transaction => $transactionStatus ) { foreach( $transactionStatus as $status ) { $output = ( $output && $status === self::SUCCESS ); } } return $output; }
php
public function isSuccess( $transaction = RecordManager::TRANSACTIONS_ALL ) { $output = true; foreach( $this->getStatus($transaction) as $transaction => $transactionStatus ) { foreach( $transactionStatus as $status ) { $output = ( $output && $status === self::SUCCESS ); } } return $output; }
[ "public", "function", "isSuccess", "(", "$", "transaction", "=", "RecordManager", "::", "TRANSACTIONS_ALL", ")", "{", "$", "output", "=", "true", ";", "foreach", "(", "$", "this", "->", "getStatus", "(", "$", "transaction", ")", "as", "$", "transaction", "=>", "$", "transactionStatus", ")", "{", "foreach", "(", "$", "transactionStatus", "as", "$", "status", ")", "{", "$", "output", "=", "(", "$", "output", "&&", "$", "status", "===", "self", "::", "SUCCESS", ")", ";", "}", "}", "return", "$", "output", ";", "}" ]
Has a named transaction been executed successfully @param scalar $transaction @return bool
[ "Has", "a", "named", "transaction", "been", "executed", "successfully" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/RecordManager/Response.php#L106-L115
train