repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.subtractOption
public function subtractOption($id, $optionName, $optionValue) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->subtractOption($id, $optionName, $optionValue); return $this; }
php
public function subtractOption($id, $optionName, $optionValue) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->subtractOption($id, $optionName, $optionValue); return $this; }
[ "public", "function", "subtractOption", "(", "$", "id", ",", "$", "optionName", ",", "$", "optionValue", ")", "{", "$", "this", "->", "replaceRoot", "(", "$", "id", ")", ";", "$", "this", "->", "replaceNamespace", "(", "$", "id", ")", ";", "$", "this", "->", "layoutManipulator", "->", "subtractOption", "(", "$", "id", ",", "$", "optionName", ",", "$", "optionValue", ")", ";", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L154-L162
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.replaceOption
public function replaceOption($id, $optionName, $oldOptionValue, $newOptionValue) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->replaceOption($id, $optionName, $oldOptionValue, $newOptionValue); return $this; }
php
public function replaceOption($id, $optionName, $oldOptionValue, $newOptionValue) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->replaceOption($id, $optionName, $oldOptionValue, $newOptionValue); return $this; }
[ "public", "function", "replaceOption", "(", "$", "id", ",", "$", "optionName", ",", "$", "oldOptionValue", ",", "$", "newOptionValue", ")", "{", "$", "this", "->", "replaceRoot", "(", "$", "id", ")", ";", "$", "this", "->", "replaceNamespace", "(", "$", "id", ")", ";", "$", "this", "->", "layoutManipulator", "->", "replaceOption", "(", "$", "id", ",", "$", "optionName", ",", "$", "oldOptionValue", ",", "$", "newOptionValue", ")", ";", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L167-L175
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.removeOption
public function removeOption($id, $optionName) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->removeOption($id, $optionName); return $this; }
php
public function removeOption($id, $optionName) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->removeOption($id, $optionName); return $this; }
[ "public", "function", "removeOption", "(", "$", "id", ",", "$", "optionName", ")", "{", "$", "this", "->", "replaceRoot", "(", "$", "id", ")", ";", "$", "this", "->", "replaceNamespace", "(", "$", "id", ")", ";", "$", "this", "->", "layoutManipulator", "->", "removeOption", "(", "$", "id", ",", "$", "optionName", ")", ";", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L180-L188
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.changeBlockType
public function changeBlockType($id, $blockType, $optionsCallback = null) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->changeBlockType($id, $blockType, $optionsCallback); return $this; }
php
public function changeBlockType($id, $blockType, $optionsCallback = null) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->changeBlockType($id, $blockType, $optionsCallback); return $this; }
[ "public", "function", "changeBlockType", "(", "$", "id", ",", "$", "blockType", ",", "$", "optionsCallback", "=", "null", ")", "{", "$", "this", "->", "replaceRoot", "(", "$", "id", ")", ";", "$", "this", "->", "replaceNamespace", "(", "$", "id", ")", ";", "$", "this", "->", "layoutManipulator", "->", "changeBlockType", "(", "$", "id", ",", "$", "blockType", ",", "$", "optionsCallback", ")", ";", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L193-L201
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.setBlockTheme
public function setBlockTheme($themes, $id = null) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->setBlockTheme($themes, $id); return $this; }
php
public function setBlockTheme($themes, $id = null) { $this->replaceRoot($id); $this->replaceNamespace($id); $this->layoutManipulator->setBlockTheme($themes, $id); return $this; }
[ "public", "function", "setBlockTheme", "(", "$", "themes", ",", "$", "id", "=", "null", ")", "{", "$", "this", "->", "replaceRoot", "(", "$", "id", ")", ";", "$", "this", "->", "replaceNamespace", "(", "$", "id", ")", ";", "$", "this", "->", "layoutManipulator", "->", "setBlockTheme", "(", "$", "themes", ",", "$", "id", ")", ";", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L206-L214
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.replaceRoot
protected function replaceRoot(&$id) { if (null !== $id && $id === self::ROOT_PLACEHOLDER) { $rootId = $this->getRootId($this->import); if ($rootId === null) { throw new LogicException('Import root is not defined.'); } $id = $rootId; } return $this; }
php
protected function replaceRoot(&$id) { if (null !== $id && $id === self::ROOT_PLACEHOLDER) { $rootId = $this->getRootId($this->import); if ($rootId === null) { throw new LogicException('Import root is not defined.'); } $id = $rootId; } return $this; }
[ "protected", "function", "replaceRoot", "(", "&", "$", "id", ")", "{", "if", "(", "null", "!==", "$", "id", "&&", "$", "id", "===", "self", "::", "ROOT_PLACEHOLDER", ")", "{", "$", "rootId", "=", "$", "this", "->", "getRootId", "(", "$", "this", "->", "import", ")", ";", "if", "(", "$", "rootId", "===", "null", ")", "{", "throw", "new", "LogicException", "(", "'Import root is not defined.'", ")", ";", "}", "$", "id", "=", "$", "rootId", ";", "}", "return", "$", "this", ";", "}" ]
@param string $id @return $this
[ "@param", "string", "$id" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L241-L252
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.getRootId
protected function getRootId(LayoutUpdateImport $import) { $rootId = $import->getRoot(); if ($import->getParent()) { if ($rootId === self::ROOT_PLACEHOLDER) { $rootId = $this->getRootId($import->getParent()); } else { $this->replaceNamespace($rootId, $this->getNamespace($import->getParent())); } } return $rootId; }
php
protected function getRootId(LayoutUpdateImport $import) { $rootId = $import->getRoot(); if ($import->getParent()) { if ($rootId === self::ROOT_PLACEHOLDER) { $rootId = $this->getRootId($import->getParent()); } else { $this->replaceNamespace($rootId, $this->getNamespace($import->getParent())); } } return $rootId; }
[ "protected", "function", "getRootId", "(", "LayoutUpdateImport", "$", "import", ")", "{", "$", "rootId", "=", "$", "import", "->", "getRoot", "(", ")", ";", "if", "(", "$", "import", "->", "getParent", "(", ")", ")", "{", "if", "(", "$", "rootId", "===", "self", "::", "ROOT_PLACEHOLDER", ")", "{", "$", "rootId", "=", "$", "this", "->", "getRootId", "(", "$", "import", "->", "getParent", "(", ")", ")", ";", "}", "else", "{", "$", "this", "->", "replaceNamespace", "(", "$", "rootId", ",", "$", "this", "->", "getNamespace", "(", "$", "import", "->", "getParent", "(", ")", ")", ")", ";", "}", "}", "return", "$", "rootId", ";", "}" ]
@param LayoutUpdateImport $import @return string
[ "@param", "LayoutUpdateImport", "$import" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L259-L270
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.replaceNamespace
protected function replaceNamespace(&$id, $namespace = null) { if ($this->hasNamespacePlaceholder($id)) { $replacement = ''; if ($namespace === null) { $namespace = $this->getNamespace($this->import); } if ($namespace) { $replacement = $namespace.self::NAMESPACE_SUFFIX; } $id = substr_replace($id, $replacement, 0, strlen(self::NAMESPACE_PLACEHOLDER)); } return $this; }
php
protected function replaceNamespace(&$id, $namespace = null) { if ($this->hasNamespacePlaceholder($id)) { $replacement = ''; if ($namespace === null) { $namespace = $this->getNamespace($this->import); } if ($namespace) { $replacement = $namespace.self::NAMESPACE_SUFFIX; } $id = substr_replace($id, $replacement, 0, strlen(self::NAMESPACE_PLACEHOLDER)); } return $this; }
[ "protected", "function", "replaceNamespace", "(", "&", "$", "id", ",", "$", "namespace", "=", "null", ")", "{", "if", "(", "$", "this", "->", "hasNamespacePlaceholder", "(", "$", "id", ")", ")", "{", "$", "replacement", "=", "''", ";", "if", "(", "$", "namespace", "===", "null", ")", "{", "$", "namespace", "=", "$", "this", "->", "getNamespace", "(", "$", "this", "->", "import", ")", ";", "}", "if", "(", "$", "namespace", ")", "{", "$", "replacement", "=", "$", "namespace", ".", "self", "::", "NAMESPACE_SUFFIX", ";", "}", "$", "id", "=", "substr_replace", "(", "$", "id", ",", "$", "replacement", ",", "0", ",", "strlen", "(", "self", "::", "NAMESPACE_PLACEHOLDER", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
@param string $id @param string|null $namespace @return $this
[ "@param", "string", "$id" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L288-L303
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.getNamespaces
protected function getNamespaces(LayoutUpdateImport $import) { $namespaces = []; if ($import->getParent()) { $namespaces = array_merge($namespaces, $this->getNamespaces($import->getParent())); } if ($import->getNamespace()) { array_push($namespaces, $import->getNamespace()); } return $namespaces; }
php
protected function getNamespaces(LayoutUpdateImport $import) { $namespaces = []; if ($import->getParent()) { $namespaces = array_merge($namespaces, $this->getNamespaces($import->getParent())); } if ($import->getNamespace()) { array_push($namespaces, $import->getNamespace()); } return $namespaces; }
[ "protected", "function", "getNamespaces", "(", "LayoutUpdateImport", "$", "import", ")", "{", "$", "namespaces", "=", "[", "]", ";", "if", "(", "$", "import", "->", "getParent", "(", ")", ")", "{", "$", "namespaces", "=", "array_merge", "(", "$", "namespaces", ",", "$", "this", "->", "getNamespaces", "(", "$", "import", "->", "getParent", "(", ")", ")", ")", ";", "}", "if", "(", "$", "import", "->", "getNamespace", "(", ")", ")", "{", "array_push", "(", "$", "namespaces", ",", "$", "import", "->", "getNamespace", "(", ")", ")", ";", "}", "return", "$", "namespaces", ";", "}" ]
@param LayoutUpdateImport $import @return array
[ "@param", "LayoutUpdateImport", "$import" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L320-L331
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.addAdditionalBlockPrefixOption
protected function addAdditionalBlockPrefixOption($id, array &$options) { if ($this->hasNamespacePlaceholder($id)) { $options[self::ADDITIONAL_BLOCK_PREFIX_OPTION] = $this->getAdditionalBlockPrefixes($id, $this->import); } return $this; }
php
protected function addAdditionalBlockPrefixOption($id, array &$options) { if ($this->hasNamespacePlaceholder($id)) { $options[self::ADDITIONAL_BLOCK_PREFIX_OPTION] = $this->getAdditionalBlockPrefixes($id, $this->import); } return $this; }
[ "protected", "function", "addAdditionalBlockPrefixOption", "(", "$", "id", ",", "array", "&", "$", "options", ")", "{", "if", "(", "$", "this", "->", "hasNamespacePlaceholder", "(", "$", "id", ")", ")", "{", "$", "options", "[", "self", "::", "ADDITIONAL_BLOCK_PREFIX_OPTION", "]", "=", "$", "this", "->", "getAdditionalBlockPrefixes", "(", "$", "id", ",", "$", "this", "->", "import", ")", ";", "}", "return", "$", "this", ";", "}" ]
@param string $id @param array $options @return $this
[ "@param", "string", "$id", "@param", "array", "$options" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L339-L346
oroinc/OroLayoutComponent
ImportLayoutManipulator.php
ImportLayoutManipulator.getAdditionalBlockPrefixes
protected function getAdditionalBlockPrefixes($id, LayoutUpdateImport $import, $prefixes = []) { $prefixes[] = sprintf(self::ADDITIONAL_BLOCK_PREFIX_PATTERN, $import->getId(), $id); if ($import->getParent()) { $prefixes = $this->getAdditionalBlockPrefixes($id, $import->getParent(), $prefixes); } return $prefixes; }
php
protected function getAdditionalBlockPrefixes($id, LayoutUpdateImport $import, $prefixes = []) { $prefixes[] = sprintf(self::ADDITIONAL_BLOCK_PREFIX_PATTERN, $import->getId(), $id); if ($import->getParent()) { $prefixes = $this->getAdditionalBlockPrefixes($id, $import->getParent(), $prefixes); } return $prefixes; }
[ "protected", "function", "getAdditionalBlockPrefixes", "(", "$", "id", ",", "LayoutUpdateImport", "$", "import", ",", "$", "prefixes", "=", "[", "]", ")", "{", "$", "prefixes", "[", "]", "=", "sprintf", "(", "self", "::", "ADDITIONAL_BLOCK_PREFIX_PATTERN", ",", "$", "import", "->", "getId", "(", ")", ",", "$", "id", ")", ";", "if", "(", "$", "import", "->", "getParent", "(", ")", ")", "{", "$", "prefixes", "=", "$", "this", "->", "getAdditionalBlockPrefixes", "(", "$", "id", ",", "$", "import", "->", "getParent", "(", ")", ",", "$", "prefixes", ")", ";", "}", "return", "$", "prefixes", ";", "}" ]
@param string $id @param LayoutUpdateImport $import @param array $prefixes @return array
[ "@param", "string", "$id", "@param", "LayoutUpdateImport", "$import", "@param", "array", "$prefixes" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/ImportLayoutManipulator.php#L355-L362
codezero-be/curl
src/OptionParser.php
OptionParser.parseUrl
public function parseUrl($url, array $data) { return (empty($data)) ? $url : $url . '?' . $this->parseData($data); }
php
public function parseUrl($url, array $data) { return (empty($data)) ? $url : $url . '?' . $this->parseData($data); }
[ "public", "function", "parseUrl", "(", "$", "url", ",", "array", "$", "data", ")", "{", "return", "(", "empty", "(", "$", "data", ")", ")", "?", "$", "url", ":", "$", "url", ".", "'?'", ".", "$", "this", "->", "parseData", "(", "$", "data", ")", ";", "}" ]
Build URL with query string @param string $url @param array $data @return string
[ "Build", "URL", "with", "query", "string" ]
train
https://github.com/codezero-be/curl/blob/c1385479886662b6276c18dd9140df529959d95c/src/OptionParser.php#L13-L16
codezero-be/curl
src/OptionParser.php
OptionParser.parseHeaders
public function parseHeaders(array $headers) { $parsed = []; foreach ($headers as $key => $val) { $parsed[] = $key . ': ' . $val; } return $parsed; }
php
public function parseHeaders(array $headers) { $parsed = []; foreach ($headers as $key => $val) { $parsed[] = $key . ': ' . $val; } return $parsed; }
[ "public", "function", "parseHeaders", "(", "array", "$", "headers", ")", "{", "$", "parsed", "=", "[", "]", ";", "foreach", "(", "$", "headers", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "parsed", "[", "]", "=", "$", "key", ".", "': '", ".", "$", "val", ";", "}", "return", "$", "parsed", ";", "}" ]
Parse header key/value array into value-only array @param array $headers @return array
[ "Parse", "header", "key", "/", "value", "array", "into", "value", "-", "only", "array" ]
train
https://github.com/codezero-be/curl/blob/c1385479886662b6276c18dd9140df529959d95c/src/OptionParser.php#L37-L47
php-lug/lug
src/Bundle/GridBundle/DependencyInjection/Compiler/ReplaceLocaleContextPass.php
ReplaceLocaleContextPass.process
public function process(ContainerBuilder $container) { if (!$container->hasDefinition('lug.locale.context')) { return; } $container ->getDefinition('lug.grid.context.locale') ->setClass(LocaleContext::class) ->replaceArgument(0, new Reference('lug.locale.context')); }
php
public function process(ContainerBuilder $container) { if (!$container->hasDefinition('lug.locale.context')) { return; } $container ->getDefinition('lug.grid.context.locale') ->setClass(LocaleContext::class) ->replaceArgument(0, new Reference('lug.locale.context')); }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "if", "(", "!", "$", "container", "->", "hasDefinition", "(", "'lug.locale.context'", ")", ")", "{", "return", ";", "}", "$", "container", "->", "getDefinition", "(", "'lug.grid.context.locale'", ")", "->", "setClass", "(", "LocaleContext", "::", "class", ")", "->", "replaceArgument", "(", "0", ",", "new", "Reference", "(", "'lug.locale.context'", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/DependencyInjection/Compiler/ReplaceLocaleContextPass.php#L27-L37
bavix/laravel-worker-command
src/Commands/ReloadCommand.php
ReloadCommand.pushReload
public function pushReload(\GearmanJob $job) { $this->info(__FUNCTION__); $workload = $job->workload(); $directoryIterator = new \RecursiveDirectoryIterator( app_path('Console/Commands'), \RecursiveDirectoryIterator::SKIP_DOTS ); $iterator = new \RecursiveIteratorIterator($directoryIterator); /** * @var $file \SplFileInfo */ foreach ($iterator as $file) { $namespace = \App\Console\Commands::class; $name = str_replace('.php', '', $file->getFilename()); $class = $namespace . '\\' . $name; /** * @var WorkerCommand $object */ $object = new $class; Gearman::client()->doBackground( $this->fnReload($object->getName()), $workload ); $this->info('class: ' . $name . ', args: ' . $workload); } }
php
public function pushReload(\GearmanJob $job) { $this->info(__FUNCTION__); $workload = $job->workload(); $directoryIterator = new \RecursiveDirectoryIterator( app_path('Console/Commands'), \RecursiveDirectoryIterator::SKIP_DOTS ); $iterator = new \RecursiveIteratorIterator($directoryIterator); /** * @var $file \SplFileInfo */ foreach ($iterator as $file) { $namespace = \App\Console\Commands::class; $name = str_replace('.php', '', $file->getFilename()); $class = $namespace . '\\' . $name; /** * @var WorkerCommand $object */ $object = new $class; Gearman::client()->doBackground( $this->fnReload($object->getName()), $workload ); $this->info('class: ' . $name . ', args: ' . $workload); } }
[ "public", "function", "pushReload", "(", "\\", "GearmanJob", "$", "job", ")", "{", "$", "this", "->", "info", "(", "__FUNCTION__", ")", ";", "$", "workload", "=", "$", "job", "->", "workload", "(", ")", ";", "$", "directoryIterator", "=", "new", "\\", "RecursiveDirectoryIterator", "(", "app_path", "(", "'Console/Commands'", ")", ",", "\\", "RecursiveDirectoryIterator", "::", "SKIP_DOTS", ")", ";", "$", "iterator", "=", "new", "\\", "RecursiveIteratorIterator", "(", "$", "directoryIterator", ")", ";", "/**\n * @var $file \\SplFileInfo\n */", "foreach", "(", "$", "iterator", "as", "$", "file", ")", "{", "$", "namespace", "=", "\\", "App", "\\", "Console", "\\", "Commands", "::", "class", ";", "$", "name", "=", "str_replace", "(", "'.php'", ",", "''", ",", "$", "file", "->", "getFilename", "(", ")", ")", ";", "$", "class", "=", "$", "namespace", ".", "'\\\\'", ".", "$", "name", ";", "/**\n * @var WorkerCommand $object\n */", "$", "object", "=", "new", "$", "class", ";", "Gearman", "::", "client", "(", ")", "->", "doBackground", "(", "$", "this", "->", "fnReload", "(", "$", "object", "->", "getName", "(", ")", ")", ",", "$", "workload", ")", ";", "$", "this", "->", "info", "(", "'class: '", ".", "$", "name", ".", "', args: '", ".", "$", "workload", ")", ";", "}", "}" ]
@param \GearmanJob $job @return void
[ "@param", "\\", "GearmanJob", "$job" ]
train
https://github.com/bavix/laravel-worker-command/blob/005d7f9d8fe13e4d992c5fbaf6ff2014753c46e6/src/Commands/ReloadCommand.php#L46-L79
php-lug/lug
src/Component/Registry/Model/Registry.php
Registry.offsetGet
public function offsetGet($type) { if (!$this->offsetExists($type)) { throw new ServiceNotFoundException(sprintf('The service "%s" could not be found.', $type)); } return $this->services[$type]; }
php
public function offsetGet($type) { if (!$this->offsetExists($type)) { throw new ServiceNotFoundException(sprintf('The service "%s" could not be found.', $type)); } return $this->services[$type]; }
[ "public", "function", "offsetGet", "(", "$", "type", ")", "{", "if", "(", "!", "$", "this", "->", "offsetExists", "(", "$", "type", ")", ")", "{", "throw", "new", "ServiceNotFoundException", "(", "sprintf", "(", "'The service \"%s\" could not be found.'", ",", "$", "type", ")", ")", ";", "}", "return", "$", "this", "->", "services", "[", "$", "type", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Registry/Model/Registry.php#L57-L64
php-lug/lug
src/Component/Registry/Model/Registry.php
Registry.offsetSet
public function offsetSet($type, $service) { if ($this->offsetExists($type)) { throw new ServiceAlreadyExistsException(sprintf('The service "%s" already exists.', $type)); } if (!$service instanceof $this->interface) { throw new InvalidServiceException(sprintf( 'The service for the registry "%s" must be an instance of "%s", got "%s".', get_class($this), $this->interface, is_object($service) ? get_class($service) : gettype($service) )); } $this->services[$type] = $service; }
php
public function offsetSet($type, $service) { if ($this->offsetExists($type)) { throw new ServiceAlreadyExistsException(sprintf('The service "%s" already exists.', $type)); } if (!$service instanceof $this->interface) { throw new InvalidServiceException(sprintf( 'The service for the registry "%s" must be an instance of "%s", got "%s".', get_class($this), $this->interface, is_object($service) ? get_class($service) : gettype($service) )); } $this->services[$type] = $service; }
[ "public", "function", "offsetSet", "(", "$", "type", ",", "$", "service", ")", "{", "if", "(", "$", "this", "->", "offsetExists", "(", "$", "type", ")", ")", "{", "throw", "new", "ServiceAlreadyExistsException", "(", "sprintf", "(", "'The service \"%s\" already exists.'", ",", "$", "type", ")", ")", ";", "}", "if", "(", "!", "$", "service", "instanceof", "$", "this", "->", "interface", ")", "{", "throw", "new", "InvalidServiceException", "(", "sprintf", "(", "'The service for the registry \"%s\" must be an instance of \"%s\", got \"%s\".'", ",", "get_class", "(", "$", "this", ")", ",", "$", "this", "->", "interface", ",", "is_object", "(", "$", "service", ")", "?", "get_class", "(", "$", "service", ")", ":", "gettype", "(", "$", "service", ")", ")", ")", ";", "}", "$", "this", "->", "services", "[", "$", "type", "]", "=", "$", "service", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Registry/Model/Registry.php#L69-L85
php-lug/lug
src/Component/Registry/Model/Registry.php
Registry.offsetUnset
public function offsetUnset($type) { if (!$this->offsetExists($type)) { throw new ServiceNotFoundException(sprintf('The service "%s" could not be found.', $type)); } unset($this->services[$type]); }
php
public function offsetUnset($type) { if (!$this->offsetExists($type)) { throw new ServiceNotFoundException(sprintf('The service "%s" could not be found.', $type)); } unset($this->services[$type]); }
[ "public", "function", "offsetUnset", "(", "$", "type", ")", "{", "if", "(", "!", "$", "this", "->", "offsetExists", "(", "$", "type", ")", ")", "{", "throw", "new", "ServiceNotFoundException", "(", "sprintf", "(", "'The service \"%s\" could not be found.'", ",", "$", "type", ")", ")", ";", "}", "unset", "(", "$", "this", "->", "services", "[", "$", "type", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Registry/Model/Registry.php#L90-L97
heidelpay/PhpDoc
src/phpDocumentor/Descriptor/Filter/ClassFactory.php
ClassFactory.getChainFor
public function getChainFor($fqcn) { if (!isset($this->chains[$fqcn])) { $this->chains[$fqcn] = new FilterChain(); } return $this->chains[$fqcn]; }
php
public function getChainFor($fqcn) { if (!isset($this->chains[$fqcn])) { $this->chains[$fqcn] = new FilterChain(); } return $this->chains[$fqcn]; }
[ "public", "function", "getChainFor", "(", "$", "fqcn", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "chains", "[", "$", "fqcn", "]", ")", ")", "{", "$", "this", "->", "chains", "[", "$", "fqcn", "]", "=", "new", "FilterChain", "(", ")", ";", "}", "return", "$", "this", "->", "chains", "[", "$", "fqcn", "]", ";", "}" ]
Retrieves the filters for a class with a given FQCN. @param string $fqcn @return FilterChain
[ "Retrieves", "the", "filters", "for", "a", "class", "with", "a", "given", "FQCN", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/Filter/ClassFactory.php#L31-L38
mothership-ec/composer
src/Composer/Repository/Vcs/GitHubDriver.php
GitHubDriver.getComposerInformation
public function getComposerInformation($identifier) { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); } if (preg_match('{[a-f0-9]{40}}i', $identifier) && $res = $this->cache->read($identifier)) { $this->infoCache[$identifier] = JsonFile::parseJson($res); } if (!isset($this->infoCache[$identifier])) { $notFoundRetries = 2; while ($notFoundRetries) { try { $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/composer.json?ref='.urlencode($identifier); $composer = JsonFile::parseJson($this->getContents($resource)); if (empty($composer['content']) || $composer['encoding'] !== 'base64' || !($composer = base64_decode($composer['content']))) { throw new \RuntimeException('Could not retrieve composer.json from '.$resource); } break; } catch (TransportException $e) { if (404 !== $e->getCode()) { throw $e; } // TODO should be removed when possible // retry fetching if github returns a 404 since they happen randomly $notFoundRetries--; $composer = false; } } if ($composer) { $composer = JsonFile::parseJson($composer, $resource); if (empty($composer['time'])) { $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/commits/'.urlencode($identifier); $commit = JsonFile::parseJson($this->getContents($resource), $resource); $composer['time'] = $commit['commit']['committer']['date']; } if (!isset($composer['support']['source'])) { $label = array_search($identifier, $this->getTags()) ?: array_search($identifier, $this->getBranches()) ?: $identifier; $composer['support']['source'] = sprintf('https://%s/%s/%s/tree/%s', $this->originUrl, $this->owner, $this->repository, $label); } if (!isset($composer['support']['issues']) && $this->hasIssues) { $composer['support']['issues'] = sprintf('https://%s/%s/%s/issues', $this->originUrl, $this->owner, $this->repository); } } if (preg_match('{[a-f0-9]{40}}i', $identifier)) { $this->cache->write($identifier, json_encode($composer)); } $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; }
php
public function getComposerInformation($identifier) { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); } if (preg_match('{[a-f0-9]{40}}i', $identifier) && $res = $this->cache->read($identifier)) { $this->infoCache[$identifier] = JsonFile::parseJson($res); } if (!isset($this->infoCache[$identifier])) { $notFoundRetries = 2; while ($notFoundRetries) { try { $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/composer.json?ref='.urlencode($identifier); $composer = JsonFile::parseJson($this->getContents($resource)); if (empty($composer['content']) || $composer['encoding'] !== 'base64' || !($composer = base64_decode($composer['content']))) { throw new \RuntimeException('Could not retrieve composer.json from '.$resource); } break; } catch (TransportException $e) { if (404 !== $e->getCode()) { throw $e; } // TODO should be removed when possible // retry fetching if github returns a 404 since they happen randomly $notFoundRetries--; $composer = false; } } if ($composer) { $composer = JsonFile::parseJson($composer, $resource); if (empty($composer['time'])) { $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/commits/'.urlencode($identifier); $commit = JsonFile::parseJson($this->getContents($resource), $resource); $composer['time'] = $commit['commit']['committer']['date']; } if (!isset($composer['support']['source'])) { $label = array_search($identifier, $this->getTags()) ?: array_search($identifier, $this->getBranches()) ?: $identifier; $composer['support']['source'] = sprintf('https://%s/%s/%s/tree/%s', $this->originUrl, $this->owner, $this->repository, $label); } if (!isset($composer['support']['issues']) && $this->hasIssues) { $composer['support']['issues'] = sprintf('https://%s/%s/%s/issues', $this->originUrl, $this->owner, $this->repository); } } if (preg_match('{[a-f0-9]{40}}i', $identifier)) { $this->cache->write($identifier, json_encode($composer)); } $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; }
[ "public", "function", "getComposerInformation", "(", "$", "identifier", ")", "{", "if", "(", "$", "this", "->", "gitDriver", ")", "{", "return", "$", "this", "->", "gitDriver", "->", "getComposerInformation", "(", "$", "identifier", ")", ";", "}", "if", "(", "preg_match", "(", "'{[a-f0-9]{40}}i'", ",", "$", "identifier", ")", "&&", "$", "res", "=", "$", "this", "->", "cache", "->", "read", "(", "$", "identifier", ")", ")", "{", "$", "this", "->", "infoCache", "[", "$", "identifier", "]", "=", "JsonFile", "::", "parseJson", "(", "$", "res", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "infoCache", "[", "$", "identifier", "]", ")", ")", "{", "$", "notFoundRetries", "=", "2", ";", "while", "(", "$", "notFoundRetries", ")", "{", "try", "{", "$", "resource", "=", "$", "this", "->", "getApiUrl", "(", ")", ".", "'/repos/'", ".", "$", "this", "->", "owner", ".", "'/'", ".", "$", "this", "->", "repository", ".", "'/contents/composer.json?ref='", ".", "urlencode", "(", "$", "identifier", ")", ";", "$", "composer", "=", "JsonFile", "::", "parseJson", "(", "$", "this", "->", "getContents", "(", "$", "resource", ")", ")", ";", "if", "(", "empty", "(", "$", "composer", "[", "'content'", "]", ")", "||", "$", "composer", "[", "'encoding'", "]", "!==", "'base64'", "||", "!", "(", "$", "composer", "=", "base64_decode", "(", "$", "composer", "[", "'content'", "]", ")", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Could not retrieve composer.json from '", ".", "$", "resource", ")", ";", "}", "break", ";", "}", "catch", "(", "TransportException", "$", "e", ")", "{", "if", "(", "404", "!==", "$", "e", "->", "getCode", "(", ")", ")", "{", "throw", "$", "e", ";", "}", "// TODO should be removed when possible", "// retry fetching if github returns a 404 since they happen randomly", "$", "notFoundRetries", "--", ";", "$", "composer", "=", "false", ";", "}", "}", "if", "(", "$", "composer", ")", "{", "$", "composer", "=", "JsonFile", "::", "parseJson", "(", "$", "composer", ",", "$", "resource", ")", ";", "if", "(", "empty", "(", "$", "composer", "[", "'time'", "]", ")", ")", "{", "$", "resource", "=", "$", "this", "->", "getApiUrl", "(", ")", ".", "'/repos/'", ".", "$", "this", "->", "owner", ".", "'/'", ".", "$", "this", "->", "repository", ".", "'/commits/'", ".", "urlencode", "(", "$", "identifier", ")", ";", "$", "commit", "=", "JsonFile", "::", "parseJson", "(", "$", "this", "->", "getContents", "(", "$", "resource", ")", ",", "$", "resource", ")", ";", "$", "composer", "[", "'time'", "]", "=", "$", "commit", "[", "'commit'", "]", "[", "'committer'", "]", "[", "'date'", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "composer", "[", "'support'", "]", "[", "'source'", "]", ")", ")", "{", "$", "label", "=", "array_search", "(", "$", "identifier", ",", "$", "this", "->", "getTags", "(", ")", ")", "?", ":", "array_search", "(", "$", "identifier", ",", "$", "this", "->", "getBranches", "(", ")", ")", "?", ":", "$", "identifier", ";", "$", "composer", "[", "'support'", "]", "[", "'source'", "]", "=", "sprintf", "(", "'https://%s/%s/%s/tree/%s'", ",", "$", "this", "->", "originUrl", ",", "$", "this", "->", "owner", ",", "$", "this", "->", "repository", ",", "$", "label", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "composer", "[", "'support'", "]", "[", "'issues'", "]", ")", "&&", "$", "this", "->", "hasIssues", ")", "{", "$", "composer", "[", "'support'", "]", "[", "'issues'", "]", "=", "sprintf", "(", "'https://%s/%s/%s/issues'", ",", "$", "this", "->", "originUrl", ",", "$", "this", "->", "owner", ",", "$", "this", "->", "repository", ")", ";", "}", "}", "if", "(", "preg_match", "(", "'{[a-f0-9]{40}}i'", ",", "$", "identifier", ")", ")", "{", "$", "this", "->", "cache", "->", "write", "(", "$", "identifier", ",", "json_encode", "(", "$", "composer", ")", ")", ";", "}", "$", "this", "->", "infoCache", "[", "$", "identifier", "]", "=", "$", "composer", ";", "}", "return", "$", "this", "->", "infoCache", "[", "$", "identifier", "]", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Repository/Vcs/GitHubDriver.php#L139-L196
mothership-ec/composer
src/Composer/Repository/Vcs/GitHubDriver.php
GitHubDriver.getContents
protected function getContents($url, $fetchingRepoData = false) { try { return parent::getContents($url); } catch (TransportException $e) { $gitHubUtil = new GitHub($this->io, $this->config, $this->process, $this->remoteFilesystem); switch ($e->getCode()) { case 401: case 404: // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404 if (!$fetchingRepoData) { throw $e; } if ($gitHubUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive()) { return $this->attemptCloneFallback(); } $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'Your GitHub credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)'); return parent::getContents($url); case 403: if (!$this->io->hasAuthentication($this->originUrl) && $gitHubUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive() && $fetchingRepoData) { return $this->attemptCloneFallback(); } $rateLimited = false; foreach ($e->getHeaders() as $header) { if (preg_match('{^X-RateLimit-Remaining: *0$}i', trim($header))) { $rateLimited = true; } } if (!$this->io->hasAuthentication($this->originUrl)) { if (!$this->io->isInteractive()) { $this->io->writeError('<error>GitHub API limit exhausted. Failed to get metadata for the '.$this->url.' repository, try running in interactive mode so that you can enter your GitHub credentials to increase the API limit</error>'); throw $e; } $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'API limit exhausted. Enter your GitHub credentials to get a larger API limit (<info>'.$this->url.'</info>)'); return parent::getContents($url); } if ($rateLimited) { $rateLimit = $this->getRateLimit($e->getHeaders()); $this->io->writeError(sprintf( '<error>GitHub API limit (%d calls/hr) is exhausted. You are already authorized so you have to wait until %s before doing more requests</error>', $rateLimit['limit'], $rateLimit['reset'] )); } throw $e; default: throw $e; } } }
php
protected function getContents($url, $fetchingRepoData = false) { try { return parent::getContents($url); } catch (TransportException $e) { $gitHubUtil = new GitHub($this->io, $this->config, $this->process, $this->remoteFilesystem); switch ($e->getCode()) { case 401: case 404: // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404 if (!$fetchingRepoData) { throw $e; } if ($gitHubUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive()) { return $this->attemptCloneFallback(); } $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'Your GitHub credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)'); return parent::getContents($url); case 403: if (!$this->io->hasAuthentication($this->originUrl) && $gitHubUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive() && $fetchingRepoData) { return $this->attemptCloneFallback(); } $rateLimited = false; foreach ($e->getHeaders() as $header) { if (preg_match('{^X-RateLimit-Remaining: *0$}i', trim($header))) { $rateLimited = true; } } if (!$this->io->hasAuthentication($this->originUrl)) { if (!$this->io->isInteractive()) { $this->io->writeError('<error>GitHub API limit exhausted. Failed to get metadata for the '.$this->url.' repository, try running in interactive mode so that you can enter your GitHub credentials to increase the API limit</error>'); throw $e; } $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'API limit exhausted. Enter your GitHub credentials to get a larger API limit (<info>'.$this->url.'</info>)'); return parent::getContents($url); } if ($rateLimited) { $rateLimit = $this->getRateLimit($e->getHeaders()); $this->io->writeError(sprintf( '<error>GitHub API limit (%d calls/hr) is exhausted. You are already authorized so you have to wait until %s before doing more requests</error>', $rateLimit['limit'], $rateLimit['reset'] )); } throw $e; default: throw $e; } } }
[ "protected", "function", "getContents", "(", "$", "url", ",", "$", "fetchingRepoData", "=", "false", ")", "{", "try", "{", "return", "parent", "::", "getContents", "(", "$", "url", ")", ";", "}", "catch", "(", "TransportException", "$", "e", ")", "{", "$", "gitHubUtil", "=", "new", "GitHub", "(", "$", "this", "->", "io", ",", "$", "this", "->", "config", ",", "$", "this", "->", "process", ",", "$", "this", "->", "remoteFilesystem", ")", ";", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "401", ":", "case", "404", ":", "// try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404", "if", "(", "!", "$", "fetchingRepoData", ")", "{", "throw", "$", "e", ";", "}", "if", "(", "$", "gitHubUtil", "->", "authorizeOAuth", "(", "$", "this", "->", "originUrl", ")", ")", "{", "return", "parent", "::", "getContents", "(", "$", "url", ")", ";", "}", "if", "(", "!", "$", "this", "->", "io", "->", "isInteractive", "(", ")", ")", "{", "return", "$", "this", "->", "attemptCloneFallback", "(", ")", ";", "}", "$", "gitHubUtil", "->", "authorizeOAuthInteractively", "(", "$", "this", "->", "originUrl", ",", "'Your GitHub credentials are required to fetch private repository metadata (<info>'", ".", "$", "this", "->", "url", ".", "'</info>)'", ")", ";", "return", "parent", "::", "getContents", "(", "$", "url", ")", ";", "case", "403", ":", "if", "(", "!", "$", "this", "->", "io", "->", "hasAuthentication", "(", "$", "this", "->", "originUrl", ")", "&&", "$", "gitHubUtil", "->", "authorizeOAuth", "(", "$", "this", "->", "originUrl", ")", ")", "{", "return", "parent", "::", "getContents", "(", "$", "url", ")", ";", "}", "if", "(", "!", "$", "this", "->", "io", "->", "isInteractive", "(", ")", "&&", "$", "fetchingRepoData", ")", "{", "return", "$", "this", "->", "attemptCloneFallback", "(", ")", ";", "}", "$", "rateLimited", "=", "false", ";", "foreach", "(", "$", "e", "->", "getHeaders", "(", ")", "as", "$", "header", ")", "{", "if", "(", "preg_match", "(", "'{^X-RateLimit-Remaining: *0$}i'", ",", "trim", "(", "$", "header", ")", ")", ")", "{", "$", "rateLimited", "=", "true", ";", "}", "}", "if", "(", "!", "$", "this", "->", "io", "->", "hasAuthentication", "(", "$", "this", "->", "originUrl", ")", ")", "{", "if", "(", "!", "$", "this", "->", "io", "->", "isInteractive", "(", ")", ")", "{", "$", "this", "->", "io", "->", "writeError", "(", "'<error>GitHub API limit exhausted. Failed to get metadata for the '", ".", "$", "this", "->", "url", ".", "' repository, try running in interactive mode so that you can enter your GitHub credentials to increase the API limit</error>'", ")", ";", "throw", "$", "e", ";", "}", "$", "gitHubUtil", "->", "authorizeOAuthInteractively", "(", "$", "this", "->", "originUrl", ",", "'API limit exhausted. Enter your GitHub credentials to get a larger API limit (<info>'", ".", "$", "this", "->", "url", ".", "'</info>)'", ")", ";", "return", "parent", "::", "getContents", "(", "$", "url", ")", ";", "}", "if", "(", "$", "rateLimited", ")", "{", "$", "rateLimit", "=", "$", "this", "->", "getRateLimit", "(", "$", "e", "->", "getHeaders", "(", ")", ")", ";", "$", "this", "->", "io", "->", "writeError", "(", "sprintf", "(", "'<error>GitHub API limit (%d calls/hr) is exhausted. You are already authorized so you have to wait until %s before doing more requests</error>'", ",", "$", "rateLimit", "[", "'limit'", "]", ",", "$", "rateLimit", "[", "'reset'", "]", ")", ")", ";", "}", "throw", "$", "e", ";", "default", ":", "throw", "$", "e", ";", "}", "}", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Repository/Vcs/GitHubDriver.php#L291-L360
mothership-ec/composer
src/Composer/Repository/Vcs/GitHubDriver.php
GitHubDriver.getRateLimit
protected function getRateLimit(array $headers) { $rateLimit = array( 'limit' => '?', 'reset' => '?', ); foreach ($headers as $header) { $header = trim($header); if (false === strpos($header, 'X-RateLimit-')) { continue; } list($type, $value) = explode(':', $header, 2); switch ($type) { case 'X-RateLimit-Limit': $rateLimit['limit'] = (int) trim($value); break; case 'X-RateLimit-Reset': $rateLimit['reset'] = date('Y-m-d H:i:s', (int) trim($value)); break; } } return $rateLimit; }
php
protected function getRateLimit(array $headers) { $rateLimit = array( 'limit' => '?', 'reset' => '?', ); foreach ($headers as $header) { $header = trim($header); if (false === strpos($header, 'X-RateLimit-')) { continue; } list($type, $value) = explode(':', $header, 2); switch ($type) { case 'X-RateLimit-Limit': $rateLimit['limit'] = (int) trim($value); break; case 'X-RateLimit-Reset': $rateLimit['reset'] = date('Y-m-d H:i:s', (int) trim($value)); break; } } return $rateLimit; }
[ "protected", "function", "getRateLimit", "(", "array", "$", "headers", ")", "{", "$", "rateLimit", "=", "array", "(", "'limit'", "=>", "'?'", ",", "'reset'", "=>", "'?'", ",", ")", ";", "foreach", "(", "$", "headers", "as", "$", "header", ")", "{", "$", "header", "=", "trim", "(", "$", "header", ")", ";", "if", "(", "false", "===", "strpos", "(", "$", "header", ",", "'X-RateLimit-'", ")", ")", "{", "continue", ";", "}", "list", "(", "$", "type", ",", "$", "value", ")", "=", "explode", "(", "':'", ",", "$", "header", ",", "2", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "'X-RateLimit-Limit'", ":", "$", "rateLimit", "[", "'limit'", "]", "=", "(", "int", ")", "trim", "(", "$", "value", ")", ";", "break", ";", "case", "'X-RateLimit-Reset'", ":", "$", "rateLimit", "[", "'reset'", "]", "=", "date", "(", "'Y-m-d H:i:s'", ",", "(", "int", ")", "trim", "(", "$", "value", ")", ")", ";", "break", ";", "}", "}", "return", "$", "rateLimit", ";", "}" ]
Extract ratelimit from response. @param array $headers Headers from Composer\Downloader\TransportException. @return array Associative array with the keys limit and reset.
[ "Extract", "ratelimit", "from", "response", "." ]
train
https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Repository/Vcs/GitHubDriver.php#L369-L393
grozzzny/catalog
models/Item.php
Item.getDataProperties
public function getDataProperties() { $this->_dataProperties = (empty($this->_dataProperties)) ? new DataProperties($this->properties, $this->data) : $this->_dataProperties; return $this->_dataProperties; }
php
public function getDataProperties() { $this->_dataProperties = (empty($this->_dataProperties)) ? new DataProperties($this->properties, $this->data) : $this->_dataProperties; return $this->_dataProperties; }
[ "public", "function", "getDataProperties", "(", ")", "{", "$", "this", "->", "_dataProperties", "=", "(", "empty", "(", "$", "this", "->", "_dataProperties", ")", ")", "?", "new", "DataProperties", "(", "$", "this", "->", "properties", ",", "$", "this", "->", "data", ")", ":", "$", "this", "->", "_dataProperties", ";", "return", "$", "this", "->", "_dataProperties", ";", "}" ]
ДИНАМИЧЕСКАЯ МОДЕЛЬ С ДАННЫМИ Возвратит динамическую модель со значениями @return DataProperties|null
[ "ДИНАМИЧЕСКАЯ", "МОДЕЛЬ", "С", "ДАННЫМИ", "Возвратит", "динамическую", "модель", "со", "значениями" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Item.php#L150-L154
grozzzny/catalog
models/Item.php
Item.getProperties
public function getProperties() { $categories = (!empty($this->_categories)) ? Category::find()->where(['IN', 'id', $this->_categories])->orderBy(['parent_id' => SORT_ASC])->all() : $this->categories; $properties = []; foreach ($categories as $category){ $properties = ArrayHelper::merge($properties, $category->properties); } return $properties; }
php
public function getProperties() { $categories = (!empty($this->_categories)) ? Category::find()->where(['IN', 'id', $this->_categories])->orderBy(['parent_id' => SORT_ASC])->all() : $this->categories; $properties = []; foreach ($categories as $category){ $properties = ArrayHelper::merge($properties, $category->properties); } return $properties; }
[ "public", "function", "getProperties", "(", ")", "{", "$", "categories", "=", "(", "!", "empty", "(", "$", "this", "->", "_categories", ")", ")", "?", "Category", "::", "find", "(", ")", "->", "where", "(", "[", "'IN'", ",", "'id'", ",", "$", "this", "->", "_categories", "]", ")", "->", "orderBy", "(", "[", "'parent_id'", "=>", "SORT_ASC", "]", ")", "->", "all", "(", ")", ":", "$", "this", "->", "categories", ";", "$", "properties", "=", "[", "]", ";", "foreach", "(", "$", "categories", "as", "$", "category", ")", "{", "$", "properties", "=", "ArrayHelper", "::", "merge", "(", "$", "properties", ",", "$", "category", "->", "properties", ")", ";", "}", "return", "$", "properties", ";", "}" ]
СВОЙСТВА, НЕОБХОДИМЫЕ ДЛЯ ПОСТРОЕНИЯ ДИНАМИЧЕСКОЙ МОДЕЛИ Возвратит список свойств @return array
[ "СВОЙСТВА", "НЕОБХОДИМЫЕ", "ДЛЯ", "ПОСТРОЕНИЯ", "ДИНАМИЧЕСКОЙ", "МОДЕЛИ", "Возвратит", "список", "свойств" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Item.php#L162-L170
grozzzny/catalog
models/Item.php
Item.load
public function load($data, $formName = null) { $ret = parent::load($data, $formName); // TODO: Change the autogenerated stub $scope = $formName === null ? (new DataProperties())->formName() : $formName; if ($scope === '' && !empty($data)) { $this->dataProperties->setAttributes($data); } elseif (isset($data[$scope])) { $_data = $data[$scope]; if(!empty($_data)) $this->dataProperties->setAttributes($_data); } return $ret; }
php
public function load($data, $formName = null) { $ret = parent::load($data, $formName); // TODO: Change the autogenerated stub $scope = $formName === null ? (new DataProperties())->formName() : $formName; if ($scope === '' && !empty($data)) { $this->dataProperties->setAttributes($data); } elseif (isset($data[$scope])) { $_data = $data[$scope]; if(!empty($_data)) $this->dataProperties->setAttributes($_data); } return $ret; }
[ "public", "function", "load", "(", "$", "data", ",", "$", "formName", "=", "null", ")", "{", "$", "ret", "=", "parent", "::", "load", "(", "$", "data", ",", "$", "formName", ")", ";", "// TODO: Change the autogenerated stub", "$", "scope", "=", "$", "formName", "===", "null", "?", "(", "new", "DataProperties", "(", ")", ")", "->", "formName", "(", ")", ":", "$", "formName", ";", "if", "(", "$", "scope", "===", "''", "&&", "!", "empty", "(", "$", "data", ")", ")", "{", "$", "this", "->", "dataProperties", "->", "setAttributes", "(", "$", "data", ")", ";", "}", "elseif", "(", "isset", "(", "$", "data", "[", "$", "scope", "]", ")", ")", "{", "$", "_data", "=", "$", "data", "[", "$", "scope", "]", ";", "if", "(", "!", "empty", "(", "$", "_data", ")", ")", "$", "this", "->", "dataProperties", "->", "setAttributes", "(", "$", "_data", ")", ";", "}", "return", "$", "ret", ";", "}" ]
1 ШАГ. ЗАГРУЖАЕМ ДВЕ МОДЕЛИ (ОСНОВНУЮ И МОДЕЛЬ С ДАННЫМИ) @param array $data @param null $formName @return bool
[ "1", "ШАГ", ".", "ЗАГРУЖАЕМ", "ДВЕ", "МОДЕЛИ", "(", "ОСНОВНУЮ", "И", "МОДЕЛЬ", "С", "ДАННЫМИ", ")" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Item.php#L182-L193
grozzzny/catalog
models/Item.php
Item.afterValidate
public function afterValidate() { parent::afterValidate(); // TODO: Change the autogenerated stub $this->dataProperties->validate(); $this->addErrors($this->dataProperties->getErrors()); }
php
public function afterValidate() { parent::afterValidate(); // TODO: Change the autogenerated stub $this->dataProperties->validate(); $this->addErrors($this->dataProperties->getErrors()); }
[ "public", "function", "afterValidate", "(", ")", "{", "parent", "::", "afterValidate", "(", ")", ";", "// TODO: Change the autogenerated stub", "$", "this", "->", "dataProperties", "->", "validate", "(", ")", ";", "$", "this", "->", "addErrors", "(", "$", "this", "->", "dataProperties", "->", "getErrors", "(", ")", ")", ";", "}" ]
2 ШАГ. ВАЛИДИРУЕМ МОДЕЛЬ С ДАННЫМИ Расширенная валидация. + валидация доп. значений
[ "2", "ШАГ", ".", "ВАЛИДИРУЕМ", "МОДЕЛЬ", "С", "ДАННЫМИ", "Расширенная", "валидация", ".", "+", "валидация", "доп", ".", "значений" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Item.php#L200-L207
grozzzny/catalog
models/Item.php
Item.afterSave
public function afterSave($insert, $changedAttributes) { parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub //Сохранение связи в релативную таблицу if(!empty($this->_categories)){ $this->saveDataRelationsTable( RelationsCategoriesItems::tableName(), ['item_id' => $this->id], ['category_id' => $this->categories]); } //Сохранение значений в таблицу "Data" $this->dataProperties->saveData($this); $this->trigger($insert ? self::EVENT_ITEM_AFTER_INSERT : self::EVENT_ITEM_AFTER_UPDATE); }
php
public function afterSave($insert, $changedAttributes) { parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub //Сохранение связи в релативную таблицу if(!empty($this->_categories)){ $this->saveDataRelationsTable( RelationsCategoriesItems::tableName(), ['item_id' => $this->id], ['category_id' => $this->categories]); } //Сохранение значений в таблицу "Data" $this->dataProperties->saveData($this); $this->trigger($insert ? self::EVENT_ITEM_AFTER_INSERT : self::EVENT_ITEM_AFTER_UPDATE); }
[ "public", "function", "afterSave", "(", "$", "insert", ",", "$", "changedAttributes", ")", "{", "parent", "::", "afterSave", "(", "$", "insert", ",", "$", "changedAttributes", ")", ";", "// TODO: Change the autogenerated stub", "//Сохранение связи в релативную таблицу", "if", "(", "!", "empty", "(", "$", "this", "->", "_categories", ")", ")", "{", "$", "this", "->", "saveDataRelationsTable", "(", "RelationsCategoriesItems", "::", "tableName", "(", ")", ",", "[", "'item_id'", "=>", "$", "this", "->", "id", "]", ",", "[", "'category_id'", "=>", "$", "this", "->", "categories", "]", ")", ";", "}", "//Сохранение значений в таблицу \"Data\"", "$", "this", "->", "dataProperties", "->", "saveData", "(", "$", "this", ")", ";", "$", "this", "->", "trigger", "(", "$", "insert", "?", "self", "::", "EVENT_ITEM_AFTER_INSERT", ":", "self", "::", "EVENT_ITEM_AFTER_UPDATE", ")", ";", "}" ]
3 ШАГ. ПОСЛЕ СОХРАНЕНИЯ ОСНОВНОЙ МОДЕЛИ, ПРИСТУПАЕМ К СОХРАНЕНИЮ МОДЕЛИ С ДАННЫМИ После сохранения элемента, установить связи с категориями и сохранить значение в таблицу "Data" @param bool $insert @param array $changedAttributes
[ "3", "ШАГ", ".", "ПОСЛЕ", "СОХРАНЕНИЯ", "ОСНОВНОЙ", "МОДЕЛИ", "ПРИСТУПАЕМ", "К", "СОХРАНЕНИЮ", "МОДЕЛИ", "С", "ДАННЫМИ", "После", "сохранения", "элемента", "установить", "связи", "с", "категориями", "и", "сохранить", "значение", "в", "таблицу", "Data" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Item.php#L216-L229
grozzzny/catalog
models/Item.php
Item.setScenario
public function setScenario($value) { if(array_key_exists($value, $this->dataProperties->scenarios())) $this->dataProperties->setScenario($value); parent::setScenario($value); // TODO: Change the autogenerated stub }
php
public function setScenario($value) { if(array_key_exists($value, $this->dataProperties->scenarios())) $this->dataProperties->setScenario($value); parent::setScenario($value); // TODO: Change the autogenerated stub }
[ "public", "function", "setScenario", "(", "$", "value", ")", "{", "if", "(", "array_key_exists", "(", "$", "value", ",", "$", "this", "->", "dataProperties", "->", "scenarios", "(", ")", ")", ")", "$", "this", "->", "dataProperties", "->", "setScenario", "(", "$", "value", ")", ";", "parent", "::", "setScenario", "(", "$", "value", ")", ";", "// TODO: Change the autogenerated stub", "}" ]
КОНЕЦ СОХРАНЕНИЯ ДАННЫХ
[ "КОНЕЦ", "СОХРАНЕНИЯ", "ДАННЫХ" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Item.php#L238-L242
grozzzny/catalog
models/Item.php
Item.queryFilter
public static function queryFilter(ItemQuery &$query, array $get) { $query->whereSearch($get['search_text']); $query->whereRange(['price' => [ArrayHelper::getValue($get, 'price_from', ''), ArrayHelper::getValue($get, 'price_to', '')]]); if(empty($query->_category) && !empty($get['category'])) $query->category(Category::findOne($get['category'])); $query->whereProperties($get); }
php
public static function queryFilter(ItemQuery &$query, array $get) { $query->whereSearch($get['search_text']); $query->whereRange(['price' => [ArrayHelper::getValue($get, 'price_from', ''), ArrayHelper::getValue($get, 'price_to', '')]]); if(empty($query->_category) && !empty($get['category'])) $query->category(Category::findOne($get['category'])); $query->whereProperties($get); }
[ "public", "static", "function", "queryFilter", "(", "ItemQuery", "&", "$", "query", ",", "array", "$", "get", ")", "{", "$", "query", "->", "whereSearch", "(", "$", "get", "[", "'search_text'", "]", ")", ";", "$", "query", "->", "whereRange", "(", "[", "'price'", "=>", "[", "ArrayHelper", "::", "getValue", "(", "$", "get", ",", "'price_from'", ",", "''", ")", ",", "ArrayHelper", "::", "getValue", "(", "$", "get", ",", "'price_to'", ",", "''", ")", "]", "]", ")", ";", "if", "(", "empty", "(", "$", "query", "->", "_category", ")", "&&", "!", "empty", "(", "$", "get", "[", "'category'", "]", ")", ")", "$", "query", "->", "category", "(", "Category", "::", "findOne", "(", "$", "get", "[", "'category'", "]", ")", ")", ";", "$", "query", "->", "whereProperties", "(", "$", "get", ")", ";", "}" ]
Параметры фильтра @param ItemQuery $query @param $get
[ "Параметры", "фильтра" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Item.php#L303-L313
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.connect
public function connect() { //if port is not set, try and determine based on transport if(!is_numeric($this->port)){ if(substr($this->host, 0, 3) == 'ssl'){ $this->port = 5223; $this->log("Connecting with SSL"); } else { $this->port = 5222; } } parent::__construct($this->host.':'.$this->port, $this->timeout); $this->open(); //begin stream $this->write("<stream:stream to='$this->host' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' xml:lang='en' version='1.0'>"); $this->read(); $this->read(); $this->connected = true; }
php
public function connect() { //if port is not set, try and determine based on transport if(!is_numeric($this->port)){ if(substr($this->host, 0, 3) == 'ssl'){ $this->port = 5223; $this->log("Connecting with SSL"); } else { $this->port = 5222; } } parent::__construct($this->host.':'.$this->port, $this->timeout); $this->open(); //begin stream $this->write("<stream:stream to='$this->host' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' xml:lang='en' version='1.0'>"); $this->read(); $this->read(); $this->connected = true; }
[ "public", "function", "connect", "(", ")", "{", "//if port is not set, try and determine based on transport", "if", "(", "!", "is_numeric", "(", "$", "this", "->", "port", ")", ")", "{", "if", "(", "substr", "(", "$", "this", "->", "host", ",", "0", ",", "3", ")", "==", "'ssl'", ")", "{", "$", "this", "->", "port", "=", "5223", ";", "$", "this", "->", "log", "(", "\"Connecting with SSL\"", ")", ";", "}", "else", "{", "$", "this", "->", "port", "=", "5222", ";", "}", "}", "parent", "::", "__construct", "(", "$", "this", "->", "host", ".", "':'", ".", "$", "this", "->", "port", ",", "$", "this", "->", "timeout", ")", ";", "$", "this", "->", "open", "(", ")", ";", "//begin stream", "$", "this", "->", "write", "(", "\"<stream:stream to='$this->host' xmlns='jabber:client'\nxmlns:stream='http://etherx.jabber.org/streams' xml:lang='en' version='1.0'>\"", ")", ";", "$", "this", "->", "read", "(", ")", ";", "$", "this", "->", "read", "(", ")", ";", "$", "this", "->", "connected", "=", "true", ";", "}" ]
Connects to the XMPP server
[ "Connects", "to", "the", "XMPP", "server" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L97-L124
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.login
public function login() { //connect if not connected if(!$this->connected){ $this->reconnect(); } //calc the jid from uname+host $this->jid = $this->uname.'@'.substr($this->host, strpos($this->host, '//')+2); if($this->pass){ $this->write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode("\x00" . $this->uname . "\x00" . $this->pass) . "</auth>"); } else { $this->write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS' />"); } $buffer = $this->read(); if(substr($buffer, 0, 5) == '<fail'){ $this->onError(0, 'Cound not log in'); return false; } $this->client_name = empty($this->client_name) ? __CLASS__ : $this->client_name; if(!$this->sendClientName()){ return false; } $this->setStatus($this->status); $this->onAfterLogin(); return true; }
php
public function login() { //connect if not connected if(!$this->connected){ $this->reconnect(); } //calc the jid from uname+host $this->jid = $this->uname.'@'.substr($this->host, strpos($this->host, '//')+2); if($this->pass){ $this->write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode("\x00" . $this->uname . "\x00" . $this->pass) . "</auth>"); } else { $this->write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS' />"); } $buffer = $this->read(); if(substr($buffer, 0, 5) == '<fail'){ $this->onError(0, 'Cound not log in'); return false; } $this->client_name = empty($this->client_name) ? __CLASS__ : $this->client_name; if(!$this->sendClientName()){ return false; } $this->setStatus($this->status); $this->onAfterLogin(); return true; }
[ "public", "function", "login", "(", ")", "{", "//connect if not connected", "if", "(", "!", "$", "this", "->", "connected", ")", "{", "$", "this", "->", "reconnect", "(", ")", ";", "}", "//calc the jid from uname+host", "$", "this", "->", "jid", "=", "$", "this", "->", "uname", ".", "'@'", ".", "substr", "(", "$", "this", "->", "host", ",", "strpos", "(", "$", "this", "->", "host", ",", "'//'", ")", "+", "2", ")", ";", "if", "(", "$", "this", "->", "pass", ")", "{", "$", "this", "->", "write", "(", "\"<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>\"", ".", "base64_encode", "(", "\"\\x00\"", ".", "$", "this", "->", "uname", ".", "\"\\x00\"", ".", "$", "this", "->", "pass", ")", ".", "\"</auth>\"", ")", ";", "}", "else", "{", "$", "this", "->", "write", "(", "\"<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS' />\"", ")", ";", "}", "$", "buffer", "=", "$", "this", "->", "read", "(", ")", ";", "if", "(", "substr", "(", "$", "buffer", ",", "0", ",", "5", ")", "==", "'<fail'", ")", "{", "$", "this", "->", "onError", "(", "0", ",", "'Cound not log in'", ")", ";", "return", "false", ";", "}", "$", "this", "->", "client_name", "=", "empty", "(", "$", "this", "->", "client_name", ")", "?", "__CLASS__", ":", "$", "this", "->", "client_name", ";", "if", "(", "!", "$", "this", "->", "sendClientName", "(", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "setStatus", "(", "$", "this", "->", "status", ")", ";", "$", "this", "->", "onAfterLogin", "(", ")", ";", "return", "true", ";", "}" ]
Login to the XMPP server as a user and set their precence to avaiable @return boolean
[ "Login", "to", "the", "XMPP", "server", "as", "a", "user", "and", "set", "their", "precence", "to", "avaiable" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L141-L178
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.sendPresence
public function sendPresence(\sb\XMPP\Presence $presence) { $presence->setFrom($this->jid); return $this->write($presence); }
php
public function sendPresence(\sb\XMPP\Presence $presence) { $presence->setFrom($this->jid); return $this->write($presence); }
[ "public", "function", "sendPresence", "(", "\\", "sb", "\\", "XMPP", "\\", "Presence", "$", "presence", ")", "{", "$", "presence", "->", "setFrom", "(", "$", "this", "->", "jid", ")", ";", "return", "$", "this", "->", "write", "(", "$", "presence", ")", ";", "}" ]
Converts a presense request instance to XML and sends it. It sets the from to the bots jid for you @param \sb\XMPP\Presence $presence The presence instance to send @return boolean
[ "Converts", "a", "presense", "request", "instance", "to", "XML", "and", "sends", "it", ".", "It", "sets", "the", "from", "to", "the", "bots", "jid", "for", "you" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L187-L192
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.setStatus
public function setStatus($status=null) { $presence = new \sb\XMPP\Presence(); $presence->setStatus(is_string($status) ? $status : $this->status); $this->sendPresence($presence); }
php
public function setStatus($status=null) { $presence = new \sb\XMPP\Presence(); $presence->setStatus(is_string($status) ? $status : $this->status); $this->sendPresence($presence); }
[ "public", "function", "setStatus", "(", "$", "status", "=", "null", ")", "{", "$", "presence", "=", "new", "\\", "sb", "\\", "XMPP", "\\", "Presence", "(", ")", ";", "$", "presence", "->", "setStatus", "(", "is_string", "(", "$", "status", ")", "?", "$", "status", ":", "$", "this", "->", "status", ")", ";", "$", "this", "->", "sendPresence", "(", "$", "presence", ")", ";", "}" ]
Sets status message @param string $status The status message to send
[ "Sets", "status", "message" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L198-L205
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.sendSimpleMessage
public function sendSimpleMessage($to, $body) { $message = new \sb\XMPP\Message(); $message->setTo($to); $message->setBody($body); $this->sendMessage($message); }
php
public function sendSimpleMessage($to, $body) { $message = new \sb\XMPP\Message(); $message->setTo($to); $message->setBody($body); $this->sendMessage($message); }
[ "public", "function", "sendSimpleMessage", "(", "$", "to", ",", "$", "body", ")", "{", "$", "message", "=", "new", "\\", "sb", "\\", "XMPP", "\\", "Message", "(", ")", ";", "$", "message", "->", "setTo", "(", "$", "to", ")", ";", "$", "message", "->", "setBody", "(", "$", "body", ")", ";", "$", "this", "->", "sendMessage", "(", "$", "message", ")", ";", "}" ]
Sends simple string based text message @param string $to The jid to send the message to @param string $body The text to send
[ "Sends", "simple", "string", "based", "text", "message" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L213-L221
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.sendAcceptSubscriptionRequest
public function sendAcceptSubscriptionRequest($to) { $presence = new \sb\XMPP\Presence(); $presence->setType('subscribed'); $presence->setTo($to); return $this->sendPresence($presence); }
php
public function sendAcceptSubscriptionRequest($to) { $presence = new \sb\XMPP\Presence(); $presence->setType('subscribed'); $presence->setTo($to); return $this->sendPresence($presence); }
[ "public", "function", "sendAcceptSubscriptionRequest", "(", "$", "to", ")", "{", "$", "presence", "=", "new", "\\", "sb", "\\", "XMPP", "\\", "Presence", "(", ")", ";", "$", "presence", "->", "setType", "(", "'subscribed'", ")", ";", "$", "presence", "->", "setTo", "(", "$", "to", ")", ";", "return", "$", "this", "->", "sendPresence", "(", "$", "presence", ")", ";", "}" ]
Send a presence message accepting subscription request to a jid @param string $to The jid of the person to send the acceptance request to @return boolean
[ "Send", "a", "presence", "message", "accepting", "subscription", "request", "to", "a", "jid" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L228-L234
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.sendSubscriptionRequest
public function sendSubscriptionRequest($to) { $presence = new \sb\XMPP\Presence(); $presence->setTo($to); $presence->setType('subscribe'); $presence->setFrom($this->jid); return $this->sendPresence($presence); }
php
public function sendSubscriptionRequest($to) { $presence = new \sb\XMPP\Presence(); $presence->setTo($to); $presence->setType('subscribe'); $presence->setFrom($this->jid); return $this->sendPresence($presence); }
[ "public", "function", "sendSubscriptionRequest", "(", "$", "to", ")", "{", "$", "presence", "=", "new", "\\", "sb", "\\", "XMPP", "\\", "Presence", "(", ")", ";", "$", "presence", "->", "setTo", "(", "$", "to", ")", ";", "$", "presence", "->", "setType", "(", "'subscribe'", ")", ";", "$", "presence", "->", "setFrom", "(", "$", "this", "->", "jid", ")", ";", "return", "$", "this", "->", "sendPresence", "(", "$", "presence", ")", ";", "}" ]
Sends a subscription request to a jid @param string $to The hid to send the subscription request to @return boolean
[ "Sends", "a", "subscription", "request", "to", "a", "jid" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L241-L250
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.broadcast
public function broadcast($message, $except=array()) { if(!$message instanceOf \sb\XMPP\Message){ $body = $message; $message = new \sb\XMPP\Message(); $message->setBody($body); } foreach($this->buddies_online as $buddy=>$status){ if(!in_array($buddy, $except)){ $message->setTo($buddy); $this->sendMessage($message); } } }
php
public function broadcast($message, $except=array()) { if(!$message instanceOf \sb\XMPP\Message){ $body = $message; $message = new \sb\XMPP\Message(); $message->setBody($body); } foreach($this->buddies_online as $buddy=>$status){ if(!in_array($buddy, $except)){ $message->setTo($buddy); $this->sendMessage($message); } } }
[ "public", "function", "broadcast", "(", "$", "message", ",", "$", "except", "=", "array", "(", ")", ")", "{", "if", "(", "!", "$", "message", "instanceOf", "\\", "sb", "\\", "XMPP", "\\", "Message", ")", "{", "$", "body", "=", "$", "message", ";", "$", "message", "=", "new", "\\", "sb", "\\", "XMPP", "\\", "Message", "(", ")", ";", "$", "message", "->", "setBody", "(", "$", "body", ")", ";", "}", "foreach", "(", "$", "this", "->", "buddies_online", "as", "$", "buddy", "=>", "$", "status", ")", "{", "if", "(", "!", "in_array", "(", "$", "buddy", ",", "$", "except", ")", ")", "{", "$", "message", "->", "setTo", "(", "$", "buddy", ")", ";", "$", "this", "->", "sendMessage", "(", "$", "message", ")", ";", "}", "}", "}" ]
Broadcasts message to all online buddies not in except array @param mixed $message String/\sb\XMPP\Message The message to send @param string $except An array of jids to not send to
[ "Broadcasts", "message", "to", "all", "online", "buddies", "not", "in", "except", "array" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L277-L293
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.sleep
public function sleep($secs) { $str = 'Going to sleep for '.$secs.'secs'; $this->log('NOTICE: '.$str); $this->setStatus($str); sleep($secs); $this->setStatus($this->status ? $this->status : 'awake'); }
php
public function sleep($secs) { $str = 'Going to sleep for '.$secs.'secs'; $this->log('NOTICE: '.$str); $this->setStatus($str); sleep($secs); $this->setStatus($this->status ? $this->status : 'awake'); }
[ "public", "function", "sleep", "(", "$", "secs", ")", "{", "$", "str", "=", "'Going to sleep for '", ".", "$", "secs", ".", "'secs'", ";", "$", "this", "->", "log", "(", "'NOTICE: '", ".", "$", "str", ")", ";", "$", "this", "->", "setStatus", "(", "$", "str", ")", ";", "sleep", "(", "$", "secs", ")", ";", "$", "this", "->", "setStatus", "(", "$", "this", "->", "status", "?", "$", "this", "->", "status", ":", "'awake'", ")", ";", "}" ]
Puts the bot to sleep for a while @param integer $secs
[ "Puts", "the", "bot", "to", "sleep", "for", "a", "while" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L310-L317
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.composingStart
public function composingStart($to) { $message = new \sb\XMPP\Message(); $message->setTo($to); $message->setFrom($this->jid); $message->setType('chat'); $node = $message->createElement('composing'); $attr = $message->createAttribute('xmlns'); $node->appendChild($attr); $attr->appendChild($message->createTextNode('http://jabber.org/protocol/chatstates')); $message->doc->appendChild($node); $this->sendMessage($message); }
php
public function composingStart($to) { $message = new \sb\XMPP\Message(); $message->setTo($to); $message->setFrom($this->jid); $message->setType('chat'); $node = $message->createElement('composing'); $attr = $message->createAttribute('xmlns'); $node->appendChild($attr); $attr->appendChild($message->createTextNode('http://jabber.org/protocol/chatstates')); $message->doc->appendChild($node); $this->sendMessage($message); }
[ "public", "function", "composingStart", "(", "$", "to", ")", "{", "$", "message", "=", "new", "\\", "sb", "\\", "XMPP", "\\", "Message", "(", ")", ";", "$", "message", "->", "setTo", "(", "$", "to", ")", ";", "$", "message", "->", "setFrom", "(", "$", "this", "->", "jid", ")", ";", "$", "message", "->", "setType", "(", "'chat'", ")", ";", "$", "node", "=", "$", "message", "->", "createElement", "(", "'composing'", ")", ";", "$", "attr", "=", "$", "message", "->", "createAttribute", "(", "'xmlns'", ")", ";", "$", "node", "->", "appendChild", "(", "$", "attr", ")", ";", "$", "attr", "->", "appendChild", "(", "$", "message", "->", "createTextNode", "(", "'http://jabber.org/protocol/chatstates'", ")", ")", ";", "$", "message", "->", "doc", "->", "appendChild", "(", "$", "node", ")", ";", "$", "this", "->", "sendMessage", "(", "$", "message", ")", ";", "}" ]
Send an indication that the bot is composing text. @param string $to The jid to send to
[ "Send", "an", "indication", "that", "the", "bot", "is", "composing", "text", "." ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L323-L338
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.read
final public function read($byte_count=null) { $buffer = ''; $read = array($this->socket); $updated = @stream_select($read, $write, $except, 1); if ($updated > 0) { $data = fread($this->socket, 4096); if($data) { $buffer = $data; } } if(!empty($buffer)){ $this->log('RECEIVED: '.$buffer); } return $buffer; }
php
final public function read($byte_count=null) { $buffer = ''; $read = array($this->socket); $updated = @stream_select($read, $write, $except, 1); if ($updated > 0) { $data = fread($this->socket, 4096); if($data) { $buffer = $data; } } if(!empty($buffer)){ $this->log('RECEIVED: '.$buffer); } return $buffer; }
[ "final", "public", "function", "read", "(", "$", "byte_count", "=", "null", ")", "{", "$", "buffer", "=", "''", ";", "$", "read", "=", "array", "(", "$", "this", "->", "socket", ")", ";", "$", "updated", "=", "@", "stream_select", "(", "$", "read", ",", "$", "write", ",", "$", "except", ",", "1", ")", ";", "if", "(", "$", "updated", ">", "0", ")", "{", "$", "data", "=", "fread", "(", "$", "this", "->", "socket", ",", "4096", ")", ";", "if", "(", "$", "data", ")", "{", "$", "buffer", "=", "$", "data", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "buffer", ")", ")", "{", "$", "this", "->", "log", "(", "'RECEIVED: '", ".", "$", "buffer", ")", ";", "}", "return", "$", "buffer", ";", "}" ]
Reads from the socket, should be protected but can't because this is inherited as public @return string The buffer data read from the socket
[ "Reads", "from", "the", "socket", "should", "be", "protected", "but", "can", "t", "because", "this", "is", "inherited", "as", "public" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L366-L387
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.listen
final public function listen() { $this->log("Listening..."); $x = 1; while($x){ $x++; $xml = $this->read(1024); if(!empty($xml)){ if($this->onRead($xml) === false){ return false; } } if(substr($xml, 0, 8 ) == '<message'){ $message = new \sb\XMPP\Message($xml); $message->client = $this; $this->onMessage($message); } elseif(substr($xml, 0, 9 ) == '<presence'){ $presence = new \sb\XMPP\Presence($xml); $from = $presence->getFrom(); $type = $presence->getType(); if(is_array($this->buddies_online)){ $status = $presence->getStatus(); if($from && $type == 'unavailable'){ unset($this->buddies_online[$from]); $this->log('NOTICE: '.$from.' is unavailable'); } elseif($from){ $this->buddies_online[$from] = $status; $this->log('NOTICE: '.$from.' is '.$status); } } if(strstr($type, 'subscribe') && $this->onSubscriptionRequest($presence)){ $this->sendAcceptSubscriptionRequest($from); $this->log('NOTICE: Auto accepting subscription request from '.$from); } $this->onPresence($presence); } if($x % 100 == 0){ $presence = new \sb\XMPP\Presence(); $presence->setStatus($this->status); $this->sendPresence($presence); $x = 1; } //extra little sleep reduces CPU usleep(100000); } }
php
final public function listen() { $this->log("Listening..."); $x = 1; while($x){ $x++; $xml = $this->read(1024); if(!empty($xml)){ if($this->onRead($xml) === false){ return false; } } if(substr($xml, 0, 8 ) == '<message'){ $message = new \sb\XMPP\Message($xml); $message->client = $this; $this->onMessage($message); } elseif(substr($xml, 0, 9 ) == '<presence'){ $presence = new \sb\XMPP\Presence($xml); $from = $presence->getFrom(); $type = $presence->getType(); if(is_array($this->buddies_online)){ $status = $presence->getStatus(); if($from && $type == 'unavailable'){ unset($this->buddies_online[$from]); $this->log('NOTICE: '.$from.' is unavailable'); } elseif($from){ $this->buddies_online[$from] = $status; $this->log('NOTICE: '.$from.' is '.$status); } } if(strstr($type, 'subscribe') && $this->onSubscriptionRequest($presence)){ $this->sendAcceptSubscriptionRequest($from); $this->log('NOTICE: Auto accepting subscription request from '.$from); } $this->onPresence($presence); } if($x % 100 == 0){ $presence = new \sb\XMPP\Presence(); $presence->setStatus($this->status); $this->sendPresence($presence); $x = 1; } //extra little sleep reduces CPU usleep(100000); } }
[ "final", "public", "function", "listen", "(", ")", "{", "$", "this", "->", "log", "(", "\"Listening...\"", ")", ";", "$", "x", "=", "1", ";", "while", "(", "$", "x", ")", "{", "$", "x", "++", ";", "$", "xml", "=", "$", "this", "->", "read", "(", "1024", ")", ";", "if", "(", "!", "empty", "(", "$", "xml", ")", ")", "{", "if", "(", "$", "this", "->", "onRead", "(", "$", "xml", ")", "===", "false", ")", "{", "return", "false", ";", "}", "}", "if", "(", "substr", "(", "$", "xml", ",", "0", ",", "8", ")", "==", "'<message'", ")", "{", "$", "message", "=", "new", "\\", "sb", "\\", "XMPP", "\\", "Message", "(", "$", "xml", ")", ";", "$", "message", "->", "client", "=", "$", "this", ";", "$", "this", "->", "onMessage", "(", "$", "message", ")", ";", "}", "elseif", "(", "substr", "(", "$", "xml", ",", "0", ",", "9", ")", "==", "'<presence'", ")", "{", "$", "presence", "=", "new", "\\", "sb", "\\", "XMPP", "\\", "Presence", "(", "$", "xml", ")", ";", "$", "from", "=", "$", "presence", "->", "getFrom", "(", ")", ";", "$", "type", "=", "$", "presence", "->", "getType", "(", ")", ";", "if", "(", "is_array", "(", "$", "this", "->", "buddies_online", ")", ")", "{", "$", "status", "=", "$", "presence", "->", "getStatus", "(", ")", ";", "if", "(", "$", "from", "&&", "$", "type", "==", "'unavailable'", ")", "{", "unset", "(", "$", "this", "->", "buddies_online", "[", "$", "from", "]", ")", ";", "$", "this", "->", "log", "(", "'NOTICE: '", ".", "$", "from", ".", "' is unavailable'", ")", ";", "}", "elseif", "(", "$", "from", ")", "{", "$", "this", "->", "buddies_online", "[", "$", "from", "]", "=", "$", "status", ";", "$", "this", "->", "log", "(", "'NOTICE: '", ".", "$", "from", ".", "' is '", ".", "$", "status", ")", ";", "}", "}", "if", "(", "strstr", "(", "$", "type", ",", "'subscribe'", ")", "&&", "$", "this", "->", "onSubscriptionRequest", "(", "$", "presence", ")", ")", "{", "$", "this", "->", "sendAcceptSubscriptionRequest", "(", "$", "from", ")", ";", "$", "this", "->", "log", "(", "'NOTICE: Auto accepting subscription request from '", ".", "$", "from", ")", ";", "}", "$", "this", "->", "onPresence", "(", "$", "presence", ")", ";", "}", "if", "(", "$", "x", "%", "100", "==", "0", ")", "{", "$", "presence", "=", "new", "\\", "sb", "\\", "XMPP", "\\", "Presence", "(", ")", ";", "$", "presence", "->", "setStatus", "(", "$", "this", "->", "status", ")", ";", "$", "this", "->", "sendPresence", "(", "$", "presence", ")", ";", "$", "x", "=", "1", ";", "}", "//extra little sleep reduces CPU", "usleep", "(", "100000", ")", ";", "}", "}" ]
Listens for incoming chat on the socket
[ "Listens", "for", "incoming", "chat", "on", "the", "socket" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L392-L456
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.write
final public function write($xml) { if($xml instanceof \SimpleXMLElement){ $xml = $xml->asXML(); } elseif($xml instanceof \DOMDocument){ $xml = $xml->saveXML(); } $this->log("SENT: ".$xml); return parent::write($xml); }
php
final public function write($xml) { if($xml instanceof \SimpleXMLElement){ $xml = $xml->asXML(); } elseif($xml instanceof \DOMDocument){ $xml = $xml->saveXML(); } $this->log("SENT: ".$xml); return parent::write($xml); }
[ "final", "public", "function", "write", "(", "$", "xml", ")", "{", "if", "(", "$", "xml", "instanceof", "\\", "SimpleXMLElement", ")", "{", "$", "xml", "=", "$", "xml", "->", "asXML", "(", ")", ";", "}", "elseif", "(", "$", "xml", "instanceof", "\\", "DOMDocument", ")", "{", "$", "xml", "=", "$", "xml", "->", "saveXML", "(", ")", ";", "}", "$", "this", "->", "log", "(", "\"SENT: \"", ".", "$", "xml", ")", ";", "return", "parent", "::", "write", "(", "$", "xml", ")", ";", "}" ]
Writes XML to the socket client @param mixed $xml Can be DOMDocument, SimpleXMLElement or string of XML @return <type>
[ "Writes", "XML", "to", "the", "socket", "client" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L463-L475
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.getMemoryUsage
final public function getMemoryUsage($peak=false) { if($peak){ $mem_usage = memory_get_peak_usage(true); } else { $mem_usage = memory_get_usage(true); } $str = ''; if ($mem_usage < 1024) { $str = $mem_usage." b"; } elseif ($mem_usage < 1048576) { $str = round($mem_usage/1024,2)." KB"; } else { $str = round($mem_usage/1048576,2)." MB"; } return $str; }
php
final public function getMemoryUsage($peak=false) { if($peak){ $mem_usage = memory_get_peak_usage(true); } else { $mem_usage = memory_get_usage(true); } $str = ''; if ($mem_usage < 1024) { $str = $mem_usage." b"; } elseif ($mem_usage < 1048576) { $str = round($mem_usage/1024,2)." KB"; } else { $str = round($mem_usage/1048576,2)." MB"; } return $str; }
[ "final", "public", "function", "getMemoryUsage", "(", "$", "peak", "=", "false", ")", "{", "if", "(", "$", "peak", ")", "{", "$", "mem_usage", "=", "memory_get_peak_usage", "(", "true", ")", ";", "}", "else", "{", "$", "mem_usage", "=", "memory_get_usage", "(", "true", ")", ";", "}", "$", "str", "=", "''", ";", "if", "(", "$", "mem_usage", "<", "1024", ")", "{", "$", "str", "=", "$", "mem_usage", ".", "\" b\"", ";", "}", "elseif", "(", "$", "mem_usage", "<", "1048576", ")", "{", "$", "str", "=", "round", "(", "$", "mem_usage", "/", "1024", ",", "2", ")", ".", "\" KB\"", ";", "}", "else", "{", "$", "str", "=", "round", "(", "$", "mem_usage", "/", "1048576", ",", "2", ")", ".", "\" MB\"", ";", "}", "return", "$", "str", ";", "}" ]
Determines the peak memory usage @return string The value in b, KB, or MB depending on size
[ "Determines", "the", "peak", "memory", "usage" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L482-L500
surebert/surebert-framework
src/sb/XMPP/Client.php
Client.close
final public function close() { $this->onCloseConnection(); if($this->socket){ $this->write("</stream:stream>"); parent::close(); $this->connected = false; } }
php
final public function close() { $this->onCloseConnection(); if($this->socket){ $this->write("</stream:stream>"); parent::close(); $this->connected = false; } }
[ "final", "public", "function", "close", "(", ")", "{", "$", "this", "->", "onCloseConnection", "(", ")", ";", "if", "(", "$", "this", "->", "socket", ")", "{", "$", "this", "->", "write", "(", "\"</stream:stream>\"", ")", ";", "parent", "::", "close", "(", ")", ";", "$", "this", "->", "connected", "=", "false", ";", "}", "}" ]
Ends the stream and closes the connection
[ "Ends", "the", "stream", "and", "closes", "the", "connection" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/XMPP/Client.php#L505-L516
GrupaZero/api
src/Gzero/Api/Controller/Admin/ContentController.php
ContentController.index
public function index($id = null) { $this->authorize('readList', Content::class); $input = $this->validator->validate('list'); $params = $this->processor->process($input)->getProcessedFields(); if ($id) { // content/id/children $content = $this->repository->getById($id); if (!empty($content)) { $results = $this->repository->getChildren( $content, $params['filter'], $params['orderBy'], $params['page'], $params['perPage'] ); return $this->respondWithSuccess($results, new ContentTransformer); } else { return $this->respondNotFound(); } } $results = $this->repository->getContents( $params['filter'], $params['orderBy'], $params['page'], $params['perPage'] ); return $this->respondWithSuccess($results, new ContentTransformer); }
php
public function index($id = null) { $this->authorize('readList', Content::class); $input = $this->validator->validate('list'); $params = $this->processor->process($input)->getProcessedFields(); if ($id) { // content/id/children $content = $this->repository->getById($id); if (!empty($content)) { $results = $this->repository->getChildren( $content, $params['filter'], $params['orderBy'], $params['page'], $params['perPage'] ); return $this->respondWithSuccess($results, new ContentTransformer); } else { return $this->respondNotFound(); } } $results = $this->repository->getContents( $params['filter'], $params['orderBy'], $params['page'], $params['perPage'] ); return $this->respondWithSuccess($results, new ContentTransformer); }
[ "public", "function", "index", "(", "$", "id", "=", "null", ")", "{", "$", "this", "->", "authorize", "(", "'readList'", ",", "Content", "::", "class", ")", ";", "$", "input", "=", "$", "this", "->", "validator", "->", "validate", "(", "'list'", ")", ";", "$", "params", "=", "$", "this", "->", "processor", "->", "process", "(", "$", "input", ")", "->", "getProcessedFields", "(", ")", ";", "if", "(", "$", "id", ")", "{", "// content/id/children", "$", "content", "=", "$", "this", "->", "repository", "->", "getById", "(", "$", "id", ")", ";", "if", "(", "!", "empty", "(", "$", "content", ")", ")", "{", "$", "results", "=", "$", "this", "->", "repository", "->", "getChildren", "(", "$", "content", ",", "$", "params", "[", "'filter'", "]", ",", "$", "params", "[", "'orderBy'", "]", ",", "$", "params", "[", "'page'", "]", ",", "$", "params", "[", "'perPage'", "]", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "results", ",", "new", "ContentTransformer", ")", ";", "}", "else", "{", "return", "$", "this", "->", "respondNotFound", "(", ")", ";", "}", "}", "$", "results", "=", "$", "this", "->", "repository", "->", "getContents", "(", "$", "params", "[", "'filter'", "]", ",", "$", "params", "[", "'orderBy'", "]", ",", "$", "params", "[", "'page'", "]", ",", "$", "params", "[", "'perPage'", "]", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "results", ",", "new", "ContentTransformer", ")", ";", "}" ]
Display a listing of the resource. @param int|null $id Id used for nested resources @return \Illuminate\Http\JsonResponse
[ "Display", "a", "listing", "of", "the", "resource", "." ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/ContentController.php#L73-L102
GrupaZero/api
src/Gzero/Api/Controller/Admin/ContentController.php
ContentController.indexOfDeleted
public function indexOfDeleted() { $this->authorize('readList', Content::class); $input = $this->validator->validate('list'); $params = $this->processor->process($input)->getProcessedFields(); $results = $this->repository->getDeletedContents( $params['filter'], $params['orderBy'], $params['page'], $params['perPage'] ); return $this->respondWithSuccess($results, new ContentTransformer); }
php
public function indexOfDeleted() { $this->authorize('readList', Content::class); $input = $this->validator->validate('list'); $params = $this->processor->process($input)->getProcessedFields(); $results = $this->repository->getDeletedContents( $params['filter'], $params['orderBy'], $params['page'], $params['perPage'] ); return $this->respondWithSuccess($results, new ContentTransformer); }
[ "public", "function", "indexOfDeleted", "(", ")", "{", "$", "this", "->", "authorize", "(", "'readList'", ",", "Content", "::", "class", ")", ";", "$", "input", "=", "$", "this", "->", "validator", "->", "validate", "(", "'list'", ")", ";", "$", "params", "=", "$", "this", "->", "processor", "->", "process", "(", "$", "input", ")", "->", "getProcessedFields", "(", ")", ";", "$", "results", "=", "$", "this", "->", "repository", "->", "getDeletedContents", "(", "$", "params", "[", "'filter'", "]", ",", "$", "params", "[", "'orderBy'", "]", ",", "$", "params", "[", "'page'", "]", ",", "$", "params", "[", "'perPage'", "]", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "results", ",", "new", "ContentTransformer", ")", ";", "}" ]
Display list of soft deleted contents @return \Illuminate\Http\JsonResponse
[ "Display", "list", "of", "soft", "deleted", "contents" ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/ContentController.php#L109-L123
GrupaZero/api
src/Gzero/Api/Controller/Admin/ContentController.php
ContentController.indexTree
public function indexTree($id = null) { $this->authorize('readList', Content::class); $input = $this->validator->validate('tree'); $params = $this->processor->process($input)->getProcessedFields(); $this->getSerializer()->parseIncludes('children'); // We need to enable children include to return tree from api if ($id) { // Single tree $content = $this->repository->getById($id); if (!empty($content)) { return $this->respondWithSuccess( $this->repository->getTree( $content, $params['filter'], $params['orderBy'] ), new ContentTransformer ); } else { return $this->respondNotFound(); } } // All trees //$params['filter'] = array_merge(['type' => ['value' => 'category', 'relation' => null]], $params['filter']); $nodes = $this->repository->getContentsByLevel( $params['filter'], $params['orderBy'], null ); $trees = $this->repository->buildTree($nodes); // We need to guarantee LaravelCollection here because buildTree will return single root // if we have only one if (!empty($trees) && !$trees instanceof LaravelCollection) { $trees = new LaravelCollection([$trees]); } return $this->respondWithSuccess($trees, new ContentTransformer); }
php
public function indexTree($id = null) { $this->authorize('readList', Content::class); $input = $this->validator->validate('tree'); $params = $this->processor->process($input)->getProcessedFields(); $this->getSerializer()->parseIncludes('children'); // We need to enable children include to return tree from api if ($id) { // Single tree $content = $this->repository->getById($id); if (!empty($content)) { return $this->respondWithSuccess( $this->repository->getTree( $content, $params['filter'], $params['orderBy'] ), new ContentTransformer ); } else { return $this->respondNotFound(); } } // All trees //$params['filter'] = array_merge(['type' => ['value' => 'category', 'relation' => null]], $params['filter']); $nodes = $this->repository->getContentsByLevel( $params['filter'], $params['orderBy'], null ); $trees = $this->repository->buildTree($nodes); // We need to guarantee LaravelCollection here because buildTree will return single root // if we have only one if (!empty($trees) && !$trees instanceof LaravelCollection) { $trees = new LaravelCollection([$trees]); } return $this->respondWithSuccess($trees, new ContentTransformer); }
[ "public", "function", "indexTree", "(", "$", "id", "=", "null", ")", "{", "$", "this", "->", "authorize", "(", "'readList'", ",", "Content", "::", "class", ")", ";", "$", "input", "=", "$", "this", "->", "validator", "->", "validate", "(", "'tree'", ")", ";", "$", "params", "=", "$", "this", "->", "processor", "->", "process", "(", "$", "input", ")", "->", "getProcessedFields", "(", ")", ";", "$", "this", "->", "getSerializer", "(", ")", "->", "parseIncludes", "(", "'children'", ")", ";", "// We need to enable children include to return tree from api", "if", "(", "$", "id", ")", "{", "// Single tree", "$", "content", "=", "$", "this", "->", "repository", "->", "getById", "(", "$", "id", ")", ";", "if", "(", "!", "empty", "(", "$", "content", ")", ")", "{", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "this", "->", "repository", "->", "getTree", "(", "$", "content", ",", "$", "params", "[", "'filter'", "]", ",", "$", "params", "[", "'orderBy'", "]", ")", ",", "new", "ContentTransformer", ")", ";", "}", "else", "{", "return", "$", "this", "->", "respondNotFound", "(", ")", ";", "}", "}", "// All trees", "//$params['filter'] = array_merge(['type' => ['value' => 'category', 'relation' => null]], $params['filter']);", "$", "nodes", "=", "$", "this", "->", "repository", "->", "getContentsByLevel", "(", "$", "params", "[", "'filter'", "]", ",", "$", "params", "[", "'orderBy'", "]", ",", "null", ")", ";", "$", "trees", "=", "$", "this", "->", "repository", "->", "buildTree", "(", "$", "nodes", ")", ";", "// We need to guarantee LaravelCollection here because buildTree will return single root", "// if we have only one", "if", "(", "!", "empty", "(", "$", "trees", ")", "&&", "!", "$", "trees", "instanceof", "LaravelCollection", ")", "{", "$", "trees", "=", "new", "LaravelCollection", "(", "[", "$", "trees", "]", ")", ";", "}", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "trees", ",", "new", "ContentTransformer", ")", ";", "}" ]
Display a listing of the resource as nested tree. @param int|null $id Id used for nested resources @return \Illuminate\Http\JsonResponse
[ "Display", "a", "listing", "of", "the", "resource", "as", "nested", "tree", "." ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/ContentController.php#L132-L168
GrupaZero/api
src/Gzero/Api/Controller/Admin/ContentController.php
ContentController.show
public function show($id) { $content = $this->repository->getById($id); if (!empty($content)) { $this->authorize('read', $content); return $this->respondWithSuccess($content, new ContentTransformer); } return $this->respondNotFound(); }
php
public function show($id) { $content = $this->repository->getById($id); if (!empty($content)) { $this->authorize('read', $content); return $this->respondWithSuccess($content, new ContentTransformer); } return $this->respondNotFound(); }
[ "public", "function", "show", "(", "$", "id", ")", "{", "$", "content", "=", "$", "this", "->", "repository", "->", "getById", "(", "$", "id", ")", ";", "if", "(", "!", "empty", "(", "$", "content", ")", ")", "{", "$", "this", "->", "authorize", "(", "'read'", ",", "$", "content", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "content", ",", "new", "ContentTransformer", ")", ";", "}", "return", "$", "this", "->", "respondNotFound", "(", ")", ";", "}" ]
Display a specified resource. @param int $id Id of the resource @return \Illuminate\Http\JsonResponse
[ "Display", "a", "specified", "resource", "." ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/ContentController.php#L203-L211
GrupaZero/api
src/Gzero/Api/Controller/Admin/ContentController.php
ContentController.store
public function store() { $this->authorize('create', Content::class); $input = $this->validator->validate('create'); $content = $this->repository->create($input, auth()->user()); return $this->respondWithSuccess($content, new ContentTransformer); }
php
public function store() { $this->authorize('create', Content::class); $input = $this->validator->validate('create'); $content = $this->repository->create($input, auth()->user()); return $this->respondWithSuccess($content, new ContentTransformer); }
[ "public", "function", "store", "(", ")", "{", "$", "this", "->", "authorize", "(", "'create'", ",", "Content", "::", "class", ")", ";", "$", "input", "=", "$", "this", "->", "validator", "->", "validate", "(", "'create'", ")", ";", "$", "content", "=", "$", "this", "->", "repository", "->", "create", "(", "$", "input", ",", "auth", "(", ")", "->", "user", "(", ")", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "content", ",", "new", "ContentTransformer", ")", ";", "}" ]
Stores newly created content in database. @return \Illuminate\Http\JsonResponse
[ "Stores", "newly", "created", "content", "in", "database", "." ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/ContentController.php#L218-L224
GrupaZero/api
src/Gzero/Api/Controller/Admin/ContentController.php
ContentController.update
public function update($id) { $content = $this->repository->getById($id); if (!empty($content)) { $this->authorize('update', $content); $input = $this->validator->validate('update'); $content = $this->repository->update($content, $input, auth()->user()); return $this->respondWithSuccess($content, new ContentTransformer); } return $this->respondNotFound(); }
php
public function update($id) { $content = $this->repository->getById($id); if (!empty($content)) { $this->authorize('update', $content); $input = $this->validator->validate('update'); $content = $this->repository->update($content, $input, auth()->user()); return $this->respondWithSuccess($content, new ContentTransformer); } return $this->respondNotFound(); }
[ "public", "function", "update", "(", "$", "id", ")", "{", "$", "content", "=", "$", "this", "->", "repository", "->", "getById", "(", "$", "id", ")", ";", "if", "(", "!", "empty", "(", "$", "content", ")", ")", "{", "$", "this", "->", "authorize", "(", "'update'", ",", "$", "content", ")", ";", "$", "input", "=", "$", "this", "->", "validator", "->", "validate", "(", "'update'", ")", ";", "$", "content", "=", "$", "this", "->", "repository", "->", "update", "(", "$", "content", ",", "$", "input", ",", "auth", "(", ")", "->", "user", "(", ")", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "content", ",", "new", "ContentTransformer", ")", ";", "}", "return", "$", "this", "->", "respondNotFound", "(", ")", ";", "}" ]
Updates the specified resource in the database. @param int $id Content id @return \Illuminate\Http\JsonResponse
[ "Updates", "the", "specified", "resource", "in", "the", "database", "." ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/ContentController.php#L233-L243
GrupaZero/api
src/Gzero/Api/Controller/Admin/ContentController.php
ContentController.restore
public function restore($id) { $content = $this->repository->getDeletedById($id); if (!empty($content)) { $this->authorize('update', $content); $content->restore(); return $this->respondWithSimpleSuccess(['success' => true]); } return $this->respondNotFound(); }
php
public function restore($id) { $content = $this->repository->getDeletedById($id); if (!empty($content)) { $this->authorize('update', $content); $content->restore(); return $this->respondWithSimpleSuccess(['success' => true]); } return $this->respondNotFound(); }
[ "public", "function", "restore", "(", "$", "id", ")", "{", "$", "content", "=", "$", "this", "->", "repository", "->", "getDeletedById", "(", "$", "id", ")", ";", "if", "(", "!", "empty", "(", "$", "content", ")", ")", "{", "$", "this", "->", "authorize", "(", "'update'", ",", "$", "content", ")", ";", "$", "content", "->", "restore", "(", ")", ";", "return", "$", "this", "->", "respondWithSimpleSuccess", "(", "[", "'success'", "=>", "true", "]", ")", ";", "}", "return", "$", "this", "->", "respondNotFound", "(", ")", ";", "}" ]
Restore soft deleted content @param int $id Content id @return mixed
[ "Restore", "soft", "deleted", "content" ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/ContentController.php#L279-L288
GrupaZero/api
src/Gzero/Api/Controller/Admin/ContentController.php
ContentController.syncFiles
public function syncFiles($contentId) { $content = $this->repository->getById($contentId); if (empty($content)) { return $this->respondNotFound(); } $this->authorize('update', $content); $input = $this->validator->validate('syncFiles'); $content = $this->fileRepository->syncWith($content, $this->buildSyncData($input)); return $this->respondWithSuccess($content); }
php
public function syncFiles($contentId) { $content = $this->repository->getById($contentId); if (empty($content)) { return $this->respondNotFound(); } $this->authorize('update', $content); $input = $this->validator->validate('syncFiles'); $content = $this->fileRepository->syncWith($content, $this->buildSyncData($input)); return $this->respondWithSuccess($content); }
[ "public", "function", "syncFiles", "(", "$", "contentId", ")", "{", "$", "content", "=", "$", "this", "->", "repository", "->", "getById", "(", "$", "contentId", ")", ";", "if", "(", "empty", "(", "$", "content", ")", ")", "{", "return", "$", "this", "->", "respondNotFound", "(", ")", ";", "}", "$", "this", "->", "authorize", "(", "'update'", ",", "$", "content", ")", ";", "$", "input", "=", "$", "this", "->", "validator", "->", "validate", "(", "'syncFiles'", ")", ";", "$", "content", "=", "$", "this", "->", "fileRepository", "->", "syncWith", "(", "$", "content", ",", "$", "this", "->", "buildSyncData", "(", "$", "input", ")", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "content", ")", ";", "}" ]
Sync files with specific content @param int $contentId Content id @return mixed
[ "Sync", "files", "with", "specific", "content" ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/ContentController.php#L297-L307
GrupaZero/api
src/Gzero/Api/Controller/Admin/ContentController.php
ContentController.buildSyncData
protected function buildSyncData(array $input) { $syncData = []; foreach ($input['data'] as $item) { $syncData[$item['id']] = ['weight' => isset($item['weight']) ? $item['weight'] : 0]; } return $syncData; }
php
protected function buildSyncData(array $input) { $syncData = []; foreach ($input['data'] as $item) { $syncData[$item['id']] = ['weight' => isset($item['weight']) ? $item['weight'] : 0]; } return $syncData; }
[ "protected", "function", "buildSyncData", "(", "array", "$", "input", ")", "{", "$", "syncData", "=", "[", "]", ";", "foreach", "(", "$", "input", "[", "'data'", "]", "as", "$", "item", ")", "{", "$", "syncData", "[", "$", "item", "[", "'id'", "]", "]", "=", "[", "'weight'", "=>", "isset", "(", "$", "item", "[", "'weight'", "]", ")", "?", "$", "item", "[", "'weight'", "]", ":", "0", "]", ";", "}", "return", "$", "syncData", ";", "}" ]
It builds syncData @param array $input Validated input @return mixed
[ "It", "builds", "syncData" ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/ContentController.php#L316-L323
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.store
public function store( $id, $data, $attributes = array() ) { // Generate the Identifier $identifier = $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; if ( isset( $this->registry[$location][$id][$identifier] ) ) { unset( $this->registry[$location][$id][$identifier] ); } // Prepare the data $dataStr = $this->prepareData( $data ); // Store the data $this->registerIdentifier( $id, $attributes, $identifier ); if ( !$this->backend->store( $identifier, $dataStr, $this->properties['options']['ttl'] ) ) { $exceptionClass = "ezcCache{$this->backendName}Exception"; throw new $exceptionClass( "{$this->backendName} store failed." ); } return $id; }
php
public function store( $id, $data, $attributes = array() ) { // Generate the Identifier $identifier = $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; if ( isset( $this->registry[$location][$id][$identifier] ) ) { unset( $this->registry[$location][$id][$identifier] ); } // Prepare the data $dataStr = $this->prepareData( $data ); // Store the data $this->registerIdentifier( $id, $attributes, $identifier ); if ( !$this->backend->store( $identifier, $dataStr, $this->properties['options']['ttl'] ) ) { $exceptionClass = "ezcCache{$this->backendName}Exception"; throw new $exceptionClass( "{$this->backendName} store failed." ); } return $id; }
[ "public", "function", "store", "(", "$", "id", ",", "$", "data", ",", "$", "attributes", "=", "array", "(", ")", ")", "{", "// Generate the Identifier", "$", "identifier", "=", "$", "this", "->", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", ")", ";", "$", "location", "=", "$", "this", "->", "properties", "[", "'location'", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", ")", ";", "}", "// Prepare the data", "$", "dataStr", "=", "$", "this", "->", "prepareData", "(", "$", "data", ")", ";", "// Store the data", "$", "this", "->", "registerIdentifier", "(", "$", "id", ",", "$", "attributes", ",", "$", "identifier", ")", ";", "if", "(", "!", "$", "this", "->", "backend", "->", "store", "(", "$", "identifier", ",", "$", "dataStr", ",", "$", "this", "->", "properties", "[", "'options'", "]", "[", "'ttl'", "]", ")", ")", "{", "$", "exceptionClass", "=", "\"ezcCache{$this->backendName}Exception\"", ";", "throw", "new", "$", "exceptionClass", "(", "\"{$this->backendName} store failed.\"", ")", ";", "}", "return", "$", "id", ";", "}" ]
Stores data to the cache storage under the key $id. The type of cache data which is expected by an ezcCacheStorageMemory implementation depends on the backend. In most cases strings and arrays will be accepted, in some rare cases only strings might be accepted. Using attributes you can describe your cache data further. This allows you to deal with multiple cache data at once later. Some ezcCacheStorageMemory implementations also use the attributes for storage purposes. Attributes form some kind of "extended ID". @return string The ID string of the newly cached data @param string $id Unique identifier for the data @param mixed $data The data to store @param array(string=>string) $attributes Attributes describing the cached data
[ "Stores", "data", "to", "the", "cache", "storage", "under", "the", "key", "$id", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L112-L135
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.restore
public function restore( $id, $attributes = array(), $search = false ) { // Generate the Identifier $identifier = $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; // Creates a registry object if ( !isset( $this->registry[$location][$id][$identifier] ) ) { if ( !isset( $this->registry[$location] ) ) { $this->registry[$location] = array(); } if ( !isset( $this->registry[$location][$id] ) ) { $this->registry[$location][$id] = array(); } $this->registry[$location][$id][$identifier] = $this->fetchData( $identifier, true ); } // Makes sure a cache exists if ( $this->registry[$location][$id][$identifier] === false ) { if ( $search === true && count( $identifiers = $this->search( $id, $attributes ) ) === 1 ) { $identifier = $identifiers[0][2]; $this->registry[$location][$id][$identifier] = $this->fetchData( $identifier, true ); } else { // There are more elements found during search, so false is returned return false; } } // Make sure the data is not supposed to be expired if ( $this->properties['options']['ttl'] !== false && $this->calcLifetime( $identifier, $this->registry[$location][$id][$identifier] ) == 0 ) { $this->delete( $id, $attributes, false ); return false; } // Return the data $data = is_object( $this->registry[$location][$id][$identifier] ) ? $this->registry[$location][$id][$identifier]->data : false; if ( $data !== false ) { return $data; } else { return false; } }
php
public function restore( $id, $attributes = array(), $search = false ) { // Generate the Identifier $identifier = $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; // Creates a registry object if ( !isset( $this->registry[$location][$id][$identifier] ) ) { if ( !isset( $this->registry[$location] ) ) { $this->registry[$location] = array(); } if ( !isset( $this->registry[$location][$id] ) ) { $this->registry[$location][$id] = array(); } $this->registry[$location][$id][$identifier] = $this->fetchData( $identifier, true ); } // Makes sure a cache exists if ( $this->registry[$location][$id][$identifier] === false ) { if ( $search === true && count( $identifiers = $this->search( $id, $attributes ) ) === 1 ) { $identifier = $identifiers[0][2]; $this->registry[$location][$id][$identifier] = $this->fetchData( $identifier, true ); } else { // There are more elements found during search, so false is returned return false; } } // Make sure the data is not supposed to be expired if ( $this->properties['options']['ttl'] !== false && $this->calcLifetime( $identifier, $this->registry[$location][$id][$identifier] ) == 0 ) { $this->delete( $id, $attributes, false ); return false; } // Return the data $data = is_object( $this->registry[$location][$id][$identifier] ) ? $this->registry[$location][$id][$identifier]->data : false; if ( $data !== false ) { return $data; } else { return false; } }
[ "public", "function", "restore", "(", "$", "id", ",", "$", "attributes", "=", "array", "(", ")", ",", "$", "search", "=", "false", ")", "{", "// Generate the Identifier", "$", "identifier", "=", "$", "this", "->", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", ")", ";", "$", "location", "=", "$", "this", "->", "properties", "[", "'location'", "]", ";", "// Creates a registry object", "if", "(", "!", "isset", "(", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "registry", "[", "$", "location", "]", ")", ")", "{", "$", "this", "->", "registry", "[", "$", "location", "]", "=", "array", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", ")", ")", "{", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", "=", "$", "this", "->", "fetchData", "(", "$", "identifier", ",", "true", ")", ";", "}", "// Makes sure a cache exists", "if", "(", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", "===", "false", ")", "{", "if", "(", "$", "search", "===", "true", "&&", "count", "(", "$", "identifiers", "=", "$", "this", "->", "search", "(", "$", "id", ",", "$", "attributes", ")", ")", "===", "1", ")", "{", "$", "identifier", "=", "$", "identifiers", "[", "0", "]", "[", "2", "]", ";", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", "=", "$", "this", "->", "fetchData", "(", "$", "identifier", ",", "true", ")", ";", "}", "else", "{", "// There are more elements found during search, so false is returned", "return", "false", ";", "}", "}", "// Make sure the data is not supposed to be expired", "if", "(", "$", "this", "->", "properties", "[", "'options'", "]", "[", "'ttl'", "]", "!==", "false", "&&", "$", "this", "->", "calcLifetime", "(", "$", "identifier", ",", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", ")", "==", "0", ")", "{", "$", "this", "->", "delete", "(", "$", "id", ",", "$", "attributes", ",", "false", ")", ";", "return", "false", ";", "}", "// Return the data", "$", "data", "=", "is_object", "(", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", ")", "?", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", "->", "data", ":", "false", ";", "if", "(", "$", "data", "!==", "false", ")", "{", "return", "$", "data", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Restores the data from the cache. During access to cached data the caches are automatically expired. This means, that the ezcCacheStorageMemory object checks before returning the data if it's still actual. If the cache has expired, data will be deleted and false is returned. You should always provide the attributes you assigned, although the cache storages must be able to find a cache ID even without them. BEWARE: Finding cache data only by ID can be much slower than finding it by ID and attributes. @param string $id The item ID to restore @param array(string=>string) $attributes Attributes describing the data to restore @param bool $search Whether to search for items if not found directly @return mixed The cached data on success, otherwise false
[ "Restores", "the", "data", "from", "the", "cache", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L155-L209
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.delete
public function delete( $id = null, $attributes = array(), $search = false ) { // Generate the Identifier $identifier = $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; // Finds the caches that require deletion $delCaches = array(); if ( $this->fetchData( $identifier ) !== false ) { $delCaches[] = array( $id, $attributes, $identifier ); } else if ( $search === true ) { $delCaches = $this->search( $id, $attributes ); } $deletedIds = array(); // Process the caches to delete $identifiers = array(); foreach ( $delCaches as $cache ) { $this->backend->delete( $cache[2] ); $deletedIds[] = $cache[0]; $this->unRegisterIdentifier( $cache[0], $cache[1], $cache[2], true ); if ( isset( $this->registry[$location][$cache[0]][$cache[2]] ) ) { unset( $this->registry[$location][$cache[0]][$cache[2]] ); } } $this->storeSearchRegistry(); return $deletedIds; }
php
public function delete( $id = null, $attributes = array(), $search = false ) { // Generate the Identifier $identifier = $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; // Finds the caches that require deletion $delCaches = array(); if ( $this->fetchData( $identifier ) !== false ) { $delCaches[] = array( $id, $attributes, $identifier ); } else if ( $search === true ) { $delCaches = $this->search( $id, $attributes ); } $deletedIds = array(); // Process the caches to delete $identifiers = array(); foreach ( $delCaches as $cache ) { $this->backend->delete( $cache[2] ); $deletedIds[] = $cache[0]; $this->unRegisterIdentifier( $cache[0], $cache[1], $cache[2], true ); if ( isset( $this->registry[$location][$cache[0]][$cache[2]] ) ) { unset( $this->registry[$location][$cache[0]][$cache[2]] ); } } $this->storeSearchRegistry(); return $deletedIds; }
[ "public", "function", "delete", "(", "$", "id", "=", "null", ",", "$", "attributes", "=", "array", "(", ")", ",", "$", "search", "=", "false", ")", "{", "// Generate the Identifier", "$", "identifier", "=", "$", "this", "->", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", ")", ";", "$", "location", "=", "$", "this", "->", "properties", "[", "'location'", "]", ";", "// Finds the caches that require deletion", "$", "delCaches", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "fetchData", "(", "$", "identifier", ")", "!==", "false", ")", "{", "$", "delCaches", "[", "]", "=", "array", "(", "$", "id", ",", "$", "attributes", ",", "$", "identifier", ")", ";", "}", "else", "if", "(", "$", "search", "===", "true", ")", "{", "$", "delCaches", "=", "$", "this", "->", "search", "(", "$", "id", ",", "$", "attributes", ")", ";", "}", "$", "deletedIds", "=", "array", "(", ")", ";", "// Process the caches to delete", "$", "identifiers", "=", "array", "(", ")", ";", "foreach", "(", "$", "delCaches", "as", "$", "cache", ")", "{", "$", "this", "->", "backend", "->", "delete", "(", "$", "cache", "[", "2", "]", ")", ";", "$", "deletedIds", "[", "]", "=", "$", "cache", "[", "0", "]", ";", "$", "this", "->", "unRegisterIdentifier", "(", "$", "cache", "[", "0", "]", ",", "$", "cache", "[", "1", "]", ",", "$", "cache", "[", "2", "]", ",", "true", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "cache", "[", "0", "]", "]", "[", "$", "cache", "[", "2", "]", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "cache", "[", "0", "]", "]", "[", "$", "cache", "[", "2", "]", "]", ")", ";", "}", "}", "$", "this", "->", "storeSearchRegistry", "(", ")", ";", "return", "$", "deletedIds", ";", "}" ]
Deletes the data associated with $id or $attributes from the cache. Additional attributes provided will matched additionally. This can give you an immense speed improvement against just searching for ID (see {@link ezcCacheStorage::restore()}). If you only provide attributes for deletion of cache data, all cache data matching these attributes will be purged. @throws ezcBaseFilePermissionException If an already existsing cache file could not be unlinked. This exception means most likely that your cache directory has been corrupted by external influences (file permission change). @param string $id The item ID to purge @param array(string=>string) $attributes Attributes describing the data to restore @param bool $search Whether to search for items if not found directly
[ "Deletes", "the", "data", "associated", "with", "$id", "or", "$attributes", "from", "the", "cache", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L231-L265
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.getRemainingLifetime
public function getRemainingLifetime( $id, $attributes = array() ) { if ( count( $found = $this->search( $id, $attributes ) ) > 0 ) { $identifier = $found[0][2]; return $this->calcLifetime( $identifier ); } return 0; }
php
public function getRemainingLifetime( $id, $attributes = array() ) { if ( count( $found = $this->search( $id, $attributes ) ) > 0 ) { $identifier = $found[0][2]; return $this->calcLifetime( $identifier ); } return 0; }
[ "public", "function", "getRemainingLifetime", "(", "$", "id", ",", "$", "attributes", "=", "array", "(", ")", ")", "{", "if", "(", "count", "(", "$", "found", "=", "$", "this", "->", "search", "(", "$", "id", ",", "$", "attributes", ")", ")", ">", "0", ")", "{", "$", "identifier", "=", "$", "found", "[", "0", "]", "[", "2", "]", ";", "return", "$", "this", "->", "calcLifetime", "(", "$", "identifier", ")", ";", "}", "return", "0", ";", "}" ]
Returns the time in seconds which remains for a cache object, before it gets outdated. In case the cache object is already outdated or does not exists, this method returns 0. @param string $id The item ID @param array(string=>string) $attributes Attributes describing the data @return int The remaining lifetime (0 if it does not exist or outdated)
[ "Returns", "the", "time", "in", "seconds", "which", "remains", "for", "a", "cache", "object", "before", "it", "gets", "outdated", ".", "In", "case", "the", "cache", "object", "is", "already", "outdated", "or", "does", "not", "exists", "this", "method", "returns", "0", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L291-L299
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.generateIdentifier
public function generateIdentifier( $id, $attributes = null ) { $identifier = strtolower( $this->backendName ) . $this->properties['location'] . $id . ( ( $attributes !== null && !empty( $attributes ) ) ? md5( serialize( $attributes ) ) : '' ); return urlencode( $identifier ); }
php
public function generateIdentifier( $id, $attributes = null ) { $identifier = strtolower( $this->backendName ) . $this->properties['location'] . $id . ( ( $attributes !== null && !empty( $attributes ) ) ? md5( serialize( $attributes ) ) : '' ); return urlencode( $identifier ); }
[ "public", "function", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", "=", "null", ")", "{", "$", "identifier", "=", "strtolower", "(", "$", "this", "->", "backendName", ")", ".", "$", "this", "->", "properties", "[", "'location'", "]", ".", "$", "id", ".", "(", "(", "$", "attributes", "!==", "null", "&&", "!", "empty", "(", "$", "attributes", ")", ")", "?", "md5", "(", "serialize", "(", "$", "attributes", ")", ")", ":", "''", ")", ";", "return", "urlencode", "(", "$", "identifier", ")", ";", "}" ]
Generates the storage internal identifier from ID and attributes. @param string $id The ID @param array(string=>string) $attributes Attributes describing the data @return string The generated identifier
[ "Generates", "the", "storage", "internal", "identifier", "from", "ID", "and", "attributes", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L308-L319
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.purge
public function purge( $limit = null ) { $this->fetchSearchRegistry( true ); $purgedIds = array(); $ttl = $this->properties['options']->ttl; foreach ( $this->searchRegistry[$this->properties['location']] as $id => $identifiers ) { $deleted = false; foreach( $identifiers as $identifier => $data ) { if ( $ttl !== false && $this->calcLifetime( $identifier ) == 0 ) { // Since ID <-> identifier mapping is ambigious, this does // not ensure that all data for an ID is deleted. However, // this should work if used properly $this->backend->delete( $identifier ); $this->unRegisterIdentifier( null, null, $identifiers, true ); // Avoid adding an ID twice to the returned array $deleted = true; } } if ( $deleted === true ) { $purgedIds[] = $id; } if ( $limit !== null && count( $purgedIds ) >= $limit ) { break; } } $this->storeSearchRegistry(); return $purgedIds; }
php
public function purge( $limit = null ) { $this->fetchSearchRegistry( true ); $purgedIds = array(); $ttl = $this->properties['options']->ttl; foreach ( $this->searchRegistry[$this->properties['location']] as $id => $identifiers ) { $deleted = false; foreach( $identifiers as $identifier => $data ) { if ( $ttl !== false && $this->calcLifetime( $identifier ) == 0 ) { // Since ID <-> identifier mapping is ambigious, this does // not ensure that all data for an ID is deleted. However, // this should work if used properly $this->backend->delete( $identifier ); $this->unRegisterIdentifier( null, null, $identifiers, true ); // Avoid adding an ID twice to the returned array $deleted = true; } } if ( $deleted === true ) { $purgedIds[] = $id; } if ( $limit !== null && count( $purgedIds ) >= $limit ) { break; } } $this->storeSearchRegistry(); return $purgedIds; }
[ "public", "function", "purge", "(", "$", "limit", "=", "null", ")", "{", "$", "this", "->", "fetchSearchRegistry", "(", "true", ")", ";", "$", "purgedIds", "=", "array", "(", ")", ";", "$", "ttl", "=", "$", "this", "->", "properties", "[", "'options'", "]", "->", "ttl", ";", "foreach", "(", "$", "this", "->", "searchRegistry", "[", "$", "this", "->", "properties", "[", "'location'", "]", "]", "as", "$", "id", "=>", "$", "identifiers", ")", "{", "$", "deleted", "=", "false", ";", "foreach", "(", "$", "identifiers", "as", "$", "identifier", "=>", "$", "data", ")", "{", "if", "(", "$", "ttl", "!==", "false", "&&", "$", "this", "->", "calcLifetime", "(", "$", "identifier", ")", "==", "0", ")", "{", "// Since ID <-> identifier mapping is ambigious, this does", "// not ensure that all data for an ID is deleted. However,", "// this should work if used properly", "$", "this", "->", "backend", "->", "delete", "(", "$", "identifier", ")", ";", "$", "this", "->", "unRegisterIdentifier", "(", "null", ",", "null", ",", "$", "identifiers", ",", "true", ")", ";", "// Avoid adding an ID twice to the returned array", "$", "deleted", "=", "true", ";", "}", "}", "if", "(", "$", "deleted", "===", "true", ")", "{", "$", "purgedIds", "[", "]", "=", "$", "id", ";", "}", "if", "(", "$", "limit", "!==", "null", "&&", "count", "(", "$", "purgedIds", ")", ">=", "$", "limit", ")", "{", "break", ";", "}", "}", "$", "this", "->", "storeSearchRegistry", "(", ")", ";", "return", "$", "purgedIds", ";", "}" ]
Purge outdated data from the storage. This method purges outdated data from the cache. If $limit is given, a maximum of $limit items is purged. Otherwise all outdated items are purged. The method returns an array containing the IDs of all cache items that have been purged. @param int $limit @return array(string)
[ "Purge", "outdated", "data", "from", "the", "storage", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L332-L366
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.reset
public function reset() { $this->backend->reset(); $this->registry = array(); $this->searchRegistry = array( $this->properties['location'] => null ); $this->storeSearchRegistry(); }
php
public function reset() { $this->backend->reset(); $this->registry = array(); $this->searchRegistry = array( $this->properties['location'] => null ); $this->storeSearchRegistry(); }
[ "public", "function", "reset", "(", ")", "{", "$", "this", "->", "backend", "->", "reset", "(", ")", ";", "$", "this", "->", "registry", "=", "array", "(", ")", ";", "$", "this", "->", "searchRegistry", "=", "array", "(", "$", "this", "->", "properties", "[", "'location'", "]", "=>", "null", ")", ";", "$", "this", "->", "storeSearchRegistry", "(", ")", ";", "}" ]
Reset the complete storage. This method resets the complete cache storage. All content (including content stored with the {@link ezcCacheStackMetaDataStorage} interfacer) must be deleted and the cache storage must appear as if it has just newly been created. @return void
[ "Reset", "the", "complete", "storage", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L378-L384
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.restoreMetaData
public function restoreMetaData() { $metaDataKey = urlencode( $this->properties['location'] ) . '_' . $this->properties['options']->metaDataKey; if ( ( $data = $this->backend->fetch( $metaDataKey ) ) === false ) { $data = null; } return $data; }
php
public function restoreMetaData() { $metaDataKey = urlencode( $this->properties['location'] ) . '_' . $this->properties['options']->metaDataKey; if ( ( $data = $this->backend->fetch( $metaDataKey ) ) === false ) { $data = null; } return $data; }
[ "public", "function", "restoreMetaData", "(", ")", "{", "$", "metaDataKey", "=", "urlencode", "(", "$", "this", "->", "properties", "[", "'location'", "]", ")", ".", "'_'", ".", "$", "this", "->", "properties", "[", "'options'", "]", "->", "metaDataKey", ";", "if", "(", "(", "$", "data", "=", "$", "this", "->", "backend", "->", "fetch", "(", "$", "metaDataKey", ")", ")", "===", "false", ")", "{", "$", "data", "=", "null", ";", "}", "return", "$", "data", ";", "}" ]
Restores and returns the meta data struct. This method fetches the meta data stored in the storage and returns the according struct of type {@link ezcCacheStackMetaData}. The meta data must be stored inside the storage, but should not be visible as normal cache items to the user. @return ezcCacheStackMetaData
[ "Restores", "and", "returns", "the", "meta", "data", "struct", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L396-L406
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.storeMetaData
public function storeMetaData( ezcCacheStackMetaData $metaData ) { $metaDataKey = urlencode( $this->properties['location'] ) . '_' . $this->properties['options']->metaDataKey; $this->backend->store( $metaDataKey, $metaData ); }
php
public function storeMetaData( ezcCacheStackMetaData $metaData ) { $metaDataKey = urlencode( $this->properties['location'] ) . '_' . $this->properties['options']->metaDataKey; $this->backend->store( $metaDataKey, $metaData ); }
[ "public", "function", "storeMetaData", "(", "ezcCacheStackMetaData", "$", "metaData", ")", "{", "$", "metaDataKey", "=", "urlencode", "(", "$", "this", "->", "properties", "[", "'location'", "]", ")", ".", "'_'", ".", "$", "this", "->", "properties", "[", "'options'", "]", "->", "metaDataKey", ";", "$", "this", "->", "backend", "->", "store", "(", "$", "metaDataKey", ",", "$", "metaData", ")", ";", "}" ]
Stores the given meta data struct. This method stores the given $metaData inside the storage. The data must be stored with the same mechanism that the storage itself uses. However, it should not be stored as a normal cache item, if possible, to avoid accedental user manipulation. @param ezcCacheStackMetaData $metaData @return void
[ "Stores", "the", "given", "meta", "data", "struct", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L419-L428
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.lock
public function lock() { $lockKey = urlencode( $this->properties['location'] ) . '_' . $this->properties['options']->lockKey; $this->backend->acquireLock( $lockKey, $this->properties['options']->lockWaitTime, $this->properties['options']->maxLockTime ); $this->lock = true; }
php
public function lock() { $lockKey = urlencode( $this->properties['location'] ) . '_' . $this->properties['options']->lockKey; $this->backend->acquireLock( $lockKey, $this->properties['options']->lockWaitTime, $this->properties['options']->maxLockTime ); $this->lock = true; }
[ "public", "function", "lock", "(", ")", "{", "$", "lockKey", "=", "urlencode", "(", "$", "this", "->", "properties", "[", "'location'", "]", ")", ".", "'_'", ".", "$", "this", "->", "properties", "[", "'options'", "]", "->", "lockKey", ";", "$", "this", "->", "backend", "->", "acquireLock", "(", "$", "lockKey", ",", "$", "this", "->", "properties", "[", "'options'", "]", "->", "lockWaitTime", ",", "$", "this", "->", "properties", "[", "'options'", "]", "->", "maxLockTime", ")", ";", "$", "this", "->", "lock", "=", "true", ";", "}" ]
Acquire a lock on the storage. This method acquires a lock on the storage. If locked, the storage must block all other method calls until the lock is freed again using {@link ezcCacheStackMetaDataStorage::unlock()}. Methods that are called within the request that successfully acquired the lock must succeed as usual. @return void
[ "Acquire", "a", "lock", "on", "the", "storage", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L440-L450
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.unlock
public function unlock() { if ( $this->lock !== false ) { $lockKey = urlencode( $this->properties['location'] ) . '_' . $this->properties['options']->lockKey; $this->backend->releaseLock( $lockKey ); $this->lock = false; } }
php
public function unlock() { if ( $this->lock !== false ) { $lockKey = urlencode( $this->properties['location'] ) . '_' . $this->properties['options']->lockKey; $this->backend->releaseLock( $lockKey ); $this->lock = false; } }
[ "public", "function", "unlock", "(", ")", "{", "if", "(", "$", "this", "->", "lock", "!==", "false", ")", "{", "$", "lockKey", "=", "urlencode", "(", "$", "this", "->", "properties", "[", "'location'", "]", ")", ".", "'_'", ".", "$", "this", "->", "properties", "[", "'options'", "]", "->", "lockKey", ";", "$", "this", "->", "backend", "->", "releaseLock", "(", "$", "lockKey", ")", ";", "$", "this", "->", "lock", "=", "false", ";", "}", "}" ]
Release a lock on the storage. This method releases the lock of the storage, that has been acquired via {@link ezcCacheStackMetaDataStorage::lock()}. After this method has been called, blocked method calls (including calls to lock()) can suceed again. @return void
[ "Release", "a", "lock", "on", "the", "storage", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L462-L473
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.calcLifetime
protected function calcLifetime( $identifier, $dataObject = false ) { $ttl = $this->options->ttl; $dataObject = is_object( $dataObject ) ? $dataObject : $this->fetchData ( $identifier, true ); if ( is_object( $dataObject ) ) { if ( $ttl === false ) { return 1; } return ( ( $lifeTime = ( time() - $dataObject->time ) < $ttl ) ? $ttl - $lifeTime : 0 ); } else { return 0; } }
php
protected function calcLifetime( $identifier, $dataObject = false ) { $ttl = $this->options->ttl; $dataObject = is_object( $dataObject ) ? $dataObject : $this->fetchData ( $identifier, true ); if ( is_object( $dataObject ) ) { if ( $ttl === false ) { return 1; } return ( ( $lifeTime = ( time() - $dataObject->time ) < $ttl ) ? $ttl - $lifeTime : 0 ); } else { return 0; } }
[ "protected", "function", "calcLifetime", "(", "$", "identifier", ",", "$", "dataObject", "=", "false", ")", "{", "$", "ttl", "=", "$", "this", "->", "options", "->", "ttl", ";", "$", "dataObject", "=", "is_object", "(", "$", "dataObject", ")", "?", "$", "dataObject", ":", "$", "this", "->", "fetchData", "(", "$", "identifier", ",", "true", ")", ";", "if", "(", "is_object", "(", "$", "dataObject", ")", ")", "{", "if", "(", "$", "ttl", "===", "false", ")", "{", "return", "1", ";", "}", "return", "(", "(", "$", "lifeTime", "=", "(", "time", "(", ")", "-", "$", "dataObject", "->", "time", ")", "<", "$", "ttl", ")", "?", "$", "ttl", "-", "$", "lifeTime", ":", "0", ")", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Calculates the lifetime remaining for a cache object. In case the TTL options is set to true, this method always returns 1. @param string $identifier The memcache identifier @param bool $dataObject The optional data object for which to calculate the lifetime @return int The remaining lifetime in seconds (0 if no time remaining)
[ "Calculates", "the", "lifetime", "remaining", "for", "a", "cache", "object", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L484-L504
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.registerIdentifier
protected function registerIdentifier( $id = null, $attributes = array(), $identifier = null ) { $identifier = ( $identifier !== null ) ? $identifier : $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; $this->fetchSearchRegistry(); // Makes sure the identifier exists if ( !isset( $this->searchRegistry[$location][$id][$identifier] ) ) { // Makes sure the id exists if ( !isset( $this->searchRegistry[$location][$id] ) || !is_array( $this->searchRegistry[$location][$id] ) ) { $this->searchRegistry[$location][$id] = array(); } $this->searchRegistry[$location][$id][$identifier] = new ezcCacheStorageMemoryRegisterStruct( $id, $attributes, $identifier, $location ); $this->storeSearchRegistry(); } }
php
protected function registerIdentifier( $id = null, $attributes = array(), $identifier = null ) { $identifier = ( $identifier !== null ) ? $identifier : $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; $this->fetchSearchRegistry(); // Makes sure the identifier exists if ( !isset( $this->searchRegistry[$location][$id][$identifier] ) ) { // Makes sure the id exists if ( !isset( $this->searchRegistry[$location][$id] ) || !is_array( $this->searchRegistry[$location][$id] ) ) { $this->searchRegistry[$location][$id] = array(); } $this->searchRegistry[$location][$id][$identifier] = new ezcCacheStorageMemoryRegisterStruct( $id, $attributes, $identifier, $location ); $this->storeSearchRegistry(); } }
[ "protected", "function", "registerIdentifier", "(", "$", "id", "=", "null", ",", "$", "attributes", "=", "array", "(", ")", ",", "$", "identifier", "=", "null", ")", "{", "$", "identifier", "=", "(", "$", "identifier", "!==", "null", ")", "?", "$", "identifier", ":", "$", "this", "->", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", ")", ";", "$", "location", "=", "$", "this", "->", "properties", "[", "'location'", "]", ";", "$", "this", "->", "fetchSearchRegistry", "(", ")", ";", "// Makes sure the identifier exists", "if", "(", "!", "isset", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", ")", ")", "{", "// Makes sure the id exists", "if", "(", "!", "isset", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", ")", "||", "!", "is_array", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", ")", ")", "{", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", "=", "new", "ezcCacheStorageMemoryRegisterStruct", "(", "$", "id", ",", "$", "attributes", ",", "$", "identifier", ",", "$", "location", ")", ";", "$", "this", "->", "storeSearchRegistry", "(", ")", ";", "}", "}" ]
Registers an identifier to facilitate searching. @param string $id ID for the cache item @param array $attributes Attributes for the cache item @param string $identifier Identifier generated for the cache item
[ "Registers", "an", "identifier", "to", "facilitate", "searching", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L513-L533
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.unRegisterIdentifier
protected function unRegisterIdentifier( $id = null, $attributes = array(), $identifier = null, $delayStore = false ) { $identifier = ( $identifier !== null ) ? $identifier : $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; $this->fetchSearchRegistry( !$delayStore ); if ( $this->searchRegistry === false ) { $this->searchRegistry = array(); } if ( isset( $this->searchRegistry[$location][$id][$identifier] ) ) { unset( $this->searchRegistry[$location][$id][$identifier], $this->registry[$location][$id][$identifier] ); if ( $delayStore === false ) { $this->storeSearchRegistry(); } } }
php
protected function unRegisterIdentifier( $id = null, $attributes = array(), $identifier = null, $delayStore = false ) { $identifier = ( $identifier !== null ) ? $identifier : $this->generateIdentifier( $id, $attributes ); $location = $this->properties['location']; $this->fetchSearchRegistry( !$delayStore ); if ( $this->searchRegistry === false ) { $this->searchRegistry = array(); } if ( isset( $this->searchRegistry[$location][$id][$identifier] ) ) { unset( $this->searchRegistry[$location][$id][$identifier], $this->registry[$location][$id][$identifier] ); if ( $delayStore === false ) { $this->storeSearchRegistry(); } } }
[ "protected", "function", "unRegisterIdentifier", "(", "$", "id", "=", "null", ",", "$", "attributes", "=", "array", "(", ")", ",", "$", "identifier", "=", "null", ",", "$", "delayStore", "=", "false", ")", "{", "$", "identifier", "=", "(", "$", "identifier", "!==", "null", ")", "?", "$", "identifier", ":", "$", "this", "->", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", ")", ";", "$", "location", "=", "$", "this", "->", "properties", "[", "'location'", "]", ";", "$", "this", "->", "fetchSearchRegistry", "(", "!", "$", "delayStore", ")", ";", "if", "(", "$", "this", "->", "searchRegistry", "===", "false", ")", "{", "$", "this", "->", "searchRegistry", "=", "array", "(", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", ",", "$", "this", "->", "registry", "[", "$", "location", "]", "[", "$", "id", "]", "[", "$", "identifier", "]", ")", ";", "if", "(", "$", "delayStore", "===", "false", ")", "{", "$", "this", "->", "storeSearchRegistry", "(", ")", ";", "}", "}", "}" ]
Un-registers a previously registered identifier. @param string $id ID for the cache item @param array $attributes Attributes for the cache item @param string $identifier Identifier generated for the cache item @param bool $delayStore Delays the storing of the updated search registry
[ "Un", "-", "registers", "a", "previously", "registered", "identifier", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L543-L563
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.fetchSearchRegistry
protected function fetchSearchRegistry( $requireFresh = false ) { $location = $this->properties['location']; if ( !is_array( $this->searchRegistry ) ) { $this->searchRegistry = array(); } if ( !isset( $this->searchRegistry[$location] ) || !is_array( $this->searchRegistry[$location] ) ) { $this->searchRegistry[$location] = array(); } // Makes sure the registry exists if ( empty( $this->searchRegistry[$location] ) || $requireFresh === true ) { $this->searchRegistry[$location] = $this->backend->fetch( $this->registryName . '_' . urlencode( $location ) ); } }
php
protected function fetchSearchRegistry( $requireFresh = false ) { $location = $this->properties['location']; if ( !is_array( $this->searchRegistry ) ) { $this->searchRegistry = array(); } if ( !isset( $this->searchRegistry[$location] ) || !is_array( $this->searchRegistry[$location] ) ) { $this->searchRegistry[$location] = array(); } // Makes sure the registry exists if ( empty( $this->searchRegistry[$location] ) || $requireFresh === true ) { $this->searchRegistry[$location] = $this->backend->fetch( $this->registryName . '_' . urlencode( $location ) ); } }
[ "protected", "function", "fetchSearchRegistry", "(", "$", "requireFresh", "=", "false", ")", "{", "$", "location", "=", "$", "this", "->", "properties", "[", "'location'", "]", ";", "if", "(", "!", "is_array", "(", "$", "this", "->", "searchRegistry", ")", ")", "{", "$", "this", "->", "searchRegistry", "=", "array", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", ")", "||", "!", "is_array", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", ")", ")", "{", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "=", "array", "(", ")", ";", "}", "// Makes sure the registry exists", "if", "(", "empty", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", ")", "||", "$", "requireFresh", "===", "true", ")", "{", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "=", "$", "this", "->", "backend", "->", "fetch", "(", "$", "this", "->", "registryName", ".", "'_'", ".", "urlencode", "(", "$", "location", ")", ")", ";", "}", "}" ]
Fetches the search registry from the backend or creates it if empty. @param bool $requireFresh To create a new search registry or not
[ "Fetches", "the", "search", "registry", "from", "the", "backend", "or", "creates", "it", "if", "empty", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L570-L589
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.storeSearchRegistry
protected function storeSearchRegistry() { $location = $this->properties['location']; $this->backend->store( $this->registryName . '_' . urlencode( $location ), $this->searchRegistry[$location] ); $this->searchRegistry[$location] = null; $this->fetchSearchRegistry( true ); }
php
protected function storeSearchRegistry() { $location = $this->properties['location']; $this->backend->store( $this->registryName . '_' . urlencode( $location ), $this->searchRegistry[$location] ); $this->searchRegistry[$location] = null; $this->fetchSearchRegistry( true ); }
[ "protected", "function", "storeSearchRegistry", "(", ")", "{", "$", "location", "=", "$", "this", "->", "properties", "[", "'location'", "]", ";", "$", "this", "->", "backend", "->", "store", "(", "$", "this", "->", "registryName", ".", "'_'", ".", "urlencode", "(", "$", "location", ")", ",", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", ")", ";", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "=", "null", ";", "$", "this", "->", "fetchSearchRegistry", "(", "true", ")", ";", "}" ]
Stores the search registry in the backend.
[ "Stores", "the", "search", "registry", "in", "the", "backend", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L594-L602
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.generateAttrStr
protected function generateAttrStr( $attributes = array() ) { ksort( $attributes ); $attrStr = ''; foreach ( $attributes as $key => $val ) { $attrStr .= '-' . $key . '=' .$val; } return $attrStr; }
php
protected function generateAttrStr( $attributes = array() ) { ksort( $attributes ); $attrStr = ''; foreach ( $attributes as $key => $val ) { $attrStr .= '-' . $key . '=' .$val; } return $attrStr; }
[ "protected", "function", "generateAttrStr", "(", "$", "attributes", "=", "array", "(", ")", ")", "{", "ksort", "(", "$", "attributes", ")", ";", "$", "attrStr", "=", "''", ";", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "attrStr", ".=", "'-'", ".", "$", "key", ".", "'='", ".", "$", "val", ";", "}", "return", "$", "attrStr", ";", "}" ]
Generates a string from the $attributes array. @param array(string=>string) $attributes Attributes describing the data @return string @apichange Was only used to generate "pseudo-regex". Attribute arrays are compared directly now.
[ "Generates", "a", "string", "from", "the", "$attributes", "array", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L613-L622
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php
ezcCacheStorageMemory.search
protected function search( $id = null, $attributes = array() ) { // Grabs the identifier registry $this->fetchSearchRegistry(); // Grabs the $location $location = $this->properties['location']; // Finds all in case of empty $id and $attributes if ( $id === null && empty( $attributes ) && isset( $this->searchRegistry[$location] ) && is_array( $this->searchRegistry[$location] ) ) { $itemArr = array(); foreach ( $this->searchRegistry[$location] as $idArr ) { foreach ( $idArr as $registryObj ) { if ( !is_null( $registryObj->id ) ) { $itemArr[] = array( $registryObj->id, $registryObj->attributes, $registryObj->identifier ); } } } return $itemArr; } $itemArr = array(); // Makes sure we've seen this ID before if ( isset( $this->searchRegistry[$location][$id] ) && is_array( $this->searchRegistry[$location][$id] ) ) { foreach ( $this->searchRegistry[$location][$id] as $identifier => $dataArr ) { if ( $this->fetchData( $identifier ) !== false ) { $itemArr[] = array( $id, $attributes, $identifier ); } } } else { // Finds cache items that fit our description if ( isset( $this->searchRegistry[$location] ) && is_array( $this->searchRegistry[$location] ) ) { foreach ( $this->searchRegistry[$location] as $id => $arr ) { foreach ( $arr as $identifier => $registryObj ) { if ( count( array_diff_assoc( $attributes, $registryObj->attributes ) ) === 0 ) { $itemArr[] = array( $registryObj->id, $registryObj->attributes, $registryObj->identifier ); } } } } } return $itemArr; }
php
protected function search( $id = null, $attributes = array() ) { // Grabs the identifier registry $this->fetchSearchRegistry(); // Grabs the $location $location = $this->properties['location']; // Finds all in case of empty $id and $attributes if ( $id === null && empty( $attributes ) && isset( $this->searchRegistry[$location] ) && is_array( $this->searchRegistry[$location] ) ) { $itemArr = array(); foreach ( $this->searchRegistry[$location] as $idArr ) { foreach ( $idArr as $registryObj ) { if ( !is_null( $registryObj->id ) ) { $itemArr[] = array( $registryObj->id, $registryObj->attributes, $registryObj->identifier ); } } } return $itemArr; } $itemArr = array(); // Makes sure we've seen this ID before if ( isset( $this->searchRegistry[$location][$id] ) && is_array( $this->searchRegistry[$location][$id] ) ) { foreach ( $this->searchRegistry[$location][$id] as $identifier => $dataArr ) { if ( $this->fetchData( $identifier ) !== false ) { $itemArr[] = array( $id, $attributes, $identifier ); } } } else { // Finds cache items that fit our description if ( isset( $this->searchRegistry[$location] ) && is_array( $this->searchRegistry[$location] ) ) { foreach ( $this->searchRegistry[$location] as $id => $arr ) { foreach ( $arr as $identifier => $registryObj ) { if ( count( array_diff_assoc( $attributes, $registryObj->attributes ) ) === 0 ) { $itemArr[] = array( $registryObj->id, $registryObj->attributes, $registryObj->identifier ); } } } } } return $itemArr; }
[ "protected", "function", "search", "(", "$", "id", "=", "null", ",", "$", "attributes", "=", "array", "(", ")", ")", "{", "// Grabs the identifier registry", "$", "this", "->", "fetchSearchRegistry", "(", ")", ";", "// Grabs the $location", "$", "location", "=", "$", "this", "->", "properties", "[", "'location'", "]", ";", "// Finds all in case of empty $id and $attributes", "if", "(", "$", "id", "===", "null", "&&", "empty", "(", "$", "attributes", ")", "&&", "isset", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", ")", "&&", "is_array", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", ")", ")", "{", "$", "itemArr", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "as", "$", "idArr", ")", "{", "foreach", "(", "$", "idArr", "as", "$", "registryObj", ")", "{", "if", "(", "!", "is_null", "(", "$", "registryObj", "->", "id", ")", ")", "{", "$", "itemArr", "[", "]", "=", "array", "(", "$", "registryObj", "->", "id", ",", "$", "registryObj", "->", "attributes", ",", "$", "registryObj", "->", "identifier", ")", ";", "}", "}", "}", "return", "$", "itemArr", ";", "}", "$", "itemArr", "=", "array", "(", ")", ";", "// Makes sure we've seen this ID before", "if", "(", "isset", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", ")", "&&", "is_array", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "[", "$", "id", "]", "as", "$", "identifier", "=>", "$", "dataArr", ")", "{", "if", "(", "$", "this", "->", "fetchData", "(", "$", "identifier", ")", "!==", "false", ")", "{", "$", "itemArr", "[", "]", "=", "array", "(", "$", "id", ",", "$", "attributes", ",", "$", "identifier", ")", ";", "}", "}", "}", "else", "{", "// Finds cache items that fit our description", "if", "(", "isset", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", ")", "&&", "is_array", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "searchRegistry", "[", "$", "location", "]", "as", "$", "id", "=>", "$", "arr", ")", "{", "foreach", "(", "$", "arr", "as", "$", "identifier", "=>", "$", "registryObj", ")", "{", "if", "(", "count", "(", "array_diff_assoc", "(", "$", "attributes", ",", "$", "registryObj", "->", "attributes", ")", ")", "===", "0", ")", "{", "$", "itemArr", "[", "]", "=", "array", "(", "$", "registryObj", "->", "id", ",", "$", "registryObj", "->", "attributes", ",", "$", "registryObj", "->", "identifier", ")", ";", "}", "}", "}", "}", "}", "return", "$", "itemArr", ";", "}" ]
Searches the storage for data defined by ID and/or attributes. @param string $id The item ID @param array(string=>string) $attributes Attributes describing the data @return array(mixed)
[ "Searches", "the", "storage", "for", "data", "defined", "by", "ID", "and", "/", "or", "attributes", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/memory.php#L639-L703
interactivesolutions/honeycomb-core
src/http/controllers/HCBaseController.php
HCBaseController.apiStore
public function apiStore() { DB::beginTransaction(); try { $record = $this->__apiStore(); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0002' . $e->getCode(), $e->getMessage()); } DB::commit(); return response($record); }
php
public function apiStore() { DB::beginTransaction(); try { $record = $this->__apiStore(); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0002' . $e->getCode(), $e->getMessage()); } DB::commit(); return response($record); }
[ "public", "function", "apiStore", "(", ")", "{", "DB", "::", "beginTransaction", "(", ")", ";", "try", "{", "$", "record", "=", "$", "this", "->", "__apiStore", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "DB", "::", "rollback", "(", ")", ";", "return", "HCLog", "::", "error", "(", "'CORE-0002'", ".", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "DB", "::", "commit", "(", ")", ";", "return", "response", "(", "$", "record", ")", ";", "}" ]
Function which will store new record @return mixed
[ "Function", "which", "will", "store", "new", "record" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/http/controllers/HCBaseController.php#L100-L115
interactivesolutions/honeycomb-core
src/http/controllers/HCBaseController.php
HCBaseController.apiUpdate
public function apiUpdate(string $id) { DB::beginTransaction(); try { $record = $this->__apiUpdate($id); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0003' . $e->getCode(), $e->getMessage()); } DB::commit(); return $record; }
php
public function apiUpdate(string $id) { DB::beginTransaction(); try { $record = $this->__apiUpdate($id); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0003' . $e->getCode(), $e->getMessage()); } DB::commit(); return $record; }
[ "public", "function", "apiUpdate", "(", "string", "$", "id", ")", "{", "DB", "::", "beginTransaction", "(", ")", ";", "try", "{", "$", "record", "=", "$", "this", "->", "__apiUpdate", "(", "$", "id", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "DB", "::", "rollback", "(", ")", ";", "return", "HCLog", "::", "error", "(", "'CORE-0003'", ".", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "DB", "::", "commit", "(", ")", ";", "return", "$", "record", ";", "}" ]
Function which will update record @param $id @return mixed
[ "Function", "which", "will", "update", "record" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/http/controllers/HCBaseController.php#L138-L153
interactivesolutions/honeycomb-core
src/http/controllers/HCBaseController.php
HCBaseController.apiUpdateStrict
public function apiUpdateStrict(string $id) { DB::beginTransaction(); try { $record = $this->__apiUpdateStrict($id); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0003' . $e->getCode(), $e->getMessage()); } DB::commit(); return $record; }
php
public function apiUpdateStrict(string $id) { DB::beginTransaction(); try { $record = $this->__apiUpdateStrict($id); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0003' . $e->getCode(), $e->getMessage()); } DB::commit(); return $record; }
[ "public", "function", "apiUpdateStrict", "(", "string", "$", "id", ")", "{", "DB", "::", "beginTransaction", "(", ")", ";", "try", "{", "$", "record", "=", "$", "this", "->", "__apiUpdateStrict", "(", "$", "id", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "DB", "::", "rollback", "(", ")", ";", "return", "HCLog", "::", "error", "(", "'CORE-0003'", ".", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "DB", "::", "commit", "(", ")", ";", "return", "$", "record", ";", "}" ]
Function which will update specific values of the record @param $id @return mixed
[ "Function", "which", "will", "update", "specific", "values", "of", "the", "record" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/http/controllers/HCBaseController.php#L177-L192
interactivesolutions/honeycomb-core
src/http/controllers/HCBaseController.php
HCBaseController.initializeDelete
private function initializeDelete(string $id = null, bool $soft) { if ($id) $list = [$id]; else $list = request()->input('list'); if (sizeOf($list) <= 0) return HCLog::info('CORE-0004', trans('HCTranslations::core.nothing_to_delete')); DB::beginTransaction(); try { if ($soft) $response = $this->__apiDestroy($list); else $response = $this->__apiForceDelete($list); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0005' . $e->getCode(), $e->getMessage()); } DB::commit(); if (isset($response)) return $response; return ['success' => true, 'list' => $list]; }
php
private function initializeDelete(string $id = null, bool $soft) { if ($id) $list = [$id]; else $list = request()->input('list'); if (sizeOf($list) <= 0) return HCLog::info('CORE-0004', trans('HCTranslations::core.nothing_to_delete')); DB::beginTransaction(); try { if ($soft) $response = $this->__apiDestroy($list); else $response = $this->__apiForceDelete($list); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0005' . $e->getCode(), $e->getMessage()); } DB::commit(); if (isset($response)) return $response; return ['success' => true, 'list' => $list]; }
[ "private", "function", "initializeDelete", "(", "string", "$", "id", "=", "null", ",", "bool", "$", "soft", ")", "{", "if", "(", "$", "id", ")", "$", "list", "=", "[", "$", "id", "]", ";", "else", "$", "list", "=", "request", "(", ")", "->", "input", "(", "'list'", ")", ";", "if", "(", "sizeOf", "(", "$", "list", ")", "<=", "0", ")", "return", "HCLog", "::", "info", "(", "'CORE-0004'", ",", "trans", "(", "'HCTranslations::core.nothing_to_delete'", ")", ")", ";", "DB", "::", "beginTransaction", "(", ")", ";", "try", "{", "if", "(", "$", "soft", ")", "$", "response", "=", "$", "this", "->", "__apiDestroy", "(", "$", "list", ")", ";", "else", "$", "response", "=", "$", "this", "->", "__apiForceDelete", "(", "$", "list", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "DB", "::", "rollback", "(", ")", ";", "return", "HCLog", "::", "error", "(", "'CORE-0005'", ".", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "DB", "::", "commit", "(", ")", ";", "if", "(", "isset", "(", "$", "response", ")", ")", "return", "$", "response", ";", "return", "[", "'success'", "=>", "true", ",", "'list'", "=>", "$", "list", "]", ";", "}" ]
Function which will actually call deletion function @param string $id @param bool $soft @return array @internal param $callback
[ "Function", "which", "will", "actually", "call", "deletion", "function" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/http/controllers/HCBaseController.php#L245-L274
interactivesolutions/honeycomb-core
src/http/controllers/HCBaseController.php
HCBaseController.apiRestore
public function apiRestore() { $toRestore = request()->input('list'); if (sizeOf($toRestore) <= 0) return HCLog::info('CORE-0006', trans('HCTranslations::core.nothing_to_restore')); $response = $this->__apiRestore($toRestore); if (isset($response)) return $response; return ['success' => true, 'list' => $toRestore]; }
php
public function apiRestore() { $toRestore = request()->input('list'); if (sizeOf($toRestore) <= 0) return HCLog::info('CORE-0006', trans('HCTranslations::core.nothing_to_restore')); $response = $this->__apiRestore($toRestore); if (isset($response)) return $response; return ['success' => true, 'list' => $toRestore]; }
[ "public", "function", "apiRestore", "(", ")", "{", "$", "toRestore", "=", "request", "(", ")", "->", "input", "(", "'list'", ")", ";", "if", "(", "sizeOf", "(", "$", "toRestore", ")", "<=", "0", ")", "return", "HCLog", "::", "info", "(", "'CORE-0006'", ",", "trans", "(", "'HCTranslations::core.nothing_to_restore'", ")", ")", ";", "$", "response", "=", "$", "this", "->", "__apiRestore", "(", "$", "toRestore", ")", ";", "if", "(", "isset", "(", "$", "response", ")", ")", "return", "$", "response", ";", "return", "[", "'success'", "=>", "true", ",", "'list'", "=>", "$", "toRestore", "]", ";", "}" ]
Recovers items from database by given id's Just need to set wanted Model name with list parameter @return mixed
[ "Recovers", "items", "from", "database", "by", "given", "id", "s", "Just", "need", "to", "set", "wanted", "Model", "name", "with", "list", "parameter" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/http/controllers/HCBaseController.php#L313-L326
interactivesolutions/honeycomb-core
src/http/controllers/HCBaseController.php
HCBaseController.apiMerge
public function apiMerge() { DB::beginTransaction(); try { $record = $this->__apiMerge(); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0007' . $e->getCode(), $e->getMessage()); } DB::commit(); return $record; }
php
public function apiMerge() { DB::beginTransaction(); try { $record = $this->__apiMerge(); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0007' . $e->getCode(), $e->getMessage()); } DB::commit(); return $record; }
[ "public", "function", "apiMerge", "(", ")", "{", "DB", "::", "beginTransaction", "(", ")", ";", "try", "{", "$", "record", "=", "$", "this", "->", "__apiMerge", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "DB", "::", "rollback", "(", ")", ";", "return", "HCLog", "::", "error", "(", "'CORE-0007'", ".", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "DB", "::", "commit", "(", ")", ";", "return", "$", "record", ";", "}" ]
Function will can be used to merge multiple records into one @return mixed
[ "Function", "will", "can", "be", "used", "to", "merge", "multiple", "records", "into", "one" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/http/controllers/HCBaseController.php#L359-L374
interactivesolutions/honeycomb-core
src/http/controllers/HCBaseController.php
HCBaseController.apiDuplicate
public function apiDuplicate(string $id) { DB::beginTransaction(); try { $record = $this->__apiDuplicate($id); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0008' . $e->getCode(), $e->getMessage()); } DB::commit(); return $record; }
php
public function apiDuplicate(string $id) { DB::beginTransaction(); try { $record = $this->__apiDuplicate($id); } catch (\Exception $e) { DB::rollback(); return HCLog::error('CORE-0008' . $e->getCode(), $e->getMessage()); } DB::commit(); return $record; }
[ "public", "function", "apiDuplicate", "(", "string", "$", "id", ")", "{", "DB", "::", "beginTransaction", "(", ")", ";", "try", "{", "$", "record", "=", "$", "this", "->", "__apiDuplicate", "(", "$", "id", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "DB", "::", "rollback", "(", ")", ";", "return", "HCLog", "::", "error", "(", "'CORE-0008'", ".", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "DB", "::", "commit", "(", ")", ";", "return", "$", "record", ";", "}" ]
Duplicate function @param string $id @return mixed
[ "Duplicate", "function" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/http/controllers/HCBaseController.php#L396-L411
graze/data-structure
src/Collection/ImmutableCollection.php
ImmutableCollection.sort
public function sort(callable $fn) { $items = $this->items; usort($items, $fn); return new self($items); }
php
public function sort(callable $fn) { $items = $this->items; usort($items, $fn); return new self($items); }
[ "public", "function", "sort", "(", "callable", "$", "fn", ")", "{", "$", "items", "=", "$", "this", "->", "items", ";", "usort", "(", "$", "items", ",", "$", "fn", ")", ";", "return", "new", "self", "(", "$", "items", ")", ";", "}" ]
@param callable $fn @return ImmutableCollection
[ "@param", "callable", "$fn" ]
train
https://github.com/graze/data-structure/blob/24e0544b7828f65b1b93ce69ad702c9efb4a64d0/src/Collection/ImmutableCollection.php#L60-L66
WellCommerce/AppBundle
Service/Currency/Importer/EcbRatesImporter.php
EcbRatesImporter.importExchangeRates
public function importExchangeRates() { $this->downloadExchangeRatesTable(); foreach ($this->getCurrencies() as $currency) { $this->updateCurrencyRates($currency); } }
php
public function importExchangeRates() { $this->downloadExchangeRatesTable(); foreach ($this->getCurrencies() as $currency) { $this->updateCurrencyRates($currency); } }
[ "public", "function", "importExchangeRates", "(", ")", "{", "$", "this", "->", "downloadExchangeRatesTable", "(", ")", ";", "foreach", "(", "$", "this", "->", "getCurrencies", "(", ")", "as", "$", "currency", ")", "{", "$", "this", "->", "updateCurrencyRates", "(", "$", "currency", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Service/Currency/Importer/EcbRatesImporter.php#L31-L38
WellCommerce/AppBundle
Service/Currency/Importer/EcbRatesImporter.php
EcbRatesImporter.downloadExchangeRatesTable
protected function downloadExchangeRatesTable() { try { $this->table[$this->baseCurrency] = 1; $xml = simplexml_load_file($this->url, 'SimpleXMLElement', LIBXML_NOWARNING); if ($xml instanceof \SimpleXMLElement) { $data = $xml->xpath('//gesmes:Envelope/*[3]/*'); foreach ($data[0]->children() as $child) { $currency = (string)$child->attributes()->currency; $exchangeRate = (string)$child->attributes()->rate; $this->table[$currency] = $exchangeRate; } } } catch (\Exception $e) { throw new \RuntimeException('Cannot download rates from ECB.'); } }
php
protected function downloadExchangeRatesTable() { try { $this->table[$this->baseCurrency] = 1; $xml = simplexml_load_file($this->url, 'SimpleXMLElement', LIBXML_NOWARNING); if ($xml instanceof \SimpleXMLElement) { $data = $xml->xpath('//gesmes:Envelope/*[3]/*'); foreach ($data[0]->children() as $child) { $currency = (string)$child->attributes()->currency; $exchangeRate = (string)$child->attributes()->rate; $this->table[$currency] = $exchangeRate; } } } catch (\Exception $e) { throw new \RuntimeException('Cannot download rates from ECB.'); } }
[ "protected", "function", "downloadExchangeRatesTable", "(", ")", "{", "try", "{", "$", "this", "->", "table", "[", "$", "this", "->", "baseCurrency", "]", "=", "1", ";", "$", "xml", "=", "simplexml_load_file", "(", "$", "this", "->", "url", ",", "'SimpleXMLElement'", ",", "LIBXML_NOWARNING", ")", ";", "if", "(", "$", "xml", "instanceof", "\\", "SimpleXMLElement", ")", "{", "$", "data", "=", "$", "xml", "->", "xpath", "(", "'//gesmes:Envelope/*[3]/*'", ")", ";", "foreach", "(", "$", "data", "[", "0", "]", "->", "children", "(", ")", "as", "$", "child", ")", "{", "$", "currency", "=", "(", "string", ")", "$", "child", "->", "attributes", "(", ")", "->", "currency", ";", "$", "exchangeRate", "=", "(", "string", ")", "$", "child", "->", "attributes", "(", ")", "->", "rate", ";", "$", "this", "->", "table", "[", "$", "currency", "]", "=", "$", "exchangeRate", ";", "}", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot download rates from ECB.'", ")", ";", "}", "}" ]
Downloads exchange rates table from ECB
[ "Downloads", "exchange", "rates", "table", "from", "ECB" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Service/Currency/Importer/EcbRatesImporter.php#L43-L63
WellCommerce/AppBundle
Service/Currency/Importer/EcbRatesImporter.php
EcbRatesImporter.updateCurrencyRates
protected function updateCurrencyRates(Currency $currency) { $baseExchangeRate = $this->table[$currency->getCode()]; foreach ($this->table as $currencySymbol => $exchangeRate) { $rate = $this->calculateExchangeRate($baseExchangeRate, $currencySymbol); $this->addUpdateExchangeRate($currency->getCode(), $currencySymbol, $rate); } $this->helper->getEntityManager()->flush(); }
php
protected function updateCurrencyRates(Currency $currency) { $baseExchangeRate = $this->table[$currency->getCode()]; foreach ($this->table as $currencySymbol => $exchangeRate) { $rate = $this->calculateExchangeRate($baseExchangeRate, $currencySymbol); $this->addUpdateExchangeRate($currency->getCode(), $currencySymbol, $rate); } $this->helper->getEntityManager()->flush(); }
[ "protected", "function", "updateCurrencyRates", "(", "Currency", "$", "currency", ")", "{", "$", "baseExchangeRate", "=", "$", "this", "->", "table", "[", "$", "currency", "->", "getCode", "(", ")", "]", ";", "foreach", "(", "$", "this", "->", "table", "as", "$", "currencySymbol", "=>", "$", "exchangeRate", ")", "{", "$", "rate", "=", "$", "this", "->", "calculateExchangeRate", "(", "$", "baseExchangeRate", ",", "$", "currencySymbol", ")", ";", "$", "this", "->", "addUpdateExchangeRate", "(", "$", "currency", "->", "getCode", "(", ")", ",", "$", "currencySymbol", ",", "$", "rate", ")", ";", "}", "$", "this", "->", "helper", "->", "getEntityManager", "(", ")", "->", "flush", "(", ")", ";", "}" ]
Updates managed currency with exchange rates @param Currency $currency
[ "Updates", "managed", "currency", "with", "exchange", "rates" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Service/Currency/Importer/EcbRatesImporter.php#L70-L80
motivatedsloth/noaa
noaa/NOAA.php
NOAA.point
protected function point(){ if(!$this->point->isLoaded()){ $url = str_replace("{point}", $this->point->getLat() . "," . $this->point->getLon(), self::POINT); $res = $this->load($url, Point::TTL); $this->point->setProperties($res); } return $this->point; }
php
protected function point(){ if(!$this->point->isLoaded()){ $url = str_replace("{point}", $this->point->getLat() . "," . $this->point->getLon(), self::POINT); $res = $this->load($url, Point::TTL); $this->point->setProperties($res); } return $this->point; }
[ "protected", "function", "point", "(", ")", "{", "if", "(", "!", "$", "this", "->", "point", "->", "isLoaded", "(", ")", ")", "{", "$", "url", "=", "str_replace", "(", "\"{point}\"", ",", "$", "this", "->", "point", "->", "getLat", "(", ")", ".", "\",\"", ".", "$", "this", "->", "point", "->", "getLon", "(", ")", ",", "self", "::", "POINT", ")", ";", "$", "res", "=", "$", "this", "->", "load", "(", "$", "url", ",", "Point", "::", "TTL", ")", ";", "$", "this", "->", "point", "->", "setProperties", "(", "$", "res", ")", ";", "}", "return", "$", "this", "->", "point", ";", "}" ]
ensure point has data loaded
[ "ensure", "point", "has", "data", "loaded" ]
train
https://github.com/motivatedsloth/noaa/blob/621c8dab1d774ec2810a508941f568b716ce779a/noaa/NOAA.php#L97-L104
thelia-modules/CustomerGroup
Handler/CustomerGroupHandler.php
CustomerGroupHandler.getGroup
public function getGroup() { /** @var Request $request */ $request = $this->container->get('request'); $groupInfo = $request->getSession()->get(CustomerGroup::getModuleCode()); return $groupInfo; }
php
public function getGroup() { /** @var Request $request */ $request = $this->container->get('request'); $groupInfo = $request->getSession()->get(CustomerGroup::getModuleCode()); return $groupInfo; }
[ "public", "function", "getGroup", "(", ")", "{", "/** @var Request $request */", "$", "request", "=", "$", "this", "->", "container", "->", "get", "(", "'request'", ")", ";", "$", "groupInfo", "=", "$", "request", "->", "getSession", "(", ")", "->", "get", "(", "CustomerGroup", "::", "getModuleCode", "(", ")", ")", ";", "return", "$", "groupInfo", ";", "}" ]
Get CustomerGroup of the current customer @return array|null
[ "Get", "CustomerGroup", "of", "the", "current", "customer" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Handler/CustomerGroupHandler.php#L33-L41
thelia-modules/CustomerGroup
Handler/CustomerGroupHandler.php
CustomerGroupHandler.checkGroup
public function checkGroup($groupCode) { /** @var SecurityContext $securityContext */ $securityContext = $this->container->get('thelia.securityContext'); return $securityContext->hasCustomerUser() && $this->getGroupCode() === $groupCode; }
php
public function checkGroup($groupCode) { /** @var SecurityContext $securityContext */ $securityContext = $this->container->get('thelia.securityContext'); return $securityContext->hasCustomerUser() && $this->getGroupCode() === $groupCode; }
[ "public", "function", "checkGroup", "(", "$", "groupCode", ")", "{", "/** @var SecurityContext $securityContext */", "$", "securityContext", "=", "$", "this", "->", "container", "->", "get", "(", "'thelia.securityContext'", ")", ";", "return", "$", "securityContext", "->", "hasCustomerUser", "(", ")", "&&", "$", "this", "->", "getGroupCode", "(", ")", "===", "$", "groupCode", ";", "}" ]
Check if the current customer is in the asked group @param string $groupCode Code for the group to check @return boolean @uses getGroupCode()
[ "Check", "if", "the", "current", "customer", "is", "in", "the", "asked", "group" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Handler/CustomerGroupHandler.php#L66-L72
thelia-modules/CustomerGroup
Handler/CustomerGroupHandler.php
CustomerGroupHandler.checkCustomerHasGroup
public function checkCustomerHasGroup(Customer $customer, $groupCode) { $group = CustomerCustomerGroupQuery::create() ->filterByCustomer($customer) ->useCustomerGroupQuery() ->filterByCode($groupCode) ->endUse() ->findOne(); return $group !== null; }
php
public function checkCustomerHasGroup(Customer $customer, $groupCode) { $group = CustomerCustomerGroupQuery::create() ->filterByCustomer($customer) ->useCustomerGroupQuery() ->filterByCode($groupCode) ->endUse() ->findOne(); return $group !== null; }
[ "public", "function", "checkCustomerHasGroup", "(", "Customer", "$", "customer", ",", "$", "groupCode", ")", "{", "$", "group", "=", "CustomerCustomerGroupQuery", "::", "create", "(", ")", "->", "filterByCustomer", "(", "$", "customer", ")", "->", "useCustomerGroupQuery", "(", ")", "->", "filterByCode", "(", "$", "groupCode", ")", "->", "endUse", "(", ")", "->", "findOne", "(", ")", ";", "return", "$", "group", "!==", "null", ";", "}" ]
Check that a customer belongs to a group. @param Customer $customer @param string $groupCode @return bool
[ "Check", "that", "a", "customer", "belongs", "to", "a", "group", "." ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Handler/CustomerGroupHandler.php#L82-L92
kenphp/ken
src/Application.php
Application.init
protected function init() { $this->container->set('logger', function($c) { $configuration = $c->get('configuration'); $logger = new Logger($configuration['logger']); return $logger; }); $this->container->set(MiddlewareFactory::class, function($c) { return new MiddlewareFactory(); }); $this->container->set('request', function($c) { $psr17Factory = new Psr17Factory(); $creator = new ServerRequestCreator( $psr17Factory, // ServerRequestFactory $psr17Factory, // UriFactory $psr17Factory, // UploadedFileFactory $psr17Factory // StreamFactory ); return $creator->fromGlobals(); }); $this->container->set('router', function($c) { return new Router(); }); $this->container->set('response', function($c) { return new Response(); }); $this->container->set('view', function($c) { $configuration = $c->get('configuration')['view']; $viewFunctions = isset($configuration['viewFunctions']) ? $configuration['viewFunctions'] : []; return new Plates($configuration['viewPath'], $viewFunctions); }); $this->registerErrorHandler(); }
php
protected function init() { $this->container->set('logger', function($c) { $configuration = $c->get('configuration'); $logger = new Logger($configuration['logger']); return $logger; }); $this->container->set(MiddlewareFactory::class, function($c) { return new MiddlewareFactory(); }); $this->container->set('request', function($c) { $psr17Factory = new Psr17Factory(); $creator = new ServerRequestCreator( $psr17Factory, // ServerRequestFactory $psr17Factory, // UriFactory $psr17Factory, // UploadedFileFactory $psr17Factory // StreamFactory ); return $creator->fromGlobals(); }); $this->container->set('router', function($c) { return new Router(); }); $this->container->set('response', function($c) { return new Response(); }); $this->container->set('view', function($c) { $configuration = $c->get('configuration')['view']; $viewFunctions = isset($configuration['viewFunctions']) ? $configuration['viewFunctions'] : []; return new Plates($configuration['viewPath'], $viewFunctions); }); $this->registerErrorHandler(); }
[ "protected", "function", "init", "(", ")", "{", "$", "this", "->", "container", "->", "set", "(", "'logger'", ",", "function", "(", "$", "c", ")", "{", "$", "configuration", "=", "$", "c", "->", "get", "(", "'configuration'", ")", ";", "$", "logger", "=", "new", "Logger", "(", "$", "configuration", "[", "'logger'", "]", ")", ";", "return", "$", "logger", ";", "}", ")", ";", "$", "this", "->", "container", "->", "set", "(", "MiddlewareFactory", "::", "class", ",", "function", "(", "$", "c", ")", "{", "return", "new", "MiddlewareFactory", "(", ")", ";", "}", ")", ";", "$", "this", "->", "container", "->", "set", "(", "'request'", ",", "function", "(", "$", "c", ")", "{", "$", "psr17Factory", "=", "new", "Psr17Factory", "(", ")", ";", "$", "creator", "=", "new", "ServerRequestCreator", "(", "$", "psr17Factory", ",", "// ServerRequestFactory", "$", "psr17Factory", ",", "// UriFactory", "$", "psr17Factory", ",", "// UploadedFileFactory", "$", "psr17Factory", "// StreamFactory", ")", ";", "return", "$", "creator", "->", "fromGlobals", "(", ")", ";", "}", ")", ";", "$", "this", "->", "container", "->", "set", "(", "'router'", ",", "function", "(", "$", "c", ")", "{", "return", "new", "Router", "(", ")", ";", "}", ")", ";", "$", "this", "->", "container", "->", "set", "(", "'response'", ",", "function", "(", "$", "c", ")", "{", "return", "new", "Response", "(", ")", ";", "}", ")", ";", "$", "this", "->", "container", "->", "set", "(", "'view'", ",", "function", "(", "$", "c", ")", "{", "$", "configuration", "=", "$", "c", "->", "get", "(", "'configuration'", ")", "[", "'view'", "]", ";", "$", "viewFunctions", "=", "isset", "(", "$", "configuration", "[", "'viewFunctions'", "]", ")", "?", "$", "configuration", "[", "'viewFunctions'", "]", ":", "[", "]", ";", "return", "new", "Plates", "(", "$", "configuration", "[", "'viewPath'", "]", ",", "$", "viewFunctions", ")", ";", "}", ")", ";", "$", "this", "->", "registerErrorHandler", "(", ")", ";", "}" ]
Initializes application's components
[ "Initializes", "application", "s", "components" ]
train
https://github.com/kenphp/ken/blob/c454a86f0ab55c52c88e9bff5bc6fb4e7bd9e0eb/src/Application.php#L62-L103
kenphp/ken
src/Application.php
Application.registerErrorHandler
public function registerErrorHandler() { $whoops = new \Whoops\Run(); $configuration = $this->getConfiguration(); if (isset($configuration['debug']) && $configuration['debug']) { $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler()); } else { $whoops->pushHandler(new \Whoops\Handler\CallbackHandler(function ($exception) { $this->logger->error($exception->getMessage(), compact('exception')); $request = $this->container->get('request'); $response = $this->container->get('response'); $view = $this->container->get('view'); $errorInfo = ['message' => $exception->getMessage()]; if (is_a($exception, HttpException::class)) { $errorInfo['code'] = $exception->getCode(); } else { $errorInfo['code'] = 500; } $headerAccept = $request->getHeader('Accept'); if (in_array('application/json', $headerAccept)) { $response = $response->withStatus($errorInfo['code']); $response->getBody()->write(json_encode($errorInfo)); $response = $response->withHeader('Content-Type', 'application/json'); } else { $response = $view->render($response, 'error', $errorInfo); } $this->emitResponse($response); return \Whoops\Handler\Handler::DONE; })); } $whoops->register(); }
php
public function registerErrorHandler() { $whoops = new \Whoops\Run(); $configuration = $this->getConfiguration(); if (isset($configuration['debug']) && $configuration['debug']) { $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler()); } else { $whoops->pushHandler(new \Whoops\Handler\CallbackHandler(function ($exception) { $this->logger->error($exception->getMessage(), compact('exception')); $request = $this->container->get('request'); $response = $this->container->get('response'); $view = $this->container->get('view'); $errorInfo = ['message' => $exception->getMessage()]; if (is_a($exception, HttpException::class)) { $errorInfo['code'] = $exception->getCode(); } else { $errorInfo['code'] = 500; } $headerAccept = $request->getHeader('Accept'); if (in_array('application/json', $headerAccept)) { $response = $response->withStatus($errorInfo['code']); $response->getBody()->write(json_encode($errorInfo)); $response = $response->withHeader('Content-Type', 'application/json'); } else { $response = $view->render($response, 'error', $errorInfo); } $this->emitResponse($response); return \Whoops\Handler\Handler::DONE; })); } $whoops->register(); }
[ "public", "function", "registerErrorHandler", "(", ")", "{", "$", "whoops", "=", "new", "\\", "Whoops", "\\", "Run", "(", ")", ";", "$", "configuration", "=", "$", "this", "->", "getConfiguration", "(", ")", ";", "if", "(", "isset", "(", "$", "configuration", "[", "'debug'", "]", ")", "&&", "$", "configuration", "[", "'debug'", "]", ")", "{", "$", "whoops", "->", "pushHandler", "(", "new", "\\", "Whoops", "\\", "Handler", "\\", "PrettyPageHandler", "(", ")", ")", ";", "}", "else", "{", "$", "whoops", "->", "pushHandler", "(", "new", "\\", "Whoops", "\\", "Handler", "\\", "CallbackHandler", "(", "function", "(", "$", "exception", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "$", "exception", "->", "getMessage", "(", ")", ",", "compact", "(", "'exception'", ")", ")", ";", "$", "request", "=", "$", "this", "->", "container", "->", "get", "(", "'request'", ")", ";", "$", "response", "=", "$", "this", "->", "container", "->", "get", "(", "'response'", ")", ";", "$", "view", "=", "$", "this", "->", "container", "->", "get", "(", "'view'", ")", ";", "$", "errorInfo", "=", "[", "'message'", "=>", "$", "exception", "->", "getMessage", "(", ")", "]", ";", "if", "(", "is_a", "(", "$", "exception", ",", "HttpException", "::", "class", ")", ")", "{", "$", "errorInfo", "[", "'code'", "]", "=", "$", "exception", "->", "getCode", "(", ")", ";", "}", "else", "{", "$", "errorInfo", "[", "'code'", "]", "=", "500", ";", "}", "$", "headerAccept", "=", "$", "request", "->", "getHeader", "(", "'Accept'", ")", ";", "if", "(", "in_array", "(", "'application/json'", ",", "$", "headerAccept", ")", ")", "{", "$", "response", "=", "$", "response", "->", "withStatus", "(", "$", "errorInfo", "[", "'code'", "]", ")", ";", "$", "response", "->", "getBody", "(", ")", "->", "write", "(", "json_encode", "(", "$", "errorInfo", ")", ")", ";", "$", "response", "=", "$", "response", "->", "withHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "}", "else", "{", "$", "response", "=", "$", "view", "->", "render", "(", "$", "response", ",", "'error'", ",", "$", "errorInfo", ")", ";", "}", "$", "this", "->", "emitResponse", "(", "$", "response", ")", ";", "return", "\\", "Whoops", "\\", "Handler", "\\", "Handler", "::", "DONE", ";", "}", ")", ")", ";", "}", "$", "whoops", "->", "register", "(", ")", ";", "}" ]
Registers error handler for this application
[ "Registers", "error", "handler", "for", "this", "application" ]
train
https://github.com/kenphp/ken/blob/c454a86f0ab55c52c88e9bff5bc6fb4e7bd9e0eb/src/Application.php#L108-L147
kenphp/ken
src/Application.php
Application.run
public function run() { $request = $this->request; $response = $this->response; $config = $this->configuration; $httpMethod = $request->getMethod(); $pathInfo = $request->getUri()->getPath(); if (empty($pathInfo)) { $pathInfo = '/'; } $routeObject = $this->router->resolve($pathInfo, $httpMethod); if($routeObject) { $middlewareList = []; if (isset($routeObject['middleware'])) { $middlewareConfig = $config->get('middlewares'); $middlewareCount = count($routeObject['middleware']); $middlewareNext = null; $middlewareFactory = $this->container->get(MiddlewareFactory::class); for ($i=$middlewareCount-1; $i >= 0; $i--) { $middlewareName = $routeObject['middleware'][$i]; $middlewareClass = $middlewareConfig[$middlewareName]; $middlewareList[$i] = $middlewareFactory->createObject($middlewareClass, [ 'response' => $response, 'next' => $middlewareNext, ]); $middlewareNext = $middlewareList[$i]; } } $baseNamespace = $config->get('controllersNamespace'); $handler = $this->convertCallbackToClosure($routeObject['handler'], $baseNamespace); $params = isset($routeObject['params']) ? $routeObject['params'] : []; $requestHandler = new ServerRequestHandler($response, $handler, $routeObject['params']); if (isset($middlewareList[0])) { $response = $middlewareList[0]->process($request, $requestHandler); } else { $response = $requestHandler->handle($request); } } else { throw new HttpException(404, "Route '{$pathInfo}' not found"); } $this->emitResponse($response); }
php
public function run() { $request = $this->request; $response = $this->response; $config = $this->configuration; $httpMethod = $request->getMethod(); $pathInfo = $request->getUri()->getPath(); if (empty($pathInfo)) { $pathInfo = '/'; } $routeObject = $this->router->resolve($pathInfo, $httpMethod); if($routeObject) { $middlewareList = []; if (isset($routeObject['middleware'])) { $middlewareConfig = $config->get('middlewares'); $middlewareCount = count($routeObject['middleware']); $middlewareNext = null; $middlewareFactory = $this->container->get(MiddlewareFactory::class); for ($i=$middlewareCount-1; $i >= 0; $i--) { $middlewareName = $routeObject['middleware'][$i]; $middlewareClass = $middlewareConfig[$middlewareName]; $middlewareList[$i] = $middlewareFactory->createObject($middlewareClass, [ 'response' => $response, 'next' => $middlewareNext, ]); $middlewareNext = $middlewareList[$i]; } } $baseNamespace = $config->get('controllersNamespace'); $handler = $this->convertCallbackToClosure($routeObject['handler'], $baseNamespace); $params = isset($routeObject['params']) ? $routeObject['params'] : []; $requestHandler = new ServerRequestHandler($response, $handler, $routeObject['params']); if (isset($middlewareList[0])) { $response = $middlewareList[0]->process($request, $requestHandler); } else { $response = $requestHandler->handle($request); } } else { throw new HttpException(404, "Route '{$pathInfo}' not found"); } $this->emitResponse($response); }
[ "public", "function", "run", "(", ")", "{", "$", "request", "=", "$", "this", "->", "request", ";", "$", "response", "=", "$", "this", "->", "response", ";", "$", "config", "=", "$", "this", "->", "configuration", ";", "$", "httpMethod", "=", "$", "request", "->", "getMethod", "(", ")", ";", "$", "pathInfo", "=", "$", "request", "->", "getUri", "(", ")", "->", "getPath", "(", ")", ";", "if", "(", "empty", "(", "$", "pathInfo", ")", ")", "{", "$", "pathInfo", "=", "'/'", ";", "}", "$", "routeObject", "=", "$", "this", "->", "router", "->", "resolve", "(", "$", "pathInfo", ",", "$", "httpMethod", ")", ";", "if", "(", "$", "routeObject", ")", "{", "$", "middlewareList", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "routeObject", "[", "'middleware'", "]", ")", ")", "{", "$", "middlewareConfig", "=", "$", "config", "->", "get", "(", "'middlewares'", ")", ";", "$", "middlewareCount", "=", "count", "(", "$", "routeObject", "[", "'middleware'", "]", ")", ";", "$", "middlewareNext", "=", "null", ";", "$", "middlewareFactory", "=", "$", "this", "->", "container", "->", "get", "(", "MiddlewareFactory", "::", "class", ")", ";", "for", "(", "$", "i", "=", "$", "middlewareCount", "-", "1", ";", "$", "i", ">=", "0", ";", "$", "i", "--", ")", "{", "$", "middlewareName", "=", "$", "routeObject", "[", "'middleware'", "]", "[", "$", "i", "]", ";", "$", "middlewareClass", "=", "$", "middlewareConfig", "[", "$", "middlewareName", "]", ";", "$", "middlewareList", "[", "$", "i", "]", "=", "$", "middlewareFactory", "->", "createObject", "(", "$", "middlewareClass", ",", "[", "'response'", "=>", "$", "response", ",", "'next'", "=>", "$", "middlewareNext", ",", "]", ")", ";", "$", "middlewareNext", "=", "$", "middlewareList", "[", "$", "i", "]", ";", "}", "}", "$", "baseNamespace", "=", "$", "config", "->", "get", "(", "'controllersNamespace'", ")", ";", "$", "handler", "=", "$", "this", "->", "convertCallbackToClosure", "(", "$", "routeObject", "[", "'handler'", "]", ",", "$", "baseNamespace", ")", ";", "$", "params", "=", "isset", "(", "$", "routeObject", "[", "'params'", "]", ")", "?", "$", "routeObject", "[", "'params'", "]", ":", "[", "]", ";", "$", "requestHandler", "=", "new", "ServerRequestHandler", "(", "$", "response", ",", "$", "handler", ",", "$", "routeObject", "[", "'params'", "]", ")", ";", "if", "(", "isset", "(", "$", "middlewareList", "[", "0", "]", ")", ")", "{", "$", "response", "=", "$", "middlewareList", "[", "0", "]", "->", "process", "(", "$", "request", ",", "$", "requestHandler", ")", ";", "}", "else", "{", "$", "response", "=", "$", "requestHandler", "->", "handle", "(", "$", "request", ")", ";", "}", "}", "else", "{", "throw", "new", "HttpException", "(", "404", ",", "\"Route '{$pathInfo}' not found\"", ")", ";", "}", "$", "this", "->", "emitResponse", "(", "$", "response", ")", ";", "}" ]
Runs application to handle request.
[ "Runs", "application", "to", "handle", "request", "." ]
train
https://github.com/kenphp/ken/blob/c454a86f0ab55c52c88e9bff5bc6fb4e7bd9e0eb/src/Application.php#L196-L244
kenphp/ken
src/Application.php
Application.emitResponse
protected function emitResponse(ResponseInterface $response) { $this->logger->flush(); (new \Zend\HttpHandlerRunner\Emitter\SapiEmitter())->emit($response); }
php
protected function emitResponse(ResponseInterface $response) { $this->logger->flush(); (new \Zend\HttpHandlerRunner\Emitter\SapiEmitter())->emit($response); }
[ "protected", "function", "emitResponse", "(", "ResponseInterface", "$", "response", ")", "{", "$", "this", "->", "logger", "->", "flush", "(", ")", ";", "(", "new", "\\", "Zend", "\\", "HttpHandlerRunner", "\\", "Emitter", "\\", "SapiEmitter", "(", ")", ")", "->", "emit", "(", "$", "response", ")", ";", "}" ]
Emits response to client @param ResponseInterface $response
[ "Emits", "response", "to", "client" ]
train
https://github.com/kenphp/ken/blob/c454a86f0ab55c52c88e9bff5bc6fb4e7bd9e0eb/src/Application.php#L250-L253
kenphp/ken
src/Application.php
Application.convertCallbackToClosure
protected function convertCallbackToClosure($callback, $namespace) { if ($callback instanceof Closure || is_callable($callback)) { return $callback; } elseif (is_string($callback)) { $namespace = rtrim($namespace, '\\').'\\'; $arrCallback = explode('::', $callback); $isStaticCall = count($arrCallback) == 2; if ($isStaticCall) { $className = $namespace.$arrCallback[0]; return [$className, $arrCallback[1]]; } else { $arrCallback = explode(':', $callback); $className = $namespace.$arrCallback[0]; // Must be replaced with a safer way to instantiate an object $obj = $this->container->get($className); return [$obj, $arrCallback[1]]; } } }
php
protected function convertCallbackToClosure($callback, $namespace) { if ($callback instanceof Closure || is_callable($callback)) { return $callback; } elseif (is_string($callback)) { $namespace = rtrim($namespace, '\\').'\\'; $arrCallback = explode('::', $callback); $isStaticCall = count($arrCallback) == 2; if ($isStaticCall) { $className = $namespace.$arrCallback[0]; return [$className, $arrCallback[1]]; } else { $arrCallback = explode(':', $callback); $className = $namespace.$arrCallback[0]; // Must be replaced with a safer way to instantiate an object $obj = $this->container->get($className); return [$obj, $arrCallback[1]]; } } }
[ "protected", "function", "convertCallbackToClosure", "(", "$", "callback", ",", "$", "namespace", ")", "{", "if", "(", "$", "callback", "instanceof", "Closure", "||", "is_callable", "(", "$", "callback", ")", ")", "{", "return", "$", "callback", ";", "}", "elseif", "(", "is_string", "(", "$", "callback", ")", ")", "{", "$", "namespace", "=", "rtrim", "(", "$", "namespace", ",", "'\\\\'", ")", ".", "'\\\\'", ";", "$", "arrCallback", "=", "explode", "(", "'::'", ",", "$", "callback", ")", ";", "$", "isStaticCall", "=", "count", "(", "$", "arrCallback", ")", "==", "2", ";", "if", "(", "$", "isStaticCall", ")", "{", "$", "className", "=", "$", "namespace", ".", "$", "arrCallback", "[", "0", "]", ";", "return", "[", "$", "className", ",", "$", "arrCallback", "[", "1", "]", "]", ";", "}", "else", "{", "$", "arrCallback", "=", "explode", "(", "':'", ",", "$", "callback", ")", ";", "$", "className", "=", "$", "namespace", ".", "$", "arrCallback", "[", "0", "]", ";", "// Must be replaced with a safer way to instantiate an object", "$", "obj", "=", "$", "this", "->", "container", "->", "get", "(", "$", "className", ")", ";", "return", "[", "$", "obj", ",", "$", "arrCallback", "[", "1", "]", "]", ";", "}", "}", "}" ]
Converts callback to Closure. @param string|Closure $callback @param string $namespace @return Closure
[ "Converts", "callback", "to", "Closure", "." ]
train
https://github.com/kenphp/ken/blob/c454a86f0ab55c52c88e9bff5bc6fb4e7bd9e0eb/src/Application.php#L263-L282
DesignPond/newsletter
src/Newsletter/Worker/CampagneWorker.php
CampagneWorker.arretsToHide
public function arretsToHide($newsletter_id = null) { $campagnes = $this->campagne->getAll($newsletter_id)->where('status','brouillon'); return $campagnes->flatMap(function ($campagne) { return $campagne->content; })->map(function ($content, $key) { if($content->arret_id) return $content->arret_id ; if($content->groupe_id > 0) return $content->groupe->arrets->pluck('id')->all(); })->filter(function ($value, $key) { return !empty($value); })->flatten()->toArray(); }
php
public function arretsToHide($newsletter_id = null) { $campagnes = $this->campagne->getAll($newsletter_id)->where('status','brouillon'); return $campagnes->flatMap(function ($campagne) { return $campagne->content; })->map(function ($content, $key) { if($content->arret_id) return $content->arret_id ; if($content->groupe_id > 0) return $content->groupe->arrets->pluck('id')->all(); })->filter(function ($value, $key) { return !empty($value); })->flatten()->toArray(); }
[ "public", "function", "arretsToHide", "(", "$", "newsletter_id", "=", "null", ")", "{", "$", "campagnes", "=", "$", "this", "->", "campagne", "->", "getAll", "(", "$", "newsletter_id", ")", "->", "where", "(", "'status'", ",", "'brouillon'", ")", ";", "return", "$", "campagnes", "->", "flatMap", "(", "function", "(", "$", "campagne", ")", "{", "return", "$", "campagne", "->", "content", ";", "}", ")", "->", "map", "(", "function", "(", "$", "content", ",", "$", "key", ")", "{", "if", "(", "$", "content", "->", "arret_id", ")", "return", "$", "content", "->", "arret_id", ";", "if", "(", "$", "content", "->", "groupe_id", ">", "0", ")", "return", "$", "content", "->", "groupe", "->", "arrets", "->", "pluck", "(", "'id'", ")", "->", "all", "(", ")", ";", "}", ")", "->", "filter", "(", "function", "(", "$", "value", ",", "$", "key", ")", "{", "return", "!", "empty", "(", "$", "value", ")", ";", "}", ")", "->", "flatten", "(", ")", "->", "toArray", "(", ")", ";", "}" ]
Interaction with site controllers List of arrets in non sent campagne to hide on frontend
[ "Interaction", "with", "site", "controllers", "List", "of", "arrets", "in", "non", "sent", "campagne", "to", "hide", "on", "frontend" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Worker/CampagneWorker.php#L28-L45
DesignPond/newsletter
src/Newsletter/Worker/CampagneWorker.php
CampagneWorker.siteCampagnes
public function siteCampagnes($site_id) { if(config('newsletter.multi')) { $newsletters = $this->newsletter->getSite($site_id); return $newsletters->map(function ($newsletter, $key) { return $newsletter->campagnes; })->flatten(1); } return null; }
php
public function siteCampagnes($site_id) { if(config('newsletter.multi')) { $newsletters = $this->newsletter->getSite($site_id); return $newsletters->map(function ($newsletter, $key) { return $newsletter->campagnes; })->flatten(1); } return null; }
[ "public", "function", "siteCampagnes", "(", "$", "site_id", ")", "{", "if", "(", "config", "(", "'newsletter.multi'", ")", ")", "{", "$", "newsletters", "=", "$", "this", "->", "newsletter", "->", "getSite", "(", "$", "site_id", ")", ";", "return", "$", "newsletters", "->", "map", "(", "function", "(", "$", "newsletter", ",", "$", "key", ")", "{", "return", "$", "newsletter", "->", "campagnes", ";", "}", ")", "->", "flatten", "(", "1", ")", ";", "}", "return", "null", ";", "}" ]
All campagnes for site
[ "All", "campagnes", "for", "site" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Worker/CampagneWorker.php#L88-L98
DesignPond/newsletter
src/Newsletter/Worker/CampagneWorker.php
CampagneWorker.html
public function html($id) { libxml_use_internal_errors(true); $htmldoc = new InlineStyle(file_get_contents( url('campagne/'.$id))); $htmldoc->applyStylesheet($htmldoc->extractStylesheets()); $html = $htmldoc->getHTML(); $html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html); return $html; }
php
public function html($id) { libxml_use_internal_errors(true); $htmldoc = new InlineStyle(file_get_contents( url('campagne/'.$id))); $htmldoc->applyStylesheet($htmldoc->extractStylesheets()); $html = $htmldoc->getHTML(); $html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html); return $html; }
[ "public", "function", "html", "(", "$", "id", ")", "{", "libxml_use_internal_errors", "(", "true", ")", ";", "$", "htmldoc", "=", "new", "InlineStyle", "(", "file_get_contents", "(", "url", "(", "'campagne/'", ".", "$", "id", ")", ")", ")", ";", "$", "htmldoc", "->", "applyStylesheet", "(", "$", "htmldoc", "->", "extractStylesheets", "(", ")", ")", ";", "$", "html", "=", "$", "htmldoc", "->", "getHTML", "(", ")", ";", "$", "html", "=", "preg_replace", "(", "'#<script(.*?)>(.*?)</script>#is'", ",", "''", ",", "$", "html", ")", ";", "return", "$", "html", ";", "}" ]
Put styles inline for campagne Used when sending cammpagne or test
[ "Put", "styles", "inline", "for", "campagne", "Used", "when", "sending", "cammpagne", "or", "test" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Worker/CampagneWorker.php#L114-L125
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Transformer/Behaviour/Tag/LicenseTag.php
LicenseTag.process
public function process(\DOMDocument $xml) { $licenseMap = array( '#^\s*(GPL|GNU General Public License)((\s?v?|version)?2)\s*$#i' => 'http://opensource.org/licenses/GPL-2.0', '#^\s*(GPL|GNU General Public License)((\s?v?|version)?3?)\s*$#i' => 'http://opensource.org/licenses/GPL-3.0', '#^\s*(LGPL|GNU (Lesser|Library) (General Public License|GPL))' .'((\s?v?|version)?2(\.1)?)\s*$#i' => 'http://opensource.org/licenses/LGPL-2.1', '#^\s*(LGPL|GNU (Lesser|Library) (General Public License|GPL))' .'((\s?v?|version)?3?)\s*$#i' => 'http://opensource.org/licenses/LGPL-3.0', '#^\s*((new |revised |modified |three-clause |3-clause )BSD' .'( License)?)\s*$#i' => 'http://opensource.org/licenses/BSD-3-Clause', '#^\s*((simplified |two-clause |2-clause |Free)BSD)( License)?\s*$#i' => 'http://opensource.org/licenses/BSD-2-Clause', '#^\s*MIT( License)?\s*$#i' => 'http://opensource.org/licenses/MIT', ); $xpath = new \DOMXPath($xml); $nodes = $xpath->query('//tag[@name="license"]/@description'); /** @var \DOMElement $node */ foreach ($nodes as $node) { $license = $node->nodeValue; // FIXME: migrate to '#^' . PHPDOC::LINK_REGEX . '(\s+(?P<text>.+)) // ?$#u' once that const exists if (preg_match( '#^(?i)\b(?P<url>(?:https?://|www\d{0,3}\.|[a-z0-9.\-]+\.' .'[a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+' .'(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|' .'[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))(\s+(?P<text>.+))?$#u', $license, $matches )) { if (!isset($matches['text']) || !$matches['text']) { // set text to URL if not present $matches['text'] = $matches['url']; } $node->parentNode->setAttribute('link', $matches['url']); $node->nodeValue = $matches['text']; // bail out early continue; } // check map if any license matches foreach ($licenseMap as $regex => $url) { if (preg_match($regex, $license, $matches)) { $node->parentNode->setAttribute('link', $url); // we're done here break; } } } return $xml; }
php
public function process(\DOMDocument $xml) { $licenseMap = array( '#^\s*(GPL|GNU General Public License)((\s?v?|version)?2)\s*$#i' => 'http://opensource.org/licenses/GPL-2.0', '#^\s*(GPL|GNU General Public License)((\s?v?|version)?3?)\s*$#i' => 'http://opensource.org/licenses/GPL-3.0', '#^\s*(LGPL|GNU (Lesser|Library) (General Public License|GPL))' .'((\s?v?|version)?2(\.1)?)\s*$#i' => 'http://opensource.org/licenses/LGPL-2.1', '#^\s*(LGPL|GNU (Lesser|Library) (General Public License|GPL))' .'((\s?v?|version)?3?)\s*$#i' => 'http://opensource.org/licenses/LGPL-3.0', '#^\s*((new |revised |modified |three-clause |3-clause )BSD' .'( License)?)\s*$#i' => 'http://opensource.org/licenses/BSD-3-Clause', '#^\s*((simplified |two-clause |2-clause |Free)BSD)( License)?\s*$#i' => 'http://opensource.org/licenses/BSD-2-Clause', '#^\s*MIT( License)?\s*$#i' => 'http://opensource.org/licenses/MIT', ); $xpath = new \DOMXPath($xml); $nodes = $xpath->query('//tag[@name="license"]/@description'); /** @var \DOMElement $node */ foreach ($nodes as $node) { $license = $node->nodeValue; // FIXME: migrate to '#^' . PHPDOC::LINK_REGEX . '(\s+(?P<text>.+)) // ?$#u' once that const exists if (preg_match( '#^(?i)\b(?P<url>(?:https?://|www\d{0,3}\.|[a-z0-9.\-]+\.' .'[a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+' .'(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|' .'[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))(\s+(?P<text>.+))?$#u', $license, $matches )) { if (!isset($matches['text']) || !$matches['text']) { // set text to URL if not present $matches['text'] = $matches['url']; } $node->parentNode->setAttribute('link', $matches['url']); $node->nodeValue = $matches['text']; // bail out early continue; } // check map if any license matches foreach ($licenseMap as $regex => $url) { if (preg_match($regex, $license, $matches)) { $node->parentNode->setAttribute('link', $url); // we're done here break; } } } return $xml; }
[ "public", "function", "process", "(", "\\", "DOMDocument", "$", "xml", ")", "{", "$", "licenseMap", "=", "array", "(", "'#^\\s*(GPL|GNU General Public License)((\\s?v?|version)?2)\\s*$#i'", "=>", "'http://opensource.org/licenses/GPL-2.0'", ",", "'#^\\s*(GPL|GNU General Public License)((\\s?v?|version)?3?)\\s*$#i'", "=>", "'http://opensource.org/licenses/GPL-3.0'", ",", "'#^\\s*(LGPL|GNU (Lesser|Library) (General Public License|GPL))'", ".", "'((\\s?v?|version)?2(\\.1)?)\\s*$#i'", "=>", "'http://opensource.org/licenses/LGPL-2.1'", ",", "'#^\\s*(LGPL|GNU (Lesser|Library) (General Public License|GPL))'", ".", "'((\\s?v?|version)?3?)\\s*$#i'", "=>", "'http://opensource.org/licenses/LGPL-3.0'", ",", "'#^\\s*((new |revised |modified |three-clause |3-clause )BSD'", ".", "'( License)?)\\s*$#i'", "=>", "'http://opensource.org/licenses/BSD-3-Clause'", ",", "'#^\\s*((simplified |two-clause |2-clause |Free)BSD)( License)?\\s*$#i'", "=>", "'http://opensource.org/licenses/BSD-2-Clause'", ",", "'#^\\s*MIT( License)?\\s*$#i'", "=>", "'http://opensource.org/licenses/MIT'", ",", ")", ";", "$", "xpath", "=", "new", "\\", "DOMXPath", "(", "$", "xml", ")", ";", "$", "nodes", "=", "$", "xpath", "->", "query", "(", "'//tag[@name=\"license\"]/@description'", ")", ";", "/** @var \\DOMElement $node */", "foreach", "(", "$", "nodes", "as", "$", "node", ")", "{", "$", "license", "=", "$", "node", "->", "nodeValue", ";", "// FIXME: migrate to '#^' . PHPDOC::LINK_REGEX . '(\\s+(?P<text>.+))", "// ?$#u' once that const exists", "if", "(", "preg_match", "(", "'#^(?i)\\b(?P<url>(?:https?://|www\\d{0,3}\\.|[a-z0-9.\\-]+\\.'", ".", "'[a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+'", ".", "'(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|'", ".", "'[^\\s`!()\\[\\]{};:\\'\".,<>?«»“”‘’]))(\\s+(?P<text>.+))?$#u',", "", "$", "license", ",", "$", "matches", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "matches", "[", "'text'", "]", ")", "||", "!", "$", "matches", "[", "'text'", "]", ")", "{", "// set text to URL if not present", "$", "matches", "[", "'text'", "]", "=", "$", "matches", "[", "'url'", "]", ";", "}", "$", "node", "->", "parentNode", "->", "setAttribute", "(", "'link'", ",", "$", "matches", "[", "'url'", "]", ")", ";", "$", "node", "->", "nodeValue", "=", "$", "matches", "[", "'text'", "]", ";", "// bail out early", "continue", ";", "}", "// check map if any license matches", "foreach", "(", "$", "licenseMap", "as", "$", "regex", "=>", "$", "url", ")", "{", "if", "(", "preg_match", "(", "$", "regex", ",", "$", "license", ",", "$", "matches", ")", ")", "{", "$", "node", "->", "parentNode", "->", "setAttribute", "(", "'link'", ",", "$", "url", ")", ";", "// we're done here", "break", ";", "}", "}", "}", "return", "$", "xml", ";", "}" ]
Find all return tags that contain 'self' or '$this' and replace those terms for the name of the current class' type. @param \DOMDocument $xml Structure source to apply behaviour onto. @return \DOMDocument
[ "Find", "all", "return", "tags", "that", "contain", "self", "or", "$this", "and", "replace", "those", "terms", "for", "the", "name", "of", "the", "current", "class", "type", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Behaviour/Tag/LicenseTag.php#L27-L89
nabab/bbn
src/bbn/appui/mapperv2.php
mapperv2.save_config
public function save_config(array $cfg, $description, $class = 'grid') { if ( isset($cfg['elements']) ){ $copy = $cfg; unset($copy['elements']); $obj_param = [ 'id_project' => 1, 'class' => $class, 'description' => $description, 'configuration' => json_encode($copy) ]; if ( isset($cfg['table']) ){ $obj_param['table'] = $cfg['table']; } $this->db->insert($this->admin_db.'.'.$this->prefix.'objects', $obj_param); $id = $this->db->last_id(); $i = 1; foreach ( $cfg['elements'] as $name => $ele ){ $table = $column = false; if ( !empty($ele['appui']['table']) ){ $table = $ele['appui']['table']; } else if ( !empty($ele['table']) ){ $table = $ele['table']; } else if ( !empty($cfg['table']) ){ $table = $cfg['table']; } if ( $table && isset($ele['attr']['name']) ){ $column = $this->db->tfn($table).'.'.$this->db->csn($ele['attr']['name']); } $this->db->insert($this->admin_db.'.'.$this->prefix.'fields',[ 'id_obj' => $id, 'column' => ( $column ?: null ), 'title' => isset($ele['label']) ? $ele['label'] : null, 'position' => $i, 'configuration' => json_encode($ele) ]); $i++; } return $id; } }
php
public function save_config(array $cfg, $description, $class = 'grid') { if ( isset($cfg['elements']) ){ $copy = $cfg; unset($copy['elements']); $obj_param = [ 'id_project' => 1, 'class' => $class, 'description' => $description, 'configuration' => json_encode($copy) ]; if ( isset($cfg['table']) ){ $obj_param['table'] = $cfg['table']; } $this->db->insert($this->admin_db.'.'.$this->prefix.'objects', $obj_param); $id = $this->db->last_id(); $i = 1; foreach ( $cfg['elements'] as $name => $ele ){ $table = $column = false; if ( !empty($ele['appui']['table']) ){ $table = $ele['appui']['table']; } else if ( !empty($ele['table']) ){ $table = $ele['table']; } else if ( !empty($cfg['table']) ){ $table = $cfg['table']; } if ( $table && isset($ele['attr']['name']) ){ $column = $this->db->tfn($table).'.'.$this->db->csn($ele['attr']['name']); } $this->db->insert($this->admin_db.'.'.$this->prefix.'fields',[ 'id_obj' => $id, 'column' => ( $column ?: null ), 'title' => isset($ele['label']) ? $ele['label'] : null, 'position' => $i, 'configuration' => json_encode($ele) ]); $i++; } return $id; } }
[ "public", "function", "save_config", "(", "array", "$", "cfg", ",", "$", "description", ",", "$", "class", "=", "'grid'", ")", "{", "if", "(", "isset", "(", "$", "cfg", "[", "'elements'", "]", ")", ")", "{", "$", "copy", "=", "$", "cfg", ";", "unset", "(", "$", "copy", "[", "'elements'", "]", ")", ";", "$", "obj_param", "=", "[", "'id_project'", "=>", "1", ",", "'class'", "=>", "$", "class", ",", "'description'", "=>", "$", "description", ",", "'configuration'", "=>", "json_encode", "(", "$", "copy", ")", "]", ";", "if", "(", "isset", "(", "$", "cfg", "[", "'table'", "]", ")", ")", "{", "$", "obj_param", "[", "'table'", "]", "=", "$", "cfg", "[", "'table'", "]", ";", "}", "$", "this", "->", "db", "->", "insert", "(", "$", "this", "->", "admin_db", ".", "'.'", ".", "$", "this", "->", "prefix", ".", "'objects'", ",", "$", "obj_param", ")", ";", "$", "id", "=", "$", "this", "->", "db", "->", "last_id", "(", ")", ";", "$", "i", "=", "1", ";", "foreach", "(", "$", "cfg", "[", "'elements'", "]", "as", "$", "name", "=>", "$", "ele", ")", "{", "$", "table", "=", "$", "column", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "ele", "[", "'appui'", "]", "[", "'table'", "]", ")", ")", "{", "$", "table", "=", "$", "ele", "[", "'appui'", "]", "[", "'table'", "]", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "ele", "[", "'table'", "]", ")", ")", "{", "$", "table", "=", "$", "ele", "[", "'table'", "]", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "cfg", "[", "'table'", "]", ")", ")", "{", "$", "table", "=", "$", "cfg", "[", "'table'", "]", ";", "}", "if", "(", "$", "table", "&&", "isset", "(", "$", "ele", "[", "'attr'", "]", "[", "'name'", "]", ")", ")", "{", "$", "column", "=", "$", "this", "->", "db", "->", "tfn", "(", "$", "table", ")", ".", "'.'", ".", "$", "this", "->", "db", "->", "csn", "(", "$", "ele", "[", "'attr'", "]", "[", "'name'", "]", ")", ";", "}", "$", "this", "->", "db", "->", "insert", "(", "$", "this", "->", "admin_db", ".", "'.'", ".", "$", "this", "->", "prefix", ".", "'fields'", ",", "[", "'id_obj'", "=>", "$", "id", ",", "'column'", "=>", "(", "$", "column", "?", ":", "null", ")", ",", "'title'", "=>", "isset", "(", "$", "ele", "[", "'label'", "]", ")", "?", "$", "ele", "[", "'label'", "]", ":", "null", ",", "'position'", "=>", "$", "i", ",", "'configuration'", "=>", "json_encode", "(", "$", "ele", ")", "]", ")", ";", "$", "i", "++", ";", "}", "return", "$", "id", ";", "}", "}" ]
Saves the given configuration in the database and returns the new ID @param array $cfg @param string $class @return int|false
[ "Saves", "the", "given", "configuration", "in", "the", "database", "and", "returns", "the", "new", "ID" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/mapperv2.php#L122-L169
nabab/bbn
src/bbn/appui/mapperv2.php
mapperv2.get_default_field_config
public function get_default_field_config($table, $column){ // Looks in the db for columns corresponding to the given table if ( $this->check() && ($full_name = $this->db->cfn($column, $table)) && ($column = $this->db->csn($column)) && /** @var array */ ($table_cfg = $this->db->modelize($table)) && isset($table_cfg['fields'][$column]) ){ $col = $table_cfg['fields'][$column]; /** @var array $cfg The input configuration array to be returned */ $cfg = [ 'name' => $column, 'nullable' => $col['null'] ? true : false ]; // Case ENUM column if ( strpos($col['type'], 'enum') === 0 ){ preg_match_all("/'((?:[^']|\\\\.)*)'/", $col['extra'], $m); if ( isset($m[1]) ){ $cfg['field'] = 'dropdown'; $cfg['data'] = $m[1]; } } else{ /** @var boolean|string $ref Another column of which this one might be a reference */ $ref = false; // We look for a reference if ( isset($table_cfg['cols'][$column]) ){ foreach ( $table_cfg['cols'][$column] as $k ){ if ( isset($table_cfg['keys'][$k]['ref_column']) ){ $key = $table_cfg['keys'][$k]; $ref = [ 'db' => $key['ref_db'], 'table' => $key['ref_table'], 'column' => $key['ref_column'] ]; break; } } } // Case where the column is a reference to another if ( \is_array($ref) && ($ref_table_cfg = $this->db->modelize($ref['table'])) ){ // Arguments for select $cols = [$ref['column']]; // Looking for the first varchar column as the text foreach ( $ref_table_cfg['fields'] as $name => $def ){ if ( ($def['type'] === 'varchar') || ($def['type'] === 'text') ){ $cols = [ 'value' => $ref['column'], 'text' => $name ]; break; } } // If the number of entries isn't higher than MAX we get the data for a dropdown if ( $this->db->count($ref['table']) < BBN_MAX_DATA_ROWS ){ $cfg['data'] = $this->db->rselect_all($ref['table'], $cols); $cfg['field'] = 'dropdown'; } // Otherwise we keep the SQL with an autocomplete /** @todo The SQL is not needed... */ else{ $cfg['sql'] = $this->db->get_full_select($ref['table'], $cols); $cfg['field'] = 'autocomplete'; } } else if ( strpos($col['type'], 'char') !== false ){ $cfg['field'] = 'text'; } else if ( strpos($col['type'], 'float') !== false ){ $cfg['field'] = 'numeric'; $dec = explode(",", $col['maxlength']); if ( isset($dec[0], $dec[1]) ){ $cfg['widget']['options']['decimals'] = (int)$dec[1]; } $cfg['attr']['maxlength'] = isset($cfg['widget']['options']['decimals']) ? (int)($col['maxlength'] + 1) : (int)$col['maxlength']; $cfg['widget']['options']['format'] = empty($cfg['widget']['options']['decimals']) ? 'n0' : 'n2'; $cfg['attr']['type'] = 'number'; $cfg['widget']['options']['step'] = 10/pow(10, $cfg['widget']['options']['decimals']+1); $max = ''; $max_length = $cfg['attr']['maxlength']; if ( isset($cfg['options']['decimals']) ){ $max_length -= $cfg['options']['decimals']; } for ( $i = 0; $i < $max_length; $i++ ){ $max .= '9'; } $max = (int)$max; $cfg['widget']['options']['max'] = ( (float)$max > (int)$max ) ? (float)$max : (int)$max; $cfg['widget']['options']['min'] = $col['signed'] ? - $cfg['widget']['options']['max'] : 0; } else if ( strpos($col['type'], 'text') !== false ){ $cfg['field'] = 'editor'; } else if ( $col['type'] === 'datetime' ){ $cfg['field'] = 'datetime'; } else if ( $col['type'] === 'date' ){ $cfg['field'] = 'date'; } else if ( $col['type'] === 'time' ){ $cfg['field'] = 'time'; } else if ( $col['type'] === 'timestamp' ){ $cfg['field'] = 'datetime'; } else if ( strpos($col['type'], 'int') !== false ){ if ( $col['maxlength'] == 1 ){ $cfg['field'] = 'checkbox'; } else if ( !isset($cfg['field']) ){ if ( strpos($col['type'], 'unsigned') ){ $cfg['widget']['options']['min'] = 0; } else{ $cfg['widget']['options']['min'] = false; } $cfg['field'] = 'numeric'; $cfg['widget']['options']['decimals'] = 0; $cfg['widget']['options']['format'] = 'd'; $cfg['attr']['type'] = 'number'; } } } return $cfg; } }
php
public function get_default_field_config($table, $column){ // Looks in the db for columns corresponding to the given table if ( $this->check() && ($full_name = $this->db->cfn($column, $table)) && ($column = $this->db->csn($column)) && /** @var array */ ($table_cfg = $this->db->modelize($table)) && isset($table_cfg['fields'][$column]) ){ $col = $table_cfg['fields'][$column]; /** @var array $cfg The input configuration array to be returned */ $cfg = [ 'name' => $column, 'nullable' => $col['null'] ? true : false ]; // Case ENUM column if ( strpos($col['type'], 'enum') === 0 ){ preg_match_all("/'((?:[^']|\\\\.)*)'/", $col['extra'], $m); if ( isset($m[1]) ){ $cfg['field'] = 'dropdown'; $cfg['data'] = $m[1]; } } else{ /** @var boolean|string $ref Another column of which this one might be a reference */ $ref = false; // We look for a reference if ( isset($table_cfg['cols'][$column]) ){ foreach ( $table_cfg['cols'][$column] as $k ){ if ( isset($table_cfg['keys'][$k]['ref_column']) ){ $key = $table_cfg['keys'][$k]; $ref = [ 'db' => $key['ref_db'], 'table' => $key['ref_table'], 'column' => $key['ref_column'] ]; break; } } } // Case where the column is a reference to another if ( \is_array($ref) && ($ref_table_cfg = $this->db->modelize($ref['table'])) ){ // Arguments for select $cols = [$ref['column']]; // Looking for the first varchar column as the text foreach ( $ref_table_cfg['fields'] as $name => $def ){ if ( ($def['type'] === 'varchar') || ($def['type'] === 'text') ){ $cols = [ 'value' => $ref['column'], 'text' => $name ]; break; } } // If the number of entries isn't higher than MAX we get the data for a dropdown if ( $this->db->count($ref['table']) < BBN_MAX_DATA_ROWS ){ $cfg['data'] = $this->db->rselect_all($ref['table'], $cols); $cfg['field'] = 'dropdown'; } // Otherwise we keep the SQL with an autocomplete /** @todo The SQL is not needed... */ else{ $cfg['sql'] = $this->db->get_full_select($ref['table'], $cols); $cfg['field'] = 'autocomplete'; } } else if ( strpos($col['type'], 'char') !== false ){ $cfg['field'] = 'text'; } else if ( strpos($col['type'], 'float') !== false ){ $cfg['field'] = 'numeric'; $dec = explode(",", $col['maxlength']); if ( isset($dec[0], $dec[1]) ){ $cfg['widget']['options']['decimals'] = (int)$dec[1]; } $cfg['attr']['maxlength'] = isset($cfg['widget']['options']['decimals']) ? (int)($col['maxlength'] + 1) : (int)$col['maxlength']; $cfg['widget']['options']['format'] = empty($cfg['widget']['options']['decimals']) ? 'n0' : 'n2'; $cfg['attr']['type'] = 'number'; $cfg['widget']['options']['step'] = 10/pow(10, $cfg['widget']['options']['decimals']+1); $max = ''; $max_length = $cfg['attr']['maxlength']; if ( isset($cfg['options']['decimals']) ){ $max_length -= $cfg['options']['decimals']; } for ( $i = 0; $i < $max_length; $i++ ){ $max .= '9'; } $max = (int)$max; $cfg['widget']['options']['max'] = ( (float)$max > (int)$max ) ? (float)$max : (int)$max; $cfg['widget']['options']['min'] = $col['signed'] ? - $cfg['widget']['options']['max'] : 0; } else if ( strpos($col['type'], 'text') !== false ){ $cfg['field'] = 'editor'; } else if ( $col['type'] === 'datetime' ){ $cfg['field'] = 'datetime'; } else if ( $col['type'] === 'date' ){ $cfg['field'] = 'date'; } else if ( $col['type'] === 'time' ){ $cfg['field'] = 'time'; } else if ( $col['type'] === 'timestamp' ){ $cfg['field'] = 'datetime'; } else if ( strpos($col['type'], 'int') !== false ){ if ( $col['maxlength'] == 1 ){ $cfg['field'] = 'checkbox'; } else if ( !isset($cfg['field']) ){ if ( strpos($col['type'], 'unsigned') ){ $cfg['widget']['options']['min'] = 0; } else{ $cfg['widget']['options']['min'] = false; } $cfg['field'] = 'numeric'; $cfg['widget']['options']['decimals'] = 0; $cfg['widget']['options']['format'] = 'd'; $cfg['attr']['type'] = 'number'; } } } return $cfg; } }
[ "public", "function", "get_default_field_config", "(", "$", "table", ",", "$", "column", ")", "{", "// Looks in the db for columns corresponding to the given table", "if", "(", "$", "this", "->", "check", "(", ")", "&&", "(", "$", "full_name", "=", "$", "this", "->", "db", "->", "cfn", "(", "$", "column", ",", "$", "table", ")", ")", "&&", "(", "$", "column", "=", "$", "this", "->", "db", "->", "csn", "(", "$", "column", ")", ")", "&&", "/** @var array */", "(", "$", "table_cfg", "=", "$", "this", "->", "db", "->", "modelize", "(", "$", "table", ")", ")", "&&", "isset", "(", "$", "table_cfg", "[", "'fields'", "]", "[", "$", "column", "]", ")", ")", "{", "$", "col", "=", "$", "table_cfg", "[", "'fields'", "]", "[", "$", "column", "]", ";", "/** @var array $cfg The input configuration array to be returned */", "$", "cfg", "=", "[", "'name'", "=>", "$", "column", ",", "'nullable'", "=>", "$", "col", "[", "'null'", "]", "?", "true", ":", "false", "]", ";", "// Case ENUM column", "if", "(", "strpos", "(", "$", "col", "[", "'type'", "]", ",", "'enum'", ")", "===", "0", ")", "{", "preg_match_all", "(", "\"/'((?:[^']|\\\\\\\\.)*)'/\"", ",", "$", "col", "[", "'extra'", "]", ",", "$", "m", ")", ";", "if", "(", "isset", "(", "$", "m", "[", "1", "]", ")", ")", "{", "$", "cfg", "[", "'field'", "]", "=", "'dropdown'", ";", "$", "cfg", "[", "'data'", "]", "=", "$", "m", "[", "1", "]", ";", "}", "}", "else", "{", "/** @var boolean|string $ref Another column of which this one might be a reference */", "$", "ref", "=", "false", ";", "// We look for a reference", "if", "(", "isset", "(", "$", "table_cfg", "[", "'cols'", "]", "[", "$", "column", "]", ")", ")", "{", "foreach", "(", "$", "table_cfg", "[", "'cols'", "]", "[", "$", "column", "]", "as", "$", "k", ")", "{", "if", "(", "isset", "(", "$", "table_cfg", "[", "'keys'", "]", "[", "$", "k", "]", "[", "'ref_column'", "]", ")", ")", "{", "$", "key", "=", "$", "table_cfg", "[", "'keys'", "]", "[", "$", "k", "]", ";", "$", "ref", "=", "[", "'db'", "=>", "$", "key", "[", "'ref_db'", "]", ",", "'table'", "=>", "$", "key", "[", "'ref_table'", "]", ",", "'column'", "=>", "$", "key", "[", "'ref_column'", "]", "]", ";", "break", ";", "}", "}", "}", "// Case where the column is a reference to another", "if", "(", "\\", "is_array", "(", "$", "ref", ")", "&&", "(", "$", "ref_table_cfg", "=", "$", "this", "->", "db", "->", "modelize", "(", "$", "ref", "[", "'table'", "]", ")", ")", ")", "{", "// Arguments for select", "$", "cols", "=", "[", "$", "ref", "[", "'column'", "]", "]", ";", "// Looking for the first varchar column as the text", "foreach", "(", "$", "ref_table_cfg", "[", "'fields'", "]", "as", "$", "name", "=>", "$", "def", ")", "{", "if", "(", "(", "$", "def", "[", "'type'", "]", "===", "'varchar'", ")", "||", "(", "$", "def", "[", "'type'", "]", "===", "'text'", ")", ")", "{", "$", "cols", "=", "[", "'value'", "=>", "$", "ref", "[", "'column'", "]", ",", "'text'", "=>", "$", "name", "]", ";", "break", ";", "}", "}", "// If the number of entries isn't higher than MAX we get the data for a dropdown", "if", "(", "$", "this", "->", "db", "->", "count", "(", "$", "ref", "[", "'table'", "]", ")", "<", "BBN_MAX_DATA_ROWS", ")", "{", "$", "cfg", "[", "'data'", "]", "=", "$", "this", "->", "db", "->", "rselect_all", "(", "$", "ref", "[", "'table'", "]", ",", "$", "cols", ")", ";", "$", "cfg", "[", "'field'", "]", "=", "'dropdown'", ";", "}", "// Otherwise we keep the SQL with an autocomplete", "/** @todo The SQL is not needed... */", "else", "{", "$", "cfg", "[", "'sql'", "]", "=", "$", "this", "->", "db", "->", "get_full_select", "(", "$", "ref", "[", "'table'", "]", ",", "$", "cols", ")", ";", "$", "cfg", "[", "'field'", "]", "=", "'autocomplete'", ";", "}", "}", "else", "if", "(", "strpos", "(", "$", "col", "[", "'type'", "]", ",", "'char'", ")", "!==", "false", ")", "{", "$", "cfg", "[", "'field'", "]", "=", "'text'", ";", "}", "else", "if", "(", "strpos", "(", "$", "col", "[", "'type'", "]", ",", "'float'", ")", "!==", "false", ")", "{", "$", "cfg", "[", "'field'", "]", "=", "'numeric'", ";", "$", "dec", "=", "explode", "(", "\",\"", ",", "$", "col", "[", "'maxlength'", "]", ")", ";", "if", "(", "isset", "(", "$", "dec", "[", "0", "]", ",", "$", "dec", "[", "1", "]", ")", ")", "{", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'decimals'", "]", "=", "(", "int", ")", "$", "dec", "[", "1", "]", ";", "}", "$", "cfg", "[", "'attr'", "]", "[", "'maxlength'", "]", "=", "isset", "(", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'decimals'", "]", ")", "?", "(", "int", ")", "(", "$", "col", "[", "'maxlength'", "]", "+", "1", ")", ":", "(", "int", ")", "$", "col", "[", "'maxlength'", "]", ";", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'format'", "]", "=", "empty", "(", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'decimals'", "]", ")", "?", "'n0'", ":", "'n2'", ";", "$", "cfg", "[", "'attr'", "]", "[", "'type'", "]", "=", "'number'", ";", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'step'", "]", "=", "10", "/", "pow", "(", "10", ",", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'decimals'", "]", "+", "1", ")", ";", "$", "max", "=", "''", ";", "$", "max_length", "=", "$", "cfg", "[", "'attr'", "]", "[", "'maxlength'", "]", ";", "if", "(", "isset", "(", "$", "cfg", "[", "'options'", "]", "[", "'decimals'", "]", ")", ")", "{", "$", "max_length", "-=", "$", "cfg", "[", "'options'", "]", "[", "'decimals'", "]", ";", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "max_length", ";", "$", "i", "++", ")", "{", "$", "max", ".=", "'9'", ";", "}", "$", "max", "=", "(", "int", ")", "$", "max", ";", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'max'", "]", "=", "(", "(", "float", ")", "$", "max", ">", "(", "int", ")", "$", "max", ")", "?", "(", "float", ")", "$", "max", ":", "(", "int", ")", "$", "max", ";", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'min'", "]", "=", "$", "col", "[", "'signed'", "]", "?", "-", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'max'", "]", ":", "0", ";", "}", "else", "if", "(", "strpos", "(", "$", "col", "[", "'type'", "]", ",", "'text'", ")", "!==", "false", ")", "{", "$", "cfg", "[", "'field'", "]", "=", "'editor'", ";", "}", "else", "if", "(", "$", "col", "[", "'type'", "]", "===", "'datetime'", ")", "{", "$", "cfg", "[", "'field'", "]", "=", "'datetime'", ";", "}", "else", "if", "(", "$", "col", "[", "'type'", "]", "===", "'date'", ")", "{", "$", "cfg", "[", "'field'", "]", "=", "'date'", ";", "}", "else", "if", "(", "$", "col", "[", "'type'", "]", "===", "'time'", ")", "{", "$", "cfg", "[", "'field'", "]", "=", "'time'", ";", "}", "else", "if", "(", "$", "col", "[", "'type'", "]", "===", "'timestamp'", ")", "{", "$", "cfg", "[", "'field'", "]", "=", "'datetime'", ";", "}", "else", "if", "(", "strpos", "(", "$", "col", "[", "'type'", "]", ",", "'int'", ")", "!==", "false", ")", "{", "if", "(", "$", "col", "[", "'maxlength'", "]", "==", "1", ")", "{", "$", "cfg", "[", "'field'", "]", "=", "'checkbox'", ";", "}", "else", "if", "(", "!", "isset", "(", "$", "cfg", "[", "'field'", "]", ")", ")", "{", "if", "(", "strpos", "(", "$", "col", "[", "'type'", "]", ",", "'unsigned'", ")", ")", "{", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'min'", "]", "=", "0", ";", "}", "else", "{", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'min'", "]", "=", "false", ";", "}", "$", "cfg", "[", "'field'", "]", "=", "'numeric'", ";", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'decimals'", "]", "=", "0", ";", "$", "cfg", "[", "'widget'", "]", "[", "'options'", "]", "[", "'format'", "]", "=", "'d'", ";", "$", "cfg", "[", "'attr'", "]", "[", "'type'", "]", "=", "'number'", ";", "}", "}", "}", "return", "$", "cfg", ";", "}", "}" ]
Creates an array for configuring an instance of input for a given field in a given table @param string $table The database's table @param string $column The table's column @return array $cfg a configuration array for bbn\html\input
[ "Creates", "an", "array", "for", "configuring", "an", "instance", "of", "input", "for", "a", "given", "field", "in", "a", "given", "table" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/mapperv2.php#L547-L675
nabab/bbn
src/bbn/appui/mapperv2.php
mapperv2.create_tables
public function create_tables(){ if ( $this->db ){ if ( !\in_array($this->prefix.'tables', $this->db->get_tables()) ){ $this->db->disable_keys(); return $this->db->query(" -- DROP TABLE IF EXISTS `{$this->prefix}clients`; CREATE TABLE IF NOT EXISTS `{$this->prefix}clients` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `nom` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- DROP TABLE IF EXISTS `{$this->prefix}columns`; CREATE TABLE IF NOT EXISTS `{$this->prefix}columns` ( `id` varchar(180) NOT NULL, `table` varchar(130) NOT NULL, `column` varchar(49) NOT NULL, `position` tinyint(3) unsigned NOT NULL, `type` varchar(50) NOT NULL, `null` tinyint(1) unsigned NOT NULL, `key` varchar(3) DEFAULT NULL, `default` text, `config` text, PRIMARY KEY (`id`), UNIQUE KEY `table` (`table`,`column`), UNIQUE KEY `table_2` (`table`,`position`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- DROP TABLE IF EXISTS `{$this->prefix}dbs`; CREATE TABLE IF NOT EXISTS `{$this->prefix}dbs` ( `id` varchar(80) NOT NULL, `id_client` int(10) unsigned DEFAULT NULL, `host` varchar(49) NOT NULL DEFAULT 'localhost', `db` varchar(30) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `host_db` (`host`,`db`), KEY `db` (`db`), KEY `id_client` (`id_client`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- DROP TABLE IF EXISTS `{$this->prefix}fields`; CREATE TABLE IF NOT EXISTS `{$this->prefix}fields` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `id_form` int(10) unsigned NOT NULL, `column` varchar(180) CHARACTER SET utf8 NOT NULL, `title` varchar(100) CHARACTER SET utf8 NOT NULL, `position` tinyint(3) unsigned NOT NULL, `configuration` text CHARACTER SET utf8 NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id_form_column` (`id_form`,`column`), KEY `id_form` (`id_form`), KEY `column` (`column`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- DROP TABLE IF EXISTS `{$this->prefix}forms`; CREATE TABLE IF NOT EXISTS `{$this->prefix}forms` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `id_project` int(10) unsigned NOT NULL, `configuration` text CHARACTER SET utf8 NOT NULL, PRIMARY KEY (`id`), KEY `id_project` (`id_project`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- DROP TABLE IF EXISTS `{$this->prefix}history`; CREATE TABLE IF NOT EXISTS `{$this->prefix}history` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `operation` enum('INSERT','UPDATE','DELETE') NOT NULL, `line` int(10) unsigned NOT NULL, `column` varchar(180) NOT NULL, `old` text DEFAULT NULL, `chrono` decimal(14,4) unsigned NOT NULL, `id_user` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `id_user` (`id_user`), KEY `column` (`column`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=52 ; -- DROP TABLE IF EXISTS `{$this->prefix}keys`; CREATE TABLE IF NOT EXISTS `{$this->prefix}keys` ( `id` varchar(230) NOT NULL, `key` varchar(49) NOT NULL, `column` varchar(180) NOT NULL, `position` tinyint(3) unsigned NOT NULL, `ref_column` varchar(180) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `key` (`key`,`column`), KEY `ref_column` (`ref_column`), KEY `column` (`column`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- DROP TABLE IF EXISTS `{$this->prefix}projects`; CREATE TABLE IF NOT EXISTS `{$this->prefix}projects` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `id_client` int(10) unsigned NOT NULL, `db` varchar(80) CHARACTER SET utf8 DEFAULT NULL, `name` varchar(50) CHARACTER SET utf8 NOT NULL, `config` text CHARACTER SET utf8, PRIMARY KEY (`id`), UNIQUE KEY `id_client_2` (`id_client`,`name`), KEY `db` (`db`), KEY `id_client` (`id_client`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- DROP TABLE IF EXISTS `{$this->prefix}tables`; CREATE TABLE IF NOT EXISTS `{$this->prefix}tables` ( `id` varchar(130) NOT NULL, `db` varchar(80) NOT NULL, `table` varchar(49) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `db_table` (`db`,`table`), KEY `table` (`table`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `{$this->prefix}columns` ADD CONSTRAINT `{$this->prefix}columns_ibfk_1` FOREIGN KEY (`table`) REFERENCES `{$this->prefix}tables` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `{$this->prefix}dbs` ADD CONSTRAINT `{$this->prefix}dbs_ibfk_1` FOREIGN KEY (`id_client`) REFERENCES `{$this->prefix}clients` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION; ALTER TABLE `{$this->prefix}history` ADD CONSTRAINT `{$this->prefix}history_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `{$this->prefix}users` (`id`) ON UPDATE NO ACTION, ADD CONSTRAINT `{$this->prefix}history_ibfk_2` FOREIGN KEY (`column`) REFERENCES `{$this->prefix}columns` (`id`) ON UPDATE CASCADE; ALTER TABLE `{$this->prefix}keys` ADD CONSTRAINT `{$this->prefix}keys_ibfk_1` FOREIGN KEY (`column`) REFERENCES `{$this->prefix}columns` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `{$this->prefix}keys_ibfk_2` FOREIGN KEY (`ref_column`) REFERENCES `{$this->prefix}columns` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `{$this->prefix}projects` ADD CONSTRAINT `{$this->prefix}projects_ibfk_2` FOREIGN KEY (`db`) REFERENCES `{$this->prefix}dbs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `{$this->prefix}projects_ibfk_1` FOREIGN KEY (`id_client`) REFERENCES `{$this->prefix}clients` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION; ALTER TABLE `{$this->prefix}tables` ADD CONSTRAINT `{$this->prefix}tables_ibfk_1` FOREIGN KEY (`db`) REFERENCES `{$this->prefix}dbs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; "); $this->db->enable_keys(); } } }
php
public function create_tables(){ if ( $this->db ){ if ( !\in_array($this->prefix.'tables', $this->db->get_tables()) ){ $this->db->disable_keys(); return $this->db->query(" -- DROP TABLE IF EXISTS `{$this->prefix}clients`; CREATE TABLE IF NOT EXISTS `{$this->prefix}clients` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `nom` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- DROP TABLE IF EXISTS `{$this->prefix}columns`; CREATE TABLE IF NOT EXISTS `{$this->prefix}columns` ( `id` varchar(180) NOT NULL, `table` varchar(130) NOT NULL, `column` varchar(49) NOT NULL, `position` tinyint(3) unsigned NOT NULL, `type` varchar(50) NOT NULL, `null` tinyint(1) unsigned NOT NULL, `key` varchar(3) DEFAULT NULL, `default` text, `config` text, PRIMARY KEY (`id`), UNIQUE KEY `table` (`table`,`column`), UNIQUE KEY `table_2` (`table`,`position`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- DROP TABLE IF EXISTS `{$this->prefix}dbs`; CREATE TABLE IF NOT EXISTS `{$this->prefix}dbs` ( `id` varchar(80) NOT NULL, `id_client` int(10) unsigned DEFAULT NULL, `host` varchar(49) NOT NULL DEFAULT 'localhost', `db` varchar(30) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `host_db` (`host`,`db`), KEY `db` (`db`), KEY `id_client` (`id_client`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- DROP TABLE IF EXISTS `{$this->prefix}fields`; CREATE TABLE IF NOT EXISTS `{$this->prefix}fields` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `id_form` int(10) unsigned NOT NULL, `column` varchar(180) CHARACTER SET utf8 NOT NULL, `title` varchar(100) CHARACTER SET utf8 NOT NULL, `position` tinyint(3) unsigned NOT NULL, `configuration` text CHARACTER SET utf8 NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id_form_column` (`id_form`,`column`), KEY `id_form` (`id_form`), KEY `column` (`column`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- DROP TABLE IF EXISTS `{$this->prefix}forms`; CREATE TABLE IF NOT EXISTS `{$this->prefix}forms` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `id_project` int(10) unsigned NOT NULL, `configuration` text CHARACTER SET utf8 NOT NULL, PRIMARY KEY (`id`), KEY `id_project` (`id_project`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- DROP TABLE IF EXISTS `{$this->prefix}history`; CREATE TABLE IF NOT EXISTS `{$this->prefix}history` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `operation` enum('INSERT','UPDATE','DELETE') NOT NULL, `line` int(10) unsigned NOT NULL, `column` varchar(180) NOT NULL, `old` text DEFAULT NULL, `chrono` decimal(14,4) unsigned NOT NULL, `id_user` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `id_user` (`id_user`), KEY `column` (`column`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=52 ; -- DROP TABLE IF EXISTS `{$this->prefix}keys`; CREATE TABLE IF NOT EXISTS `{$this->prefix}keys` ( `id` varchar(230) NOT NULL, `key` varchar(49) NOT NULL, `column` varchar(180) NOT NULL, `position` tinyint(3) unsigned NOT NULL, `ref_column` varchar(180) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `key` (`key`,`column`), KEY `ref_column` (`ref_column`), KEY `column` (`column`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- DROP TABLE IF EXISTS `{$this->prefix}projects`; CREATE TABLE IF NOT EXISTS `{$this->prefix}projects` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `id_client` int(10) unsigned NOT NULL, `db` varchar(80) CHARACTER SET utf8 DEFAULT NULL, `name` varchar(50) CHARACTER SET utf8 NOT NULL, `config` text CHARACTER SET utf8, PRIMARY KEY (`id`), UNIQUE KEY `id_client_2` (`id_client`,`name`), KEY `db` (`db`), KEY `id_client` (`id_client`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- DROP TABLE IF EXISTS `{$this->prefix}tables`; CREATE TABLE IF NOT EXISTS `{$this->prefix}tables` ( `id` varchar(130) NOT NULL, `db` varchar(80) NOT NULL, `table` varchar(49) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `db_table` (`db`,`table`), KEY `table` (`table`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `{$this->prefix}columns` ADD CONSTRAINT `{$this->prefix}columns_ibfk_1` FOREIGN KEY (`table`) REFERENCES `{$this->prefix}tables` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `{$this->prefix}dbs` ADD CONSTRAINT `{$this->prefix}dbs_ibfk_1` FOREIGN KEY (`id_client`) REFERENCES `{$this->prefix}clients` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION; ALTER TABLE `{$this->prefix}history` ADD CONSTRAINT `{$this->prefix}history_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `{$this->prefix}users` (`id`) ON UPDATE NO ACTION, ADD CONSTRAINT `{$this->prefix}history_ibfk_2` FOREIGN KEY (`column`) REFERENCES `{$this->prefix}columns` (`id`) ON UPDATE CASCADE; ALTER TABLE `{$this->prefix}keys` ADD CONSTRAINT `{$this->prefix}keys_ibfk_1` FOREIGN KEY (`column`) REFERENCES `{$this->prefix}columns` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `{$this->prefix}keys_ibfk_2` FOREIGN KEY (`ref_column`) REFERENCES `{$this->prefix}columns` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `{$this->prefix}projects` ADD CONSTRAINT `{$this->prefix}projects_ibfk_2` FOREIGN KEY (`db`) REFERENCES `{$this->prefix}dbs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `{$this->prefix}projects_ibfk_1` FOREIGN KEY (`id_client`) REFERENCES `{$this->prefix}clients` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION; ALTER TABLE `{$this->prefix}tables` ADD CONSTRAINT `{$this->prefix}tables_ibfk_1` FOREIGN KEY (`db`) REFERENCES `{$this->prefix}dbs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; "); $this->db->enable_keys(); } } }
[ "public", "function", "create_tables", "(", ")", "{", "if", "(", "$", "this", "->", "db", ")", "{", "if", "(", "!", "\\", "in_array", "(", "$", "this", "->", "prefix", ".", "'tables'", ",", "$", "this", "->", "db", "->", "get_tables", "(", ")", ")", ")", "{", "$", "this", "->", "db", "->", "disable_keys", "(", ")", ";", "return", "$", "this", "->", "db", "->", "query", "(", "\"\n -- DROP TABLE IF EXISTS `{$this->prefix}clients`;\n CREATE TABLE IF NOT EXISTS `{$this->prefix}clients` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `nom` varchar(100) NOT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;\n\n -- DROP TABLE IF EXISTS `{$this->prefix}columns`;\n CREATE TABLE IF NOT EXISTS `{$this->prefix}columns` (\n `id` varchar(180) NOT NULL,\n `table` varchar(130) NOT NULL,\n `column` varchar(49) NOT NULL,\n `position` tinyint(3) unsigned NOT NULL,\n `type` varchar(50) NOT NULL,\n `null` tinyint(1) unsigned NOT NULL,\n `key` varchar(3) DEFAULT NULL,\n `default` text,\n `config` text,\n PRIMARY KEY (`id`),\n UNIQUE KEY `table` (`table`,`column`),\n UNIQUE KEY `table_2` (`table`,`position`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n -- DROP TABLE IF EXISTS `{$this->prefix}dbs`;\n CREATE TABLE IF NOT EXISTS `{$this->prefix}dbs` (\n `id` varchar(80) NOT NULL,\n `id_client` int(10) unsigned DEFAULT NULL,\n `host` varchar(49) NOT NULL DEFAULT 'localhost',\n `db` varchar(30) NOT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `host_db` (`host`,`db`),\n KEY `db` (`db`),\n KEY `id_client` (`id_client`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n -- DROP TABLE IF EXISTS `{$this->prefix}fields`;\n CREATE TABLE IF NOT EXISTS `{$this->prefix}fields` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `id_form` int(10) unsigned NOT NULL,\n `column` varchar(180) CHARACTER SET utf8 NOT NULL,\n `title` varchar(100) CHARACTER SET utf8 NOT NULL,\n `position` tinyint(3) unsigned NOT NULL,\n `configuration` text CHARACTER SET utf8 NOT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `id_form_column` (`id_form`,`column`),\n KEY `id_form` (`id_form`),\n KEY `column` (`column`)\n ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;\n\n -- DROP TABLE IF EXISTS `{$this->prefix}forms`;\n CREATE TABLE IF NOT EXISTS `{$this->prefix}forms` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `id_project` int(10) unsigned NOT NULL,\n `configuration` text CHARACTER SET utf8 NOT NULL,\n PRIMARY KEY (`id`),\n KEY `id_project` (`id_project`)\n ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;\n\n -- DROP TABLE IF EXISTS `{$this->prefix}history`;\n CREATE TABLE IF NOT EXISTS `{$this->prefix}history` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `operation` enum('INSERT','UPDATE','DELETE') NOT NULL,\n `line` int(10) unsigned NOT NULL,\n `column` varchar(180) NOT NULL,\n `old` text DEFAULT NULL,\n `chrono` decimal(14,4) unsigned NOT NULL,\n `id_user` int(10) unsigned NOT NULL,\n PRIMARY KEY (`id`),\n KEY `id_user` (`id_user`),\n KEY `column` (`column`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=52 ;\n\n -- DROP TABLE IF EXISTS `{$this->prefix}keys`;\n CREATE TABLE IF NOT EXISTS `{$this->prefix}keys` (\n `id` varchar(230) NOT NULL,\n `key` varchar(49) NOT NULL,\n `column` varchar(180) NOT NULL,\n `position` tinyint(3) unsigned NOT NULL,\n `ref_column` varchar(180) DEFAULT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `key` (`key`,`column`),\n KEY `ref_column` (`ref_column`),\n KEY `column` (`column`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n -- DROP TABLE IF EXISTS `{$this->prefix}projects`;\n CREATE TABLE IF NOT EXISTS `{$this->prefix}projects` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `id_client` int(10) unsigned NOT NULL,\n `db` varchar(80) CHARACTER SET utf8 DEFAULT NULL,\n `name` varchar(50) CHARACTER SET utf8 NOT NULL,\n `config` text CHARACTER SET utf8,\n PRIMARY KEY (`id`),\n UNIQUE KEY `id_client_2` (`id_client`,`name`),\n KEY `db` (`db`),\n KEY `id_client` (`id_client`)\n ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;\n\n -- DROP TABLE IF EXISTS `{$this->prefix}tables`;\n CREATE TABLE IF NOT EXISTS `{$this->prefix}tables` (\n `id` varchar(130) NOT NULL,\n `db` varchar(80) NOT NULL,\n `table` varchar(49) NOT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `db_table` (`db`,`table`),\n KEY `table` (`table`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n\n ALTER TABLE `{$this->prefix}columns`\n ADD CONSTRAINT `{$this->prefix}columns_ibfk_1` FOREIGN KEY (`table`) REFERENCES `{$this->prefix}tables` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;\n\n ALTER TABLE `{$this->prefix}dbs`\n ADD CONSTRAINT `{$this->prefix}dbs_ibfk_1` FOREIGN KEY (`id_client`) REFERENCES `{$this->prefix}clients` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;\n\n ALTER TABLE `{$this->prefix}history`\n ADD CONSTRAINT `{$this->prefix}history_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `{$this->prefix}users` (`id`) ON UPDATE NO ACTION,\n ADD CONSTRAINT `{$this->prefix}history_ibfk_2` FOREIGN KEY (`column`) REFERENCES `{$this->prefix}columns` (`id`) ON UPDATE CASCADE;\n\n ALTER TABLE `{$this->prefix}keys`\n ADD CONSTRAINT `{$this->prefix}keys_ibfk_1` FOREIGN KEY (`column`) REFERENCES `{$this->prefix}columns` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n ADD CONSTRAINT `{$this->prefix}keys_ibfk_2` FOREIGN KEY (`ref_column`) REFERENCES `{$this->prefix}columns` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;\n\n ALTER TABLE `{$this->prefix}projects`\n ADD CONSTRAINT `{$this->prefix}projects_ibfk_2` FOREIGN KEY (`db`) REFERENCES `{$this->prefix}dbs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n ADD CONSTRAINT `{$this->prefix}projects_ibfk_1` FOREIGN KEY (`id_client`) REFERENCES `{$this->prefix}clients` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;\n\n ALTER TABLE `{$this->prefix}tables`\n ADD CONSTRAINT `{$this->prefix}tables_ibfk_1` FOREIGN KEY (`db`) REFERENCES `{$this->prefix}dbs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;\n \"", ")", ";", "$", "this", "->", "db", "->", "enable_keys", "(", ")", ";", "}", "}", "}" ]
Creates the empty appui tables @return void
[ "Creates", "the", "empty", "appui", "tables" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/mapperv2.php#L838-L976
Speicher210/monsum-api
src/Service/Subscription/SubscriptionService.php
SubscriptionService.getSubscriptionById
public function getSubscriptionById($subscriptionId) { $subscriptions = $this ->getSubscriptions(null, null, null, $subscriptionId) ->getResponse() ->getSubscriptions(); return count($subscriptions) ? reset($subscriptions) : null; }
php
public function getSubscriptionById($subscriptionId) { $subscriptions = $this ->getSubscriptions(null, null, null, $subscriptionId) ->getResponse() ->getSubscriptions(); return count($subscriptions) ? reset($subscriptions) : null; }
[ "public", "function", "getSubscriptionById", "(", "$", "subscriptionId", ")", "{", "$", "subscriptions", "=", "$", "this", "->", "getSubscriptions", "(", "null", ",", "null", ",", "null", ",", "$", "subscriptionId", ")", "->", "getResponse", "(", ")", "->", "getSubscriptions", "(", ")", ";", "return", "count", "(", "$", "subscriptions", ")", "?", "reset", "(", "$", "subscriptions", ")", ":", "null", ";", "}" ]
Get one subscription by using the Monsum subscription ID. @param integer $subscriptionId The Monsum subscription ID. @return Subscription|null
[ "Get", "one", "subscription", "by", "using", "the", "Monsum", "subscription", "ID", "." ]
train
https://github.com/Speicher210/monsum-api/blob/4611a048097de5d2b0efe9d4426779c783c0af4d/src/Service/Subscription/SubscriptionService.php#L21-L29
Speicher210/monsum-api
src/Service/Subscription/SubscriptionService.php
SubscriptionService.getSubscriptions
public function getSubscriptions( $customerId = null, $externalCustomerId = null, $subscriptionExternalId = null, $subscriptionId = null ) { $requestData = new Get\RequestData(); $requestData->setCustomerId($customerId); $requestData->setExternalCustomerId($externalCustomerId); $requestData->setSubscriptionExternalId($subscriptionExternalId); $requestData->setSubscriptionId($subscriptionId); $request = new Get\Request($requestData); return $this->sendRequest($request, Get\ApiResponse::class); }
php
public function getSubscriptions( $customerId = null, $externalCustomerId = null, $subscriptionExternalId = null, $subscriptionId = null ) { $requestData = new Get\RequestData(); $requestData->setCustomerId($customerId); $requestData->setExternalCustomerId($externalCustomerId); $requestData->setSubscriptionExternalId($subscriptionExternalId); $requestData->setSubscriptionId($subscriptionId); $request = new Get\Request($requestData); return $this->sendRequest($request, Get\ApiResponse::class); }
[ "public", "function", "getSubscriptions", "(", "$", "customerId", "=", "null", ",", "$", "externalCustomerId", "=", "null", ",", "$", "subscriptionExternalId", "=", "null", ",", "$", "subscriptionId", "=", "null", ")", "{", "$", "requestData", "=", "new", "Get", "\\", "RequestData", "(", ")", ";", "$", "requestData", "->", "setCustomerId", "(", "$", "customerId", ")", ";", "$", "requestData", "->", "setExternalCustomerId", "(", "$", "externalCustomerId", ")", ";", "$", "requestData", "->", "setSubscriptionExternalId", "(", "$", "subscriptionExternalId", ")", ";", "$", "requestData", "->", "setSubscriptionId", "(", "$", "subscriptionId", ")", ";", "$", "request", "=", "new", "Get", "\\", "Request", "(", "$", "requestData", ")", ";", "return", "$", "this", "->", "sendRequest", "(", "$", "request", ",", "Get", "\\", "ApiResponse", "::", "class", ")", ";", "}" ]
Get the subscriptions. @param integer $customerId The customer ID. @param string $externalCustomerId The external customer ID. @param string $subscriptionExternalId The external subscription ID. @param integer $subscriptionId The subscription ID. @return Get\ApiResponse
[ "Get", "the", "subscriptions", "." ]
train
https://github.com/Speicher210/monsum-api/blob/4611a048097de5d2b0efe9d4426779c783c0af4d/src/Service/Subscription/SubscriptionService.php#L40-L55