id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
26,200
spiral/security
src/Traits/GuardedTrait.php
GuardedTrait.resolvePermission
protected function resolvePermission(string $permission): string { if (defined('static::GUARD_NAMESPACE')) { //Yay! Isolation $permission = constant(get_called_class() . '::' . 'GUARD_NAMESPACE') . '.' . $permission; } return $permission; }
php
protected function resolvePermission(string $permission): string { if (defined('static::GUARD_NAMESPACE')) { //Yay! Isolation $permission = constant(get_called_class() . '::' . 'GUARD_NAMESPACE') . '.' . $permission; } return $permission; }
[ "protected", "function", "resolvePermission", "(", "string", "$", "permission", ")", ":", "string", "{", "if", "(", "defined", "(", "'static::GUARD_NAMESPACE'", ")", ")", "{", "//Yay! Isolation", "$", "permission", "=", "constant", "(", "get_called_class", "(", ")", ".", "'::'", ".", "'GUARD_NAMESPACE'", ")", ".", "'.'", ".", "$", "permission", ";", "}", "return", "$", "permission", ";", "}" ]
Automatically prepend permission name with local RBAC namespace. @param string $permission @return string
[ "Automatically", "prepend", "permission", "name", "with", "local", "RBAC", "namespace", "." ]
a36decbf237460e1e2059bb12b41c69a1cd59ec3
https://github.com/spiral/security/blob/a36decbf237460e1e2059bb12b41c69a1cd59ec3/src/Traits/GuardedTrait.php#L64-L72
26,201
spiral/security
src/RuleManager.php
RuleManager.validateRule
private function validateRule($rule): bool { if ($rule instanceof \Closure || $rule instanceof RuleInterface) { return true; } if (is_array($rule)) { return is_callable($rule, true); } if (is_string($rule) && class_exists($rule)) { try { $reflection = new \ReflectionClass($rule); } catch (\ReflectionException $e) { return false; } return $reflection->isSubclassOf(RuleInterface::class); } return false; }
php
private function validateRule($rule): bool { if ($rule instanceof \Closure || $rule instanceof RuleInterface) { return true; } if (is_array($rule)) { return is_callable($rule, true); } if (is_string($rule) && class_exists($rule)) { try { $reflection = new \ReflectionClass($rule); } catch (\ReflectionException $e) { return false; } return $reflection->isSubclassOf(RuleInterface::class); } return false; }
[ "private", "function", "validateRule", "(", "$", "rule", ")", ":", "bool", "{", "if", "(", "$", "rule", "instanceof", "\\", "Closure", "||", "$", "rule", "instanceof", "RuleInterface", ")", "{", "return", "true", ";", "}", "if", "(", "is_array", "(", "$", "rule", ")", ")", "{", "return", "is_callable", "(", "$", "rule", ",", "true", ")", ";", "}", "if", "(", "is_string", "(", "$", "rule", ")", "&&", "class_exists", "(", "$", "rule", ")", ")", "{", "try", "{", "$", "reflection", "=", "new", "\\", "ReflectionClass", "(", "$", "rule", ")", ";", "}", "catch", "(", "\\", "ReflectionException", "$", "e", ")", "{", "return", "false", ";", "}", "return", "$", "reflection", "->", "isSubclassOf", "(", "RuleInterface", "::", "class", ")", ";", "}", "return", "false", ";", "}" ]
Must return true if rule is valid. @param mixed $rule @return bool
[ "Must", "return", "true", "if", "rule", "is", "valid", "." ]
a36decbf237460e1e2059bb12b41c69a1cd59ec3
https://github.com/spiral/security/blob/a36decbf237460e1e2059bb12b41c69a1cd59ec3/src/RuleManager.php#L135-L156
26,202
mirko-pagliai/cakephp-assets
src/View/Helper/AssetHelper.php
AssetHelper.path
protected function path($path, $type) { if (Configure::read('debug') && !Configure::read('Assets.force')) { return $path; } $asset = new AssetsCreator($path, $type); $path = '/assets/' . $asset->create(); //Appends the timestamp $stamp = Configure::read('Asset.timestamp'); if ($stamp === 'force' || ($stamp === true && Configure::read('debug'))) { $path = sprintf('%s.%s?%s', $path, $type, filemtime($asset->path())); } return $path; }
php
protected function path($path, $type) { if (Configure::read('debug') && !Configure::read('Assets.force')) { return $path; } $asset = new AssetsCreator($path, $type); $path = '/assets/' . $asset->create(); //Appends the timestamp $stamp = Configure::read('Asset.timestamp'); if ($stamp === 'force' || ($stamp === true && Configure::read('debug'))) { $path = sprintf('%s.%s?%s', $path, $type, filemtime($asset->path())); } return $path; }
[ "protected", "function", "path", "(", "$", "path", ",", "$", "type", ")", "{", "if", "(", "Configure", "::", "read", "(", "'debug'", ")", "&&", "!", "Configure", "::", "read", "(", "'Assets.force'", ")", ")", "{", "return", "$", "path", ";", "}", "$", "asset", "=", "new", "AssetsCreator", "(", "$", "path", ",", "$", "type", ")", ";", "$", "path", "=", "'/assets/'", ".", "$", "asset", "->", "create", "(", ")", ";", "//Appends the timestamp", "$", "stamp", "=", "Configure", "::", "read", "(", "'Asset.timestamp'", ")", ";", "if", "(", "$", "stamp", "===", "'force'", "||", "(", "$", "stamp", "===", "true", "&&", "Configure", "::", "read", "(", "'debug'", ")", ")", ")", "{", "$", "path", "=", "sprintf", "(", "'%s.%s?%s'", ",", "$", "path", ",", "$", "type", ",", "filemtime", "(", "$", "asset", "->", "path", "(", ")", ")", ")", ";", "}", "return", "$", "path", ";", "}" ]
Gets the asset path @param string|array $path String or array of css/js files @param string $type `css` or `js` @return string Asset path @uses Assets\Utility\AssetsCreator::create() @uses Assets\Utility\AssetsCreator::path()
[ "Gets", "the", "asset", "path" ]
5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b
https://github.com/mirko-pagliai/cakephp-assets/blob/5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b/src/View/Helper/AssetHelper.php#L40-L56
26,203
mirko-pagliai/cakephp-assets
src/View/Helper/AssetHelper.php
AssetHelper.css
public function css($path, array $options = []) { return $this->Html->css($this->path($path, 'css'), $options); }
php
public function css($path, array $options = []) { return $this->Html->css($this->path($path, 'css'), $options); }
[ "public", "function", "css", "(", "$", "path", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "$", "this", "->", "Html", "->", "css", "(", "$", "this", "->", "path", "(", "$", "path", ",", "'css'", ")", ",", "$", "options", ")", ";", "}" ]
Compresses and adds a css file to the layout @param string|array $path String or array of css files @param array $options Array of options and HTML attributes @return string Html, `<link>` or `<style>` tag @uses path()
[ "Compresses", "and", "adds", "a", "css", "file", "to", "the", "layout" ]
5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b
https://github.com/mirko-pagliai/cakephp-assets/blob/5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b/src/View/Helper/AssetHelper.php#L65-L68
26,204
mirko-pagliai/cakephp-assets
src/View/Helper/AssetHelper.php
AssetHelper.script
public function script($url, array $options = []) { return $this->Html->script($this->path($url, 'js'), $options); }
php
public function script($url, array $options = []) { return $this->Html->script($this->path($url, 'js'), $options); }
[ "public", "function", "script", "(", "$", "url", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "$", "this", "->", "Html", "->", "script", "(", "$", "this", "->", "path", "(", "$", "url", ",", "'js'", ")", ",", "$", "options", ")", ";", "}" ]
Compresses and adds js files to the layout @param string|array $url String or array of js files @param array $options Array of options and HTML attributes @return mixed String of `<script />` tags or null if `$inline` is false or if `$once` is true @uses path()
[ "Compresses", "and", "adds", "js", "files", "to", "the", "layout" ]
5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b
https://github.com/mirko-pagliai/cakephp-assets/blob/5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b/src/View/Helper/AssetHelper.php#L78-L81
26,205
joomla-framework/archive
src/Gzip.php
Gzip.extract
public function extract($archive, $destination) { $this->data = null; if (!isset($this->options['use_streams']) || $this->options['use_streams'] == false) { $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } $position = $this->getFilePosition(); $buffer = gzinflate(substr($this->data, $position, \strlen($this->data) - $position)); if (empty($buffer)) { throw new \RuntimeException('Unable to decompress data'); } if (!File::write($destination, $buffer)) { throw new \RuntimeException('Unable to write archive to file ' . $destination); } } else { // New style! streams! $input = Stream::getStream(); // Use gz $input->set('processingmethod', 'gz'); if (!$input->open($archive)) { throw new \RuntimeException('Unable to read archive'); } $output = Stream::getStream(); if (!$output->open($destination, 'w')) { $input->close(); throw new \RuntimeException('Unable to open file "' . $destination . '" for writing'); } do { $this->data = $input->read($input->get('chunksize', 8196)); if ($this->data) { if (!$output->write($this->data)) { $input->close(); throw new \RuntimeException('Unable to write archive to file ' . $destination); } } } while ($this->data); $output->close(); $input->close(); } return true; }
php
public function extract($archive, $destination) { $this->data = null; if (!isset($this->options['use_streams']) || $this->options['use_streams'] == false) { $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } $position = $this->getFilePosition(); $buffer = gzinflate(substr($this->data, $position, \strlen($this->data) - $position)); if (empty($buffer)) { throw new \RuntimeException('Unable to decompress data'); } if (!File::write($destination, $buffer)) { throw new \RuntimeException('Unable to write archive to file ' . $destination); } } else { // New style! streams! $input = Stream::getStream(); // Use gz $input->set('processingmethod', 'gz'); if (!$input->open($archive)) { throw new \RuntimeException('Unable to read archive'); } $output = Stream::getStream(); if (!$output->open($destination, 'w')) { $input->close(); throw new \RuntimeException('Unable to open file "' . $destination . '" for writing'); } do { $this->data = $input->read($input->get('chunksize', 8196)); if ($this->data) { if (!$output->write($this->data)) { $input->close(); throw new \RuntimeException('Unable to write archive to file ' . $destination); } } } while ($this->data); $output->close(); $input->close(); } return true; }
[ "public", "function", "extract", "(", "$", "archive", ",", "$", "destination", ")", "{", "$", "this", "->", "data", "=", "null", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "options", "[", "'use_streams'", "]", ")", "||", "$", "this", "->", "options", "[", "'use_streams'", "]", "==", "false", ")", "{", "$", "this", "->", "data", "=", "file_get_contents", "(", "$", "archive", ")", ";", "if", "(", "!", "$", "this", "->", "data", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to read archive'", ")", ";", "}", "$", "position", "=", "$", "this", "->", "getFilePosition", "(", ")", ";", "$", "buffer", "=", "gzinflate", "(", "substr", "(", "$", "this", "->", "data", ",", "$", "position", ",", "\\", "strlen", "(", "$", "this", "->", "data", ")", "-", "$", "position", ")", ")", ";", "if", "(", "empty", "(", "$", "buffer", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to decompress data'", ")", ";", "}", "if", "(", "!", "File", "::", "write", "(", "$", "destination", ",", "$", "buffer", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to write archive to file '", ".", "$", "destination", ")", ";", "}", "}", "else", "{", "// New style! streams!", "$", "input", "=", "Stream", "::", "getStream", "(", ")", ";", "// Use gz", "$", "input", "->", "set", "(", "'processingmethod'", ",", "'gz'", ")", ";", "if", "(", "!", "$", "input", "->", "open", "(", "$", "archive", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to read archive'", ")", ";", "}", "$", "output", "=", "Stream", "::", "getStream", "(", ")", ";", "if", "(", "!", "$", "output", "->", "open", "(", "$", "destination", ",", "'w'", ")", ")", "{", "$", "input", "->", "close", "(", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "'Unable to open file \"'", ".", "$", "destination", ".", "'\" for writing'", ")", ";", "}", "do", "{", "$", "this", "->", "data", "=", "$", "input", "->", "read", "(", "$", "input", "->", "get", "(", "'chunksize'", ",", "8196", ")", ")", ";", "if", "(", "$", "this", "->", "data", ")", "{", "if", "(", "!", "$", "output", "->", "write", "(", "$", "this", "->", "data", ")", ")", "{", "$", "input", "->", "close", "(", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "'Unable to write archive to file '", ".", "$", "destination", ")", ";", "}", "}", "}", "while", "(", "$", "this", "->", "data", ")", ";", "$", "output", "->", "close", "(", ")", ";", "$", "input", "->", "close", "(", ")", ";", "}", "return", "true", ";", "}" ]
Extract a Gzip compressed file to a given path @param string $archive Path to ZIP archive to extract @param string $destination Path to extract archive to @return boolean True if successful @since 1.0 @throws \RuntimeException
[ "Extract", "a", "Gzip", "compressed", "file", "to", "a", "given", "path" ]
b1d496e8c7814f1e376cb14296c38d5ef4e08c78
https://github.com/joomla-framework/archive/blob/b1d496e8c7814f1e376cb14296c38d5ef4e08c78/src/Gzip.php#L82-L151
26,206
joomla-framework/archive
src/Gzip.php
Gzip.getFilePosition
public function getFilePosition() { // Gzipped file... unpack it first $position = 0; $info = @ unpack('CCM/CFLG/VTime/CXFL/COS', substr($this->data, $position + 2)); if (!$info) { throw new \RuntimeException('Unable to decompress data.'); } $position += 10; if ($info['FLG'] & $this->flags['FEXTRA']) { $XLEN = unpack('vLength', substr($this->data, $position + 0, 2)); $XLEN = $XLEN['Length']; $position += $XLEN + 2; } if ($info['FLG'] & $this->flags['FNAME']) { $filenamePos = strpos($this->data, "\x0", $position); $position = $filenamePos + 1; } if ($info['FLG'] & $this->flags['FCOMMENT']) { $commentPos = strpos($this->data, "\x0", $position); $position = $commentPos + 1; } if ($info['FLG'] & $this->flags['FHCRC']) { $hcrc = unpack('vCRC', substr($this->data, $position + 0, 2)); $hcrc = $hcrc['CRC']; $position += 2; } return $position; }
php
public function getFilePosition() { // Gzipped file... unpack it first $position = 0; $info = @ unpack('CCM/CFLG/VTime/CXFL/COS', substr($this->data, $position + 2)); if (!$info) { throw new \RuntimeException('Unable to decompress data.'); } $position += 10; if ($info['FLG'] & $this->flags['FEXTRA']) { $XLEN = unpack('vLength', substr($this->data, $position + 0, 2)); $XLEN = $XLEN['Length']; $position += $XLEN + 2; } if ($info['FLG'] & $this->flags['FNAME']) { $filenamePos = strpos($this->data, "\x0", $position); $position = $filenamePos + 1; } if ($info['FLG'] & $this->flags['FCOMMENT']) { $commentPos = strpos($this->data, "\x0", $position); $position = $commentPos + 1; } if ($info['FLG'] & $this->flags['FHCRC']) { $hcrc = unpack('vCRC', substr($this->data, $position + 0, 2)); $hcrc = $hcrc['CRC']; $position += 2; } return $position; }
[ "public", "function", "getFilePosition", "(", ")", "{", "// Gzipped file... unpack it first", "$", "position", "=", "0", ";", "$", "info", "=", "@", "unpack", "(", "'CCM/CFLG/VTime/CXFL/COS'", ",", "substr", "(", "$", "this", "->", "data", ",", "$", "position", "+", "2", ")", ")", ";", "if", "(", "!", "$", "info", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to decompress data.'", ")", ";", "}", "$", "position", "+=", "10", ";", "if", "(", "$", "info", "[", "'FLG'", "]", "&", "$", "this", "->", "flags", "[", "'FEXTRA'", "]", ")", "{", "$", "XLEN", "=", "unpack", "(", "'vLength'", ",", "substr", "(", "$", "this", "->", "data", ",", "$", "position", "+", "0", ",", "2", ")", ")", ";", "$", "XLEN", "=", "$", "XLEN", "[", "'Length'", "]", ";", "$", "position", "+=", "$", "XLEN", "+", "2", ";", "}", "if", "(", "$", "info", "[", "'FLG'", "]", "&", "$", "this", "->", "flags", "[", "'FNAME'", "]", ")", "{", "$", "filenamePos", "=", "strpos", "(", "$", "this", "->", "data", ",", "\"\\x0\"", ",", "$", "position", ")", ";", "$", "position", "=", "$", "filenamePos", "+", "1", ";", "}", "if", "(", "$", "info", "[", "'FLG'", "]", "&", "$", "this", "->", "flags", "[", "'FCOMMENT'", "]", ")", "{", "$", "commentPos", "=", "strpos", "(", "$", "this", "->", "data", ",", "\"\\x0\"", ",", "$", "position", ")", ";", "$", "position", "=", "$", "commentPos", "+", "1", ";", "}", "if", "(", "$", "info", "[", "'FLG'", "]", "&", "$", "this", "->", "flags", "[", "'FHCRC'", "]", ")", "{", "$", "hcrc", "=", "unpack", "(", "'vCRC'", ",", "substr", "(", "$", "this", "->", "data", ",", "$", "position", "+", "0", ",", "2", ")", ")", ";", "$", "hcrc", "=", "$", "hcrc", "[", "'CRC'", "]", ";", "$", "position", "+=", "2", ";", "}", "return", "$", "position", ";", "}" ]
Get file data offset for archive @return integer Data position marker for archive @since 1.0 @throws \RuntimeException
[ "Get", "file", "data", "offset", "for", "archive" ]
b1d496e8c7814f1e376cb14296c38d5ef4e08c78
https://github.com/joomla-framework/archive/blob/b1d496e8c7814f1e376cb14296c38d5ef4e08c78/src/Gzip.php#L173-L213
26,207
Domraider/rxnet
src/Rxnet/Httpd/RequestParser.php
RequestParser.parseChunk
public function parseChunk($data) { if (!$data) { return; } // Detect end of transfer if ($end = strpos($data, "0\r\n\r\n")) { $data = substr($data, 0, $end); } $this->buffer.= $data; $this->request->onData($data); if ($end) { $this->buffer = $this->parseChunkedBuffer($this->buffer); $this->request->setBody($this->buffer); $this->notifyCompleted(); $this->buffer = ''; } }
php
public function parseChunk($data) { if (!$data) { return; } // Detect end of transfer if ($end = strpos($data, "0\r\n\r\n")) { $data = substr($data, 0, $end); } $this->buffer.= $data; $this->request->onData($data); if ($end) { $this->buffer = $this->parseChunkedBuffer($this->buffer); $this->request->setBody($this->buffer); $this->notifyCompleted(); $this->buffer = ''; } }
[ "public", "function", "parseChunk", "(", "$", "data", ")", "{", "if", "(", "!", "$", "data", ")", "{", "return", ";", "}", "// Detect end of transfer", "if", "(", "$", "end", "=", "strpos", "(", "$", "data", ",", "\"0\\r\\n\\r\\n\"", ")", ")", "{", "$", "data", "=", "substr", "(", "$", "data", ",", "0", ",", "$", "end", ")", ";", "}", "$", "this", "->", "buffer", ".=", "$", "data", ";", "$", "this", "->", "request", "->", "onData", "(", "$", "data", ")", ";", "if", "(", "$", "end", ")", "{", "$", "this", "->", "buffer", "=", "$", "this", "->", "parseChunkedBuffer", "(", "$", "this", "->", "buffer", ")", ";", "$", "this", "->", "request", "->", "setBody", "(", "$", "this", "->", "buffer", ")", ";", "$", "this", "->", "notifyCompleted", "(", ")", ";", "$", "this", "->", "buffer", "=", "''", ";", "}", "}" ]
Wait end of transfer packet to complete @param $data
[ "Wait", "end", "of", "transfer", "packet", "to", "complete" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Httpd/RequestParser.php#L128-L146
26,208
UseMuffin/Tags
src/Model/Entity/TagAwareTrait.php
TagAwareTrait.untag
public function untag($tags = null) { if (empty($tags)) { return $this->_updateTags([], 'replace'); } $table = TableRegistry::getTableLocator()->get($this->source()); $behavior = $table->behaviors()->Tag; $assoc = $table->getAssociation($behavior->getConfig('tagsAlias')); $property = $assoc->getProperty(); $id = $this->get($table->getPrimaryKey()); $untags = $behavior->normalizeTags($tags); $tags = $this->get($property); if (!$tags) { $contain = [$behavior->getConfig('tagsAlias')]; $tags = $table->get($id, compact('contain'))->get($property); } $tagsTable = $table->{$behavior->getConfig('tagsAlias')}; $pk = $tagsTable->getPrimaryKey(); $df = $tagsTable->getDisplayField(); foreach ($tags as $k => $tag) { $tags[$k] = [ $pk => $tag->{$pk}, $df => $tag->{$df}, ]; } foreach ($untags as $untag) { foreach ($tags as $k => $tag) { if ((empty($untag[$pk]) || $tag[$pk] === $untag[$pk]) && (empty($untag[$df]) || $tag[$df] === $untag[$df]) ) { unset($tags[$k]); } } } return $this->_updateTags( array_map( function ($i) { return implode(':', $i); }, $tags ), 'replace' ); }
php
public function untag($tags = null) { if (empty($tags)) { return $this->_updateTags([], 'replace'); } $table = TableRegistry::getTableLocator()->get($this->source()); $behavior = $table->behaviors()->Tag; $assoc = $table->getAssociation($behavior->getConfig('tagsAlias')); $property = $assoc->getProperty(); $id = $this->get($table->getPrimaryKey()); $untags = $behavior->normalizeTags($tags); $tags = $this->get($property); if (!$tags) { $contain = [$behavior->getConfig('tagsAlias')]; $tags = $table->get($id, compact('contain'))->get($property); } $tagsTable = $table->{$behavior->getConfig('tagsAlias')}; $pk = $tagsTable->getPrimaryKey(); $df = $tagsTable->getDisplayField(); foreach ($tags as $k => $tag) { $tags[$k] = [ $pk => $tag->{$pk}, $df => $tag->{$df}, ]; } foreach ($untags as $untag) { foreach ($tags as $k => $tag) { if ((empty($untag[$pk]) || $tag[$pk] === $untag[$pk]) && (empty($untag[$df]) || $tag[$df] === $untag[$df]) ) { unset($tags[$k]); } } } return $this->_updateTags( array_map( function ($i) { return implode(':', $i); }, $tags ), 'replace' ); }
[ "public", "function", "untag", "(", "$", "tags", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "tags", ")", ")", "{", "return", "$", "this", "->", "_updateTags", "(", "[", "]", ",", "'replace'", ")", ";", "}", "$", "table", "=", "TableRegistry", "::", "getTableLocator", "(", ")", "->", "get", "(", "$", "this", "->", "source", "(", ")", ")", ";", "$", "behavior", "=", "$", "table", "->", "behaviors", "(", ")", "->", "Tag", ";", "$", "assoc", "=", "$", "table", "->", "getAssociation", "(", "$", "behavior", "->", "getConfig", "(", "'tagsAlias'", ")", ")", ";", "$", "property", "=", "$", "assoc", "->", "getProperty", "(", ")", ";", "$", "id", "=", "$", "this", "->", "get", "(", "$", "table", "->", "getPrimaryKey", "(", ")", ")", ";", "$", "untags", "=", "$", "behavior", "->", "normalizeTags", "(", "$", "tags", ")", ";", "$", "tags", "=", "$", "this", "->", "get", "(", "$", "property", ")", ";", "if", "(", "!", "$", "tags", ")", "{", "$", "contain", "=", "[", "$", "behavior", "->", "getConfig", "(", "'tagsAlias'", ")", "]", ";", "$", "tags", "=", "$", "table", "->", "get", "(", "$", "id", ",", "compact", "(", "'contain'", ")", ")", "->", "get", "(", "$", "property", ")", ";", "}", "$", "tagsTable", "=", "$", "table", "->", "{", "$", "behavior", "->", "getConfig", "(", "'tagsAlias'", ")", "}", ";", "$", "pk", "=", "$", "tagsTable", "->", "getPrimaryKey", "(", ")", ";", "$", "df", "=", "$", "tagsTable", "->", "getDisplayField", "(", ")", ";", "foreach", "(", "$", "tags", "as", "$", "k", "=>", "$", "tag", ")", "{", "$", "tags", "[", "$", "k", "]", "=", "[", "$", "pk", "=>", "$", "tag", "->", "{", "$", "pk", "}", ",", "$", "df", "=>", "$", "tag", "->", "{", "$", "df", "}", ",", "]", ";", "}", "foreach", "(", "$", "untags", "as", "$", "untag", ")", "{", "foreach", "(", "$", "tags", "as", "$", "k", "=>", "$", "tag", ")", "{", "if", "(", "(", "empty", "(", "$", "untag", "[", "$", "pk", "]", ")", "||", "$", "tag", "[", "$", "pk", "]", "===", "$", "untag", "[", "$", "pk", "]", ")", "&&", "(", "empty", "(", "$", "untag", "[", "$", "df", "]", ")", "||", "$", "tag", "[", "$", "df", "]", "===", "$", "untag", "[", "$", "df", "]", ")", ")", "{", "unset", "(", "$", "tags", "[", "$", "k", "]", ")", ";", "}", "}", "}", "return", "$", "this", "->", "_updateTags", "(", "array_map", "(", "function", "(", "$", "i", ")", "{", "return", "implode", "(", "':'", ",", "$", "i", ")", ";", "}", ",", "$", "tags", ")", ",", "'replace'", ")", ";", "}" ]
Untag entity from given tags. @param string|array $tags List of tags as an array or a delimited string (comma by default). If no value is passed all tags will be removed. @return bool|\Cake\ORM\Entity False on failure, entity on success.
[ "Untag", "entity", "from", "given", "tags", "." ]
6fb767375a39829ea348d64b8fd1b0204b9f26ff
https://github.com/UseMuffin/Tags/blob/6fb767375a39829ea348d64b8fd1b0204b9f26ff/src/Model/Entity/TagAwareTrait.php#L28-L77
26,209
UseMuffin/Tags
src/Model/Entity/TagAwareTrait.php
TagAwareTrait._updateTags
protected function _updateTags($tags, $saveStrategy) { $table = TableRegistry::getTableLocator()->get($this->source()); $behavior = $table->behaviors()->Tag; $assoc = $table->getAssociation($behavior->getConfig('tagsAlias')); $resetStrategy = $assoc->getSaveStrategy(); $assoc->setSaveStrategy($saveStrategy); $table->patchEntity($this, [$assoc->getProperty() => $tags]); $result = $table->save($this); $assoc->setSaveStrategy($resetStrategy); return $result; }
php
protected function _updateTags($tags, $saveStrategy) { $table = TableRegistry::getTableLocator()->get($this->source()); $behavior = $table->behaviors()->Tag; $assoc = $table->getAssociation($behavior->getConfig('tagsAlias')); $resetStrategy = $assoc->getSaveStrategy(); $assoc->setSaveStrategy($saveStrategy); $table->patchEntity($this, [$assoc->getProperty() => $tags]); $result = $table->save($this); $assoc->setSaveStrategy($resetStrategy); return $result; }
[ "protected", "function", "_updateTags", "(", "$", "tags", ",", "$", "saveStrategy", ")", "{", "$", "table", "=", "TableRegistry", "::", "getTableLocator", "(", ")", "->", "get", "(", "$", "this", "->", "source", "(", ")", ")", ";", "$", "behavior", "=", "$", "table", "->", "behaviors", "(", ")", "->", "Tag", ";", "$", "assoc", "=", "$", "table", "->", "getAssociation", "(", "$", "behavior", "->", "getConfig", "(", "'tagsAlias'", ")", ")", ";", "$", "resetStrategy", "=", "$", "assoc", "->", "getSaveStrategy", "(", ")", ";", "$", "assoc", "->", "setSaveStrategy", "(", "$", "saveStrategy", ")", ";", "$", "table", "->", "patchEntity", "(", "$", "this", ",", "[", "$", "assoc", "->", "getProperty", "(", ")", "=>", "$", "tags", "]", ")", ";", "$", "result", "=", "$", "table", "->", "save", "(", "$", "this", ")", ";", "$", "assoc", "->", "setSaveStrategy", "(", "$", "resetStrategy", ")", ";", "return", "$", "result", ";", "}" ]
Tag entity with given tags. @param string|array $tags List of tags as an array or a delimited string (comma by default). @param string $saveStrategy Whether to merge or replace tags. Valid values 'append', 'replace'. @return bool|\Cake\ORM\Entity False on failure, entity on success.
[ "Tag", "entity", "with", "given", "tags", "." ]
6fb767375a39829ea348d64b8fd1b0204b9f26ff
https://github.com/UseMuffin/Tags/blob/6fb767375a39829ea348d64b8fd1b0204b9f26ff/src/Model/Entity/TagAwareTrait.php#L87-L99
26,210
Domraider/rxnet
src/Rxnet/RabbitMq/RabbitQueue.php
RabbitQueue.get
public function get($queue, $noAck = false) { $promise = $this->channel->get($queue, $noAck); return \Rxnet\fromPromise($promise) ->map(function (Message $message) { return new RabbitMessage($this->channel, $message, $this->serializer); }); }
php
public function get($queue, $noAck = false) { $promise = $this->channel->get($queue, $noAck); return \Rxnet\fromPromise($promise) ->map(function (Message $message) { return new RabbitMessage($this->channel, $message, $this->serializer); }); }
[ "public", "function", "get", "(", "$", "queue", ",", "$", "noAck", "=", "false", ")", "{", "$", "promise", "=", "$", "this", "->", "channel", "->", "get", "(", "$", "queue", ",", "$", "noAck", ")", ";", "return", "\\", "Rxnet", "\\", "fromPromise", "(", "$", "promise", ")", "->", "map", "(", "function", "(", "Message", "$", "message", ")", "{", "return", "new", "RabbitMessage", "(", "$", "this", "->", "channel", ",", "$", "message", ",", "$", "this", "->", "serializer", ")", ";", "}", ")", ";", "}" ]
Pop one element from the queue @param $queue @param bool $noAck @return Observable
[ "Pop", "one", "element", "from", "the", "queue" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/RabbitMq/RabbitQueue.php#L126-L133
26,211
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.upload
public function upload($directory, $run_filename, $code_name, $options = array()) { $temp_file = tempnam(sys_get_temp_dir(), 'iron_worker_php'); if (array_key_exists('ignored', $options)) { if (!is_array($options['ignored'])) { $options['ignored'] = [$options['ignored']]; } } else { $options['ignored'] = []; } if (!self::zipDirectory($directory, $temp_file, true, $options['ignored'])) { unlink($temp_file); return false; } unset($options['ignored']); try { $this->postCode($run_filename, $temp_file, $code_name, $options); } catch (\Exception $e) { unlink($temp_file); throw $e; } return true; }
php
public function upload($directory, $run_filename, $code_name, $options = array()) { $temp_file = tempnam(sys_get_temp_dir(), 'iron_worker_php'); if (array_key_exists('ignored', $options)) { if (!is_array($options['ignored'])) { $options['ignored'] = [$options['ignored']]; } } else { $options['ignored'] = []; } if (!self::zipDirectory($directory, $temp_file, true, $options['ignored'])) { unlink($temp_file); return false; } unset($options['ignored']); try { $this->postCode($run_filename, $temp_file, $code_name, $options); } catch (\Exception $e) { unlink($temp_file); throw $e; } return true; }
[ "public", "function", "upload", "(", "$", "directory", ",", "$", "run_filename", ",", "$", "code_name", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "temp_file", "=", "tempnam", "(", "sys_get_temp_dir", "(", ")", ",", "'iron_worker_php'", ")", ";", "if", "(", "array_key_exists", "(", "'ignored'", ",", "$", "options", ")", ")", "{", "if", "(", "!", "is_array", "(", "$", "options", "[", "'ignored'", "]", ")", ")", "{", "$", "options", "[", "'ignored'", "]", "=", "[", "$", "options", "[", "'ignored'", "]", "]", ";", "}", "}", "else", "{", "$", "options", "[", "'ignored'", "]", "=", "[", "]", ";", "}", "if", "(", "!", "self", "::", "zipDirectory", "(", "$", "directory", ",", "$", "temp_file", ",", "true", ",", "$", "options", "[", "'ignored'", "]", ")", ")", "{", "unlink", "(", "$", "temp_file", ")", ";", "return", "false", ";", "}", "unset", "(", "$", "options", "[", "'ignored'", "]", ")", ";", "try", "{", "$", "this", "->", "postCode", "(", "$", "run_filename", ",", "$", "temp_file", ",", "$", "code_name", ",", "$", "options", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "unlink", "(", "$", "temp_file", ")", ";", "throw", "$", "e", ";", "}", "return", "true", ";", "}" ]
Zips and uploads your code Shortcut for zipDirectory() + postCode() @param string $directory Directory with worker files @param string $run_filename This file will be launched as worker @param string $code_name Referenceable (unique) name for your worker @param array $options Optional parameters: - "max_concurrency" The maximum number of tasks that should be run in parallel. - "retries" The number of auto-retries of failed task. - "retries_delay" Delay in seconds between retries. - "config" : An arbitrary string (usually YAML or JSON) that, if provided, will be available in a file that your worker can access. File location will be passed in via the -config argument. The config cannot be larger than 64KB in size. - "ignored" The list of files to be excluded from uploading process. @return bool Result of operation @throws \Exception
[ "Zips", "and", "uploads", "your", "code" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L79-L101
26,212
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.createZip
public static function createZip($base_dir, $files, $destination, $overwrite = false) { //if the zip file already exists and overwrite is false, return false if (file_exists($destination) && !$overwrite) { return false; } if (!empty($base_dir)) { $base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } //vars $valid_files = array(); //if files were passed in... if (is_array($files)) { //cycle through each file foreach ($files as $file) { //make sure the file exists if (file_exists($base_dir . $file)) { $valid_files[] = $file; } } } if (count($valid_files)) { $zip = new \ZipArchive(); if ($zip->open($destination, $overwrite ? \ZIPARCHIVE::OVERWRITE : \ZIPARCHIVE::CREATE) !== true) { return false; } foreach ($valid_files as $file) { $zip->addFile($base_dir . $file, $file); } $zip->close(); return file_exists($destination); } else { return false; } }
php
public static function createZip($base_dir, $files, $destination, $overwrite = false) { //if the zip file already exists and overwrite is false, return false if (file_exists($destination) && !$overwrite) { return false; } if (!empty($base_dir)) { $base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } //vars $valid_files = array(); //if files were passed in... if (is_array($files)) { //cycle through each file foreach ($files as $file) { //make sure the file exists if (file_exists($base_dir . $file)) { $valid_files[] = $file; } } } if (count($valid_files)) { $zip = new \ZipArchive(); if ($zip->open($destination, $overwrite ? \ZIPARCHIVE::OVERWRITE : \ZIPARCHIVE::CREATE) !== true) { return false; } foreach ($valid_files as $file) { $zip->addFile($base_dir . $file, $file); } $zip->close(); return file_exists($destination); } else { return false; } }
[ "public", "static", "function", "createZip", "(", "$", "base_dir", ",", "$", "files", ",", "$", "destination", ",", "$", "overwrite", "=", "false", ")", "{", "//if the zip file already exists and overwrite is false, return false", "if", "(", "file_exists", "(", "$", "destination", ")", "&&", "!", "$", "overwrite", ")", "{", "return", "false", ";", "}", "if", "(", "!", "empty", "(", "$", "base_dir", ")", ")", "{", "$", "base_dir", "=", "rtrim", "(", "$", "base_dir", ",", "DIRECTORY_SEPARATOR", ")", ".", "DIRECTORY_SEPARATOR", ";", "}", "//vars", "$", "valid_files", "=", "array", "(", ")", ";", "//if files were passed in...", "if", "(", "is_array", "(", "$", "files", ")", ")", "{", "//cycle through each file", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "//make sure the file exists", "if", "(", "file_exists", "(", "$", "base_dir", ".", "$", "file", ")", ")", "{", "$", "valid_files", "[", "]", "=", "$", "file", ";", "}", "}", "}", "if", "(", "count", "(", "$", "valid_files", ")", ")", "{", "$", "zip", "=", "new", "\\", "ZipArchive", "(", ")", ";", "if", "(", "$", "zip", "->", "open", "(", "$", "destination", ",", "$", "overwrite", "?", "\\", "ZIPARCHIVE", "::", "OVERWRITE", ":", "\\", "ZIPARCHIVE", "::", "CREATE", ")", "!==", "true", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "valid_files", "as", "$", "file", ")", "{", "$", "zip", "->", "addFile", "(", "$", "base_dir", ".", "$", "file", ",", "$", "file", ")", ";", "}", "$", "zip", "->", "close", "(", ")", ";", "return", "file_exists", "(", "$", "destination", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Creates a zip archive from array of file names Example: <code> IronWorker::createZip(dirname(__FILE__), array('HelloWorld.php'), 'worker.zip', true); </code> @static @param string $base_dir Full path to directory which contain files @param array $files File names, path (both passesed and stored) is relative to $base_dir. Examples: 'worker.php','lib/file.php' @param string $destination Zip file name. @param bool $overwrite Overwite existing file or not. @return bool
[ "Creates", "a", "zip", "archive", "from", "array", "of", "file", "names" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L119-L153
26,213
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.zipDirectory
public static function zipDirectory($directory, $destination, $overwrite = false, $ignored = []) { if (!file_exists($directory) || !is_dir($directory)) { return false; } $directory = rtrim($directory, DIRECTORY_SEPARATOR); $files = self::fileNamesRecursive($directory, '', $ignored); if (empty($files)) { return false; } return self::createZip($directory, $files, $destination, $overwrite); }
php
public static function zipDirectory($directory, $destination, $overwrite = false, $ignored = []) { if (!file_exists($directory) || !is_dir($directory)) { return false; } $directory = rtrim($directory, DIRECTORY_SEPARATOR); $files = self::fileNamesRecursive($directory, '', $ignored); if (empty($files)) { return false; } return self::createZip($directory, $files, $destination, $overwrite); }
[ "public", "static", "function", "zipDirectory", "(", "$", "directory", ",", "$", "destination", ",", "$", "overwrite", "=", "false", ",", "$", "ignored", "=", "[", "]", ")", "{", "if", "(", "!", "file_exists", "(", "$", "directory", ")", "||", "!", "is_dir", "(", "$", "directory", ")", ")", "{", "return", "false", ";", "}", "$", "directory", "=", "rtrim", "(", "$", "directory", ",", "DIRECTORY_SEPARATOR", ")", ";", "$", "files", "=", "self", "::", "fileNamesRecursive", "(", "$", "directory", ",", "''", ",", "$", "ignored", ")", ";", "if", "(", "empty", "(", "$", "files", ")", ")", "{", "return", "false", ";", "}", "return", "self", "::", "createZip", "(", "$", "directory", ",", "$", "files", ",", "$", "destination", ",", "$", "overwrite", ")", ";", "}" ]
Creates a zip archive with all files and folders inside specific directory except for the list of ignored files. Example: <code> IronWorker::zipDirectory(dirname(__FILE__)."/worker/", 'worker.zip', true); </code> @static @param string $directory @param string $destination @param bool $overwrite @param array $ignored @return bool
[ "Creates", "a", "zip", "archive", "with", "all", "files", "and", "folders", "inside", "specific", "directory", "except", "for", "the", "list", "of", "ignored", "files", "." ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L170-L184
26,214
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.postCode
public function postCode($filename, $zipFilename, $name, $options = array()) { // Add IronWorker functions to the uploaded worker $this->addRunnerToArchive($zipFilename, $filename, $options); $this->setPostHeaders(); $ts = time(); $runtime_type = $this->runtimeFileType($filename); $sendingData = array( "code_name" => $name, "name" => $name, "standalone" => true, "runtime" => $runtime_type, "file_name" => "runner.php", "version" => $this->version, "timestamp" => $ts, "oauth" => $this->token, "class_name" => $name, "options" => array(), "access_key" => $name, ); $sendingData = array_merge($sendingData, $options); $url = "projects/{$this->project_id}/codes"; $post = array( "data" => json_encode($sendingData), ); if ($this->curlEnabled() && version_compare(PHP_VERSION, '5.5.0', '>=')) { $post['file'] = new \CURLFile($zipFilename); } else { $post['file'] = '@' . $zipFilename; } $response = $this->apiCall(self::POST, $url, array(), $post); return self::json_decode($response); }
php
public function postCode($filename, $zipFilename, $name, $options = array()) { // Add IronWorker functions to the uploaded worker $this->addRunnerToArchive($zipFilename, $filename, $options); $this->setPostHeaders(); $ts = time(); $runtime_type = $this->runtimeFileType($filename); $sendingData = array( "code_name" => $name, "name" => $name, "standalone" => true, "runtime" => $runtime_type, "file_name" => "runner.php", "version" => $this->version, "timestamp" => $ts, "oauth" => $this->token, "class_name" => $name, "options" => array(), "access_key" => $name, ); $sendingData = array_merge($sendingData, $options); $url = "projects/{$this->project_id}/codes"; $post = array( "data" => json_encode($sendingData), ); if ($this->curlEnabled() && version_compare(PHP_VERSION, '5.5.0', '>=')) { $post['file'] = new \CURLFile($zipFilename); } else { $post['file'] = '@' . $zipFilename; } $response = $this->apiCall(self::POST, $url, array(), $post); return self::json_decode($response); }
[ "public", "function", "postCode", "(", "$", "filename", ",", "$", "zipFilename", ",", "$", "name", ",", "$", "options", "=", "array", "(", ")", ")", "{", "// Add IronWorker functions to the uploaded worker", "$", "this", "->", "addRunnerToArchive", "(", "$", "zipFilename", ",", "$", "filename", ",", "$", "options", ")", ";", "$", "this", "->", "setPostHeaders", "(", ")", ";", "$", "ts", "=", "time", "(", ")", ";", "$", "runtime_type", "=", "$", "this", "->", "runtimeFileType", "(", "$", "filename", ")", ";", "$", "sendingData", "=", "array", "(", "\"code_name\"", "=>", "$", "name", ",", "\"name\"", "=>", "$", "name", ",", "\"standalone\"", "=>", "true", ",", "\"runtime\"", "=>", "$", "runtime_type", ",", "\"file_name\"", "=>", "\"runner.php\"", ",", "\"version\"", "=>", "$", "this", "->", "version", ",", "\"timestamp\"", "=>", "$", "ts", ",", "\"oauth\"", "=>", "$", "this", "->", "token", ",", "\"class_name\"", "=>", "$", "name", ",", "\"options\"", "=>", "array", "(", ")", ",", "\"access_key\"", "=>", "$", "name", ",", ")", ";", "$", "sendingData", "=", "array_merge", "(", "$", "sendingData", ",", "$", "options", ")", ";", "$", "url", "=", "\"projects/{$this->project_id}/codes\"", ";", "$", "post", "=", "array", "(", "\"data\"", "=>", "json_encode", "(", "$", "sendingData", ")", ",", ")", ";", "if", "(", "$", "this", "->", "curlEnabled", "(", ")", "&&", "version_compare", "(", "PHP_VERSION", ",", "'5.5.0'", ",", "'>='", ")", ")", "{", "$", "post", "[", "'file'", "]", "=", "new", "\\", "CURLFile", "(", "$", "zipFilename", ")", ";", "}", "else", "{", "$", "post", "[", "'file'", "]", "=", "'@'", ".", "$", "zipFilename", ";", "}", "$", "response", "=", "$", "this", "->", "apiCall", "(", "self", "::", "POST", ",", "$", "url", ",", "array", "(", ")", ",", "$", "post", ")", ";", "return", "self", "::", "json_decode", "(", "$", "response", ")", ";", "}" ]
Uploads your code package @param string $filename This file will be launched as worker @param string $zipFilename zip file containing code to execute @param string $name referenceable (unique) name for your worker @param array $options Optional parameters: - "max_concurrency" The maximum number of tasks that should be run in parallel. - "retries" The number of auto-retries of failed task. - "retries_delay" Delay in seconds between retries. - "config" : An arbitrary string (usually YAML or JSON) that, if provided, will be available in a file that your worker can access. File location will be passed in via the -config argument. The config cannot be larger than 64KB in size. @return mixed
[ "Uploads", "your", "code", "package" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L277-L310
26,215
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.downloadCode
public function downloadCode($code_id) { if (empty($code_id)) { throw new \InvalidArgumentException("Please set code_id"); } $url = "projects/{$this->project_id}/codes/$code_id/download"; return $this->apiCall(self::GET, $url); }
php
public function downloadCode($code_id) { if (empty($code_id)) { throw new \InvalidArgumentException("Please set code_id"); } $url = "projects/{$this->project_id}/codes/$code_id/download"; return $this->apiCall(self::GET, $url); }
[ "public", "function", "downloadCode", "(", "$", "code_id", ")", "{", "if", "(", "empty", "(", "$", "code_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Please set code_id\"", ")", ";", "}", "$", "url", "=", "\"projects/{$this->project_id}/codes/$code_id/download\"", ";", "return", "$", "this", "->", "apiCall", "(", "self", "::", "GET", ",", "$", "url", ")", ";", "}" ]
Download Code Package @param String $code_id. @throws \InvalidArgumentException @return string zipped file
[ "Download", "Code", "Package" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L320-L327
26,216
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.getCodeRevisions
public function getCodeRevisions($code_id, $page = 0, $per_page = 30) { if (empty($code_id)) { throw new \InvalidArgumentException("Please set code_id"); } $params = array( 'page' => $page, 'per_page' => $per_page, ); $this->setJsonHeaders(); $url = "projects/{$this->project_id}/codes/$code_id/revisions"; $res = json_decode($this->apiCall(self::GET, $url, $params)); return $res->revisions; }
php
public function getCodeRevisions($code_id, $page = 0, $per_page = 30) { if (empty($code_id)) { throw new \InvalidArgumentException("Please set code_id"); } $params = array( 'page' => $page, 'per_page' => $per_page, ); $this->setJsonHeaders(); $url = "projects/{$this->project_id}/codes/$code_id/revisions"; $res = json_decode($this->apiCall(self::GET, $url, $params)); return $res->revisions; }
[ "public", "function", "getCodeRevisions", "(", "$", "code_id", ",", "$", "page", "=", "0", ",", "$", "per_page", "=", "30", ")", "{", "if", "(", "empty", "(", "$", "code_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Please set code_id\"", ")", ";", "}", "$", "params", "=", "array", "(", "'page'", "=>", "$", "page", ",", "'per_page'", "=>", "$", "per_page", ",", ")", ";", "$", "this", "->", "setJsonHeaders", "(", ")", ";", "$", "url", "=", "\"projects/{$this->project_id}/codes/$code_id/revisions\"", ";", "$", "res", "=", "json_decode", "(", "$", "this", "->", "apiCall", "(", "self", "::", "GET", ",", "$", "url", ",", "$", "params", ")", ")", ";", "return", "$", "res", "->", "revisions", ";", "}" ]
Get all code revisions @param String $code_id. @param int $page Page. Default is 0, maximum is 100. @param int $per_page The number of tasks to return per page. Default is 30, maximum is 100. @throws \InvalidArgumentException @return array of revisions
[ "Get", "all", "code", "revisions" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L339-L352
26,217
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.getSchedules
public function getSchedules($page = 0, $per_page = 30) { $url = "projects/{$this->project_id}/schedules"; $this->setJsonHeaders(); $params = array( 'page' => $page, 'per_page' => $per_page, ); $schedules = self::json_decode($this->apiCall(self::GET, $url, $params)); return $schedules->schedules; }
php
public function getSchedules($page = 0, $per_page = 30) { $url = "projects/{$this->project_id}/schedules"; $this->setJsonHeaders(); $params = array( 'page' => $page, 'per_page' => $per_page, ); $schedules = self::json_decode($this->apiCall(self::GET, $url, $params)); return $schedules->schedules; }
[ "public", "function", "getSchedules", "(", "$", "page", "=", "0", ",", "$", "per_page", "=", "30", ")", "{", "$", "url", "=", "\"projects/{$this->project_id}/schedules\"", ";", "$", "this", "->", "setJsonHeaders", "(", ")", ";", "$", "params", "=", "array", "(", "'page'", "=>", "$", "page", ",", "'per_page'", "=>", "$", "per_page", ",", ")", ";", "$", "schedules", "=", "self", "::", "json_decode", "(", "$", "this", "->", "apiCall", "(", "self", "::", "GET", ",", "$", "url", ",", "$", "params", ")", ")", ";", "return", "$", "schedules", "->", "schedules", ";", "}" ]
Get information about all schedules for project @param int $page @param int $per_page @return mixed
[ "Get", "information", "about", "all", "schedules", "for", "project" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L378-L388
26,218
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.getSchedule
public function getSchedule($schedule_id) { if (empty($schedule_id)) { throw new \InvalidArgumentException("Please set schedule_id"); } $this->setJsonHeaders(); $url = "projects/{$this->project_id}/schedules/$schedule_id"; return self::json_decode($this->apiCall(self::GET, $url)); }
php
public function getSchedule($schedule_id) { if (empty($schedule_id)) { throw new \InvalidArgumentException("Please set schedule_id"); } $this->setJsonHeaders(); $url = "projects/{$this->project_id}/schedules/$schedule_id"; return self::json_decode($this->apiCall(self::GET, $url)); }
[ "public", "function", "getSchedule", "(", "$", "schedule_id", ")", "{", "if", "(", "empty", "(", "$", "schedule_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Please set schedule_id\"", ")", ";", "}", "$", "this", "->", "setJsonHeaders", "(", ")", ";", "$", "url", "=", "\"projects/{$this->project_id}/schedules/$schedule_id\"", ";", "return", "self", "::", "json_decode", "(", "$", "this", "->", "apiCall", "(", "self", "::", "GET", ",", "$", "url", ")", ")", ";", "}" ]
Get information about schedule @param string $schedule_id Schedule ID @return mixed @throws \InvalidArgumentException
[ "Get", "information", "about", "schedule" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L397-L406
26,219
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.postTask
public function postTask($name, $payload = array(), $options = array()) { $ids = $this->postTasks($name, array($payload), $options); return $ids[0]; }
php
public function postTask($name, $payload = array(), $options = array()) { $ids = $this->postTasks($name, array($payload), $options); return $ids[0]; }
[ "public", "function", "postTask", "(", "$", "name", ",", "$", "payload", "=", "array", "(", ")", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "ids", "=", "$", "this", "->", "postTasks", "(", "$", "name", ",", "array", "(", "$", "payload", ")", ",", "$", "options", ")", ";", "return", "$", "ids", "[", "0", "]", ";", "}" ]
Queues already uploaded worker @param string $name Package name @param array $payload Payload for task @param array $options Optional parameters: - "priority" priority queue to run the job in (0, 1, 2). 0 is default. - "timeout" maximum runtime of your task in seconds. Maximum time is 3600 seconds (60 minutes). Default is 3600 seconds (60 minutes). - "delay" delay before actually queueing the task in seconds. Default is 0 seconds. @return string Created Task ID
[ "Queues", "already", "uploaded", "worker" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L474-L479
26,220
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.postTasks
public function postTasks($name, $payloads = array(), $options = array()) { $url = "projects/{$this->project_id}/tasks"; $request = array( 'tasks' => array(), ); foreach ($payloads as $payload) { $task_data = array( "name" => $name, "code_name" => $name, 'payload' => json_encode($payload), ); foreach ($options as $k => $v) { $task_data[$k] = $v; } $request['tasks'][] = $task_data; } $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); $tasks = self::json_decode($res); $ids = array(); foreach ($tasks->tasks as $task) { $ids[] = $task->id; } return $ids; }
php
public function postTasks($name, $payloads = array(), $options = array()) { $url = "projects/{$this->project_id}/tasks"; $request = array( 'tasks' => array(), ); foreach ($payloads as $payload) { $task_data = array( "name" => $name, "code_name" => $name, 'payload' => json_encode($payload), ); foreach ($options as $k => $v) { $task_data[$k] = $v; } $request['tasks'][] = $task_data; } $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); $tasks = self::json_decode($res); $ids = array(); foreach ($tasks->tasks as $task) { $ids[] = $task->id; } return $ids; }
[ "public", "function", "postTasks", "(", "$", "name", ",", "$", "payloads", "=", "array", "(", ")", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "url", "=", "\"projects/{$this->project_id}/tasks\"", ";", "$", "request", "=", "array", "(", "'tasks'", "=>", "array", "(", ")", ",", ")", ";", "foreach", "(", "$", "payloads", "as", "$", "payload", ")", "{", "$", "task_data", "=", "array", "(", "\"name\"", "=>", "$", "name", ",", "\"code_name\"", "=>", "$", "name", ",", "'payload'", "=>", "json_encode", "(", "$", "payload", ")", ",", ")", ";", "foreach", "(", "$", "options", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "task_data", "[", "$", "k", "]", "=", "$", "v", ";", "}", "$", "request", "[", "'tasks'", "]", "[", "]", "=", "$", "task_data", ";", "}", "$", "this", "->", "setCommonHeaders", "(", ")", ";", "$", "res", "=", "$", "this", "->", "apiCall", "(", "self", "::", "POST", ",", "$", "url", ",", "$", "request", ")", ";", "$", "tasks", "=", "self", "::", "json_decode", "(", "$", "res", ")", ";", "$", "ids", "=", "array", "(", ")", ";", "foreach", "(", "$", "tasks", "->", "tasks", "as", "$", "task", ")", "{", "$", "ids", "[", "]", "=", "$", "task", "->", "id", ";", "}", "return", "$", "ids", ";", "}" ]
Queues many tasks at a time @param string $name Package name @param array $payloads. Each payload will be converted to separate task @param array $options same as postTask() @return array IDs
[ "Queues", "many", "tasks", "at", "a", "time" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L489-L521
26,221
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.cancelTask
public function cancelTask($task_id) { if (empty($task_id)) { throw new \InvalidArgumentException("Please set task_id"); } $url = "projects/{$this->project_id}/tasks/$task_id/cancel"; $request = array(); $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); return self::json_decode($res); }
php
public function cancelTask($task_id) { if (empty($task_id)) { throw new \InvalidArgumentException("Please set task_id"); } $url = "projects/{$this->project_id}/tasks/$task_id/cancel"; $request = array(); $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); return self::json_decode($res); }
[ "public", "function", "cancelTask", "(", "$", "task_id", ")", "{", "if", "(", "empty", "(", "$", "task_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Please set task_id\"", ")", ";", "}", "$", "url", "=", "\"projects/{$this->project_id}/tasks/$task_id/cancel\"", ";", "$", "request", "=", "array", "(", ")", ";", "$", "this", "->", "setCommonHeaders", "(", ")", ";", "$", "res", "=", "$", "this", "->", "apiCall", "(", "self", "::", "POST", ",", "$", "url", ",", "$", "request", ")", ";", "return", "self", "::", "json_decode", "(", "$", "res", ")", ";", "}" ]
Cancels task. @param string $task_id Task ID @return mixed @throws \InvalidArgumentException
[ "Cancels", "task", "." ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L552-L563
26,222
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.retryTask
public function retryTask($task_id, $delay = 1) { if (empty($task_id)) { throw new \InvalidArgumentException("Please set task_id"); } $url = "projects/{$this->project_id}/tasks/$task_id/retry"; $request = array('delay' => $delay); $this->setCommonHeaders(); $res = json_decode($this->apiCall(self::POST, $url, $request)); return $res->tasks[0]->id; }
php
public function retryTask($task_id, $delay = 1) { if (empty($task_id)) { throw new \InvalidArgumentException("Please set task_id"); } $url = "projects/{$this->project_id}/tasks/$task_id/retry"; $request = array('delay' => $delay); $this->setCommonHeaders(); $res = json_decode($this->apiCall(self::POST, $url, $request)); return $res->tasks[0]->id; }
[ "public", "function", "retryTask", "(", "$", "task_id", ",", "$", "delay", "=", "1", ")", "{", "if", "(", "empty", "(", "$", "task_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Please set task_id\"", ")", ";", "}", "$", "url", "=", "\"projects/{$this->project_id}/tasks/$task_id/retry\"", ";", "$", "request", "=", "array", "(", "'delay'", "=>", "$", "delay", ")", ";", "$", "this", "->", "setCommonHeaders", "(", ")", ";", "$", "res", "=", "json_decode", "(", "$", "this", "->", "apiCall", "(", "self", "::", "POST", ",", "$", "url", ",", "$", "request", ")", ")", ";", "return", "$", "res", "->", "tasks", "[", "0", "]", "->", "id", ";", "}" ]
Retry task. @param string $task_id Task ID @param int $delay The number of seconds the task should be delayed before it runs again. @return string Retried Task ID @throws \InvalidArgumentException
[ "Retry", "task", "." ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L573-L584
26,223
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.waitFor
public function waitFor($task_id, $sleep = 5, $max_wait_time = 0) { while (1) { $details = $this->getTaskDetails($task_id); if ($details->status != 'queued' && $details->status != 'running') { return $details; } if ($max_wait_time > 0) { $max_wait_time -= $sleep; if ($max_wait_time <= 0) { return false; } } sleep($sleep); } return false; }
php
public function waitFor($task_id, $sleep = 5, $max_wait_time = 0) { while (1) { $details = $this->getTaskDetails($task_id); if ($details->status != 'queued' && $details->status != 'running') { return $details; } if ($max_wait_time > 0) { $max_wait_time -= $sleep; if ($max_wait_time <= 0) { return false; } } sleep($sleep); } return false; }
[ "public", "function", "waitFor", "(", "$", "task_id", ",", "$", "sleep", "=", "5", ",", "$", "max_wait_time", "=", "0", ")", "{", "while", "(", "1", ")", "{", "$", "details", "=", "$", "this", "->", "getTaskDetails", "(", "$", "task_id", ")", ";", "if", "(", "$", "details", "->", "status", "!=", "'queued'", "&&", "$", "details", "->", "status", "!=", "'running'", ")", "{", "return", "$", "details", ";", "}", "if", "(", "$", "max_wait_time", ">", "0", ")", "{", "$", "max_wait_time", "-=", "$", "sleep", ";", "if", "(", "$", "max_wait_time", "<=", "0", ")", "{", "return", "false", ";", "}", "}", "sleep", "(", "$", "sleep", ")", ";", "}", "return", "false", ";", "}" ]
Wait while the task specified by task_id executes @param string $task_id Task ID @param int $sleep Delay between API invocations in seconds @param int $max_wait_time Maximum waiting time in seconds, 0 for infinity @return mixed $details Task details or false
[ "Wait", "while", "the", "task", "specified", "by", "task_id", "executes" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L606-L624
26,224
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.postSchedule
public function postSchedule($name, $options, $payload = array()) { $url = "projects/{$this->project_id}/schedules"; $shedule = array( 'name' => $name, 'code_name' => $name, 'payload' => json_encode($payload), ); $request = array( 'schedules' => array( array_merge($shedule, $options), ), ); $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); $shedules = self::json_decode($res); return $shedules->schedules[0]->id; }
php
public function postSchedule($name, $options, $payload = array()) { $url = "projects/{$this->project_id}/schedules"; $shedule = array( 'name' => $name, 'code_name' => $name, 'payload' => json_encode($payload), ); $request = array( 'schedules' => array( array_merge($shedule, $options), ), ); $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); $shedules = self::json_decode($res); return $shedules->schedules[0]->id; }
[ "public", "function", "postSchedule", "(", "$", "name", ",", "$", "options", ",", "$", "payload", "=", "array", "(", ")", ")", "{", "$", "url", "=", "\"projects/{$this->project_id}/schedules\"", ";", "$", "shedule", "=", "array", "(", "'name'", "=>", "$", "name", ",", "'code_name'", "=>", "$", "name", ",", "'payload'", "=>", "json_encode", "(", "$", "payload", ")", ",", ")", ";", "$", "request", "=", "array", "(", "'schedules'", "=>", "array", "(", "array_merge", "(", "$", "shedule", ",", "$", "options", ")", ",", ")", ",", ")", ";", "$", "this", "->", "setCommonHeaders", "(", ")", ";", "$", "res", "=", "$", "this", "->", "apiCall", "(", "self", "::", "POST", ",", "$", "url", ",", "$", "request", ")", ";", "$", "shedules", "=", "self", "::", "json_decode", "(", "$", "res", ")", ";", "return", "$", "shedules", "->", "schedules", "[", "0", "]", "->", "id", ";", "}" ]
Schedule a task @param string $name @param array $options options contain: start_at OR delay — required - start_at is time of first run. Delay is number of seconds to wait before starting. run_every — optional - Time in seconds between runs. If omitted, task will only run once. end_at — optional - Time tasks will stop being enqueued. (Should be a Time or DateTime object.) run_times — optional - Number of times to run task. For example, if run_times: is 5, the task will run 5 times. priority — optional - Priority queue to run the job in (0, 1, 2). p0 is default. Running at higher priorities to reduce time jobs may spend in the queue, once they come off schedule. Same as priority when queuing up a task. @param array $payload @return mixed
[ "Schedule", "a", "task" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L643-L661
26,225
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.workerHeader
private function workerHeader($worker_file_name, $envs = array()) { $export_env = ""; foreach ($envs as $env => $value) { $export_env .= "putenv(\"$env=$value\");\r\n"; } $header = <<<EOL <?php /*IRON_WORKER_HEADER*/ $export_env function getArgs(\$assoc = true) { global \$argv; \$args = array('task_id' => null, 'dir' => null, 'payload' => array(), 'config' => null); foreach (\$argv as \$k => \$v) { if (empty(\$argv[\$k + 1])) { continue; } if (\$v == '-id') \$args['task_id'] = \$argv[\$k + 1]; if (\$v == '-d') \$args['dir'] = \$argv[\$k + 1]; if (\$v == '-payload') \$args['payload_file'] = \$argv[\$k + 1]; if (\$v == '-config') \$args['config_file'] = \$argv[\$k + 1]; } if (getenv('TASK_ID')) \$args['task_id'] = getenv('TASK_ID'); if (getenv('TASK_DIR')) \$args['dir'] = getenv('TASK_DIR'); if (getenv('PAYLOAD_FILE')) \$args['payload_file'] = getenv('PAYLOAD_FILE'); if (getenv('CONFIG_FILE')) \$args['config_file'] = getenv('CONFIG_FILE'); if (array_key_exists('payload_file',\$args) && file_exists(\$args['payload_file'])) { \$args['payload'] = file_get_contents(\$args['payload_file']); \$parsed_payload = json_decode(\$args['payload'], \$assoc); if (\$parsed_payload != null) { \$args['payload'] = \$parsed_payload; } } if (array_key_exists('config_file',\$args) && file_exists(\$args['config_file'])) { \$args['config'] = file_get_contents(\$args['config_file']); \$parsed_config = json_decode(\$args['config'], \$assoc); if (\$parsed_config != null) { \$args['config'] = \$parsed_config; } } return \$args; } function getPayload(\$assoc = false) { \$args = getArgs(\$assoc); return \$args['payload']; } function getConfig(\$assoc = true) { \$args = getArgs(\$assoc); return \$args['config']; } require dirname(__FILE__)."/[SCRIPT]"; EOL; $header = str_replace( array('[PROJECT_ID]', '[URL]', '[HEADERS]', '[SCRIPT]'), array($this->project_id, $this->url, var_export($this->compiledHeaders(), true), $worker_file_name), $header ); return trim($header, " \n\r"); }
php
private function workerHeader($worker_file_name, $envs = array()) { $export_env = ""; foreach ($envs as $env => $value) { $export_env .= "putenv(\"$env=$value\");\r\n"; } $header = <<<EOL <?php /*IRON_WORKER_HEADER*/ $export_env function getArgs(\$assoc = true) { global \$argv; \$args = array('task_id' => null, 'dir' => null, 'payload' => array(), 'config' => null); foreach (\$argv as \$k => \$v) { if (empty(\$argv[\$k + 1])) { continue; } if (\$v == '-id') \$args['task_id'] = \$argv[\$k + 1]; if (\$v == '-d') \$args['dir'] = \$argv[\$k + 1]; if (\$v == '-payload') \$args['payload_file'] = \$argv[\$k + 1]; if (\$v == '-config') \$args['config_file'] = \$argv[\$k + 1]; } if (getenv('TASK_ID')) \$args['task_id'] = getenv('TASK_ID'); if (getenv('TASK_DIR')) \$args['dir'] = getenv('TASK_DIR'); if (getenv('PAYLOAD_FILE')) \$args['payload_file'] = getenv('PAYLOAD_FILE'); if (getenv('CONFIG_FILE')) \$args['config_file'] = getenv('CONFIG_FILE'); if (array_key_exists('payload_file',\$args) && file_exists(\$args['payload_file'])) { \$args['payload'] = file_get_contents(\$args['payload_file']); \$parsed_payload = json_decode(\$args['payload'], \$assoc); if (\$parsed_payload != null) { \$args['payload'] = \$parsed_payload; } } if (array_key_exists('config_file',\$args) && file_exists(\$args['config_file'])) { \$args['config'] = file_get_contents(\$args['config_file']); \$parsed_config = json_decode(\$args['config'], \$assoc); if (\$parsed_config != null) { \$args['config'] = \$parsed_config; } } return \$args; } function getPayload(\$assoc = false) { \$args = getArgs(\$assoc); return \$args['payload']; } function getConfig(\$assoc = true) { \$args = getArgs(\$assoc); return \$args['config']; } require dirname(__FILE__)."/[SCRIPT]"; EOL; $header = str_replace( array('[PROJECT_ID]', '[URL]', '[HEADERS]', '[SCRIPT]'), array($this->project_id, $this->url, var_export($this->compiledHeaders(), true), $worker_file_name), $header ); return trim($header, " \n\r"); }
[ "private", "function", "workerHeader", "(", "$", "worker_file_name", ",", "$", "envs", "=", "array", "(", ")", ")", "{", "$", "export_env", "=", "\"\"", ";", "foreach", "(", "$", "envs", "as", "$", "env", "=>", "$", "value", ")", "{", "$", "export_env", ".=", "\"putenv(\\\"$env=$value\\\");\\r\\n\"", ";", "}", "$", "header", "=", " <<<EOL\n<?php\n/*IRON_WORKER_HEADER*/\n$export_env\nfunction getArgs(\\$assoc = true)\n{\n global \\$argv;\n\n \\$args = array('task_id' => null, 'dir' => null, 'payload' => array(), 'config' => null);\n\n foreach (\\$argv as \\$k => \\$v)\n {\n if (empty(\\$argv[\\$k + 1]))\n {\n continue;\n }\n\n if (\\$v == '-id') \\$args['task_id'] = \\$argv[\\$k + 1];\n if (\\$v == '-d') \\$args['dir'] = \\$argv[\\$k + 1];\n if (\\$v == '-payload') \\$args['payload_file'] = \\$argv[\\$k + 1];\n if (\\$v == '-config') \\$args['config_file'] = \\$argv[\\$k + 1];\n }\n\n if (getenv('TASK_ID')) \\$args['task_id'] = getenv('TASK_ID');\n if (getenv('TASK_DIR')) \\$args['dir'] = getenv('TASK_DIR');\n if (getenv('PAYLOAD_FILE')) \\$args['payload_file'] = getenv('PAYLOAD_FILE');\n if (getenv('CONFIG_FILE')) \\$args['config_file'] = getenv('CONFIG_FILE');\n\n if (array_key_exists('payload_file',\\$args) && file_exists(\\$args['payload_file']))\n {\n \\$args['payload'] = file_get_contents(\\$args['payload_file']);\n\n \\$parsed_payload = json_decode(\\$args['payload'], \\$assoc);\n\n if (\\$parsed_payload != null)\n {\n \\$args['payload'] = \\$parsed_payload;\n }\n }\n\n if (array_key_exists('config_file',\\$args) && file_exists(\\$args['config_file']))\n {\n \\$args['config'] = file_get_contents(\\$args['config_file']);\n\n \\$parsed_config = json_decode(\\$args['config'], \\$assoc);\n\n if (\\$parsed_config != null)\n {\n \\$args['config'] = \\$parsed_config;\n }\n }\n\n return \\$args;\n}\n\nfunction getPayload(\\$assoc = false)\n{\n \\$args = getArgs(\\$assoc);\n\n return \\$args['payload'];\n}\n\nfunction getConfig(\\$assoc = true)\n{\n \\$args = getArgs(\\$assoc);\n\n return \\$args['config'];\n}\n\nrequire dirname(__FILE__).\"/[SCRIPT]\";\nEOL", ";", "$", "header", "=", "str_replace", "(", "array", "(", "'[PROJECT_ID]'", ",", "'[URL]'", ",", "'[HEADERS]'", ",", "'[SCRIPT]'", ")", ",", "array", "(", "$", "this", "->", "project_id", ",", "$", "this", "->", "url", ",", "var_export", "(", "$", "this", "->", "compiledHeaders", "(", ")", ",", "true", ")", ",", "$", "worker_file_name", ")", ",", "$", "header", ")", ";", "return", "trim", "(", "$", "header", ",", "\" \\n\\r\"", ")", ";", "}" ]
Contain php code that adds to worker before upload @param string $worker_file_name @param array $envs @return string
[ "Contain", "php", "code", "that", "adds", "to", "worker", "before", "upload" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L800-L883
26,226
iron-io/iron_worker_php
src/Runtime.php
Runtime.getArgs
public static function getArgs($assoc = true) { global $argv; $args = array('task_id' => null, 'dir' => null, 'payload' => array(), 'config' => null); foreach ($argv as $k => $v) { if (empty($argv[$k + 1])) { continue; } if ($v == '-id') { $args['task_id'] = $argv[$k + 1]; } if ($v == '-d') { $args['dir'] = $argv[$k + 1]; } if ($v == '-payload') { $args['payload_file'] = $argv[$k + 1]; } if ($v == '-config') { $args['config_file'] = $argv[$k + 1]; } } if (getenv('TASK_ID')) { $args['task_id'] = getenv('TASK_ID'); } if (getenv('TASK_DIR')) { $args['dir'] = getenv('TASK_DIR'); } if (getenv('PAYLOAD_FILE')) { $args['payload_file'] = getenv('PAYLOAD_FILE'); } if (getenv('CONFIG_FILE')) { $args['config_file'] = getenv('CONFIG_FILE'); } if (array_key_exists('payload_file', $args) && file_exists($args['payload_file'])) { $args['payload'] = file_get_contents($args['payload_file']); $parsed_payload = json_decode($args['payload'], $assoc); if ($parsed_payload != null) { $args['payload'] = $parsed_payload; } } if (array_key_exists('config_file', $args) && file_exists($args['config_file'])) { $args['config'] = file_get_contents($args['config_file']); $parsed_config = json_decode($args['config'], $assoc); if ($parsed_config != null) { $args['config'] = $parsed_config; } } return $args; }
php
public static function getArgs($assoc = true) { global $argv; $args = array('task_id' => null, 'dir' => null, 'payload' => array(), 'config' => null); foreach ($argv as $k => $v) { if (empty($argv[$k + 1])) { continue; } if ($v == '-id') { $args['task_id'] = $argv[$k + 1]; } if ($v == '-d') { $args['dir'] = $argv[$k + 1]; } if ($v == '-payload') { $args['payload_file'] = $argv[$k + 1]; } if ($v == '-config') { $args['config_file'] = $argv[$k + 1]; } } if (getenv('TASK_ID')) { $args['task_id'] = getenv('TASK_ID'); } if (getenv('TASK_DIR')) { $args['dir'] = getenv('TASK_DIR'); } if (getenv('PAYLOAD_FILE')) { $args['payload_file'] = getenv('PAYLOAD_FILE'); } if (getenv('CONFIG_FILE')) { $args['config_file'] = getenv('CONFIG_FILE'); } if (array_key_exists('payload_file', $args) && file_exists($args['payload_file'])) { $args['payload'] = file_get_contents($args['payload_file']); $parsed_payload = json_decode($args['payload'], $assoc); if ($parsed_payload != null) { $args['payload'] = $parsed_payload; } } if (array_key_exists('config_file', $args) && file_exists($args['config_file'])) { $args['config'] = file_get_contents($args['config_file']); $parsed_config = json_decode($args['config'], $assoc); if ($parsed_config != null) { $args['config'] = $parsed_config; } } return $args; }
[ "public", "static", "function", "getArgs", "(", "$", "assoc", "=", "true", ")", "{", "global", "$", "argv", ";", "$", "args", "=", "array", "(", "'task_id'", "=>", "null", ",", "'dir'", "=>", "null", ",", "'payload'", "=>", "array", "(", ")", ",", "'config'", "=>", "null", ")", ";", "foreach", "(", "$", "argv", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "empty", "(", "$", "argv", "[", "$", "k", "+", "1", "]", ")", ")", "{", "continue", ";", "}", "if", "(", "$", "v", "==", "'-id'", ")", "{", "$", "args", "[", "'task_id'", "]", "=", "$", "argv", "[", "$", "k", "+", "1", "]", ";", "}", "if", "(", "$", "v", "==", "'-d'", ")", "{", "$", "args", "[", "'dir'", "]", "=", "$", "argv", "[", "$", "k", "+", "1", "]", ";", "}", "if", "(", "$", "v", "==", "'-payload'", ")", "{", "$", "args", "[", "'payload_file'", "]", "=", "$", "argv", "[", "$", "k", "+", "1", "]", ";", "}", "if", "(", "$", "v", "==", "'-config'", ")", "{", "$", "args", "[", "'config_file'", "]", "=", "$", "argv", "[", "$", "k", "+", "1", "]", ";", "}", "}", "if", "(", "getenv", "(", "'TASK_ID'", ")", ")", "{", "$", "args", "[", "'task_id'", "]", "=", "getenv", "(", "'TASK_ID'", ")", ";", "}", "if", "(", "getenv", "(", "'TASK_DIR'", ")", ")", "{", "$", "args", "[", "'dir'", "]", "=", "getenv", "(", "'TASK_DIR'", ")", ";", "}", "if", "(", "getenv", "(", "'PAYLOAD_FILE'", ")", ")", "{", "$", "args", "[", "'payload_file'", "]", "=", "getenv", "(", "'PAYLOAD_FILE'", ")", ";", "}", "if", "(", "getenv", "(", "'CONFIG_FILE'", ")", ")", "{", "$", "args", "[", "'config_file'", "]", "=", "getenv", "(", "'CONFIG_FILE'", ")", ";", "}", "if", "(", "array_key_exists", "(", "'payload_file'", ",", "$", "args", ")", "&&", "file_exists", "(", "$", "args", "[", "'payload_file'", "]", ")", ")", "{", "$", "args", "[", "'payload'", "]", "=", "file_get_contents", "(", "$", "args", "[", "'payload_file'", "]", ")", ";", "$", "parsed_payload", "=", "json_decode", "(", "$", "args", "[", "'payload'", "]", ",", "$", "assoc", ")", ";", "if", "(", "$", "parsed_payload", "!=", "null", ")", "{", "$", "args", "[", "'payload'", "]", "=", "$", "parsed_payload", ";", "}", "}", "if", "(", "array_key_exists", "(", "'config_file'", ",", "$", "args", ")", "&&", "file_exists", "(", "$", "args", "[", "'config_file'", "]", ")", ")", "{", "$", "args", "[", "'config'", "]", "=", "file_get_contents", "(", "$", "args", "[", "'config_file'", "]", ")", ";", "$", "parsed_config", "=", "json_decode", "(", "$", "args", "[", "'config'", "]", ",", "$", "assoc", ")", ";", "if", "(", "$", "parsed_config", "!=", "null", ")", "{", "$", "args", "[", "'config'", "]", "=", "$", "parsed_config", ";", "}", "}", "return", "$", "args", ";", "}" ]
getArgs gets the arguments from the input to this worker
[ "getArgs", "gets", "the", "arguments", "from", "the", "input", "to", "this", "worker" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/Runtime.php#L33-L99
26,227
freearhey/knowledge-graph
src/KnowledgeGraph.php
KnowledgeGraph.search
public function search($query, $type = null, $lang = null, $limit = null) { $results = $this->client->request([ 'query' => $query, 'types' => $type, 'languages' => $lang, 'limit' => $limit ]); return $results; }
php
public function search($query, $type = null, $lang = null, $limit = null) { $results = $this->client->request([ 'query' => $query, 'types' => $type, 'languages' => $lang, 'limit' => $limit ]); return $results; }
[ "public", "function", "search", "(", "$", "query", ",", "$", "type", "=", "null", ",", "$", "lang", "=", "null", ",", "$", "limit", "=", "null", ")", "{", "$", "results", "=", "$", "this", "->", "client", "->", "request", "(", "[", "'query'", "=>", "$", "query", ",", "'types'", "=>", "$", "type", ",", "'languages'", "=>", "$", "lang", ",", "'limit'", "=>", "$", "limit", "]", ")", ";", "return", "$", "results", ";", "}" ]
Search by entity name @param string $query @param string $type Restricts returned results to those of the specified types. (e.g. "Person") @param string $lang Language code (ISO 639) to run the query with (e.g. "es") @param string $limit Limits the number of results to be returned. (default: 20) @return \Illuminate\Support\Collection Return collection of \KnowledgeGraph\SearchResult
[ "Search", "by", "entity", "name" ]
62eadb4bb2cdf97a14de2b4973d8aa361411e21a
https://github.com/freearhey/knowledge-graph/blob/62eadb4bb2cdf97a14de2b4973d8aa361411e21a/src/KnowledgeGraph.php#L30-L40
26,228
Domraider/rxnet
src/Rxnet/RabbitMq/RabbitMq.php
RabbitMq.channel
public function channel($bind = []) { if (!is_array($bind)) { $bind = func_get_args(); } return $this->bunny->connect() ->flatMap(function () { return $this->bunny->channel(); }) ->map(function (Channel $channel) use ($bind) { foreach ($bind as $obj) { $obj->setChannel($channel); } return $channel; }); }
php
public function channel($bind = []) { if (!is_array($bind)) { $bind = func_get_args(); } return $this->bunny->connect() ->flatMap(function () { return $this->bunny->channel(); }) ->map(function (Channel $channel) use ($bind) { foreach ($bind as $obj) { $obj->setChannel($channel); } return $channel; }); }
[ "public", "function", "channel", "(", "$", "bind", "=", "[", "]", ")", "{", "if", "(", "!", "is_array", "(", "$", "bind", ")", ")", "{", "$", "bind", "=", "func_get_args", "(", ")", ";", "}", "return", "$", "this", "->", "bunny", "->", "connect", "(", ")", "->", "flatMap", "(", "function", "(", ")", "{", "return", "$", "this", "->", "bunny", "->", "channel", "(", ")", ";", "}", ")", "->", "map", "(", "function", "(", "Channel", "$", "channel", ")", "use", "(", "$", "bind", ")", "{", "foreach", "(", "$", "bind", "as", "$", "obj", ")", "{", "$", "obj", "->", "setChannel", "(", "$", "channel", ")", ";", "}", "return", "$", "channel", ";", "}", ")", ";", "}" ]
Open a new channel and attribute it to given queues or exchanges @param RabbitQueue[]|RabbitExchange[] $bind @return Observable\AnonymousObservable
[ "Open", "a", "new", "channel", "and", "attribute", "it", "to", "given", "queues", "or", "exchanges" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/RabbitMq/RabbitMq.php#L73-L88
26,229
Domraider/rxnet
src/Rxnet/RabbitMq/RabbitMq.php
RabbitMq.consume
public function consume($queue, $prefetchCount = null, $prefetchSize = null, $consumerId = null, $opts = []) { return $this->channel() ->doOnNext(function (Channel $channel) use ($prefetchCount, $prefetchSize) { $channel->qos($prefetchSize, $prefetchCount); }) ->flatMap( function (Channel $channel) use ($queue, $consumerId, $opts) { return $this->queue($queue, $opts, $channel) ->consume($consumerId); } ); }
php
public function consume($queue, $prefetchCount = null, $prefetchSize = null, $consumerId = null, $opts = []) { return $this->channel() ->doOnNext(function (Channel $channel) use ($prefetchCount, $prefetchSize) { $channel->qos($prefetchSize, $prefetchCount); }) ->flatMap( function (Channel $channel) use ($queue, $consumerId, $opts) { return $this->queue($queue, $opts, $channel) ->consume($consumerId); } ); }
[ "public", "function", "consume", "(", "$", "queue", ",", "$", "prefetchCount", "=", "null", ",", "$", "prefetchSize", "=", "null", ",", "$", "consumerId", "=", "null", ",", "$", "opts", "=", "[", "]", ")", "{", "return", "$", "this", "->", "channel", "(", ")", "->", "doOnNext", "(", "function", "(", "Channel", "$", "channel", ")", "use", "(", "$", "prefetchCount", ",", "$", "prefetchSize", ")", "{", "$", "channel", "->", "qos", "(", "$", "prefetchSize", ",", "$", "prefetchCount", ")", ";", "}", ")", "->", "flatMap", "(", "function", "(", "Channel", "$", "channel", ")", "use", "(", "$", "queue", ",", "$", "consumerId", ",", "$", "opts", ")", "{", "return", "$", "this", "->", "queue", "(", "$", "queue", ",", "$", "opts", ",", "$", "channel", ")", "->", "consume", "(", "$", "consumerId", ")", ";", "}", ")", ";", "}" ]
Consume given queue at @param string $queue name of the queue @param int|null $prefetchCount @param int|null $prefetchSize @param string $consumerId @param array $opts @return Observable\AnonymousObservable
[ "Consume", "given", "queue", "at" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/RabbitMq/RabbitMq.php#L99-L111
26,230
Domraider/rxnet
src/Rxnet/RabbitMq/RabbitMq.php
RabbitMq.produce
public function produce($data, $headers = [], $exchange = '', $routingKey) { return Observable::create(function (ObserverInterface $observer) use ($exchange, $data, $headers, $routingKey) { return $this->channel() ->flatMap( function (Channel $channel) use ($exchange, $data, $headers, $routingKey) { return $this->exchange($exchange, [], $channel) ->produce($data, $routingKey, $headers) ->doOnNext(function () use ($channel) { $channel->close(); }); } )->subscribe($observer); }); }
php
public function produce($data, $headers = [], $exchange = '', $routingKey) { return Observable::create(function (ObserverInterface $observer) use ($exchange, $data, $headers, $routingKey) { return $this->channel() ->flatMap( function (Channel $channel) use ($exchange, $data, $headers, $routingKey) { return $this->exchange($exchange, [], $channel) ->produce($data, $routingKey, $headers) ->doOnNext(function () use ($channel) { $channel->close(); }); } )->subscribe($observer); }); }
[ "public", "function", "produce", "(", "$", "data", ",", "$", "headers", "=", "[", "]", ",", "$", "exchange", "=", "''", ",", "$", "routingKey", ")", "{", "return", "Observable", "::", "create", "(", "function", "(", "ObserverInterface", "$", "observer", ")", "use", "(", "$", "exchange", ",", "$", "data", ",", "$", "headers", ",", "$", "routingKey", ")", "{", "return", "$", "this", "->", "channel", "(", ")", "->", "flatMap", "(", "function", "(", "Channel", "$", "channel", ")", "use", "(", "$", "exchange", ",", "$", "data", ",", "$", "headers", ",", "$", "routingKey", ")", "{", "return", "$", "this", "->", "exchange", "(", "$", "exchange", ",", "[", "]", ",", "$", "channel", ")", "->", "produce", "(", "$", "data", ",", "$", "routingKey", ",", "$", "headers", ")", "->", "doOnNext", "(", "function", "(", ")", "use", "(", "$", "channel", ")", "{", "$", "channel", "->", "close", "(", ")", ";", "}", ")", ";", "}", ")", "->", "subscribe", "(", "$", "observer", ")", ";", "}", ")", ";", "}" ]
One time produce on dedicated channel and close after @param $data @param array $headers @param string $exchange @param $routingKey @return Observable\AnonymousObservable
[ "One", "time", "produce", "on", "dedicated", "channel", "and", "close", "after" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/RabbitMq/RabbitMq.php#L121-L135
26,231
UseMuffin/Tags
src/Model/Behavior/TagBehavior.php
TagBehavior.bindAssociations
public function bindAssociations() { $config = $this->getConfig(); $tagsAlias = $config['tagsAlias']; $tagsAssoc = $config['tagsAssoc']; $taggedAlias = $config['taggedAlias']; $taggedAssoc = $config['taggedAssoc']; $table = $this->_table; $tableAlias = $this->_table->getAlias(); $assocConditions = [$taggedAlias . '.' . $this->getConfig('fkTableField') => $table->getTable()]; if (!$table->hasAssociation($taggedAlias)) { $table->hasMany($taggedAlias, $taggedAssoc + [ 'foreignKey' => $tagsAssoc['foreignKey'], 'conditions' => $assocConditions, ]); } if (!$table->hasAssociation($tagsAlias)) { $table->belongsToMany($tagsAlias, $tagsAssoc + [ 'through' => $table->{$taggedAlias}->getTarget(), 'conditions' => $assocConditions, ]); } if (!$table->{$tagsAlias}->hasAssociation($tableAlias)) { $table->{$tagsAlias} ->belongsToMany($tableAlias, [ 'className' => $table->getTable(), ] + $tagsAssoc); } if (!$table->{$taggedAlias}->hasAssociation($tableAlias)) { $table->{$taggedAlias} ->belongsTo($tableAlias, [ 'className' => $table->getTable(), 'foreignKey' => $tagsAssoc['foreignKey'], 'conditions' => $assocConditions, 'joinType' => 'INNER', ]); } if (!$table->{$taggedAlias}->hasAssociation($tableAlias . $tagsAlias)) { $table->{$taggedAlias} ->belongsTo($tableAlias . $tagsAlias, [ 'className' => $tagsAssoc['className'], 'foreignKey' => $tagsAssoc['targetForeignKey'], 'conditions' => $assocConditions, 'joinType' => 'INNER', ]); } }
php
public function bindAssociations() { $config = $this->getConfig(); $tagsAlias = $config['tagsAlias']; $tagsAssoc = $config['tagsAssoc']; $taggedAlias = $config['taggedAlias']; $taggedAssoc = $config['taggedAssoc']; $table = $this->_table; $tableAlias = $this->_table->getAlias(); $assocConditions = [$taggedAlias . '.' . $this->getConfig('fkTableField') => $table->getTable()]; if (!$table->hasAssociation($taggedAlias)) { $table->hasMany($taggedAlias, $taggedAssoc + [ 'foreignKey' => $tagsAssoc['foreignKey'], 'conditions' => $assocConditions, ]); } if (!$table->hasAssociation($tagsAlias)) { $table->belongsToMany($tagsAlias, $tagsAssoc + [ 'through' => $table->{$taggedAlias}->getTarget(), 'conditions' => $assocConditions, ]); } if (!$table->{$tagsAlias}->hasAssociation($tableAlias)) { $table->{$tagsAlias} ->belongsToMany($tableAlias, [ 'className' => $table->getTable(), ] + $tagsAssoc); } if (!$table->{$taggedAlias}->hasAssociation($tableAlias)) { $table->{$taggedAlias} ->belongsTo($tableAlias, [ 'className' => $table->getTable(), 'foreignKey' => $tagsAssoc['foreignKey'], 'conditions' => $assocConditions, 'joinType' => 'INNER', ]); } if (!$table->{$taggedAlias}->hasAssociation($tableAlias . $tagsAlias)) { $table->{$taggedAlias} ->belongsTo($tableAlias . $tagsAlias, [ 'className' => $tagsAssoc['className'], 'foreignKey' => $tagsAssoc['targetForeignKey'], 'conditions' => $assocConditions, 'joinType' => 'INNER', ]); } }
[ "public", "function", "bindAssociations", "(", ")", "{", "$", "config", "=", "$", "this", "->", "getConfig", "(", ")", ";", "$", "tagsAlias", "=", "$", "config", "[", "'tagsAlias'", "]", ";", "$", "tagsAssoc", "=", "$", "config", "[", "'tagsAssoc'", "]", ";", "$", "taggedAlias", "=", "$", "config", "[", "'taggedAlias'", "]", ";", "$", "taggedAssoc", "=", "$", "config", "[", "'taggedAssoc'", "]", ";", "$", "table", "=", "$", "this", "->", "_table", ";", "$", "tableAlias", "=", "$", "this", "->", "_table", "->", "getAlias", "(", ")", ";", "$", "assocConditions", "=", "[", "$", "taggedAlias", ".", "'.'", ".", "$", "this", "->", "getConfig", "(", "'fkTableField'", ")", "=>", "$", "table", "->", "getTable", "(", ")", "]", ";", "if", "(", "!", "$", "table", "->", "hasAssociation", "(", "$", "taggedAlias", ")", ")", "{", "$", "table", "->", "hasMany", "(", "$", "taggedAlias", ",", "$", "taggedAssoc", "+", "[", "'foreignKey'", "=>", "$", "tagsAssoc", "[", "'foreignKey'", "]", ",", "'conditions'", "=>", "$", "assocConditions", ",", "]", ")", ";", "}", "if", "(", "!", "$", "table", "->", "hasAssociation", "(", "$", "tagsAlias", ")", ")", "{", "$", "table", "->", "belongsToMany", "(", "$", "tagsAlias", ",", "$", "tagsAssoc", "+", "[", "'through'", "=>", "$", "table", "->", "{", "$", "taggedAlias", "}", "->", "getTarget", "(", ")", ",", "'conditions'", "=>", "$", "assocConditions", ",", "]", ")", ";", "}", "if", "(", "!", "$", "table", "->", "{", "$", "tagsAlias", "}", "->", "hasAssociation", "(", "$", "tableAlias", ")", ")", "{", "$", "table", "->", "{", "$", "tagsAlias", "}", "->", "belongsToMany", "(", "$", "tableAlias", ",", "[", "'className'", "=>", "$", "table", "->", "getTable", "(", ")", ",", "]", "+", "$", "tagsAssoc", ")", ";", "}", "if", "(", "!", "$", "table", "->", "{", "$", "taggedAlias", "}", "->", "hasAssociation", "(", "$", "tableAlias", ")", ")", "{", "$", "table", "->", "{", "$", "taggedAlias", "}", "->", "belongsTo", "(", "$", "tableAlias", ",", "[", "'className'", "=>", "$", "table", "->", "getTable", "(", ")", ",", "'foreignKey'", "=>", "$", "tagsAssoc", "[", "'foreignKey'", "]", ",", "'conditions'", "=>", "$", "assocConditions", ",", "'joinType'", "=>", "'INNER'", ",", "]", ")", ";", "}", "if", "(", "!", "$", "table", "->", "{", "$", "taggedAlias", "}", "->", "hasAssociation", "(", "$", "tableAlias", ".", "$", "tagsAlias", ")", ")", "{", "$", "table", "->", "{", "$", "taggedAlias", "}", "->", "belongsTo", "(", "$", "tableAlias", ".", "$", "tagsAlias", ",", "[", "'className'", "=>", "$", "tagsAssoc", "[", "'className'", "]", ",", "'foreignKey'", "=>", "$", "tagsAssoc", "[", "'targetForeignKey'", "]", ",", "'conditions'", "=>", "$", "assocConditions", ",", "'joinType'", "=>", "'INNER'", ",", "]", ")", ";", "}", "}" ]
Binds all required associations if an association of the same name has not already been configured. @return void
[ "Binds", "all", "required", "associations", "if", "an", "association", "of", "the", "same", "name", "has", "not", "already", "been", "configured", "." ]
6fb767375a39829ea348d64b8fd1b0204b9f26ff
https://github.com/UseMuffin/Tags/blob/6fb767375a39829ea348d64b8fd1b0204b9f26ff/src/Model/Behavior/TagBehavior.php#L98-L151
26,232
UseMuffin/Tags
src/Model/Behavior/TagBehavior.php
TagBehavior.attachCounters
public function attachCounters() { $config = $this->getConfig(); $tagsAlias = $config['tagsAlias']; $taggedAlias = $config['taggedAlias']; $taggedTable = $this->_table->{$taggedAlias}; if (!$taggedTable->hasBehavior('CounterCache')) { $taggedTable->addBehavior('CounterCache'); } $counterCache = $taggedTable->behaviors()->CounterCache; if (!$counterCache->getConfig($tagsAlias)) { $counterCache->setConfig($tagsAlias, $config['tagsCounter']); } if ($config['taggedCounter'] === false) { return; } foreach ($config['taggedCounter'] as $field => $o) { if (!$this->_table->hasField($field)) { throw new RuntimeException(sprintf( 'Field "%s" does not exist in table "%s"', $field, $this->_table->getTable() )); } } if (!$counterCache->getConfig($taggedAlias)) { $field = key($config['taggedCounter']); $config['taggedCounter']['tag_count']['conditions'] = [ $taggedTable->aliasField($this->getConfig('fkTableField')) => $this->_table->getTable(), ]; $counterCache->setConfig($this->_table->getAlias(), $config['taggedCounter']); } }
php
public function attachCounters() { $config = $this->getConfig(); $tagsAlias = $config['tagsAlias']; $taggedAlias = $config['taggedAlias']; $taggedTable = $this->_table->{$taggedAlias}; if (!$taggedTable->hasBehavior('CounterCache')) { $taggedTable->addBehavior('CounterCache'); } $counterCache = $taggedTable->behaviors()->CounterCache; if (!$counterCache->getConfig($tagsAlias)) { $counterCache->setConfig($tagsAlias, $config['tagsCounter']); } if ($config['taggedCounter'] === false) { return; } foreach ($config['taggedCounter'] as $field => $o) { if (!$this->_table->hasField($field)) { throw new RuntimeException(sprintf( 'Field "%s" does not exist in table "%s"', $field, $this->_table->getTable() )); } } if (!$counterCache->getConfig($taggedAlias)) { $field = key($config['taggedCounter']); $config['taggedCounter']['tag_count']['conditions'] = [ $taggedTable->aliasField($this->getConfig('fkTableField')) => $this->_table->getTable(), ]; $counterCache->setConfig($this->_table->getAlias(), $config['taggedCounter']); } }
[ "public", "function", "attachCounters", "(", ")", "{", "$", "config", "=", "$", "this", "->", "getConfig", "(", ")", ";", "$", "tagsAlias", "=", "$", "config", "[", "'tagsAlias'", "]", ";", "$", "taggedAlias", "=", "$", "config", "[", "'taggedAlias'", "]", ";", "$", "taggedTable", "=", "$", "this", "->", "_table", "->", "{", "$", "taggedAlias", "}", ";", "if", "(", "!", "$", "taggedTable", "->", "hasBehavior", "(", "'CounterCache'", ")", ")", "{", "$", "taggedTable", "->", "addBehavior", "(", "'CounterCache'", ")", ";", "}", "$", "counterCache", "=", "$", "taggedTable", "->", "behaviors", "(", ")", "->", "CounterCache", ";", "if", "(", "!", "$", "counterCache", "->", "getConfig", "(", "$", "tagsAlias", ")", ")", "{", "$", "counterCache", "->", "setConfig", "(", "$", "tagsAlias", ",", "$", "config", "[", "'tagsCounter'", "]", ")", ";", "}", "if", "(", "$", "config", "[", "'taggedCounter'", "]", "===", "false", ")", "{", "return", ";", "}", "foreach", "(", "$", "config", "[", "'taggedCounter'", "]", "as", "$", "field", "=>", "$", "o", ")", "{", "if", "(", "!", "$", "this", "->", "_table", "->", "hasField", "(", "$", "field", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'Field \"%s\" does not exist in table \"%s\"'", ",", "$", "field", ",", "$", "this", "->", "_table", "->", "getTable", "(", ")", ")", ")", ";", "}", "}", "if", "(", "!", "$", "counterCache", "->", "getConfig", "(", "$", "taggedAlias", ")", ")", "{", "$", "field", "=", "key", "(", "$", "config", "[", "'taggedCounter'", "]", ")", ";", "$", "config", "[", "'taggedCounter'", "]", "[", "'tag_count'", "]", "[", "'conditions'", "]", "=", "[", "$", "taggedTable", "->", "aliasField", "(", "$", "this", "->", "getConfig", "(", "'fkTableField'", ")", ")", "=>", "$", "this", "->", "_table", "->", "getTable", "(", ")", ",", "]", ";", "$", "counterCache", "->", "setConfig", "(", "$", "this", "->", "_table", "->", "getAlias", "(", ")", ",", "$", "config", "[", "'taggedCounter'", "]", ")", ";", "}", "}" ]
Attaches the `CounterCache` behavior to the `Tagged` table to keep counts on both the `Tags` and the tagged entities. @return void @throws \RuntimeException If configured counter cache field does not exist in table.
[ "Attaches", "the", "CounterCache", "behavior", "to", "the", "Tagged", "table", "to", "keep", "counts", "on", "both", "the", "Tags", "and", "the", "tagged", "entities", "." ]
6fb767375a39829ea348d64b8fd1b0204b9f26ff
https://github.com/UseMuffin/Tags/blob/6fb767375a39829ea348d64b8fd1b0204b9f26ff/src/Model/Behavior/TagBehavior.php#L160-L199
26,233
freearhey/knowledge-graph
src/Client.php
Client.request
public function request($params) { $query = array_merge($params, [ 'key' => $this->key ]); try { $response = $this->client->get(self::API_ENDPOINT, [ 'query' => $query ]); } catch (ClientException $exception) { return collect([]); } $results = json_decode($response->getBody(), true); $output = []; for($i = 0; $i < count($results['itemListElement']); $i++) { $output[] = new SearchResult($results['itemListElement'][$i]); } return collect($output); }
php
public function request($params) { $query = array_merge($params, [ 'key' => $this->key ]); try { $response = $this->client->get(self::API_ENDPOINT, [ 'query' => $query ]); } catch (ClientException $exception) { return collect([]); } $results = json_decode($response->getBody(), true); $output = []; for($i = 0; $i < count($results['itemListElement']); $i++) { $output[] = new SearchResult($results['itemListElement'][$i]); } return collect($output); }
[ "public", "function", "request", "(", "$", "params", ")", "{", "$", "query", "=", "array_merge", "(", "$", "params", ",", "[", "'key'", "=>", "$", "this", "->", "key", "]", ")", ";", "try", "{", "$", "response", "=", "$", "this", "->", "client", "->", "get", "(", "self", "::", "API_ENDPOINT", ",", "[", "'query'", "=>", "$", "query", "]", ")", ";", "}", "catch", "(", "ClientException", "$", "exception", ")", "{", "return", "collect", "(", "[", "]", ")", ";", "}", "$", "results", "=", "json_decode", "(", "$", "response", "->", "getBody", "(", ")", ",", "true", ")", ";", "$", "output", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "results", "[", "'itemListElement'", "]", ")", ";", "$", "i", "++", ")", "{", "$", "output", "[", "]", "=", "new", "SearchResult", "(", "$", "results", "[", "'itemListElement'", "]", "[", "$", "i", "]", ")", ";", "}", "return", "collect", "(", "$", "output", ")", ";", "}" ]
Make request to Knowledge Graph API @var array $params @return \Illuminate\Support\Collection Return collection of \KnowledgeGraph\Result
[ "Make", "request", "to", "Knowledge", "Graph", "API" ]
62eadb4bb2cdf97a14de2b4973d8aa361411e21a
https://github.com/freearhey/knowledge-graph/blob/62eadb4bb2cdf97a14de2b4973d8aa361411e21a/src/Client.php#L44-L71
26,234
joomla-framework/archive
src/Zip.php
Zip.extractCustom
protected function extractCustom($archive, $destination) { $this->data = null; $this->metadata = null; $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } if (!$this->readZipInfo($this->data)) { throw new \RuntimeException('Get ZIP Information failed'); } for ($i = 0, $n = \count($this->metadata); $i < $n; $i++) { $lastPathCharacter = substr($this->metadata[$i]['name'], -1, 1); if ($lastPathCharacter !== '/' && $lastPathCharacter !== '\\') { $buffer = $this->getFileData($i); $path = Path::clean($destination . '/' . $this->metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(\dirname($path))) { throw new \RuntimeException('Unable to create destination folder ' . \dirname($path)); } if (!File::write($path, $buffer)) { throw new \RuntimeException('Unable to write entry to file ' . $path); } } } return true; }
php
protected function extractCustom($archive, $destination) { $this->data = null; $this->metadata = null; $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } if (!$this->readZipInfo($this->data)) { throw new \RuntimeException('Get ZIP Information failed'); } for ($i = 0, $n = \count($this->metadata); $i < $n; $i++) { $lastPathCharacter = substr($this->metadata[$i]['name'], -1, 1); if ($lastPathCharacter !== '/' && $lastPathCharacter !== '\\') { $buffer = $this->getFileData($i); $path = Path::clean($destination . '/' . $this->metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(\dirname($path))) { throw new \RuntimeException('Unable to create destination folder ' . \dirname($path)); } if (!File::write($path, $buffer)) { throw new \RuntimeException('Unable to write entry to file ' . $path); } } } return true; }
[ "protected", "function", "extractCustom", "(", "$", "archive", ",", "$", "destination", ")", "{", "$", "this", "->", "data", "=", "null", ";", "$", "this", "->", "metadata", "=", "null", ";", "$", "this", "->", "data", "=", "file_get_contents", "(", "$", "archive", ")", ";", "if", "(", "!", "$", "this", "->", "data", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to read archive'", ")", ";", "}", "if", "(", "!", "$", "this", "->", "readZipInfo", "(", "$", "this", "->", "data", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Get ZIP Information failed'", ")", ";", "}", "for", "(", "$", "i", "=", "0", ",", "$", "n", "=", "\\", "count", "(", "$", "this", "->", "metadata", ")", ";", "$", "i", "<", "$", "n", ";", "$", "i", "++", ")", "{", "$", "lastPathCharacter", "=", "substr", "(", "$", "this", "->", "metadata", "[", "$", "i", "]", "[", "'name'", "]", ",", "-", "1", ",", "1", ")", ";", "if", "(", "$", "lastPathCharacter", "!==", "'/'", "&&", "$", "lastPathCharacter", "!==", "'\\\\'", ")", "{", "$", "buffer", "=", "$", "this", "->", "getFileData", "(", "$", "i", ")", ";", "$", "path", "=", "Path", "::", "clean", "(", "$", "destination", ".", "'/'", ".", "$", "this", "->", "metadata", "[", "$", "i", "]", "[", "'name'", "]", ")", ";", "// Make sure the destination folder exists", "if", "(", "!", "Folder", "::", "create", "(", "\\", "dirname", "(", "$", "path", ")", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to create destination folder '", ".", "\\", "dirname", "(", "$", "path", ")", ")", ";", "}", "if", "(", "!", "File", "::", "write", "(", "$", "path", ",", "$", "buffer", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to write entry to file '", ".", "$", "path", ")", ";", "}", "}", "}", "return", "true", ";", "}" ]
Extract a ZIP compressed file to a given path using a php based algorithm that only requires zlib support @param string $archive Path to ZIP archive to extract. @param string $destination Path to extract archive into. @return boolean True if successful @since 1.0 @throws \RuntimeException
[ "Extract", "a", "ZIP", "compressed", "file", "to", "a", "given", "path", "using", "a", "php", "based", "algorithm", "that", "only", "requires", "zlib", "support" ]
b1d496e8c7814f1e376cb14296c38d5ef4e08c78
https://github.com/joomla-framework/archive/blob/b1d496e8c7814f1e376cb14296c38d5ef4e08c78/src/Zip.php#L223-L263
26,235
joomla-framework/archive
src/Zip.php
Zip.extractNative
protected function extractNative($archive, $destination) { $zip = zip_open($archive); if (!\is_resource($zip)) { throw new \RuntimeException('Unable to open archive'); } // Make sure the destination folder exists if (!Folder::create($destination)) { throw new \RuntimeException('Unable to create destination folder ' . \dirname($path)); } // Read files in the archive while ($file = @zip_read($zip)) { if (!zip_entry_open($zip, $file, 'r')) { throw new \RuntimeException('Unable to read ZIP entry'); } if (substr(zip_entry_name($file), \strlen(zip_entry_name($file)) - 1) != '/') { $buffer = zip_entry_read($file, zip_entry_filesize($file)); if (File::write($destination . '/' . zip_entry_name($file), $buffer) === false) { throw new \RuntimeException('Unable to write ZIP entry to file ' . $destination . '/' . zip_entry_name($file)); } zip_entry_close($file); } } @zip_close($zip); return true; }
php
protected function extractNative($archive, $destination) { $zip = zip_open($archive); if (!\is_resource($zip)) { throw new \RuntimeException('Unable to open archive'); } // Make sure the destination folder exists if (!Folder::create($destination)) { throw new \RuntimeException('Unable to create destination folder ' . \dirname($path)); } // Read files in the archive while ($file = @zip_read($zip)) { if (!zip_entry_open($zip, $file, 'r')) { throw new \RuntimeException('Unable to read ZIP entry'); } if (substr(zip_entry_name($file), \strlen(zip_entry_name($file)) - 1) != '/') { $buffer = zip_entry_read($file, zip_entry_filesize($file)); if (File::write($destination . '/' . zip_entry_name($file), $buffer) === false) { throw new \RuntimeException('Unable to write ZIP entry to file ' . $destination . '/' . zip_entry_name($file)); } zip_entry_close($file); } } @zip_close($zip); return true; }
[ "protected", "function", "extractNative", "(", "$", "archive", ",", "$", "destination", ")", "{", "$", "zip", "=", "zip_open", "(", "$", "archive", ")", ";", "if", "(", "!", "\\", "is_resource", "(", "$", "zip", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to open archive'", ")", ";", "}", "// Make sure the destination folder exists", "if", "(", "!", "Folder", "::", "create", "(", "$", "destination", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to create destination folder '", ".", "\\", "dirname", "(", "$", "path", ")", ")", ";", "}", "// Read files in the archive", "while", "(", "$", "file", "=", "@", "zip_read", "(", "$", "zip", ")", ")", "{", "if", "(", "!", "zip_entry_open", "(", "$", "zip", ",", "$", "file", ",", "'r'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to read ZIP entry'", ")", ";", "}", "if", "(", "substr", "(", "zip_entry_name", "(", "$", "file", ")", ",", "\\", "strlen", "(", "zip_entry_name", "(", "$", "file", ")", ")", "-", "1", ")", "!=", "'/'", ")", "{", "$", "buffer", "=", "zip_entry_read", "(", "$", "file", ",", "zip_entry_filesize", "(", "$", "file", ")", ")", ";", "if", "(", "File", "::", "write", "(", "$", "destination", ".", "'/'", ".", "zip_entry_name", "(", "$", "file", ")", ",", "$", "buffer", ")", "===", "false", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to write ZIP entry to file '", ".", "$", "destination", ".", "'/'", ".", "zip_entry_name", "(", "$", "file", ")", ")", ";", "}", "zip_entry_close", "(", "$", "file", ")", ";", "}", "}", "@", "zip_close", "(", "$", "zip", ")", ";", "return", "true", ";", "}" ]
Extract a ZIP compressed file to a given path using native php api calls for speed @param string $archive Path to ZIP archive to extract @param string $destination Path to extract archive into @return boolean True on success @since 1.0 @throws \RuntimeException
[ "Extract", "a", "ZIP", "compressed", "file", "to", "a", "given", "path", "using", "native", "php", "api", "calls", "for", "speed" ]
b1d496e8c7814f1e376cb14296c38d5ef4e08c78
https://github.com/joomla-framework/archive/blob/b1d496e8c7814f1e376cb14296c38d5ef4e08c78/src/Zip.php#L276-L315
26,236
Domraider/rxnet
src/Rxnet/Contract/DataContainerTrait.php
DataContainerTrait.toStdClass
protected function toStdClass($data) { if (is_array($data) || $data instanceof \ArrayObject) { $data = json_decode(json_encode($data)); } return $data; }
php
protected function toStdClass($data) { if (is_array($data) || $data instanceof \ArrayObject) { $data = json_decode(json_encode($data)); } return $data; }
[ "protected", "function", "toStdClass", "(", "$", "data", ")", "{", "if", "(", "is_array", "(", "$", "data", ")", "||", "$", "data", "instanceof", "\\", "ArrayObject", ")", "{", "$", "data", "=", "json_decode", "(", "json_encode", "(", "$", "data", ")", ")", ";", "}", "return", "$", "data", ";", "}" ]
Transform array or array object to json compatible stdClass @param $data @return mixed
[ "Transform", "array", "or", "array", "object", "to", "json", "compatible", "stdClass" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Contract/DataContainerTrait.php#L127-L133
26,237
Domraider/rxnet
src/Rxnet/Contract/DataContainerTrait.php
DataContainerTrait.normalize
protected function normalize($payload) { $data = get_object_vars($payload); foreach ($data as $k => $v) { if ($v instanceof \DateTime) { $payload->$k = $v->format('c'); continue; } if (is_object($v)) { $payload->$k = $this->normalize($v); continue; } } return $payload; }
php
protected function normalize($payload) { $data = get_object_vars($payload); foreach ($data as $k => $v) { if ($v instanceof \DateTime) { $payload->$k = $v->format('c'); continue; } if (is_object($v)) { $payload->$k = $this->normalize($v); continue; } } return $payload; }
[ "protected", "function", "normalize", "(", "$", "payload", ")", "{", "$", "data", "=", "get_object_vars", "(", "$", "payload", ")", ";", "foreach", "(", "$", "data", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "v", "instanceof", "\\", "DateTime", ")", "{", "$", "payload", "->", "$", "k", "=", "$", "v", "->", "format", "(", "'c'", ")", ";", "continue", ";", "}", "if", "(", "is_object", "(", "$", "v", ")", ")", "{", "$", "payload", "->", "$", "k", "=", "$", "this", "->", "normalize", "(", "$", "v", ")", ";", "continue", ";", "}", "}", "return", "$", "payload", ";", "}" ]
Transform nested sub objects to string if needed Only DateTime or Carbon now @param object $payload @return object
[ "Transform", "nested", "sub", "objects", "to", "string", "if", "needed", "Only", "DateTime", "or", "Carbon", "now" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Contract/DataContainerTrait.php#L141-L155
26,238
Domraider/rxnet
src/Rxnet/Statsd/Statsd.php
Statsd.timing
public function timing($stat, $time, $sampleRate = 1, array $tags = null) { return $this->send(array($stat => "$time|ms"), $sampleRate, $tags); }
php
public function timing($stat, $time, $sampleRate = 1, array $tags = null) { return $this->send(array($stat => "$time|ms"), $sampleRate, $tags); }
[ "public", "function", "timing", "(", "$", "stat", ",", "$", "time", ",", "$", "sampleRate", "=", "1", ",", "array", "$", "tags", "=", "null", ")", "{", "return", "$", "this", "->", "send", "(", "array", "(", "$", "stat", "=>", "\"$time|ms\"", ")", ",", "$", "sampleRate", ",", "$", "tags", ")", ";", "}" ]
Log timing information @param string $stat The metric to in log timing info for. @param float $time The ellapsed time (ms) to log @param float|1.0 $sampleRate the rate (0-1) for sampling. @param array|null $tags @return Observable
[ "Log", "timing", "information" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Statsd/Statsd.php#L58-L61
26,239
Domraider/rxnet
src/Rxnet/Statsd/Statsd.php
Statsd.increment
public function increment($stats, $sampleRate = 1, array $tags = null) { return $this->updateStats($stats, 1, $sampleRate, $tags); }
php
public function increment($stats, $sampleRate = 1, array $tags = null) { return $this->updateStats($stats, 1, $sampleRate, $tags); }
[ "public", "function", "increment", "(", "$", "stats", ",", "$", "sampleRate", "=", "1", ",", "array", "$", "tags", "=", "null", ")", "{", "return", "$", "this", "->", "updateStats", "(", "$", "stats", ",", "1", ",", "$", "sampleRate", ",", "$", "tags", ")", ";", "}" ]
Increments one or more stats counters @param string|array $stats The metric(s) to increment. @param float|1 $sampleRate the rate (0-1) for sampling. @param array|null $tags @return Observable
[ "Increments", "one", "or", "more", "stats", "counters" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Statsd/Statsd.php#L113-L116
26,240
Domraider/rxnet
src/Rxnet/Statsd/Statsd.php
Statsd.decrement
public function decrement($stats, $sampleRate = 1, array $tags = null) { return $this->updateStats($stats, -1, $sampleRate, $tags); }
php
public function decrement($stats, $sampleRate = 1, array $tags = null) { return $this->updateStats($stats, -1, $sampleRate, $tags); }
[ "public", "function", "decrement", "(", "$", "stats", ",", "$", "sampleRate", "=", "1", ",", "array", "$", "tags", "=", "null", ")", "{", "return", "$", "this", "->", "updateStats", "(", "$", "stats", ",", "-", "1", ",", "$", "sampleRate", ",", "$", "tags", ")", ";", "}" ]
Decrements one or more stats counters. @param string|array $stats The metric(s) to decrement. @param float|1 $sampleRate the rate (0-1) for sampling. @param array|null $tags @return Observable
[ "Decrements", "one", "or", "more", "stats", "counters", "." ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Statsd/Statsd.php#L126-L129
26,241
Domraider/rxnet
src/Rxnet/Statsd/Statsd.php
Statsd.updateStats
public function updateStats($stats, $delta = 1, $sampleRate = 1, array $tags = null) { if (!is_array($stats)) { $stats = array($stats); } $data = array(); foreach ($stats as $stat) { $data[$stat] = "$delta|c"; } return $this->send($data, $sampleRate, $tags); }
php
public function updateStats($stats, $delta = 1, $sampleRate = 1, array $tags = null) { if (!is_array($stats)) { $stats = array($stats); } $data = array(); foreach ($stats as $stat) { $data[$stat] = "$delta|c"; } return $this->send($data, $sampleRate, $tags); }
[ "public", "function", "updateStats", "(", "$", "stats", ",", "$", "delta", "=", "1", ",", "$", "sampleRate", "=", "1", ",", "array", "$", "tags", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "stats", ")", ")", "{", "$", "stats", "=", "array", "(", "$", "stats", ")", ";", "}", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "stats", "as", "$", "stat", ")", "{", "$", "data", "[", "$", "stat", "]", "=", "\"$delta|c\"", ";", "}", "return", "$", "this", "->", "send", "(", "$", "data", ",", "$", "sampleRate", ",", "$", "tags", ")", ";", "}" ]
Updates one or more stats counters by arbitrary amounts. @param string|array $stats The metric(s) to update. Should be either a string or array of metrics. @param int|1 $delta The amount to increment/decrement each metric by. @param float|1 $sampleRate the rate (0-1) for sampling. @param array|string $tags Key Value array of Tag => Value, or single tag as string @return Observable
[ "Updates", "one", "or", "more", "stats", "counters", "by", "arbitrary", "amounts", "." ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Statsd/Statsd.php#L141-L151
26,242
joecampo/random-user-agent
src/UserAgent.php
UserAgent.random
public static function random($filterBy = []) { $agents = self::loadUserAgents($filterBy); if (empty($agents)) { throw new \Exception('No user agents matched the filter'); } return $agents[mt_rand(0, count($agents) - 1)]; }
php
public static function random($filterBy = []) { $agents = self::loadUserAgents($filterBy); if (empty($agents)) { throw new \Exception('No user agents matched the filter'); } return $agents[mt_rand(0, count($agents) - 1)]; }
[ "public", "static", "function", "random", "(", "$", "filterBy", "=", "[", "]", ")", "{", "$", "agents", "=", "self", "::", "loadUserAgents", "(", "$", "filterBy", ")", ";", "if", "(", "empty", "(", "$", "agents", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'No user agents matched the filter'", ")", ";", "}", "return", "$", "agents", "[", "mt_rand", "(", "0", ",", "count", "(", "$", "agents", ")", "-", "1", ")", "]", ";", "}" ]
Grab a random user agent from the library's agent list @param array $filterBy @return string @throws \Exception
[ "Grab", "a", "random", "user", "agent", "from", "the", "library", "s", "agent", "list" ]
4a88bd90f66ca398b050b19848e3c6ea143ce8a0
https://github.com/joecampo/random-user-agent/blob/4a88bd90f66ca398b050b19848e3c6ea143ce8a0/src/UserAgent.php#L31-L40
26,243
joecampo/random-user-agent
src/UserAgent.php
UserAgent.validateFilter
private static function validateFilter($filterBy = []) { // Components of $filterBy that will not be ignored $filterParams = [ 'agent_name', 'agent_type', 'device_type', 'os_name', 'os_type', ]; $outputFilter = []; foreach ($filterParams as $field) { if (!empty($filterBy[$field])) { $outputFilter[$field] = $filterBy[$field]; } } return $outputFilter; }
php
private static function validateFilter($filterBy = []) { // Components of $filterBy that will not be ignored $filterParams = [ 'agent_name', 'agent_type', 'device_type', 'os_name', 'os_type', ]; $outputFilter = []; foreach ($filterParams as $field) { if (!empty($filterBy[$field])) { $outputFilter[$field] = $filterBy[$field]; } } return $outputFilter; }
[ "private", "static", "function", "validateFilter", "(", "$", "filterBy", "=", "[", "]", ")", "{", "// Components of $filterBy that will not be ignored", "$", "filterParams", "=", "[", "'agent_name'", ",", "'agent_type'", ",", "'device_type'", ",", "'os_name'", ",", "'os_type'", ",", "]", ";", "$", "outputFilter", "=", "[", "]", ";", "foreach", "(", "$", "filterParams", "as", "$", "field", ")", "{", "if", "(", "!", "empty", "(", "$", "filterBy", "[", "$", "field", "]", ")", ")", "{", "$", "outputFilter", "[", "$", "field", "]", "=", "$", "filterBy", "[", "$", "field", "]", ";", "}", "}", "return", "$", "outputFilter", ";", "}" ]
Validates the filter so that no unexpected values make their way through @param array $filterBy @return array
[ "Validates", "the", "filter", "so", "that", "no", "unexpected", "values", "make", "their", "way", "through" ]
4a88bd90f66ca398b050b19848e3c6ea143ce8a0
https://github.com/joecampo/random-user-agent/blob/4a88bd90f66ca398b050b19848e3c6ea143ce8a0/src/UserAgent.php#L127-L147
26,244
joecampo/random-user-agent
src/UserAgent.php
UserAgent.loadUserAgents
private static function loadUserAgents($filterBy = []) { $filterBy = self::validateFilter($filterBy); $agentDetails = self::getAgentDetails(); $agentStrings = []; for ($i = 0; $i < count($agentDetails); $i++) { foreach ($filterBy as $key => $value) { if (!isset($agentDetails[$i][$key]) || !self::inFilter($agentDetails[$i][$key], $value)) { continue 2; } } $agentStrings[] = $agentDetails[$i]['agent_string']; } return array_values($agentStrings); }
php
private static function loadUserAgents($filterBy = []) { $filterBy = self::validateFilter($filterBy); $agentDetails = self::getAgentDetails(); $agentStrings = []; for ($i = 0; $i < count($agentDetails); $i++) { foreach ($filterBy as $key => $value) { if (!isset($agentDetails[$i][$key]) || !self::inFilter($agentDetails[$i][$key], $value)) { continue 2; } } $agentStrings[] = $agentDetails[$i]['agent_string']; } return array_values($agentStrings); }
[ "private", "static", "function", "loadUserAgents", "(", "$", "filterBy", "=", "[", "]", ")", "{", "$", "filterBy", "=", "self", "::", "validateFilter", "(", "$", "filterBy", ")", ";", "$", "agentDetails", "=", "self", "::", "getAgentDetails", "(", ")", ";", "$", "agentStrings", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "agentDetails", ")", ";", "$", "i", "++", ")", "{", "foreach", "(", "$", "filterBy", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "agentDetails", "[", "$", "i", "]", "[", "$", "key", "]", ")", "||", "!", "self", "::", "inFilter", "(", "$", "agentDetails", "[", "$", "i", "]", "[", "$", "key", "]", ",", "$", "value", ")", ")", "{", "continue", "2", ";", "}", "}", "$", "agentStrings", "[", "]", "=", "$", "agentDetails", "[", "$", "i", "]", "[", "'agent_string'", "]", ";", "}", "return", "array_values", "(", "$", "agentStrings", ")", ";", "}" ]
Returns an array of user agents that match a filter if one is provided @param array $filterBy @return array
[ "Returns", "an", "array", "of", "user", "agents", "that", "match", "a", "filter", "if", "one", "is", "provided" ]
4a88bd90f66ca398b050b19848e3c6ea143ce8a0
https://github.com/joecampo/random-user-agent/blob/4a88bd90f66ca398b050b19848e3c6ea143ce8a0/src/UserAgent.php#L155-L172
26,245
libgraviton/graviton
src/Graviton/CoreBundle/Controller/VersionController.php
VersionController.versionsAction
public function versionsAction() { $versions = [ 'versions' => $this->versionInformation ]; $response = $this->getResponse() ->setStatusCode(Response::HTTP_OK) ->setContent(json_encode($versions)); $response->headers->set('Content-Type', 'application/json'); return $response; }
php
public function versionsAction() { $versions = [ 'versions' => $this->versionInformation ]; $response = $this->getResponse() ->setStatusCode(Response::HTTP_OK) ->setContent(json_encode($versions)); $response->headers->set('Content-Type', 'application/json'); return $response; }
[ "public", "function", "versionsAction", "(", ")", "{", "$", "versions", "=", "[", "'versions'", "=>", "$", "this", "->", "versionInformation", "]", ";", "$", "response", "=", "$", "this", "->", "getResponse", "(", ")", "->", "setStatusCode", "(", "Response", "::", "HTTP_OK", ")", "->", "setContent", "(", "json_encode", "(", "$", "versions", ")", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "return", "$", "response", ";", "}" ]
Returns all version numbers @return \Symfony\Component\HttpFoundation\Response $response Response with result or error
[ "Returns", "all", "version", "numbers" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/VersionController.php#L38-L51
26,246
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php
ConstraintUtils.getSerializedEntity
public function getSerializedEntity($documentClass, $recordId, array $fields = null) { if (is_array($fields)) { return $this->getSingleEntity($documentClass, $recordId, $fields); } if (!isset($this->entities[$documentClass][$recordId])) { $current = $this->getSingleEntity($documentClass, $recordId, $fields); if (is_null($current)) { $this->entities[$documentClass][$recordId] = null; } else { $this->entities[$documentClass][$recordId] = $current; } } return $this->entities[$documentClass][$recordId]; }
php
public function getSerializedEntity($documentClass, $recordId, array $fields = null) { if (is_array($fields)) { return $this->getSingleEntity($documentClass, $recordId, $fields); } if (!isset($this->entities[$documentClass][$recordId])) { $current = $this->getSingleEntity($documentClass, $recordId, $fields); if (is_null($current)) { $this->entities[$documentClass][$recordId] = null; } else { $this->entities[$documentClass][$recordId] = $current; } } return $this->entities[$documentClass][$recordId]; }
[ "public", "function", "getSerializedEntity", "(", "$", "documentClass", ",", "$", "recordId", ",", "array", "$", "fields", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "fields", ")", ")", "{", "return", "$", "this", "->", "getSingleEntity", "(", "$", "documentClass", ",", "$", "recordId", ",", "$", "fields", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "entities", "[", "$", "documentClass", "]", "[", "$", "recordId", "]", ")", ")", "{", "$", "current", "=", "$", "this", "->", "getSingleEntity", "(", "$", "documentClass", ",", "$", "recordId", ",", "$", "fields", ")", ";", "if", "(", "is_null", "(", "$", "current", ")", ")", "{", "$", "this", "->", "entities", "[", "$", "documentClass", "]", "[", "$", "recordId", "]", "=", "null", ";", "}", "else", "{", "$", "this", "->", "entities", "[", "$", "documentClass", "]", "[", "$", "recordId", "]", "=", "$", "current", ";", "}", "}", "return", "$", "this", "->", "entities", "[", "$", "documentClass", "]", "[", "$", "recordId", "]", ";", "}" ]
Gets a entity from the database as a generic object. All constraints that need the saved data to compare values or anything should call this function to get what they need. As this is cached in the instance, it will fetched only once even if multiple constraints need that object. @param string $documentClass document class @param string $recordId record id @param array $fields if you only need certain fields, you can specify them here @throws \Exception @return object|null entity
[ "Gets", "a", "entity", "from", "the", "database", "as", "a", "generic", "object", ".", "All", "constraints", "that", "need", "the", "saved", "data", "to", "compare", "values", "or", "anything", "should", "call", "this", "function", "to", "get", "what", "they", "need", ".", "As", "this", "is", "cached", "in", "the", "instance", "it", "will", "fetched", "only", "once", "even", "if", "multiple", "constraints", "need", "that", "object", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L71-L88
26,247
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php
ConstraintUtils.getSingleEntity
private function getSingleEntity($documentClass, $recordId, array $fields = null) { // only get certain fields! will not be cached in instance $queryBuilder = $this->dm->createQueryBuilder($documentClass); $queryBuilder->field('id')->equals($recordId); if (is_array($fields)) { $queryBuilder->select($fields); } $query = $queryBuilder->getQuery(); $query->setRefresh(true); $records = array_values($query->execute()->toArray()); if (is_array($records) && !empty($records)) { return json_decode($this->restUtils->serializeContent($records[0])); } return null; }
php
private function getSingleEntity($documentClass, $recordId, array $fields = null) { // only get certain fields! will not be cached in instance $queryBuilder = $this->dm->createQueryBuilder($documentClass); $queryBuilder->field('id')->equals($recordId); if (is_array($fields)) { $queryBuilder->select($fields); } $query = $queryBuilder->getQuery(); $query->setRefresh(true); $records = array_values($query->execute()->toArray()); if (is_array($records) && !empty($records)) { return json_decode($this->restUtils->serializeContent($records[0])); } return null; }
[ "private", "function", "getSingleEntity", "(", "$", "documentClass", ",", "$", "recordId", ",", "array", "$", "fields", "=", "null", ")", "{", "// only get certain fields! will not be cached in instance", "$", "queryBuilder", "=", "$", "this", "->", "dm", "->", "createQueryBuilder", "(", "$", "documentClass", ")", ";", "$", "queryBuilder", "->", "field", "(", "'id'", ")", "->", "equals", "(", "$", "recordId", ")", ";", "if", "(", "is_array", "(", "$", "fields", ")", ")", "{", "$", "queryBuilder", "->", "select", "(", "$", "fields", ")", ";", "}", "$", "query", "=", "$", "queryBuilder", "->", "getQuery", "(", ")", ";", "$", "query", "->", "setRefresh", "(", "true", ")", ";", "$", "records", "=", "array_values", "(", "$", "query", "->", "execute", "(", ")", "->", "toArray", "(", ")", ")", ";", "if", "(", "is_array", "(", "$", "records", ")", "&&", "!", "empty", "(", "$", "records", ")", ")", "{", "return", "json_decode", "(", "$", "this", "->", "restUtils", "->", "serializeContent", "(", "$", "records", "[", "0", "]", ")", ")", ";", "}", "return", "null", ";", "}" ]
returns an already serialized entity depending on fields, making sure the query is fresh @param string $documentClass document class @param string $recordId record id @param array $fields if you only need certain fields, you can specify them here @throws \Exception @return object|null entity
[ "returns", "an", "already", "serialized", "entity", "depending", "on", "fields", "making", "sure", "the", "query", "is", "fresh" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L102-L119
26,248
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php
ConstraintUtils.getCurrentRequestMethod
public function getCurrentRequestMethod() { if ($this->requestStack->getCurrentRequest() instanceof Request) { return $this->requestStack->getCurrentRequest()->getMethod(); } return null; }
php
public function getCurrentRequestMethod() { if ($this->requestStack->getCurrentRequest() instanceof Request) { return $this->requestStack->getCurrentRequest()->getMethod(); } return null; }
[ "public", "function", "getCurrentRequestMethod", "(", ")", "{", "if", "(", "$", "this", "->", "requestStack", "->", "getCurrentRequest", "(", ")", "instanceof", "Request", ")", "{", "return", "$", "this", "->", "requestStack", "->", "getCurrentRequest", "(", ")", "->", "getMethod", "(", ")", ";", "}", "return", "null", ";", "}" ]
Returns the request method of the current request @return null|string the request method
[ "Returns", "the", "request", "method", "of", "the", "current", "request" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L159-L165
26,249
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php
ConstraintUtils.getCurrentRequestContent
public function getCurrentRequestContent() { if ($this->requestStack->getCurrentRequest() instanceof Request) { return $this->requestStack->getCurrentRequest()->getContent(); } return null; }
php
public function getCurrentRequestContent() { if ($this->requestStack->getCurrentRequest() instanceof Request) { return $this->requestStack->getCurrentRequest()->getContent(); } return null; }
[ "public", "function", "getCurrentRequestContent", "(", ")", "{", "if", "(", "$", "this", "->", "requestStack", "->", "getCurrentRequest", "(", ")", "instanceof", "Request", ")", "{", "return", "$", "this", "->", "requestStack", "->", "getCurrentRequest", "(", ")", "->", "getContent", "(", ")", ";", "}", "return", "null", ";", "}" ]
Returns the current request content @return bool|null|resource|string the content
[ "Returns", "the", "current", "request", "content" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L172-L178
26,250
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php
ConstraintUtils.getNormalizedPathFromPointer
public function getNormalizedPathFromPointer(JsonPointer $pointer = null) { $result = array_map( function ($path) { return sprintf(is_numeric($path) ? '[%d]' : '.%s', $path); }, $pointer->getPropertyPaths() ); return trim(implode('', $result), '.'); }
php
public function getNormalizedPathFromPointer(JsonPointer $pointer = null) { $result = array_map( function ($path) { return sprintf(is_numeric($path) ? '[%d]' : '.%s', $path); }, $pointer->getPropertyPaths() ); return trim(implode('', $result), '.'); }
[ "public", "function", "getNormalizedPathFromPointer", "(", "JsonPointer", "$", "pointer", "=", "null", ")", "{", "$", "result", "=", "array_map", "(", "function", "(", "$", "path", ")", "{", "return", "sprintf", "(", "is_numeric", "(", "$", "path", ")", "?", "'[%d]'", ":", "'.%s'", ",", "$", "path", ")", ";", "}", ",", "$", "pointer", "->", "getPropertyPaths", "(", ")", ")", ";", "return", "trim", "(", "implode", "(", "''", ",", "$", "result", ")", ",", "'.'", ")", ";", "}" ]
own function to get standard path from a JsonPointer object @param JsonPointer|null $pointer pointer @return string path as string
[ "own", "function", "to", "get", "standard", "path", "from", "a", "JsonPointer", "object" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L208-L217
26,251
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php
ConstraintUtils.onSchemaValidation
public function onSchemaValidation(ConstraintEventSchema $event) { $this->currentSchema = $event->getSchema(); $this->currentData = $event->getElement(); }
php
public function onSchemaValidation(ConstraintEventSchema $event) { $this->currentSchema = $event->getSchema(); $this->currentData = $event->getElement(); }
[ "public", "function", "onSchemaValidation", "(", "ConstraintEventSchema", "$", "event", ")", "{", "$", "this", "->", "currentSchema", "=", "$", "event", "->", "getSchema", "(", ")", ";", "$", "this", "->", "currentData", "=", "$", "event", "->", "getElement", "(", ")", ";", "}" ]
called on the first schema validation, before anything else. @param ConstraintEventSchema $event event @return void
[ "called", "on", "the", "first", "schema", "validation", "before", "anything", "else", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L226-L230
26,252
libgraviton/graviton
src/Graviton/RestBundle/Listener/SpecialMimetypeRequestListener.php
SpecialMimetypeRequestListener.onKernelRequest
public function onKernelRequest(RestEvent $event) { $request = $event->getRequest(); if ($request->headers->has('Accept')) { $format = $request->getFormat($request->headers->get('Accept')); if (empty($format)) { foreach ($this->container->getParameter('graviton.rest.special_mimetypes') as $format => $types) { $mimetypes = $request->getMimeType($format); if (!empty($mimetypes)) { $mimetypes = is_array($mimetypes)? $mimetypes : array($mimetypes); $types = array_unique(array_merge_recursive($mimetypes, $types)); } $request->setFormat($format, $types); } } } }
php
public function onKernelRequest(RestEvent $event) { $request = $event->getRequest(); if ($request->headers->has('Accept')) { $format = $request->getFormat($request->headers->get('Accept')); if (empty($format)) { foreach ($this->container->getParameter('graviton.rest.special_mimetypes') as $format => $types) { $mimetypes = $request->getMimeType($format); if (!empty($mimetypes)) { $mimetypes = is_array($mimetypes)? $mimetypes : array($mimetypes); $types = array_unique(array_merge_recursive($mimetypes, $types)); } $request->setFormat($format, $types); } } } }
[ "public", "function", "onKernelRequest", "(", "RestEvent", "$", "event", ")", "{", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";", "if", "(", "$", "request", "->", "headers", "->", "has", "(", "'Accept'", ")", ")", "{", "$", "format", "=", "$", "request", "->", "getFormat", "(", "$", "request", "->", "headers", "->", "get", "(", "'Accept'", ")", ")", ";", "if", "(", "empty", "(", "$", "format", ")", ")", "{", "foreach", "(", "$", "this", "->", "container", "->", "getParameter", "(", "'graviton.rest.special_mimetypes'", ")", "as", "$", "format", "=>", "$", "types", ")", "{", "$", "mimetypes", "=", "$", "request", "->", "getMimeType", "(", "$", "format", ")", ";", "if", "(", "!", "empty", "(", "$", "mimetypes", ")", ")", "{", "$", "mimetypes", "=", "is_array", "(", "$", "mimetypes", ")", "?", "$", "mimetypes", ":", "array", "(", "$", "mimetypes", ")", ";", "$", "types", "=", "array_unique", "(", "array_merge_recursive", "(", "$", "mimetypes", ",", "$", "types", ")", ")", ";", "}", "$", "request", "->", "setFormat", "(", "$", "format", ",", "$", "types", ")", ";", "}", "}", "}", "}" ]
Adds the configured formats and mimetypes to the request. @param RestEvent $event Event @return void|null
[ "Adds", "the", "configured", "formats", "and", "mimetypes", "to", "the", "request", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/SpecialMimetypeRequestListener.php#L42-L61
26,253
libgraviton/graviton
src/Graviton/CacheBundle/Listener/ETagResponseListener.php
ETagResponseListener.onKernelResponse
public function onKernelResponse(FilterResponseEvent $event) { $response = $event->getResponse(); /** * the "W/" prefix is necessary to qualify it as a "weak" Etag. * only then a proxy like nginx will leave the tag alone because a strong cannot * match if gzip is applied. */ $response->headers->set('ETag', 'W/'.sha1($response->getContent())); }
php
public function onKernelResponse(FilterResponseEvent $event) { $response = $event->getResponse(); /** * the "W/" prefix is necessary to qualify it as a "weak" Etag. * only then a proxy like nginx will leave the tag alone because a strong cannot * match if gzip is applied. */ $response->headers->set('ETag', 'W/'.sha1($response->getContent())); }
[ "public", "function", "onKernelResponse", "(", "FilterResponseEvent", "$", "event", ")", "{", "$", "response", "=", "$", "event", "->", "getResponse", "(", ")", ";", "/**\n * the \"W/\" prefix is necessary to qualify it as a \"weak\" Etag.\n * only then a proxy like nginx will leave the tag alone because a strong cannot\n * match if gzip is applied.\n */", "$", "response", "->", "headers", "->", "set", "(", "'ETag'", ",", "'W/'", ".", "sha1", "(", "$", "response", "->", "getContent", "(", ")", ")", ")", ";", "}" ]
add a ETag header to the response @param FilterResponseEvent $event response listener event @return void
[ "add", "a", "ETag", "header", "to", "the", "response" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CacheBundle/Listener/ETagResponseListener.php#L26-L36
26,254
libgraviton/graviton
src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php
EventStatusLinkResponseListener.onKernelResponse
public function onKernelResponse(FilterResponseEvent $event) { /** * @var Response $response */ $response = $event->getResponse(); // exit if not master request, uninteresting method or an error occurred if (!$event->isMasterRequest() || $this->isNotConcerningRequest() || !$response->isSuccessful()) { return; } // we can always safely call this, it doesn't need much resources. // only if we have subscribers, it will create more load as it persists an EventStatus $queueEvent = $this->createQueueEventObject(); if (!empty($queueEvent->getStatusurl()) && !empty($queueEvent->getEvent())) { $linkHeader = LinkHeader::fromResponse($response); $linkHeader->add( new LinkHeaderItem( $queueEvent->getStatusurl(), array('rel' => 'eventStatus') ) ); $response->headers->set( 'Link', (string) $linkHeader ); } // let's send it to the queue(s) if appropriate if (!empty($queueEvent->getEvent())) { $queuesForEvent = $this->getSubscribedWorkerIds($queueEvent); // if needed and activated, change urls relative to workers if (!empty($queuesForEvent) && $this->workerRelativeUrl instanceof Uri) { $queueEvent = $this->getWorkerQueueEvent($queueEvent); } foreach ($queuesForEvent as $queueForEvent) { // declare the Queue for the Event if its not there already declared $this->rabbitMqProducer->getChannel()->queue_declare($queueForEvent, false, true, false, false); $this->rabbitMqProducer->publish(json_encode($queueEvent), $queueForEvent); } } }
php
public function onKernelResponse(FilterResponseEvent $event) { /** * @var Response $response */ $response = $event->getResponse(); // exit if not master request, uninteresting method or an error occurred if (!$event->isMasterRequest() || $this->isNotConcerningRequest() || !$response->isSuccessful()) { return; } // we can always safely call this, it doesn't need much resources. // only if we have subscribers, it will create more load as it persists an EventStatus $queueEvent = $this->createQueueEventObject(); if (!empty($queueEvent->getStatusurl()) && !empty($queueEvent->getEvent())) { $linkHeader = LinkHeader::fromResponse($response); $linkHeader->add( new LinkHeaderItem( $queueEvent->getStatusurl(), array('rel' => 'eventStatus') ) ); $response->headers->set( 'Link', (string) $linkHeader ); } // let's send it to the queue(s) if appropriate if (!empty($queueEvent->getEvent())) { $queuesForEvent = $this->getSubscribedWorkerIds($queueEvent); // if needed and activated, change urls relative to workers if (!empty($queuesForEvent) && $this->workerRelativeUrl instanceof Uri) { $queueEvent = $this->getWorkerQueueEvent($queueEvent); } foreach ($queuesForEvent as $queueForEvent) { // declare the Queue for the Event if its not there already declared $this->rabbitMqProducer->getChannel()->queue_declare($queueForEvent, false, true, false, false); $this->rabbitMqProducer->publish(json_encode($queueEvent), $queueForEvent); } } }
[ "public", "function", "onKernelResponse", "(", "FilterResponseEvent", "$", "event", ")", "{", "/**\n * @var Response $response\n */", "$", "response", "=", "$", "event", "->", "getResponse", "(", ")", ";", "// exit if not master request, uninteresting method or an error occurred", "if", "(", "!", "$", "event", "->", "isMasterRequest", "(", ")", "||", "$", "this", "->", "isNotConcerningRequest", "(", ")", "||", "!", "$", "response", "->", "isSuccessful", "(", ")", ")", "{", "return", ";", "}", "// we can always safely call this, it doesn't need much resources.", "// only if we have subscribers, it will create more load as it persists an EventStatus", "$", "queueEvent", "=", "$", "this", "->", "createQueueEventObject", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "queueEvent", "->", "getStatusurl", "(", ")", ")", "&&", "!", "empty", "(", "$", "queueEvent", "->", "getEvent", "(", ")", ")", ")", "{", "$", "linkHeader", "=", "LinkHeader", "::", "fromResponse", "(", "$", "response", ")", ";", "$", "linkHeader", "->", "add", "(", "new", "LinkHeaderItem", "(", "$", "queueEvent", "->", "getStatusurl", "(", ")", ",", "array", "(", "'rel'", "=>", "'eventStatus'", ")", ")", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Link'", ",", "(", "string", ")", "$", "linkHeader", ")", ";", "}", "// let's send it to the queue(s) if appropriate", "if", "(", "!", "empty", "(", "$", "queueEvent", "->", "getEvent", "(", ")", ")", ")", "{", "$", "queuesForEvent", "=", "$", "this", "->", "getSubscribedWorkerIds", "(", "$", "queueEvent", ")", ";", "// if needed and activated, change urls relative to workers", "if", "(", "!", "empty", "(", "$", "queuesForEvent", ")", "&&", "$", "this", "->", "workerRelativeUrl", "instanceof", "Uri", ")", "{", "$", "queueEvent", "=", "$", "this", "->", "getWorkerQueueEvent", "(", "$", "queueEvent", ")", ";", "}", "foreach", "(", "$", "queuesForEvent", "as", "$", "queueForEvent", ")", "{", "// declare the Queue for the Event if its not there already declared", "$", "this", "->", "rabbitMqProducer", "->", "getChannel", "(", ")", "->", "queue_declare", "(", "$", "queueForEvent", ",", "false", ",", "true", ",", "false", ",", "false", ")", ";", "$", "this", "->", "rabbitMqProducer", "->", "publish", "(", "json_encode", "(", "$", "queueEvent", ")", ",", "$", "queueForEvent", ")", ";", "}", "}", "}" ]
add a rel=eventStatus Link header to the response if necessary @param FilterResponseEvent $event response listener event @return void
[ "add", "a", "rel", "=", "eventStatus", "Link", "header", "to", "the", "response", "if", "necessary" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L160-L206
26,255
libgraviton/graviton
src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php
EventStatusLinkResponseListener.getStatusUrl
private function getStatusUrl($queueEvent) { // this has to be checked after cause we should not call getSubscribedWorkerIds() if above is true $workerIds = $this->getSubscribedWorkerIds($queueEvent); if (empty($workerIds)) { return ''; } // we have subscribers; create the EventStatus entry /** @var EventStatus $eventStatus **/ $eventStatus = new $this->eventStatusClassname(); $eventStatus->setCreatedate(new \DateTime()); $eventStatus->setEventname($queueEvent->getEvent()); // if available, transport the ref document to the eventStatus instance if (!empty($queueEvent->getDocumenturl())) { $eventStatusResource = new $this->eventStatusEventResourceClassname(); $eventStatusResource->setRef($this->extRefConverter->getExtReference($queueEvent->getDocumenturl())); $eventStatus->setEventresource($eventStatusResource); } foreach ($workerIds as $workerId) { /** @var \GravitonDyn\EventStatusBundle\Document\EventStatusStatus $eventStatusStatus **/ $eventStatusStatus = new $this->eventStatusStatusClassname(); $eventStatusStatus->setWorkerid($workerId); $eventStatusStatus->setStatus('opened'); $eventStatus->addStatus($eventStatusStatus); } // Set username to Event $eventStatus->setUserid($this->getSecurityUsername()); $this->documentManager->persist($eventStatus); $this->documentManager->flush(); // get the url.. $url = $this->router->generate( $this->eventStatusRouteName, [ 'id' => $eventStatus->getId() ], UrlGeneratorInterface::ABSOLUTE_URL ); return $url; }
php
private function getStatusUrl($queueEvent) { // this has to be checked after cause we should not call getSubscribedWorkerIds() if above is true $workerIds = $this->getSubscribedWorkerIds($queueEvent); if (empty($workerIds)) { return ''; } // we have subscribers; create the EventStatus entry /** @var EventStatus $eventStatus **/ $eventStatus = new $this->eventStatusClassname(); $eventStatus->setCreatedate(new \DateTime()); $eventStatus->setEventname($queueEvent->getEvent()); // if available, transport the ref document to the eventStatus instance if (!empty($queueEvent->getDocumenturl())) { $eventStatusResource = new $this->eventStatusEventResourceClassname(); $eventStatusResource->setRef($this->extRefConverter->getExtReference($queueEvent->getDocumenturl())); $eventStatus->setEventresource($eventStatusResource); } foreach ($workerIds as $workerId) { /** @var \GravitonDyn\EventStatusBundle\Document\EventStatusStatus $eventStatusStatus **/ $eventStatusStatus = new $this->eventStatusStatusClassname(); $eventStatusStatus->setWorkerid($workerId); $eventStatusStatus->setStatus('opened'); $eventStatus->addStatus($eventStatusStatus); } // Set username to Event $eventStatus->setUserid($this->getSecurityUsername()); $this->documentManager->persist($eventStatus); $this->documentManager->flush(); // get the url.. $url = $this->router->generate( $this->eventStatusRouteName, [ 'id' => $eventStatus->getId() ], UrlGeneratorInterface::ABSOLUTE_URL ); return $url; }
[ "private", "function", "getStatusUrl", "(", "$", "queueEvent", ")", "{", "// this has to be checked after cause we should not call getSubscribedWorkerIds() if above is true", "$", "workerIds", "=", "$", "this", "->", "getSubscribedWorkerIds", "(", "$", "queueEvent", ")", ";", "if", "(", "empty", "(", "$", "workerIds", ")", ")", "{", "return", "''", ";", "}", "// we have subscribers; create the EventStatus entry", "/** @var EventStatus $eventStatus **/", "$", "eventStatus", "=", "new", "$", "this", "->", "eventStatusClassname", "(", ")", ";", "$", "eventStatus", "->", "setCreatedate", "(", "new", "\\", "DateTime", "(", ")", ")", ";", "$", "eventStatus", "->", "setEventname", "(", "$", "queueEvent", "->", "getEvent", "(", ")", ")", ";", "// if available, transport the ref document to the eventStatus instance", "if", "(", "!", "empty", "(", "$", "queueEvent", "->", "getDocumenturl", "(", ")", ")", ")", "{", "$", "eventStatusResource", "=", "new", "$", "this", "->", "eventStatusEventResourceClassname", "(", ")", ";", "$", "eventStatusResource", "->", "setRef", "(", "$", "this", "->", "extRefConverter", "->", "getExtReference", "(", "$", "queueEvent", "->", "getDocumenturl", "(", ")", ")", ")", ";", "$", "eventStatus", "->", "setEventresource", "(", "$", "eventStatusResource", ")", ";", "}", "foreach", "(", "$", "workerIds", "as", "$", "workerId", ")", "{", "/** @var \\GravitonDyn\\EventStatusBundle\\Document\\EventStatusStatus $eventStatusStatus **/", "$", "eventStatusStatus", "=", "new", "$", "this", "->", "eventStatusStatusClassname", "(", ")", ";", "$", "eventStatusStatus", "->", "setWorkerid", "(", "$", "workerId", ")", ";", "$", "eventStatusStatus", "->", "setStatus", "(", "'opened'", ")", ";", "$", "eventStatus", "->", "addStatus", "(", "$", "eventStatusStatus", ")", ";", "}", "// Set username to Event", "$", "eventStatus", "->", "setUserid", "(", "$", "this", "->", "getSecurityUsername", "(", ")", ")", ";", "$", "this", "->", "documentManager", "->", "persist", "(", "$", "eventStatus", ")", ";", "$", "this", "->", "documentManager", "->", "flush", "(", ")", ";", "// get the url..", "$", "url", "=", "$", "this", "->", "router", "->", "generate", "(", "$", "this", "->", "eventStatusRouteName", ",", "[", "'id'", "=>", "$", "eventStatus", "->", "getId", "(", ")", "]", ",", "UrlGeneratorInterface", "::", "ABSOLUTE_URL", ")", ";", "return", "$", "url", ";", "}" ]
Creates a EventStatus object that gets persisted.. @param QueueEvent $queueEvent queueEvent object @return string
[ "Creates", "a", "EventStatus", "object", "that", "gets", "persisted", ".." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L270-L315
26,256
libgraviton/graviton
src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php
EventStatusLinkResponseListener.getSubscribedWorkerIds
private function getSubscribedWorkerIds(QueueEvent $queueEvent) { // compose our regex to match stars ;-) // results in = /((\*|document)+)\.((\*|dude)+)\.((\*|config)+)\.((\*|update)+)/ $routingArgs = explode('.', $queueEvent->getEvent()); $regex = '/'. implode( '\.', array_map( function ($arg) { return '((\*|'.$arg.')+)'; }, $routingArgs ) ). '/'; // look up workers by class name $qb = $this->documentManager->createQueryBuilder($this->eventWorkerClassname); $data = $qb ->select('id') ->field('subscription.event') ->equals(new \MongoRegex($regex)) ->getQuery() ->execute() ->toArray(); return array_keys($data); }
php
private function getSubscribedWorkerIds(QueueEvent $queueEvent) { // compose our regex to match stars ;-) // results in = /((\*|document)+)\.((\*|dude)+)\.((\*|config)+)\.((\*|update)+)/ $routingArgs = explode('.', $queueEvent->getEvent()); $regex = '/'. implode( '\.', array_map( function ($arg) { return '((\*|'.$arg.')+)'; }, $routingArgs ) ). '/'; // look up workers by class name $qb = $this->documentManager->createQueryBuilder($this->eventWorkerClassname); $data = $qb ->select('id') ->field('subscription.event') ->equals(new \MongoRegex($regex)) ->getQuery() ->execute() ->toArray(); return array_keys($data); }
[ "private", "function", "getSubscribedWorkerIds", "(", "QueueEvent", "$", "queueEvent", ")", "{", "// compose our regex to match stars ;-)", "// results in = /((\\*|document)+)\\.((\\*|dude)+)\\.((\\*|config)+)\\.((\\*|update)+)/", "$", "routingArgs", "=", "explode", "(", "'.'", ",", "$", "queueEvent", "->", "getEvent", "(", ")", ")", ";", "$", "regex", "=", "'/'", ".", "implode", "(", "'\\.'", ",", "array_map", "(", "function", "(", "$", "arg", ")", "{", "return", "'((\\*|'", ".", "$", "arg", ".", "')+)'", ";", "}", ",", "$", "routingArgs", ")", ")", ".", "'/'", ";", "// look up workers by class name", "$", "qb", "=", "$", "this", "->", "documentManager", "->", "createQueryBuilder", "(", "$", "this", "->", "eventWorkerClassname", ")", ";", "$", "data", "=", "$", "qb", "->", "select", "(", "'id'", ")", "->", "field", "(", "'subscription.event'", ")", "->", "equals", "(", "new", "\\", "MongoRegex", "(", "$", "regex", ")", ")", "->", "getQuery", "(", ")", "->", "execute", "(", ")", "->", "toArray", "(", ")", ";", "return", "array_keys", "(", "$", "data", ")", ";", "}" ]
Checks EventWorker for worker that are subscribed to our event and returns their workerIds as array @param QueueEvent $queueEvent queueEvent object @return array array of worker ids
[ "Checks", "EventWorker", "for", "worker", "that", "are", "subscribed", "to", "our", "event", "and", "returns", "their", "workerIds", "as", "array" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L325-L354
26,257
libgraviton/graviton
src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php
EventStatusLinkResponseListener.getWorkerQueueEvent
private function getWorkerQueueEvent(QueueEvent $queueEvent) { $queueEvent->setDocumenturl($this->getWorkerRelativeUrl($queueEvent->getDocumenturl())); $queueEvent->setStatusurl($this->getWorkerRelativeUrl($queueEvent->getStatusurl())); return $queueEvent; }
php
private function getWorkerQueueEvent(QueueEvent $queueEvent) { $queueEvent->setDocumenturl($this->getWorkerRelativeUrl($queueEvent->getDocumenturl())); $queueEvent->setStatusurl($this->getWorkerRelativeUrl($queueEvent->getStatusurl())); return $queueEvent; }
[ "private", "function", "getWorkerQueueEvent", "(", "QueueEvent", "$", "queueEvent", ")", "{", "$", "queueEvent", "->", "setDocumenturl", "(", "$", "this", "->", "getWorkerRelativeUrl", "(", "$", "queueEvent", "->", "getDocumenturl", "(", ")", ")", ")", ";", "$", "queueEvent", "->", "setStatusurl", "(", "$", "this", "->", "getWorkerRelativeUrl", "(", "$", "queueEvent", "->", "getStatusurl", "(", ")", ")", ")", ";", "return", "$", "queueEvent", ";", "}" ]
Changes the urls in the QueueEvent for the workers @param QueueEvent $queueEvent queue event @return QueueEvent altered queue event
[ "Changes", "the", "urls", "in", "the", "QueueEvent", "for", "the", "workers" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L377-L382
26,258
libgraviton/graviton
src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php
EventStatusLinkResponseListener.getWorkerRelativeUrl
private function getWorkerRelativeUrl($uri) { $uri = new Uri($uri); $uri = $uri ->withHost($this->workerRelativeUrl->getHost()) ->withScheme($this->workerRelativeUrl->getScheme()) ->withPort($this->workerRelativeUrl->getPort()); return (string) $uri; }
php
private function getWorkerRelativeUrl($uri) { $uri = new Uri($uri); $uri = $uri ->withHost($this->workerRelativeUrl->getHost()) ->withScheme($this->workerRelativeUrl->getScheme()) ->withPort($this->workerRelativeUrl->getPort()); return (string) $uri; }
[ "private", "function", "getWorkerRelativeUrl", "(", "$", "uri", ")", "{", "$", "uri", "=", "new", "Uri", "(", "$", "uri", ")", ";", "$", "uri", "=", "$", "uri", "->", "withHost", "(", "$", "this", "->", "workerRelativeUrl", "->", "getHost", "(", ")", ")", "->", "withScheme", "(", "$", "this", "->", "workerRelativeUrl", "->", "getScheme", "(", ")", ")", "->", "withPort", "(", "$", "this", "->", "workerRelativeUrl", "->", "getPort", "(", ")", ")", ";", "return", "(", "string", ")", "$", "uri", ";", "}" ]
changes an uri for the workers @param string $uri uri @return string changed uri
[ "changes", "an", "uri", "for", "the", "workers" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L391-L399
26,259
libgraviton/graviton
src/Graviton/SchemaBundle/Serializer/Handler/SchemaTypeHandler.php
SchemaTypeHandler.serializeSchemaTypeToJson
public function serializeSchemaTypeToJson( JsonSerializationVisitor $visitor, SchemaType $schemaType, array $type, Context $context ) { $types = $schemaType->getTypes(); if (count($types) === 1) { return array_pop($types); } return $types; }
php
public function serializeSchemaTypeToJson( JsonSerializationVisitor $visitor, SchemaType $schemaType, array $type, Context $context ) { $types = $schemaType->getTypes(); if (count($types) === 1) { return array_pop($types); } return $types; }
[ "public", "function", "serializeSchemaTypeToJson", "(", "JsonSerializationVisitor", "$", "visitor", ",", "SchemaType", "$", "schemaType", ",", "array", "$", "type", ",", "Context", "$", "context", ")", "{", "$", "types", "=", "$", "schemaType", "->", "getTypes", "(", ")", ";", "if", "(", "count", "(", "$", "types", ")", "===", "1", ")", "{", "return", "array_pop", "(", "$", "types", ")", ";", "}", "return", "$", "types", ";", "}" ]
Serialize SchemaType to JSON @param JsonSerializationVisitor $visitor Visitor @param SchemaType $schemaType type @param array $type Type @param Context $context Context @return array
[ "Serialize", "SchemaType", "to", "JSON" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Serializer/Handler/SchemaTypeHandler.php#L30-L43
26,260
libgraviton/graviton
src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php
HashHandler.serializeHashToJson
public function serializeHashToJson( JsonSerializationVisitor $visitor, Hash $data, array $type, Context $context ) { return new Hash($data); }
php
public function serializeHashToJson( JsonSerializationVisitor $visitor, Hash $data, array $type, Context $context ) { return new Hash($data); }
[ "public", "function", "serializeHashToJson", "(", "JsonSerializationVisitor", "$", "visitor", ",", "Hash", "$", "data", ",", "array", "$", "type", ",", "Context", "$", "context", ")", "{", "return", "new", "Hash", "(", "$", "data", ")", ";", "}" ]
Serialize Hash object @param JsonSerializationVisitor $visitor Visitor @param Hash $data Data @param array $type Type @param Context $context Context @return Hash
[ "Serialize", "Hash", "object" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php#L58-L65
26,261
libgraviton/graviton
src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php
HashHandler.deserializeHashFromJson
public function deserializeHashFromJson( JsonDeserializationVisitor $visitor, array $data, array $type, Context $context ) { $currentPath = $context->getCurrentPath(); $currentRequestContent = $this->getCurrentRequestContent(); $dataObj = null; if (!is_null($currentRequestContent)) { $dataObj = $currentRequestContent; foreach ($currentPath as $pathElement) { if (isset($dataObj->{$pathElement})) { $dataObj = $dataObj->{$pathElement}; } else { $dataObj = null; break; } } } if (!is_null($dataObj)) { if ($this->isSequentialArrayCase($dataObj, $data)) { $dataObj = $dataObj[$this->getLocationCounter($currentPath)]; } $data = $dataObj; } return new Hash($visitor->visitArray((array) $data, $type, $context)); }
php
public function deserializeHashFromJson( JsonDeserializationVisitor $visitor, array $data, array $type, Context $context ) { $currentPath = $context->getCurrentPath(); $currentRequestContent = $this->getCurrentRequestContent(); $dataObj = null; if (!is_null($currentRequestContent)) { $dataObj = $currentRequestContent; foreach ($currentPath as $pathElement) { if (isset($dataObj->{$pathElement})) { $dataObj = $dataObj->{$pathElement}; } else { $dataObj = null; break; } } } if (!is_null($dataObj)) { if ($this->isSequentialArrayCase($dataObj, $data)) { $dataObj = $dataObj[$this->getLocationCounter($currentPath)]; } $data = $dataObj; } return new Hash($visitor->visitArray((array) $data, $type, $context)); }
[ "public", "function", "deserializeHashFromJson", "(", "JsonDeserializationVisitor", "$", "visitor", ",", "array", "$", "data", ",", "array", "$", "type", ",", "Context", "$", "context", ")", "{", "$", "currentPath", "=", "$", "context", "->", "getCurrentPath", "(", ")", ";", "$", "currentRequestContent", "=", "$", "this", "->", "getCurrentRequestContent", "(", ")", ";", "$", "dataObj", "=", "null", ";", "if", "(", "!", "is_null", "(", "$", "currentRequestContent", ")", ")", "{", "$", "dataObj", "=", "$", "currentRequestContent", ";", "foreach", "(", "$", "currentPath", "as", "$", "pathElement", ")", "{", "if", "(", "isset", "(", "$", "dataObj", "->", "{", "$", "pathElement", "}", ")", ")", "{", "$", "dataObj", "=", "$", "dataObj", "->", "{", "$", "pathElement", "}", ";", "}", "else", "{", "$", "dataObj", "=", "null", ";", "break", ";", "}", "}", "}", "if", "(", "!", "is_null", "(", "$", "dataObj", ")", ")", "{", "if", "(", "$", "this", "->", "isSequentialArrayCase", "(", "$", "dataObj", ",", "$", "data", ")", ")", "{", "$", "dataObj", "=", "$", "dataObj", "[", "$", "this", "->", "getLocationCounter", "(", "$", "currentPath", ")", "]", ";", "}", "$", "data", "=", "$", "dataObj", ";", "}", "return", "new", "Hash", "(", "$", "visitor", "->", "visitArray", "(", "(", "array", ")", "$", "data", ",", "$", "type", ",", "$", "context", ")", ")", ";", "}" ]
Deserialize Hash object @param JsonDeserializationVisitor $visitor Visitor @param array $data Data @param array $type Type @param Context $context Context @return Hash
[ "Deserialize", "Hash", "object" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php#L76-L107
26,262
libgraviton/graviton
src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php
HashHandler.getCurrentRequestContent
private function getCurrentRequestContent() { $currentRequest = $this->requestStack->getCurrentRequest(); if (!is_null($currentRequest)) { $this->currentRequestContent = json_decode($currentRequest->getContent()); } return $this->currentRequestContent; }
php
private function getCurrentRequestContent() { $currentRequest = $this->requestStack->getCurrentRequest(); if (!is_null($currentRequest)) { $this->currentRequestContent = json_decode($currentRequest->getContent()); } return $this->currentRequestContent; }
[ "private", "function", "getCurrentRequestContent", "(", ")", "{", "$", "currentRequest", "=", "$", "this", "->", "requestStack", "->", "getCurrentRequest", "(", ")", ";", "if", "(", "!", "is_null", "(", "$", "currentRequest", ")", ")", "{", "$", "this", "->", "currentRequestContent", "=", "json_decode", "(", "$", "currentRequest", "->", "getContent", "(", ")", ")", ";", "}", "return", "$", "this", "->", "currentRequestContent", ";", "}" ]
returns the json_decoded content of the current request. if there is no request, it will return null @return mixed|null|object the json_decoded request content
[ "returns", "the", "json_decoded", "content", "of", "the", "current", "request", ".", "if", "there", "is", "no", "request", "it", "will", "return", "null" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php#L115-L122
26,263
libgraviton/graviton
src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php
HashHandler.getLocationCounter
private function getLocationCounter($location) { $locationHash = md5(implode(',', $location)); if (!isset($this->seenCounter[$locationHash])) { $this->seenCounter[$locationHash] = 0; } else { $this->seenCounter[$locationHash]++; } return $this->seenCounter[$locationHash]; }
php
private function getLocationCounter($location) { $locationHash = md5(implode(',', $location)); if (!isset($this->seenCounter[$locationHash])) { $this->seenCounter[$locationHash] = 0; } else { $this->seenCounter[$locationHash]++; } return $this->seenCounter[$locationHash]; }
[ "private", "function", "getLocationCounter", "(", "$", "location", ")", "{", "$", "locationHash", "=", "md5", "(", "implode", "(", "','", ",", "$", "location", ")", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "seenCounter", "[", "$", "locationHash", "]", ")", ")", "{", "$", "this", "->", "seenCounter", "[", "$", "locationHash", "]", "=", "0", ";", "}", "else", "{", "$", "this", "->", "seenCounter", "[", "$", "locationHash", "]", "++", ";", "}", "return", "$", "this", "->", "seenCounter", "[", "$", "locationHash", "]", ";", "}" ]
convenience function for the location counting for the "sequential array case" as described above. @param array $location the current path from the serializer @return int the counter
[ "convenience", "function", "for", "the", "location", "counting", "for", "the", "sequential", "array", "case", "as", "described", "above", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php#L154-L163
26,264
libgraviton/graviton
src/Graviton/SecurityBundle/Authentication/Strategies/AbstractHttpStrategy.php
AbstractHttpStrategy.extractFieldInfo
protected function extractFieldInfo($header, $fieldName) { if ($header instanceof ParameterBag || $header instanceof HeaderBag) { $this->validateField($header, $fieldName); return $header->get($fieldName, ''); } throw new \InvalidArgumentException('Provided request information are not valid.'); }
php
protected function extractFieldInfo($header, $fieldName) { if ($header instanceof ParameterBag || $header instanceof HeaderBag) { $this->validateField($header, $fieldName); return $header->get($fieldName, ''); } throw new \InvalidArgumentException('Provided request information are not valid.'); }
[ "protected", "function", "extractFieldInfo", "(", "$", "header", ",", "$", "fieldName", ")", "{", "if", "(", "$", "header", "instanceof", "ParameterBag", "||", "$", "header", "instanceof", "HeaderBag", ")", "{", "$", "this", "->", "validateField", "(", "$", "header", ",", "$", "fieldName", ")", ";", "return", "$", "header", "->", "get", "(", "$", "fieldName", ",", "''", ")", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "'Provided request information are not valid.'", ")", ";", "}" ]
Extracts information from the a request header field. @param ParameterBag|HeaderBag $header object representation of the request header. @param string $fieldName Name of the field to be read. @return string
[ "Extracts", "information", "from", "the", "a", "request", "header", "field", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/Strategies/AbstractHttpStrategy.php#L36-L44
26,265
libgraviton/graviton
src/Graviton/GeneratorBundle/Generator/AbstractGenerator.php
AbstractGenerator.renderFile
protected function renderFile($template, $target, $parameters) { $this->fs->dumpFile( $target, $this->render($template, $parameters) ); }
php
protected function renderFile($template, $target, $parameters) { $this->fs->dumpFile( $target, $this->render($template, $parameters) ); }
[ "protected", "function", "renderFile", "(", "$", "template", ",", "$", "target", ",", "$", "parameters", ")", "{", "$", "this", "->", "fs", "->", "dumpFile", "(", "$", "target", ",", "$", "this", "->", "render", "(", "$", "template", ",", "$", "parameters", ")", ")", ";", "}" ]
renders a file form a twig template @param string $template template filename @param string $target where to generate to @param array $parameters template params @return void
[ "renders", "a", "file", "form", "a", "twig", "template" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/AbstractGenerator.php#L89-L95
26,266
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/RecordOriginConstraint.php
RecordOriginConstraint.convertDatetimeToUTC
private function convertDatetimeToUTC($object, $schema, \DateTimeZone $timezone) { foreach ($schema->properties as $field => $property) { if (isset($property->format) && $property->format == 'date-time' && isset($object->{$field})) { $dateTime = Rfc3339::createFromString($object->{$field}); $dateTime->setTimezone($timezone); $object->{$field} = $dateTime->format(\DateTime::ISO8601); } elseif (isset($property->properties) && isset($object->{$field})) { $object->{$field} = $this->convertDatetimeToUTC($object->{$field}, $property, $timezone); } } return $object; }
php
private function convertDatetimeToUTC($object, $schema, \DateTimeZone $timezone) { foreach ($schema->properties as $field => $property) { if (isset($property->format) && $property->format == 'date-time' && isset($object->{$field})) { $dateTime = Rfc3339::createFromString($object->{$field}); $dateTime->setTimezone($timezone); $object->{$field} = $dateTime->format(\DateTime::ISO8601); } elseif (isset($property->properties) && isset($object->{$field})) { $object->{$field} = $this->convertDatetimeToUTC($object->{$field}, $property, $timezone); } } return $object; }
[ "private", "function", "convertDatetimeToUTC", "(", "$", "object", ",", "$", "schema", ",", "\\", "DateTimeZone", "$", "timezone", ")", "{", "foreach", "(", "$", "schema", "->", "properties", "as", "$", "field", "=>", "$", "property", ")", "{", "if", "(", "isset", "(", "$", "property", "->", "format", ")", "&&", "$", "property", "->", "format", "==", "'date-time'", "&&", "isset", "(", "$", "object", "->", "{", "$", "field", "}", ")", ")", "{", "$", "dateTime", "=", "Rfc3339", "::", "createFromString", "(", "$", "object", "->", "{", "$", "field", "}", ")", ";", "$", "dateTime", "->", "setTimezone", "(", "$", "timezone", ")", ";", "$", "object", "->", "{", "$", "field", "}", "=", "$", "dateTime", "->", "format", "(", "\\", "DateTime", "::", "ISO8601", ")", ";", "}", "elseif", "(", "isset", "(", "$", "property", "->", "properties", ")", "&&", "isset", "(", "$", "object", "->", "{", "$", "field", "}", ")", ")", "{", "$", "object", "->", "{", "$", "field", "}", "=", "$", "this", "->", "convertDatetimeToUTC", "(", "$", "object", "->", "{", "$", "field", "}", ",", "$", "property", ",", "$", "timezone", ")", ";", "}", "}", "return", "$", "object", ";", "}" ]
Recursive convert date time to UTC @param object $object Form data to be verified @param object $schema Entity schema @param \DateTimeZone $timezone to be converted to @return object
[ "Recursive", "convert", "date", "time", "to", "UTC" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/RecordOriginConstraint.php#L185-L197
26,267
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/RecordOriginConstraint.php
RecordOriginConstraint.addProperties
private function addProperties($expression, $obj) { $val = &$obj; $parts = explode('.', $expression); $numParts = count($parts); if ($numParts == 1) { $val->{$parts[0]} = null; } else { $iteration = 1; foreach ($parts as $part) { if ($iteration < $numParts) { if (!isset($val->{$part}) || !is_object($val->{$part})) { $val->{$part} = new \stdClass(); } $val = &$val->{$part}; } else { $val->{$part} = null; } $iteration++; } } return $val; }
php
private function addProperties($expression, $obj) { $val = &$obj; $parts = explode('.', $expression); $numParts = count($parts); if ($numParts == 1) { $val->{$parts[0]} = null; } else { $iteration = 1; foreach ($parts as $part) { if ($iteration < $numParts) { if (!isset($val->{$part}) || !is_object($val->{$part})) { $val->{$part} = new \stdClass(); } $val = &$val->{$part}; } else { $val->{$part} = null; } $iteration++; } } return $val; }
[ "private", "function", "addProperties", "(", "$", "expression", ",", "$", "obj", ")", "{", "$", "val", "=", "&", "$", "obj", ";", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "expression", ")", ";", "$", "numParts", "=", "count", "(", "$", "parts", ")", ";", "if", "(", "$", "numParts", "==", "1", ")", "{", "$", "val", "->", "{", "$", "parts", "[", "0", "]", "}", "=", "null", ";", "}", "else", "{", "$", "iteration", "=", "1", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "{", "if", "(", "$", "iteration", "<", "$", "numParts", ")", "{", "if", "(", "!", "isset", "(", "$", "val", "->", "{", "$", "part", "}", ")", "||", "!", "is_object", "(", "$", "val", "->", "{", "$", "part", "}", ")", ")", "{", "$", "val", "->", "{", "$", "part", "}", "=", "new", "\\", "stdClass", "(", ")", ";", "}", "$", "val", "=", "&", "$", "val", "->", "{", "$", "part", "}", ";", "}", "else", "{", "$", "val", "->", "{", "$", "part", "}", "=", "null", ";", "}", "$", "iteration", "++", ";", "}", "}", "return", "$", "val", ";", "}" ]
if the user provides properties that are in the exception list but not on the currently saved object, we try here to synthetically add them to our representation. and yes, this won't support exclusions in an array structure for the moment, but that is also not needed for now. @param string $expression the expression @param object $obj the object @return object the modified object
[ "if", "the", "user", "provides", "properties", "that", "are", "in", "the", "exception", "list", "but", "not", "on", "the", "currently", "saved", "object", "we", "try", "here", "to", "synthetically", "add", "them", "to", "our", "representation", ".", "and", "yes", "this", "won", "t", "support", "exclusions", "in", "an", "array", "structure", "for", "the", "moment", "but", "that", "is", "also", "not", "needed", "for", "now", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/RecordOriginConstraint.php#L233-L257
26,268
libgraviton/graviton
src/Graviton/SwaggerBundle/Service/Swagger.php
Swagger.getBasicPathStructure
protected function getBasicPathStructure($isCollectionRequest, $entityName, $entityClassName, $idType) { $thisPath = array( 'consumes' => array('application/json'), 'produces' => array('application/json') ); // collection return or not? if (!$isCollectionRequest) { // add object response $thisPath['responses'] = array( 200 => array( 'description' => $entityName . ' response', 'schema' => array('$ref' => '#/definitions/' . $entityClassName) ), 404 => array( 'description' => 'Resource not found' ) ); // add id param $thisPath['parameters'][] = array( 'name' => 'id', 'in' => 'path', 'description' => 'ID of ' . $entityName . ' item to fetch/update', 'required' => true, 'type' => $idType ); } else { // add array response $thisPath['responses'][200] = array( 'description' => $entityName . ' response', 'schema' => array( 'type' => 'array', 'items' => array('$ref' => '#/definitions/' . $entityClassName) ) ); } return $thisPath; }
php
protected function getBasicPathStructure($isCollectionRequest, $entityName, $entityClassName, $idType) { $thisPath = array( 'consumes' => array('application/json'), 'produces' => array('application/json') ); // collection return or not? if (!$isCollectionRequest) { // add object response $thisPath['responses'] = array( 200 => array( 'description' => $entityName . ' response', 'schema' => array('$ref' => '#/definitions/' . $entityClassName) ), 404 => array( 'description' => 'Resource not found' ) ); // add id param $thisPath['parameters'][] = array( 'name' => 'id', 'in' => 'path', 'description' => 'ID of ' . $entityName . ' item to fetch/update', 'required' => true, 'type' => $idType ); } else { // add array response $thisPath['responses'][200] = array( 'description' => $entityName . ' response', 'schema' => array( 'type' => 'array', 'items' => array('$ref' => '#/definitions/' . $entityClassName) ) ); } return $thisPath; }
[ "protected", "function", "getBasicPathStructure", "(", "$", "isCollectionRequest", ",", "$", "entityName", ",", "$", "entityClassName", ",", "$", "idType", ")", "{", "$", "thisPath", "=", "array", "(", "'consumes'", "=>", "array", "(", "'application/json'", ")", ",", "'produces'", "=>", "array", "(", "'application/json'", ")", ")", ";", "// collection return or not?", "if", "(", "!", "$", "isCollectionRequest", ")", "{", "// add object response", "$", "thisPath", "[", "'responses'", "]", "=", "array", "(", "200", "=>", "array", "(", "'description'", "=>", "$", "entityName", ".", "' response'", ",", "'schema'", "=>", "array", "(", "'$ref'", "=>", "'#/definitions/'", ".", "$", "entityClassName", ")", ")", ",", "404", "=>", "array", "(", "'description'", "=>", "'Resource not found'", ")", ")", ";", "// add id param", "$", "thisPath", "[", "'parameters'", "]", "[", "]", "=", "array", "(", "'name'", "=>", "'id'", ",", "'in'", "=>", "'path'", ",", "'description'", "=>", "'ID of '", ".", "$", "entityName", ".", "' item to fetch/update'", ",", "'required'", "=>", "true", ",", "'type'", "=>", "$", "idType", ")", ";", "}", "else", "{", "// add array response", "$", "thisPath", "[", "'responses'", "]", "[", "200", "]", "=", "array", "(", "'description'", "=>", "$", "entityName", ".", "' response'", ",", "'schema'", "=>", "array", "(", "'type'", "=>", "'array'", ",", "'items'", "=>", "array", "(", "'$ref'", "=>", "'#/definitions/'", ".", "$", "entityClassName", ")", ")", ")", ";", "}", "return", "$", "thisPath", ";", "}" ]
Return the basic structure of a path element @param bool $isCollectionRequest if collection request @param string $entityName entity name @param string $entityClassName class name @param string $idType type of id field @return array Path spec
[ "Return", "the", "basic", "structure", "of", "a", "path", "element" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SwaggerBundle/Service/Swagger.php#L213-L253
26,269
libgraviton/graviton
src/Graviton/SwaggerBundle/Service/Swagger.php
Swagger.getSummary
protected function getSummary($method, $isCollectionRequest, $entityName) { $ret = ''; // meaningful descriptions.. switch ($method) { case 'get': if ($isCollectionRequest) { $ret = 'Get collection of ' . $entityName . ' resources'; } else { $ret = 'Get single ' . $entityName . ' resources'; } break; case 'post': $ret = 'Create new ' . $entityName . ' resource'; break; case 'put': $ret = 'Update existing ' . $entityName . ' resource'; break; case 'delete': $ret = 'Delete existing ' . $entityName . ' resource'; } return $ret; }
php
protected function getSummary($method, $isCollectionRequest, $entityName) { $ret = ''; // meaningful descriptions.. switch ($method) { case 'get': if ($isCollectionRequest) { $ret = 'Get collection of ' . $entityName . ' resources'; } else { $ret = 'Get single ' . $entityName . ' resources'; } break; case 'post': $ret = 'Create new ' . $entityName . ' resource'; break; case 'put': $ret = 'Update existing ' . $entityName . ' resource'; break; case 'delete': $ret = 'Delete existing ' . $entityName . ' resource'; } return $ret; }
[ "protected", "function", "getSummary", "(", "$", "method", ",", "$", "isCollectionRequest", ",", "$", "entityName", ")", "{", "$", "ret", "=", "''", ";", "// meaningful descriptions..", "switch", "(", "$", "method", ")", "{", "case", "'get'", ":", "if", "(", "$", "isCollectionRequest", ")", "{", "$", "ret", "=", "'Get collection of '", ".", "$", "entityName", ".", "' resources'", ";", "}", "else", "{", "$", "ret", "=", "'Get single '", ".", "$", "entityName", ".", "' resources'", ";", "}", "break", ";", "case", "'post'", ":", "$", "ret", "=", "'Create new '", ".", "$", "entityName", ".", "' resource'", ";", "break", ";", "case", "'put'", ":", "$", "ret", "=", "'Update existing '", ".", "$", "entityName", ".", "' resource'", ";", "break", ";", "case", "'delete'", ":", "$", "ret", "=", "'Delete existing '", ".", "$", "entityName", ".", "' resource'", ";", "}", "return", "$", "ret", ";", "}" ]
Returns a meaningful summary depending on certain conditions @param string $method Method @param bool $isCollectionRequest If collection request @param string $entityName Name of entity @return string summary
[ "Returns", "a", "meaningful", "summary", "depending", "on", "certain", "conditions" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SwaggerBundle/Service/Swagger.php#L282-L304
26,270
libgraviton/graviton
src/Graviton/FileBundle/Controller/FileController.php
FileController.postAction
public function postAction(Request $request) { $file = new File(); $request = $this->requestManager->updateFileRequest($request); if ($formData = $request->get('metadata')) { $file = $this->restUtils->validateRequest($formData, $this->getModel()); } /** @var FileModel $model */ $model = $this->getModel(); $file = $this->fileManager->handleSaveRequest($file, $request, $model); // Set status code and content $response = $this->getResponse(); $response->setStatusCode(Response::HTTP_CREATED); $response->headers->set( 'Location', $this->getRouter()->generate('gravitondyn.file.rest.file.get', array('id' => $file->getId())) ); return $response; }
php
public function postAction(Request $request) { $file = new File(); $request = $this->requestManager->updateFileRequest($request); if ($formData = $request->get('metadata')) { $file = $this->restUtils->validateRequest($formData, $this->getModel()); } /** @var FileModel $model */ $model = $this->getModel(); $file = $this->fileManager->handleSaveRequest($file, $request, $model); // Set status code and content $response = $this->getResponse(); $response->setStatusCode(Response::HTTP_CREATED); $response->headers->set( 'Location', $this->getRouter()->generate('gravitondyn.file.rest.file.get', array('id' => $file->getId())) ); return $response; }
[ "public", "function", "postAction", "(", "Request", "$", "request", ")", "{", "$", "file", "=", "new", "File", "(", ")", ";", "$", "request", "=", "$", "this", "->", "requestManager", "->", "updateFileRequest", "(", "$", "request", ")", ";", "if", "(", "$", "formData", "=", "$", "request", "->", "get", "(", "'metadata'", ")", ")", "{", "$", "file", "=", "$", "this", "->", "restUtils", "->", "validateRequest", "(", "$", "formData", ",", "$", "this", "->", "getModel", "(", ")", ")", ";", "}", "/** @var FileModel $model */", "$", "model", "=", "$", "this", "->", "getModel", "(", ")", ";", "$", "file", "=", "$", "this", "->", "fileManager", "->", "handleSaveRequest", "(", "$", "file", ",", "$", "request", ",", "$", "model", ")", ";", "// Set status code and content", "$", "response", "=", "$", "this", "->", "getResponse", "(", ")", ";", "$", "response", "->", "setStatusCode", "(", "Response", "::", "HTTP_CREATED", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Location'", ",", "$", "this", "->", "getRouter", "(", ")", "->", "generate", "(", "'gravitondyn.file.rest.file.get'", ",", "array", "(", "'id'", "=>", "$", "file", "->", "getId", "(", ")", ")", ")", ")", ";", "return", "$", "response", ";", "}" ]
Writes a new Entry to the database Can accept either direct Post data or Form upload @param Request $request Current http request @return Response $response Result of action with data (if successful)
[ "Writes", "a", "new", "Entry", "to", "the", "database", "Can", "accept", "either", "direct", "Post", "data", "or", "Form", "upload" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Controller/FileController.php#L66-L87
26,271
libgraviton/graviton
src/Graviton/FileBundle/Controller/FileController.php
FileController.getAction
public function getAction(Request $request, $id) { // If a json request, let parent handle it if (in_array('application/json', $request->getAcceptableContentTypes())) { return parent::getAction($request, $id); } /** @var File $file */ $file = $this->getModel()->find($id); /** @var Response $response */ return $this->fileManager->buildGetContentResponse( $this->getResponse(), $file ); }
php
public function getAction(Request $request, $id) { // If a json request, let parent handle it if (in_array('application/json', $request->getAcceptableContentTypes())) { return parent::getAction($request, $id); } /** @var File $file */ $file = $this->getModel()->find($id); /** @var Response $response */ return $this->fileManager->buildGetContentResponse( $this->getResponse(), $file ); }
[ "public", "function", "getAction", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "// If a json request, let parent handle it", "if", "(", "in_array", "(", "'application/json'", ",", "$", "request", "->", "getAcceptableContentTypes", "(", ")", ")", ")", "{", "return", "parent", "::", "getAction", "(", "$", "request", ",", "$", "id", ")", ";", "}", "/** @var File $file */", "$", "file", "=", "$", "this", "->", "getModel", "(", ")", "->", "find", "(", "$", "id", ")", ";", "/** @var Response $response */", "return", "$", "this", "->", "fileManager", "->", "buildGetContentResponse", "(", "$", "this", "->", "getResponse", "(", ")", ",", "$", "file", ")", ";", "}" ]
respond with document if non json mime-type is requested @param Request $request Current http request @param string $id id of file @return Response
[ "respond", "with", "document", "if", "non", "json", "mime", "-", "type", "is", "requested" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Controller/FileController.php#L97-L112
26,272
libgraviton/graviton
src/Graviton/FileBundle/Controller/FileController.php
FileController.patchAction
public function patchAction($id, Request $request) { // Update modified date $content = json_decode($request->getContent(), true); if ($content) { // Checking so update time is correct $now = new \DateTime(); $patch = [ 'op' => 'replace', 'path' => '/metadata/modificationDate', 'value' => $now->format(DATE_ISO8601) ]; // It can be a simple patch or a multi array patching. if (array_key_exists(0, $content)) { $content[] = $patch; } else { $content = [$content, $patch]; } $request = new Request( $request->query->all(), $request->request->all(), $request->attributes->all(), $request->cookies->all(), $request->files->all(), $request->server->all(), json_encode($content) ); } return parent::patchAction($id, $request); }
php
public function patchAction($id, Request $request) { // Update modified date $content = json_decode($request->getContent(), true); if ($content) { // Checking so update time is correct $now = new \DateTime(); $patch = [ 'op' => 'replace', 'path' => '/metadata/modificationDate', 'value' => $now->format(DATE_ISO8601) ]; // It can be a simple patch or a multi array patching. if (array_key_exists(0, $content)) { $content[] = $patch; } else { $content = [$content, $patch]; } $request = new Request( $request->query->all(), $request->request->all(), $request->attributes->all(), $request->cookies->all(), $request->files->all(), $request->server->all(), json_encode($content) ); } return parent::patchAction($id, $request); }
[ "public", "function", "patchAction", "(", "$", "id", ",", "Request", "$", "request", ")", "{", "// Update modified date", "$", "content", "=", "json_decode", "(", "$", "request", "->", "getContent", "(", ")", ",", "true", ")", ";", "if", "(", "$", "content", ")", "{", "// Checking so update time is correct", "$", "now", "=", "new", "\\", "DateTime", "(", ")", ";", "$", "patch", "=", "[", "'op'", "=>", "'replace'", ",", "'path'", "=>", "'/metadata/modificationDate'", ",", "'value'", "=>", "$", "now", "->", "format", "(", "DATE_ISO8601", ")", "]", ";", "// It can be a simple patch or a multi array patching.", "if", "(", "array_key_exists", "(", "0", ",", "$", "content", ")", ")", "{", "$", "content", "[", "]", "=", "$", "patch", ";", "}", "else", "{", "$", "content", "=", "[", "$", "content", ",", "$", "patch", "]", ";", "}", "$", "request", "=", "new", "Request", "(", "$", "request", "->", "query", "->", "all", "(", ")", ",", "$", "request", "->", "request", "->", "all", "(", ")", ",", "$", "request", "->", "attributes", "->", "all", "(", ")", ",", "$", "request", "->", "cookies", "->", "all", "(", ")", ",", "$", "request", "->", "files", "->", "all", "(", ")", ",", "$", "request", "->", "server", "->", "all", "(", ")", ",", "json_encode", "(", "$", "content", ")", ")", ";", "}", "return", "parent", "::", "patchAction", "(", "$", "id", ",", "$", "request", ")", ";", "}" ]
Patch a record, we add here a patch on Modification Data. @param Number $id ID of record @param Request $request Current http request @throws MalformedInputException @return Response $response Result of action with data (if successful)
[ "Patch", "a", "record", "we", "add", "here", "a", "patch", "on", "Modification", "Data", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Controller/FileController.php#L170-L201
26,273
libgraviton/graviton
src/Graviton/CoreBundle/Controller/MainController.php
MainController.indexAction
public function indexAction() { $response = $this->response; $mainPage = new \stdClass(); $mainPage->services = $this->determineServices( $this->restUtils->getOptionRoutes() ); $mainPage->thirdparty = $this->registerThirdPartyServices(); $response->setContent(json_encode($mainPage)); $response->setStatusCode(Response::HTTP_OK); $response->headers->set('Link', $this->prepareLinkHeader()); // todo: make sure, that the correct content type is set. // todo: this should be covered by a kernel.response event listener? $response->headers->set('Content-Type', 'application/json'); return $response; }
php
public function indexAction() { $response = $this->response; $mainPage = new \stdClass(); $mainPage->services = $this->determineServices( $this->restUtils->getOptionRoutes() ); $mainPage->thirdparty = $this->registerThirdPartyServices(); $response->setContent(json_encode($mainPage)); $response->setStatusCode(Response::HTTP_OK); $response->headers->set('Link', $this->prepareLinkHeader()); // todo: make sure, that the correct content type is set. // todo: this should be covered by a kernel.response event listener? $response->headers->set('Content-Type', 'application/json'); return $response; }
[ "public", "function", "indexAction", "(", ")", "{", "$", "response", "=", "$", "this", "->", "response", ";", "$", "mainPage", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "mainPage", "->", "services", "=", "$", "this", "->", "determineServices", "(", "$", "this", "->", "restUtils", "->", "getOptionRoutes", "(", ")", ")", ";", "$", "mainPage", "->", "thirdparty", "=", "$", "this", "->", "registerThirdPartyServices", "(", ")", ";", "$", "response", "->", "setContent", "(", "json_encode", "(", "$", "mainPage", ")", ")", ";", "$", "response", "->", "setStatusCode", "(", "Response", "::", "HTTP_OK", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Link'", ",", "$", "this", "->", "prepareLinkHeader", "(", ")", ")", ";", "// todo: make sure, that the correct content type is set.", "// todo: this should be covered by a kernel.response event listener?", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "return", "$", "response", ";", "}" ]
create simple start page. @return Response $response Response with result or error
[ "create", "simple", "start", "page", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L103-L123
26,274
libgraviton/graviton
src/Graviton/CoreBundle/Controller/MainController.php
MainController.determineServices
protected function determineServices(array $optionRoutes) { $router = $this->router; foreach ($this->addditionalRoutes as $route) { $optionRoutes[$route] = null; } $services = array_map( function ($routeName) use ($router) { $routeParts = explode('.', $routeName); if (count($routeParts) > 3) { list($app, $bundle, $rest, $document) = $routeParts; $schemaRoute = implode('.', [$app, $bundle, $rest, $document, 'canonicalSchema']); return [ '$ref' => $router->generate($routeName, [], UrlGeneratorInterface::ABSOLUTE_URL), 'profile' => $router->generate($schemaRoute, [], UrlGeneratorInterface::ABSOLUTE_URL), ]; } }, array_keys($optionRoutes) ); $sortArr = []; foreach ($services as $key => $val) { if ($this->isRelevantForMainPage($val) && !in_array($val['$ref'], $sortArr)) { $sortArr[$key] = $val['$ref']; } else { unset($services[$key]); } } // get additional routes $additionalRoutes = $this->getAdditionalRoutes($sortArr); $services = array_merge($services, $additionalRoutes); array_multisort($sortArr, SORT_ASC, $services); return $services; }
php
protected function determineServices(array $optionRoutes) { $router = $this->router; foreach ($this->addditionalRoutes as $route) { $optionRoutes[$route] = null; } $services = array_map( function ($routeName) use ($router) { $routeParts = explode('.', $routeName); if (count($routeParts) > 3) { list($app, $bundle, $rest, $document) = $routeParts; $schemaRoute = implode('.', [$app, $bundle, $rest, $document, 'canonicalSchema']); return [ '$ref' => $router->generate($routeName, [], UrlGeneratorInterface::ABSOLUTE_URL), 'profile' => $router->generate($schemaRoute, [], UrlGeneratorInterface::ABSOLUTE_URL), ]; } }, array_keys($optionRoutes) ); $sortArr = []; foreach ($services as $key => $val) { if ($this->isRelevantForMainPage($val) && !in_array($val['$ref'], $sortArr)) { $sortArr[$key] = $val['$ref']; } else { unset($services[$key]); } } // get additional routes $additionalRoutes = $this->getAdditionalRoutes($sortArr); $services = array_merge($services, $additionalRoutes); array_multisort($sortArr, SORT_ASC, $services); return $services; }
[ "protected", "function", "determineServices", "(", "array", "$", "optionRoutes", ")", "{", "$", "router", "=", "$", "this", "->", "router", ";", "foreach", "(", "$", "this", "->", "addditionalRoutes", "as", "$", "route", ")", "{", "$", "optionRoutes", "[", "$", "route", "]", "=", "null", ";", "}", "$", "services", "=", "array_map", "(", "function", "(", "$", "routeName", ")", "use", "(", "$", "router", ")", "{", "$", "routeParts", "=", "explode", "(", "'.'", ",", "$", "routeName", ")", ";", "if", "(", "count", "(", "$", "routeParts", ")", ">", "3", ")", "{", "list", "(", "$", "app", ",", "$", "bundle", ",", "$", "rest", ",", "$", "document", ")", "=", "$", "routeParts", ";", "$", "schemaRoute", "=", "implode", "(", "'.'", ",", "[", "$", "app", ",", "$", "bundle", ",", "$", "rest", ",", "$", "document", ",", "'canonicalSchema'", "]", ")", ";", "return", "[", "'$ref'", "=>", "$", "router", "->", "generate", "(", "$", "routeName", ",", "[", "]", ",", "UrlGeneratorInterface", "::", "ABSOLUTE_URL", ")", ",", "'profile'", "=>", "$", "router", "->", "generate", "(", "$", "schemaRoute", ",", "[", "]", ",", "UrlGeneratorInterface", "::", "ABSOLUTE_URL", ")", ",", "]", ";", "}", "}", ",", "array_keys", "(", "$", "optionRoutes", ")", ")", ";", "$", "sortArr", "=", "[", "]", ";", "foreach", "(", "$", "services", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "$", "this", "->", "isRelevantForMainPage", "(", "$", "val", ")", "&&", "!", "in_array", "(", "$", "val", "[", "'$ref'", "]", ",", "$", "sortArr", ")", ")", "{", "$", "sortArr", "[", "$", "key", "]", "=", "$", "val", "[", "'$ref'", "]", ";", "}", "else", "{", "unset", "(", "$", "services", "[", "$", "key", "]", ")", ";", "}", "}", "// get additional routes", "$", "additionalRoutes", "=", "$", "this", "->", "getAdditionalRoutes", "(", "$", "sortArr", ")", ";", "$", "services", "=", "array_merge", "(", "$", "services", ",", "$", "additionalRoutes", ")", ";", "array_multisort", "(", "$", "sortArr", ",", "SORT_ASC", ",", "$", "services", ")", ";", "return", "$", "services", ";", "}" ]
Determines what service endpoints are available. @param array $optionRoutes List of routing options. @return array
[ "Determines", "what", "service", "endpoints", "are", "available", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L132-L172
26,275
libgraviton/graviton
src/Graviton/CoreBundle/Controller/MainController.php
MainController.prepareLinkHeader
protected function prepareLinkHeader() { $links = new LinkHeader(array()); $links->add( new LinkHeaderItem( $this->router->generate('graviton.core.rest.app.all', array (), UrlGeneratorInterface::ABSOLUTE_URL), array ('rel' => 'apps', 'type' => 'application/json') ) ); return (string) $links; }
php
protected function prepareLinkHeader() { $links = new LinkHeader(array()); $links->add( new LinkHeaderItem( $this->router->generate('graviton.core.rest.app.all', array (), UrlGeneratorInterface::ABSOLUTE_URL), array ('rel' => 'apps', 'type' => 'application/json') ) ); return (string) $links; }
[ "protected", "function", "prepareLinkHeader", "(", ")", "{", "$", "links", "=", "new", "LinkHeader", "(", "array", "(", ")", ")", ";", "$", "links", "->", "add", "(", "new", "LinkHeaderItem", "(", "$", "this", "->", "router", "->", "generate", "(", "'graviton.core.rest.app.all'", ",", "array", "(", ")", ",", "UrlGeneratorInterface", "::", "ABSOLUTE_URL", ")", ",", "array", "(", "'rel'", "=>", "'apps'", ",", "'type'", "=>", "'application/json'", ")", ")", ")", ";", "return", "(", "string", ")", "$", "links", ";", "}" ]
Prepares the header field containing information about pagination. @return string
[ "Prepares", "the", "header", "field", "containing", "information", "about", "pagination", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L208-L219
26,276
libgraviton/graviton
src/Graviton/CoreBundle/Controller/MainController.php
MainController.isRelevantForMainPage
private function isRelevantForMainPage($val) { return (substr($val['$ref'], -1) === '/') || in_array(parse_url($val['$ref'], PHP_URL_PATH), $this->pathWhitelist); }
php
private function isRelevantForMainPage($val) { return (substr($val['$ref'], -1) === '/') || in_array(parse_url($val['$ref'], PHP_URL_PATH), $this->pathWhitelist); }
[ "private", "function", "isRelevantForMainPage", "(", "$", "val", ")", "{", "return", "(", "substr", "(", "$", "val", "[", "'$ref'", "]", ",", "-", "1", ")", "===", "'/'", ")", "||", "in_array", "(", "parse_url", "(", "$", "val", "[", "'$ref'", "]", ",", "PHP_URL_PATH", ")", ",", "$", "this", "->", "pathWhitelist", ")", ";", "}" ]
tells if a service is relevant for the mainpage @param array $val value of service spec @return boolean
[ "tells", "if", "a", "service", "is", "relevant", "for", "the", "mainpage" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L228-L232
26,277
libgraviton/graviton
src/Graviton/CoreBundle/Controller/MainController.php
MainController.determineThirdPartyServices
protected function determineThirdPartyServices(array $thirdApiRoutes) { $definition = $this->apiLoader; $mainRoute = $this->router->generate( 'graviton.core.static.main.all', [], UrlGeneratorInterface::ABSOLUTE_URL ); $services = array_map( function ($apiRoute) use ($mainRoute, $definition) { return array ( '$ref' => $mainRoute.$apiRoute, 'profile' => $mainRoute."schema/".$apiRoute."/item", ); }, $thirdApiRoutes ); return $services; }
php
protected function determineThirdPartyServices(array $thirdApiRoutes) { $definition = $this->apiLoader; $mainRoute = $this->router->generate( 'graviton.core.static.main.all', [], UrlGeneratorInterface::ABSOLUTE_URL ); $services = array_map( function ($apiRoute) use ($mainRoute, $definition) { return array ( '$ref' => $mainRoute.$apiRoute, 'profile' => $mainRoute."schema/".$apiRoute."/item", ); }, $thirdApiRoutes ); return $services; }
[ "protected", "function", "determineThirdPartyServices", "(", "array", "$", "thirdApiRoutes", ")", "{", "$", "definition", "=", "$", "this", "->", "apiLoader", ";", "$", "mainRoute", "=", "$", "this", "->", "router", "->", "generate", "(", "'graviton.core.static.main.all'", ",", "[", "]", ",", "UrlGeneratorInterface", "::", "ABSOLUTE_URL", ")", ";", "$", "services", "=", "array_map", "(", "function", "(", "$", "apiRoute", ")", "use", "(", "$", "mainRoute", ",", "$", "definition", ")", "{", "return", "array", "(", "'$ref'", "=>", "$", "mainRoute", ".", "$", "apiRoute", ",", "'profile'", "=>", "$", "mainRoute", ".", "\"schema/\"", ".", "$", "apiRoute", ".", "\"/item\"", ",", ")", ";", "}", ",", "$", "thirdApiRoutes", ")", ";", "return", "$", "services", ";", "}" ]
Resolves all third party routes and add schema info @param array $thirdApiRoutes list of all routes from an API @return array
[ "Resolves", "all", "third", "party", "routes", "and", "add", "schema", "info" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L241-L261
26,278
libgraviton/graviton
src/Graviton/CoreBundle/Controller/MainController.php
MainController.registerThirdPartyServices
private function registerThirdPartyServices() { $services = []; // getenv()... it's a workaround for run all tests on travis! will be removed! if (getenv('USER') !== 'travis' && getenv('HAS_JOSH_K_SEAL_OF_APPROVAL') !== true) { foreach (array_keys($this->proxySourceConfiguration) as $source) { foreach ($this->proxySourceConfiguration[$source] as $thirdparty => $option) { $this->apiLoader->resetDefinitionLoader(); $this->apiLoader->setOption($option); $this->apiLoader->addOptions($this->decideApiAndEndpoint($option)); $services[$thirdparty] = $this->determineThirdPartyServices( $this->apiLoader->getAllEndpoints(false, true) ); } } } return $services; }
php
private function registerThirdPartyServices() { $services = []; // getenv()... it's a workaround for run all tests on travis! will be removed! if (getenv('USER') !== 'travis' && getenv('HAS_JOSH_K_SEAL_OF_APPROVAL') !== true) { foreach (array_keys($this->proxySourceConfiguration) as $source) { foreach ($this->proxySourceConfiguration[$source] as $thirdparty => $option) { $this->apiLoader->resetDefinitionLoader(); $this->apiLoader->setOption($option); $this->apiLoader->addOptions($this->decideApiAndEndpoint($option)); $services[$thirdparty] = $this->determineThirdPartyServices( $this->apiLoader->getAllEndpoints(false, true) ); } } } return $services; }
[ "private", "function", "registerThirdPartyServices", "(", ")", "{", "$", "services", "=", "[", "]", ";", "// getenv()... it's a workaround for run all tests on travis! will be removed!", "if", "(", "getenv", "(", "'USER'", ")", "!==", "'travis'", "&&", "getenv", "(", "'HAS_JOSH_K_SEAL_OF_APPROVAL'", ")", "!==", "true", ")", "{", "foreach", "(", "array_keys", "(", "$", "this", "->", "proxySourceConfiguration", ")", "as", "$", "source", ")", "{", "foreach", "(", "$", "this", "->", "proxySourceConfiguration", "[", "$", "source", "]", "as", "$", "thirdparty", "=>", "$", "option", ")", "{", "$", "this", "->", "apiLoader", "->", "resetDefinitionLoader", "(", ")", ";", "$", "this", "->", "apiLoader", "->", "setOption", "(", "$", "option", ")", ";", "$", "this", "->", "apiLoader", "->", "addOptions", "(", "$", "this", "->", "decideApiAndEndpoint", "(", "$", "option", ")", ")", ";", "$", "services", "[", "$", "thirdparty", "]", "=", "$", "this", "->", "determineThirdPartyServices", "(", "$", "this", "->", "apiLoader", "->", "getAllEndpoints", "(", "false", ",", "true", ")", ")", ";", "}", "}", "}", "return", "$", "services", ";", "}" ]
Finds configured external apis to be exposed via G2. @return array
[ "Finds", "configured", "external", "apis", "to", "be", "exposed", "via", "G2", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L268-L287
26,279
libgraviton/graviton
src/Graviton/RestBundle/Event/ModelEvent.php
ModelEvent.setActionByDispatchName
public function setActionByDispatchName($dispatchName) { if (array_key_exists($dispatchName, $this->availableEvents)) { $this->action = $this->availableEvents[$dispatchName]; } else { throw new \RuntimeException('Document Model event dispatch type not found: ' . $dispatchName); } }
php
public function setActionByDispatchName($dispatchName) { if (array_key_exists($dispatchName, $this->availableEvents)) { $this->action = $this->availableEvents[$dispatchName]; } else { throw new \RuntimeException('Document Model event dispatch type not found: ' . $dispatchName); } }
[ "public", "function", "setActionByDispatchName", "(", "$", "dispatchName", ")", "{", "if", "(", "array_key_exists", "(", "$", "dispatchName", ",", "$", "this", "->", "availableEvents", ")", ")", "{", "$", "this", "->", "action", "=", "$", "this", "->", "availableEvents", "[", "$", "dispatchName", "]", ";", "}", "else", "{", "throw", "new", "\\", "RuntimeException", "(", "'Document Model event dispatch type not found: '", ".", "$", "dispatchName", ")", ";", "}", "}" ]
Set the event ACTION name based on the fired name @param string $dispatchName the CONST value for dispatch names @return string @throws Exception
[ "Set", "the", "event", "ACTION", "name", "based", "on", "the", "fired", "name" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Event/ModelEvent.php#L82-L89
26,280
libgraviton/graviton
src/Graviton/RestBundle/HttpFoundation/LinkHeader.php
LinkHeader.fromString
public static function fromString($headerValue) { return new self( array_map( function ($itemValue) use (&$index) { $item = LinkHeaderItem::fromString(trim($itemValue)); return $item; }, preg_split('/(".+?"|[^,]+)(?:,|$)/', $headerValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) ) ); }
php
public static function fromString($headerValue) { return new self( array_map( function ($itemValue) use (&$index) { $item = LinkHeaderItem::fromString(trim($itemValue)); return $item; }, preg_split('/(".+?"|[^,]+)(?:,|$)/', $headerValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) ) ); }
[ "public", "static", "function", "fromString", "(", "$", "headerValue", ")", "{", "return", "new", "self", "(", "array_map", "(", "function", "(", "$", "itemValue", ")", "use", "(", "&", "$", "index", ")", "{", "$", "item", "=", "LinkHeaderItem", "::", "fromString", "(", "trim", "(", "$", "itemValue", ")", ")", ";", "return", "$", "item", ";", "}", ",", "preg_split", "(", "'/(\".+?\"|[^,]+)(?:,|$)/'", ",", "$", "headerValue", ",", "0", ",", "PREG_SPLIT_NO_EMPTY", "|", "PREG_SPLIT_DELIM_CAPTURE", ")", ")", ")", ";", "}" ]
Builds a LinkHeader instance from a string. @param string $headerValue value of complete header @return LinkHeader
[ "Builds", "a", "LinkHeader", "instance", "from", "a", "string", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/HttpFoundation/LinkHeader.php#L41-L53
26,281
libgraviton/graviton
src/Graviton/RestBundle/HttpFoundation/LinkHeader.php
LinkHeader.fromResponse
public static function fromResponse(Response $response) { $header = $response->headers->get('Link'); if (is_array($header)) { implode(',', $header); } return self::fromString($header); }
php
public static function fromResponse(Response $response) { $header = $response->headers->get('Link'); if (is_array($header)) { implode(',', $header); } return self::fromString($header); }
[ "public", "static", "function", "fromResponse", "(", "Response", "$", "response", ")", "{", "$", "header", "=", "$", "response", "->", "headers", "->", "get", "(", "'Link'", ")", ";", "if", "(", "is_array", "(", "$", "header", ")", ")", "{", "implode", "(", "','", ",", "$", "header", ")", ";", "}", "return", "self", "::", "fromString", "(", "$", "header", ")", ";", "}" ]
get LinkHeader instance from response @param \Symfony\Component\HttpFoundation\Response $response response to get header from @return LinkHeader
[ "get", "LinkHeader", "instance", "from", "response" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/HttpFoundation/LinkHeader.php#L62-L70
26,282
duncan3dc/domparser
src/Xml/Writer.php
Writer.toString
public function toString($format = null) { if ($format) { $this->dom->formatOutput = true; } return $this->dom->saveXML(); }
php
public function toString($format = null) { if ($format) { $this->dom->formatOutput = true; } return $this->dom->saveXML(); }
[ "public", "function", "toString", "(", "$", "format", "=", "null", ")", "{", "if", "(", "$", "format", ")", "{", "$", "this", "->", "dom", "->", "formatOutput", "=", "true", ";", "}", "return", "$", "this", "->", "dom", "->", "saveXML", "(", ")", ";", "}" ]
Convert the internal dom instance to a string. @param boolean $format Whether to pretty format the string or not @return string
[ "Convert", "the", "internal", "dom", "instance", "to", "a", "string", "." ]
d5523b58337cab3b9ad90e8d135f87793795f93f
https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/Xml/Writer.php#L53-L59
26,283
duncan3dc/domparser
src/Xml/Writer.php
Writer.addElement
public function addElement($name, $params, $parent) { $name = preg_replace("/_[0-9]+$/", "", $name); $element = $this->dom->createElement($name); if (!is_array($params)) { $this->setElementValue($element, $params); } else { foreach ($params as $key => $val) { if ($key == "_attributes") { foreach ($val as $k => $v) { $element->setAttribute($k, $v); } } elseif ($key == "_value") { $this->setElementValue($element, $val); } else { $this->addElement($key, $val, $element); } } } $parent->appendChild($element); return $element; }
php
public function addElement($name, $params, $parent) { $name = preg_replace("/_[0-9]+$/", "", $name); $element = $this->dom->createElement($name); if (!is_array($params)) { $this->setElementValue($element, $params); } else { foreach ($params as $key => $val) { if ($key == "_attributes") { foreach ($val as $k => $v) { $element->setAttribute($k, $v); } } elseif ($key == "_value") { $this->setElementValue($element, $val); } else { $this->addElement($key, $val, $element); } } } $parent->appendChild($element); return $element; }
[ "public", "function", "addElement", "(", "$", "name", ",", "$", "params", ",", "$", "parent", ")", "{", "$", "name", "=", "preg_replace", "(", "\"/_[0-9]+$/\"", ",", "\"\"", ",", "$", "name", ")", ";", "$", "element", "=", "$", "this", "->", "dom", "->", "createElement", "(", "$", "name", ")", ";", "if", "(", "!", "is_array", "(", "$", "params", ")", ")", "{", "$", "this", "->", "setElementValue", "(", "$", "element", ",", "$", "params", ")", ";", "}", "else", "{", "foreach", "(", "$", "params", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "$", "key", "==", "\"_attributes\"", ")", "{", "foreach", "(", "$", "val", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "element", "->", "setAttribute", "(", "$", "k", ",", "$", "v", ")", ";", "}", "}", "elseif", "(", "$", "key", "==", "\"_value\"", ")", "{", "$", "this", "->", "setElementValue", "(", "$", "element", ",", "$", "val", ")", ";", "}", "else", "{", "$", "this", "->", "addElement", "(", "$", "key", ",", "$", "val", ",", "$", "element", ")", ";", "}", "}", "}", "$", "parent", "->", "appendChild", "(", "$", "element", ")", ";", "return", "$", "element", ";", "}" ]
Append an element recursively to a dom instance. @param string $name The name of the element to append @param mixed $params The value to set the new element to, or the elements to append to it @param mixed $parent The dom instance to append the element to @return \DOMElement
[ "Append", "an", "element", "recursively", "to", "a", "dom", "instance", "." ]
d5523b58337cab3b9ad90e8d135f87793795f93f
https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/Xml/Writer.php#L71-L96
26,284
duncan3dc/domparser
src/Xml/Writer.php
Writer.setElementValue
public function setElementValue($element, $value) { $node = $this->dom->createTextNode($value); $element->appendChild($node); }
php
public function setElementValue($element, $value) { $node = $this->dom->createTextNode($value); $element->appendChild($node); }
[ "public", "function", "setElementValue", "(", "$", "element", ",", "$", "value", ")", "{", "$", "node", "=", "$", "this", "->", "dom", "->", "createTextNode", "(", "$", "value", ")", ";", "$", "element", "->", "appendChild", "(", "$", "node", ")", ";", "}" ]
Append an element on to the xml document with a simple value. @param mixed $element The dom instance to append the element to @param mixed $value The value to set the new element to @return void
[ "Append", "an", "element", "on", "to", "the", "xml", "document", "with", "a", "simple", "value", "." ]
d5523b58337cab3b9ad90e8d135f87793795f93f
https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/Xml/Writer.php#L107-L111
26,285
duncan3dc/domparser
src/Xml/Writer.php
Writer.createXml
public static function createXml($structure, $encoding = null) { $writer = new static($structure, $encoding); return trim($writer->toString()); }
php
public static function createXml($structure, $encoding = null) { $writer = new static($structure, $encoding); return trim($writer->toString()); }
[ "public", "static", "function", "createXml", "(", "$", "structure", ",", "$", "encoding", "=", "null", ")", "{", "$", "writer", "=", "new", "static", "(", "$", "structure", ",", "$", "encoding", ")", ";", "return", "trim", "(", "$", "writer", "->", "toString", "(", ")", ")", ";", "}" ]
Convert the passed array structure to an xml string. @param array $structure The array representation of the xml structure @param string $encoding The encoding to declare in the <?xml tag @return string
[ "Convert", "the", "passed", "array", "structure", "to", "an", "xml", "string", "." ]
d5523b58337cab3b9ad90e8d135f87793795f93f
https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/Xml/Writer.php#L122-L126
26,286
libgraviton/graviton
src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php
ExtReferenceSearchListener.processScalarNode
private function processScalarNode(AbstractScalarOperatorNode $node) { $copy = clone $node; $copy->setValue($this->getDbRefValue($node->getValue())); return $copy; }
php
private function processScalarNode(AbstractScalarOperatorNode $node) { $copy = clone $node; $copy->setValue($this->getDbRefValue($node->getValue())); return $copy; }
[ "private", "function", "processScalarNode", "(", "AbstractScalarOperatorNode", "$", "node", ")", "{", "$", "copy", "=", "clone", "$", "node", ";", "$", "copy", "->", "setValue", "(", "$", "this", "->", "getDbRefValue", "(", "$", "node", "->", "getValue", "(", ")", ")", ")", ";", "return", "$", "copy", ";", "}" ]
Process scalar condition @param AbstractScalarOperatorNode $node Query node @return AbstractScalarOperatorNode
[ "Process", "scalar", "condition" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php#L83-L88
26,287
libgraviton/graviton
src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php
ExtReferenceSearchListener.processArrayNode
private function processArrayNode(AbstractArrayOperatorNode $node) { $copy = clone $node; $copy->setValues(array_map([$this, 'getDbRefValue'], $node->getValues())); return $copy; }
php
private function processArrayNode(AbstractArrayOperatorNode $node) { $copy = clone $node; $copy->setValues(array_map([$this, 'getDbRefValue'], $node->getValues())); return $copy; }
[ "private", "function", "processArrayNode", "(", "AbstractArrayOperatorNode", "$", "node", ")", "{", "$", "copy", "=", "clone", "$", "node", ";", "$", "copy", "->", "setValues", "(", "array_map", "(", "[", "$", "this", ",", "'getDbRefValue'", "]", ",", "$", "node", "->", "getValues", "(", ")", ")", ")", ";", "return", "$", "copy", ";", "}" ]
Process array condition @param AbstractArrayOperatorNode $node Query node @return AbstractArrayOperatorNode
[ "Process", "array", "condition" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php#L96-L101
26,288
libgraviton/graviton
src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php
ExtReferenceSearchListener.getDbRefValue
private function getDbRefValue($url) { if ($url === null) { return null; } try { $extref = $this->converter->getExtReference($url); return \MongoDBRef::create($extref->getRef(), $extref->getId()); } catch (\InvalidArgumentException $e) { //make up some invalid refs to ensure we find nothing if an invalid url was given return \MongoDBRef::create(false, false); } }
php
private function getDbRefValue($url) { if ($url === null) { return null; } try { $extref = $this->converter->getExtReference($url); return \MongoDBRef::create($extref->getRef(), $extref->getId()); } catch (\InvalidArgumentException $e) { //make up some invalid refs to ensure we find nothing if an invalid url was given return \MongoDBRef::create(false, false); } }
[ "private", "function", "getDbRefValue", "(", "$", "url", ")", "{", "if", "(", "$", "url", "===", "null", ")", "{", "return", "null", ";", "}", "try", "{", "$", "extref", "=", "$", "this", "->", "converter", "->", "getExtReference", "(", "$", "url", ")", ";", "return", "\\", "MongoDBRef", "::", "create", "(", "$", "extref", "->", "getRef", "(", ")", ",", "$", "extref", "->", "getId", "(", ")", ")", ";", "}", "catch", "(", "\\", "InvalidArgumentException", "$", "e", ")", "{", "//make up some invalid refs to ensure we find nothing if an invalid url was given", "return", "\\", "MongoDBRef", "::", "create", "(", "false", ",", "false", ")", ";", "}", "}" ]
Get DbRef from extref URL @param string $url Extref URL representation @return object
[ "Get", "DbRef", "from", "extref", "URL" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php#L109-L122
26,289
libgraviton/graviton
src/Graviton/SchemaBundle/Document/Schema.php
Schema.removeProperty
public function removeProperty($name) { if ($this->properties->containsKey($name)) { $this->properties->remove($name); } }
php
public function removeProperty($name) { if ($this->properties->containsKey($name)) { $this->properties->remove($name); } }
[ "public", "function", "removeProperty", "(", "$", "name", ")", "{", "if", "(", "$", "this", "->", "properties", "->", "containsKey", "(", "$", "name", ")", ")", "{", "$", "this", "->", "properties", "->", "remove", "(", "$", "name", ")", ";", "}", "}" ]
removes a property @param string $name property name @return void
[ "removes", "a", "property" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Document/Schema.php#L664-L669
26,290
libgraviton/graviton
src/Graviton/SchemaBundle/Document/Schema.php
Schema.getProperty
public function getProperty($name = null) { if (is_null($name)) { return null; } return $this->properties->get($name); }
php
public function getProperty($name = null) { if (is_null($name)) { return null; } return $this->properties->get($name); }
[ "public", "function", "getProperty", "(", "$", "name", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "name", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "properties", "->", "get", "(", "$", "name", ")", ";", "}" ]
returns a property @param string $name property name @return null|Schema property
[ "returns", "a", "property" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Document/Schema.php#L678-L684
26,291
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/RecordOriginExceptionFieldsCompilerPass.php
RecordOriginExceptionFieldsCompilerPass.process
public function process(ContainerBuilder $container) { $this->documentMap = $container->get('graviton.document.map'); $map = []; foreach ($this->documentMap->getDocuments() as $document) { $recordOriginExceptionFields = $this->documentMap->getFieldNamesFlat( $document, '', '', function ($field) { return $field->isRecordOriginException(); } ); if (!empty($recordOriginExceptionFields)) { foreach ($recordOriginExceptionFields as $key => $recordOriginExceptionField) { if (substr($recordOriginExceptionField, -2) == '.0') { unset($recordOriginExceptionFields[$key]); } } $map[$document->getClass()] = array_values($recordOriginExceptionFields); } } $container->setParameter('graviton.document.recordoriginexception.fields', $map); }
php
public function process(ContainerBuilder $container) { $this->documentMap = $container->get('graviton.document.map'); $map = []; foreach ($this->documentMap->getDocuments() as $document) { $recordOriginExceptionFields = $this->documentMap->getFieldNamesFlat( $document, '', '', function ($field) { return $field->isRecordOriginException(); } ); if (!empty($recordOriginExceptionFields)) { foreach ($recordOriginExceptionFields as $key => $recordOriginExceptionField) { if (substr($recordOriginExceptionField, -2) == '.0') { unset($recordOriginExceptionFields[$key]); } } $map[$document->getClass()] = array_values($recordOriginExceptionFields); } } $container->setParameter('graviton.document.recordoriginexception.fields', $map); }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "$", "this", "->", "documentMap", "=", "$", "container", "->", "get", "(", "'graviton.document.map'", ")", ";", "$", "map", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "documentMap", "->", "getDocuments", "(", ")", "as", "$", "document", ")", "{", "$", "recordOriginExceptionFields", "=", "$", "this", "->", "documentMap", "->", "getFieldNamesFlat", "(", "$", "document", ",", "''", ",", "''", ",", "function", "(", "$", "field", ")", "{", "return", "$", "field", "->", "isRecordOriginException", "(", ")", ";", "}", ")", ";", "if", "(", "!", "empty", "(", "$", "recordOriginExceptionFields", ")", ")", "{", "foreach", "(", "$", "recordOriginExceptionFields", "as", "$", "key", "=>", "$", "recordOriginExceptionField", ")", "{", "if", "(", "substr", "(", "$", "recordOriginExceptionField", ",", "-", "2", ")", "==", "'.0'", ")", "{", "unset", "(", "$", "recordOriginExceptionFields", "[", "$", "key", "]", ")", ";", "}", "}", "$", "map", "[", "$", "document", "->", "getClass", "(", ")", "]", "=", "array_values", "(", "$", "recordOriginExceptionFields", ")", ";", "}", "}", "$", "container", "->", "setParameter", "(", "'graviton.document.recordoriginexception.fields'", ",", "$", "map", ")", ";", "}" ]
Make recordOriginException fields map and set it to parameter @param ContainerBuilder $container container builder @return void
[ "Make", "recordOriginException", "fields", "map", "and", "set", "it", "to", "parameter" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/RecordOriginExceptionFieldsCompilerPass.php#L31-L58
26,292
libgraviton/graviton
src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php
SwaggerStrategy.supports
public function supports($input) { /** * @var array $swagger */ $swagger = $this->decodeJson($input, true); if (empty($swagger)) { return false; } $mandatoryFields = ['swagger', 'info', 'paths', 'version', 'title', 'definitions']; $fields = array_merge(array_keys($swagger), array_keys($swagger['info'])); $intersect = array_intersect($mandatoryFields, $fields); // every mandatory field was found in provided json definition. return empty(array_diff($mandatoryFields, $intersect)); }
php
public function supports($input) { /** * @var array $swagger */ $swagger = $this->decodeJson($input, true); if (empty($swagger)) { return false; } $mandatoryFields = ['swagger', 'info', 'paths', 'version', 'title', 'definitions']; $fields = array_merge(array_keys($swagger), array_keys($swagger['info'])); $intersect = array_intersect($mandatoryFields, $fields); // every mandatory field was found in provided json definition. return empty(array_diff($mandatoryFields, $intersect)); }
[ "public", "function", "supports", "(", "$", "input", ")", "{", "/**\n * @var array $swagger\n */", "$", "swagger", "=", "$", "this", "->", "decodeJson", "(", "$", "input", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "swagger", ")", ")", "{", "return", "false", ";", "}", "$", "mandatoryFields", "=", "[", "'swagger'", ",", "'info'", ",", "'paths'", ",", "'version'", ",", "'title'", ",", "'definitions'", "]", ";", "$", "fields", "=", "array_merge", "(", "array_keys", "(", "$", "swagger", ")", ",", "array_keys", "(", "$", "swagger", "[", "'info'", "]", ")", ")", ";", "$", "intersect", "=", "array_intersect", "(", "$", "mandatoryFields", ",", "$", "fields", ")", ";", "// every mandatory field was found in provided json definition.", "return", "empty", "(", "array_diff", "(", "$", "mandatoryFields", ",", "$", "intersect", ")", ")", ";", "}" ]
is input data valid json @param string $input json string @return boolean
[ "is", "input", "data", "valid", "json" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L92-L109
26,293
libgraviton/graviton
src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php
SwaggerStrategy.decodeJson
private function decodeJson($input, $assoc = false) { $input = trim($input); return json_decode($input, $assoc); }
php
private function decodeJson($input, $assoc = false) { $input = trim($input); return json_decode($input, $assoc); }
[ "private", "function", "decodeJson", "(", "$", "input", ",", "$", "assoc", "=", "false", ")", "{", "$", "input", "=", "trim", "(", "$", "input", ")", ";", "return", "json_decode", "(", "$", "input", ",", "$", "assoc", ")", ";", "}" ]
decode a json string @param string $input json string @param bool $assoc Force the encoded result to be a hash. @return array|\stdClass
[ "decode", "a", "json", "string" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L119-L124
26,294
libgraviton/graviton
src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php
SwaggerStrategy.setBaseValues
private function setBaseValues(ApiDefinition $apiDef) { $this->registerHost($apiDef); $basePath = $this->document->getBasePath(); if (isset($basePath)) { $apiDef->setBasePath($basePath); } }
php
private function setBaseValues(ApiDefinition $apiDef) { $this->registerHost($apiDef); $basePath = $this->document->getBasePath(); if (isset($basePath)) { $apiDef->setBasePath($basePath); } }
[ "private", "function", "setBaseValues", "(", "ApiDefinition", "$", "apiDef", ")", "{", "$", "this", "->", "registerHost", "(", "$", "apiDef", ")", ";", "$", "basePath", "=", "$", "this", "->", "document", "->", "getBasePath", "(", ")", ";", "if", "(", "isset", "(", "$", "basePath", ")", ")", "{", "$", "apiDef", "->", "setBasePath", "(", "$", "basePath", ")", ";", "}", "}" ]
set base values @param ApiDefinition $apiDef API definition @return void
[ "set", "base", "values" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L133-L140
26,295
libgraviton/graviton
src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php
SwaggerStrategy.getServiceSchema
private function getServiceSchema($service) { $operation = $service->getOperation(); $schema = new \stdClass(); switch (strtolower($service->getMethod())) { case "post": case "put": try { $parameters = $operation->getDocumentObjectProperty('parameters', Parameter\Body::class, true); } catch (MissingDocumentPropertyException $e) { // request has no params break; } foreach ($parameters as $parameter) { /** * there is no schema information available, if $action->parameters[0]->in != 'body' * * @link http://swagger.io/specification/#parameterObject */ if ($parameter instanceof Parameter\Body && $parameter->getIn() === 'body') { $ref = $parameter->getDocumentObjectProperty('schema', Reference::class)->getDocument(); $schema = $this->resolveSchema($ref); break; } } break; case "get": try { $response = $operation->getResponses()->getHttpStatusCode(200); } catch (MissingDocumentPropertyException $e) { // no response with status code 200 is defined break; } $schema = $this->resolveSchema($response->getSchema()->getDocument()); break; } return $schema; }
php
private function getServiceSchema($service) { $operation = $service->getOperation(); $schema = new \stdClass(); switch (strtolower($service->getMethod())) { case "post": case "put": try { $parameters = $operation->getDocumentObjectProperty('parameters', Parameter\Body::class, true); } catch (MissingDocumentPropertyException $e) { // request has no params break; } foreach ($parameters as $parameter) { /** * there is no schema information available, if $action->parameters[0]->in != 'body' * * @link http://swagger.io/specification/#parameterObject */ if ($parameter instanceof Parameter\Body && $parameter->getIn() === 'body') { $ref = $parameter->getDocumentObjectProperty('schema', Reference::class)->getDocument(); $schema = $this->resolveSchema($ref); break; } } break; case "get": try { $response = $operation->getResponses()->getHttpStatusCode(200); } catch (MissingDocumentPropertyException $e) { // no response with status code 200 is defined break; } $schema = $this->resolveSchema($response->getSchema()->getDocument()); break; } return $schema; }
[ "private", "function", "getServiceSchema", "(", "$", "service", ")", "{", "$", "operation", "=", "$", "service", "->", "getOperation", "(", ")", ";", "$", "schema", "=", "new", "\\", "stdClass", "(", ")", ";", "switch", "(", "strtolower", "(", "$", "service", "->", "getMethod", "(", ")", ")", ")", "{", "case", "\"post\"", ":", "case", "\"put\"", ":", "try", "{", "$", "parameters", "=", "$", "operation", "->", "getDocumentObjectProperty", "(", "'parameters'", ",", "Parameter", "\\", "Body", "::", "class", ",", "true", ")", ";", "}", "catch", "(", "MissingDocumentPropertyException", "$", "e", ")", "{", "// request has no params", "break", ";", "}", "foreach", "(", "$", "parameters", "as", "$", "parameter", ")", "{", "/**\n * there is no schema information available, if $action->parameters[0]->in != 'body'\n *\n * @link http://swagger.io/specification/#parameterObject\n */", "if", "(", "$", "parameter", "instanceof", "Parameter", "\\", "Body", "&&", "$", "parameter", "->", "getIn", "(", ")", "===", "'body'", ")", "{", "$", "ref", "=", "$", "parameter", "->", "getDocumentObjectProperty", "(", "'schema'", ",", "Reference", "::", "class", ")", "->", "getDocument", "(", ")", ";", "$", "schema", "=", "$", "this", "->", "resolveSchema", "(", "$", "ref", ")", ";", "break", ";", "}", "}", "break", ";", "case", "\"get\"", ":", "try", "{", "$", "response", "=", "$", "operation", "->", "getResponses", "(", ")", "->", "getHttpStatusCode", "(", "200", ")", ";", "}", "catch", "(", "MissingDocumentPropertyException", "$", "e", ")", "{", "// no response with status code 200 is defined", "break", ";", "}", "$", "schema", "=", "$", "this", "->", "resolveSchema", "(", "$", "response", "->", "getSchema", "(", ")", "->", "getDocument", "(", ")", ")", ";", "break", ";", "}", "return", "$", "schema", ";", "}" ]
get the schema @param OperationReference $service service endpoint @return \stdClass
[ "get", "the", "schema" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L149-L187
26,296
libgraviton/graviton
src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php
SwaggerStrategy.registerHost
private function registerHost(ApiDefinition $apiDef) { try { $host = $this->document->getHost(); } catch (MissingDocumentPropertyException $e) { $host = $this->fallbackData['host']; } $apiDef->setHost($host); }
php
private function registerHost(ApiDefinition $apiDef) { try { $host = $this->document->getHost(); } catch (MissingDocumentPropertyException $e) { $host = $this->fallbackData['host']; } $apiDef->setHost($host); }
[ "private", "function", "registerHost", "(", "ApiDefinition", "$", "apiDef", ")", "{", "try", "{", "$", "host", "=", "$", "this", "->", "document", "->", "getHost", "(", ")", ";", "}", "catch", "(", "MissingDocumentPropertyException", "$", "e", ")", "{", "$", "host", "=", "$", "this", "->", "fallbackData", "[", "'host'", "]", ";", "}", "$", "apiDef", "->", "setHost", "(", "$", "host", ")", ";", "}" ]
Sets the destination host for the api definition. @param ApiDefinition $apiDef Configuration for the swagger api to be recognized. @return void
[ "Sets", "the", "destination", "host", "for", "the", "api", "definition", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L233-L241
26,297
libgraviton/graviton
src/Graviton/AnalyticsBundle/Compiler/AnalyticsCompilerPass.php
AnalyticsCompilerPass.process
public function process(ContainerBuilder $container) { $services = []; $finder = Finder::create() ->files() ->in(Graviton::getBundleScanDir()) ->path('/\/analytics\//i') ->name('*.json') ->notName('_*') ->notName('*.pipeline.*') ->sortByName(); foreach ($finder as $file) { $key = $file->getFilename(); $data = json_decode($file->getContents(), true); if (json_last_error()) { throw new InvalidConfigurationException( sprintf('Analytics file: %s could not be loaded due to error: %s', $key, json_last_error_msg()) ); } if (isset($data['route']) && !empty($data['route'])) { $services[$data['route']] = $data; } else { $services[] = $data; } } $container->setParameter('analytics.services', $services); }
php
public function process(ContainerBuilder $container) { $services = []; $finder = Finder::create() ->files() ->in(Graviton::getBundleScanDir()) ->path('/\/analytics\//i') ->name('*.json') ->notName('_*') ->notName('*.pipeline.*') ->sortByName(); foreach ($finder as $file) { $key = $file->getFilename(); $data = json_decode($file->getContents(), true); if (json_last_error()) { throw new InvalidConfigurationException( sprintf('Analytics file: %s could not be loaded due to error: %s', $key, json_last_error_msg()) ); } if (isset($data['route']) && !empty($data['route'])) { $services[$data['route']] = $data; } else { $services[] = $data; } } $container->setParameter('analytics.services', $services); }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "$", "services", "=", "[", "]", ";", "$", "finder", "=", "Finder", "::", "create", "(", ")", "->", "files", "(", ")", "->", "in", "(", "Graviton", "::", "getBundleScanDir", "(", ")", ")", "->", "path", "(", "'/\\/analytics\\//i'", ")", "->", "name", "(", "'*.json'", ")", "->", "notName", "(", "'_*'", ")", "->", "notName", "(", "'*.pipeline.*'", ")", "->", "sortByName", "(", ")", ";", "foreach", "(", "$", "finder", "as", "$", "file", ")", "{", "$", "key", "=", "$", "file", "->", "getFilename", "(", ")", ";", "$", "data", "=", "json_decode", "(", "$", "file", "->", "getContents", "(", ")", ",", "true", ")", ";", "if", "(", "json_last_error", "(", ")", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "sprintf", "(", "'Analytics file: %s could not be loaded due to error: %s'", ",", "$", "key", ",", "json_last_error_msg", "(", ")", ")", ")", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'route'", "]", ")", "&&", "!", "empty", "(", "$", "data", "[", "'route'", "]", ")", ")", "{", "$", "services", "[", "$", "data", "[", "'route'", "]", "]", "=", "$", "data", ";", "}", "else", "{", "$", "services", "[", "]", "=", "$", "data", ";", "}", "}", "$", "container", "->", "setParameter", "(", "'analytics.services'", ",", "$", "services", ")", ";", "}" ]
add our map of the available analytics services @param ContainerBuilder $container container @return void
[ "add", "our", "map", "of", "the", "available", "analytics", "services" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Compiler/AnalyticsCompilerPass.php#L27-L56
26,298
libgraviton/graviton
src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php
I18nRqlParsingListener.getAlteredQueryNode
private function getAlteredQueryNode($fieldName, array $values) { $newNode = new OrNode(); $defaultLanguageFieldName = $fieldName.'.'.$this->intUtils->getDefaultLanguage(); foreach ($values as $singleValue) { $newNode->addQuery($this->getEqNode($fieldName, $singleValue)); // search default language field (as new structure only has 'en' set after creation and no save) $newNode->addQuery( $this->getEqNode( $defaultLanguageFieldName, $singleValue ) ); } // add default match $newNode->addQuery($this->getEqNode($this->node->getField(), $this->getNodeValue())); if (!$this->nodeFieldNameHasLanguage()) { // if no language, we add it to the query to default node for default language $newNode->addQuery( $this->getEqNode( $defaultLanguageFieldName, $this->getNodeValue() ) ); } return $newNode; }
php
private function getAlteredQueryNode($fieldName, array $values) { $newNode = new OrNode(); $defaultLanguageFieldName = $fieldName.'.'.$this->intUtils->getDefaultLanguage(); foreach ($values as $singleValue) { $newNode->addQuery($this->getEqNode($fieldName, $singleValue)); // search default language field (as new structure only has 'en' set after creation and no save) $newNode->addQuery( $this->getEqNode( $defaultLanguageFieldName, $singleValue ) ); } // add default match $newNode->addQuery($this->getEqNode($this->node->getField(), $this->getNodeValue())); if (!$this->nodeFieldNameHasLanguage()) { // if no language, we add it to the query to default node for default language $newNode->addQuery( $this->getEqNode( $defaultLanguageFieldName, $this->getNodeValue() ) ); } return $newNode; }
[ "private", "function", "getAlteredQueryNode", "(", "$", "fieldName", ",", "array", "$", "values", ")", "{", "$", "newNode", "=", "new", "OrNode", "(", ")", ";", "$", "defaultLanguageFieldName", "=", "$", "fieldName", ".", "'.'", ".", "$", "this", "->", "intUtils", "->", "getDefaultLanguage", "(", ")", ";", "foreach", "(", "$", "values", "as", "$", "singleValue", ")", "{", "$", "newNode", "->", "addQuery", "(", "$", "this", "->", "getEqNode", "(", "$", "fieldName", ",", "$", "singleValue", ")", ")", ";", "// search default language field (as new structure only has 'en' set after creation and no save)", "$", "newNode", "->", "addQuery", "(", "$", "this", "->", "getEqNode", "(", "$", "defaultLanguageFieldName", ",", "$", "singleValue", ")", ")", ";", "}", "// add default match", "$", "newNode", "->", "addQuery", "(", "$", "this", "->", "getEqNode", "(", "$", "this", "->", "node", "->", "getField", "(", ")", ",", "$", "this", "->", "getNodeValue", "(", ")", ")", ")", ";", "if", "(", "!", "$", "this", "->", "nodeFieldNameHasLanguage", "(", ")", ")", "{", "// if no language, we add it to the query to default node for default language", "$", "newNode", "->", "addQuery", "(", "$", "this", "->", "getEqNode", "(", "$", "defaultLanguageFieldName", ",", "$", "this", "->", "getNodeValue", "(", ")", ")", ")", ";", "}", "return", "$", "newNode", ";", "}" ]
Gets a new query node @param string $fieldName target fieldname @param array $values the values to set @return OrNode some node
[ "Gets", "a", "new", "query", "node" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php#L105-L135
26,299
libgraviton/graviton
src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php
I18nRqlParsingListener.getNodeValue
private function getNodeValue() { if ($this->node->getValue() instanceof \Xiag\Rql\Parser\DataType\Glob) { return new \MongoRegex($this->node->getValue()->toRegex()); } return $this->node->getValue(); }
php
private function getNodeValue() { if ($this->node->getValue() instanceof \Xiag\Rql\Parser\DataType\Glob) { return new \MongoRegex($this->node->getValue()->toRegex()); } return $this->node->getValue(); }
[ "private", "function", "getNodeValue", "(", ")", "{", "if", "(", "$", "this", "->", "node", "->", "getValue", "(", ")", "instanceof", "\\", "Xiag", "\\", "Rql", "\\", "Parser", "\\", "DataType", "\\", "Glob", ")", "{", "return", "new", "\\", "MongoRegex", "(", "$", "this", "->", "node", "->", "getValue", "(", ")", "->", "toRegex", "(", ")", ")", ";", "}", "return", "$", "this", "->", "node", "->", "getValue", "(", ")", ";", "}" ]
gets the node value @throws \MongoException @return \MongoRegex|string value
[ "gets", "the", "node", "value" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php#L144-L151