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
16,100
markdegrootnl/omnipay-ideal
src/Message/AbstractRequest.php
AbstractRequest.generateDigest
public function generateDigest(DOMDocument $xml) { $xml = $xml->cloneNode(true); // strip Signature foreach ($this->getXPath($xml)->query('ds:Signature') as $node) { $node->parentNode->removeChild($node); } $message = $this->c14n($xml); return base64_encode(hash('sha256', $message, true)); }
php
public function generateDigest(DOMDocument $xml) { $xml = $xml->cloneNode(true); // strip Signature foreach ($this->getXPath($xml)->query('ds:Signature') as $node) { $node->parentNode->removeChild($node); } $message = $this->c14n($xml); return base64_encode(hash('sha256', $message, true)); }
[ "public", "function", "generateDigest", "(", "DOMDocument", "$", "xml", ")", "{", "$", "xml", "=", "$", "xml", "->", "cloneNode", "(", "true", ")", ";", "// strip Signature", "foreach", "(", "$", "this", "->", "getXPath", "(", "$", "xml", ")", "->", "query", "(", "'ds:Signature'", ")", "as", "$", "node", ")", "{", "$", "node", "->", "parentNode", "->", "removeChild", "(", "$", "node", ")", ";", "}", "$", "message", "=", "$", "this", "->", "c14n", "(", "$", "xml", ")", ";", "return", "base64_encode", "(", "hash", "(", "'sha256'", ",", "$", "message", ",", "true", ")", ")", ";", "}" ]
Generate sha256 digest of xml @param DOMNode @return string
[ "Generate", "sha256", "digest", "of", "xml" ]
565e942c2d22dd160ce6101cc5743f131af54660
https://github.com/markdegrootnl/omnipay-ideal/blob/565e942c2d22dd160ce6101cc5743f131af54660/src/Message/AbstractRequest.php#L186-L198
16,101
markdegrootnl/omnipay-ideal
src/Message/AbstractRequest.php
AbstractRequest.generateSignature
public function generateSignature(DOMNode $xml) { $message = $this->c14n($xml); $key = openssl_get_privatekey('file://'.$this->getPrivateKeyPath(), $this->getPrivateKeyPassphrase()); if ($key && openssl_sign($message, $signature, $key, OPENSSL_ALGO_SHA256)) { openssl_free_key($key); return base64_encode($signature); } $error = 'Invalid private key.'; while ($msg = openssl_error_string()) { $error .= ' '.$msg; } throw new InvalidRequestException($error); }
php
public function generateSignature(DOMNode $xml) { $message = $this->c14n($xml); $key = openssl_get_privatekey('file://'.$this->getPrivateKeyPath(), $this->getPrivateKeyPassphrase()); if ($key && openssl_sign($message, $signature, $key, OPENSSL_ALGO_SHA256)) { openssl_free_key($key); return base64_encode($signature); } $error = 'Invalid private key.'; while ($msg = openssl_error_string()) { $error .= ' '.$msg; } throw new InvalidRequestException($error); }
[ "public", "function", "generateSignature", "(", "DOMNode", "$", "xml", ")", "{", "$", "message", "=", "$", "this", "->", "c14n", "(", "$", "xml", ")", ";", "$", "key", "=", "openssl_get_privatekey", "(", "'file://'", ".", "$", "this", "->", "getPrivateKeyPath", "(", ")", ",", "$", "this", "->", "getPrivateKeyPassphrase", "(", ")", ")", ";", "if", "(", "$", "key", "&&", "openssl_sign", "(", "$", "message", ",", "$", "signature", ",", "$", "key", ",", "OPENSSL_ALGO_SHA256", ")", ")", "{", "openssl_free_key", "(", "$", "key", ")", ";", "return", "base64_encode", "(", "$", "signature", ")", ";", "}", "$", "error", "=", "'Invalid private key.'", ";", "while", "(", "$", "msg", "=", "openssl_error_string", "(", ")", ")", "{", "$", "error", ".=", "' '", ".", "$", "msg", ";", "}", "throw", "new", "InvalidRequestException", "(", "$", "error", ")", ";", "}" ]
Generate RSA signature of SignedInfo element @param DOMNode @return string
[ "Generate", "RSA", "signature", "of", "SignedInfo", "element" ]
565e942c2d22dd160ce6101cc5743f131af54660
https://github.com/markdegrootnl/omnipay-ideal/blob/565e942c2d22dd160ce6101cc5743f131af54660/src/Message/AbstractRequest.php#L206-L223
16,102
prooph/link-app-core
src/Service/AbstractQueryController.php
AbstractQueryController.getProcessingTypesForClient
protected function getProcessingTypesForClient(array $processingTypes = null) { if (is_null($processingTypes)) { $processingTypes = $this->systemConfig->getAllAvailableProcessingTypes(); } return array_map(function($processingTypeClass) { return $this->prepareProcessingType($processingTypeClass); }, $processingTypes); }
php
protected function getProcessingTypesForClient(array $processingTypes = null) { if (is_null($processingTypes)) { $processingTypes = $this->systemConfig->getAllAvailableProcessingTypes(); } return array_map(function($processingTypeClass) { return $this->prepareProcessingType($processingTypeClass); }, $processingTypes); }
[ "protected", "function", "getProcessingTypesForClient", "(", "array", "$", "processingTypes", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "processingTypes", ")", ")", "{", "$", "processingTypes", "=", "$", "this", "->", "systemConfig", "->", "getAllAvailableProcessingTypes", "(", ")", ";", "}", "return", "array_map", "(", "function", "(", "$", "processingTypeClass", ")", "{", "return", "$", "this", "->", "prepareProcessingType", "(", "$", "processingTypeClass", ")", ";", "}", ",", "$", "processingTypes", ")", ";", "}" ]
Loads available DataTypes from system config and converts some to cient format If optional data type array is passed as argument, this is used instead of all available types @param array|null $processingTypes @return array
[ "Loads", "available", "DataTypes", "from", "system", "config", "and", "converts", "some", "to", "cient", "format" ]
835a5945dfa7be7b2cebfa6e84e757ecfd783357
https://github.com/prooph/link-app-core/blob/835a5945dfa7be7b2cebfa6e84e757ecfd783357/src/Service/AbstractQueryController.php#L49-L56
16,103
crossjoin/Css
src/Crossjoin/Css/Reader/ReaderAbstract.php
ReaderAbstract.getPreparedCssContent
protected function getPreparedCssContent() { if ($this->preparedContent === null) { $this->preparedContent = Placeholder::replaceStringsAndComments($this->getCssContent()); // Move comments from the end of the line to the beginning to make it easier to // detect, to which rule they belong to $this->preparedContent = preg_replace( '/^([^\r\n]+)(_COMMENT_[a-f0-9]{32}_)([\r\n\t\f]+)/m', "\\2\n\\1\\3", $this->preparedContent ); // Remove white space characters before comments $this->preparedContent = preg_replace( '/^([ \t\f]*)(_COMMENT_[a-f0-9]{32}_)/m', "\\2\n", $this->preparedContent ); // Very important: Split long lines, because parsing long lines (char by char) costs a lot performance // (several thousand percent...). $this->preparedContent = str_replace(["{", "}", ";"], ["{\n", "}\n", ";\n"], $this->preparedContent); } return $this->preparedContent; }
php
protected function getPreparedCssContent() { if ($this->preparedContent === null) { $this->preparedContent = Placeholder::replaceStringsAndComments($this->getCssContent()); // Move comments from the end of the line to the beginning to make it easier to // detect, to which rule they belong to $this->preparedContent = preg_replace( '/^([^\r\n]+)(_COMMENT_[a-f0-9]{32}_)([\r\n\t\f]+)/m', "\\2\n\\1\\3", $this->preparedContent ); // Remove white space characters before comments $this->preparedContent = preg_replace( '/^([ \t\f]*)(_COMMENT_[a-f0-9]{32}_)/m', "\\2\n", $this->preparedContent ); // Very important: Split long lines, because parsing long lines (char by char) costs a lot performance // (several thousand percent...). $this->preparedContent = str_replace(["{", "}", ";"], ["{\n", "}\n", ";\n"], $this->preparedContent); } return $this->preparedContent; }
[ "protected", "function", "getPreparedCssContent", "(", ")", "{", "if", "(", "$", "this", "->", "preparedContent", "===", "null", ")", "{", "$", "this", "->", "preparedContent", "=", "Placeholder", "::", "replaceStringsAndComments", "(", "$", "this", "->", "getCssContent", "(", ")", ")", ";", "// Move comments from the end of the line to the beginning to make it easier to", "// detect, to which rule they belong to", "$", "this", "->", "preparedContent", "=", "preg_replace", "(", "'/^([^\\r\\n]+)(_COMMENT_[a-f0-9]{32}_)([\\r\\n\\t\\f]+)/m'", ",", "\"\\\\2\\n\\\\1\\\\3\"", ",", "$", "this", "->", "preparedContent", ")", ";", "// Remove white space characters before comments", "$", "this", "->", "preparedContent", "=", "preg_replace", "(", "'/^([ \\t\\f]*)(_COMMENT_[a-f0-9]{32}_)/m'", ",", "\"\\\\2\\n\"", ",", "$", "this", "->", "preparedContent", ")", ";", "// Very important: Split long lines, because parsing long lines (char by char) costs a lot performance", "// (several thousand percent...).", "$", "this", "->", "preparedContent", "=", "str_replace", "(", "[", "\"{\"", ",", "\"}\"", ",", "\";\"", "]", ",", "[", "\"{\\n\"", ",", "\"}\\n\"", ",", "\";\\n\"", "]", ",", "$", "this", "->", "preparedContent", ")", ";", "}", "return", "$", "this", "->", "preparedContent", ";", "}" ]
Gets a prepared version of the CSS content for parsing. @return string
[ "Gets", "a", "prepared", "version", "of", "the", "CSS", "content", "for", "parsing", "." ]
7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Reader/ReaderAbstract.php#L72-L98
16,104
crossjoin/Css
src/Crossjoin/Css/Reader/ReaderAbstract.php
ReaderAbstract.getCssResource
protected function getCssResource() { $handle = fopen("php://memory", "rw"); fputs($handle, $this->getPreparedCssContent()); rewind($handle); return $handle; }
php
protected function getCssResource() { $handle = fopen("php://memory", "rw"); fputs($handle, $this->getPreparedCssContent()); rewind($handle); return $handle; }
[ "protected", "function", "getCssResource", "(", ")", "{", "$", "handle", "=", "fopen", "(", "\"php://memory\"", ",", "\"rw\"", ")", ";", "fputs", "(", "$", "handle", ",", "$", "this", "->", "getPreparedCssContent", "(", ")", ")", ";", "rewind", "(", "$", "handle", ")", ";", "return", "$", "handle", ";", "}" ]
Gets the CSS content as resource. @return resource
[ "Gets", "the", "CSS", "content", "as", "resource", "." ]
7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Reader/ReaderAbstract.php#L105-L112
16,105
comodojo/dispatcher.framework
src/Comodojo/Dispatcher/Router/Route.php
Route.serialize
public function serialize() { return serialize( (object) [ 'classname' => $this->classname, 'type' => $this->type, 'service' => $this->service, 'parameters' => $this->parameters, 'request' => $this->request, 'query' => $this->query ]); }
php
public function serialize() { return serialize( (object) [ 'classname' => $this->classname, 'type' => $this->type, 'service' => $this->service, 'parameters' => $this->parameters, 'request' => $this->request, 'query' => $this->query ]); }
[ "public", "function", "serialize", "(", ")", "{", "return", "serialize", "(", "(", "object", ")", "[", "'classname'", "=>", "$", "this", "->", "classname", ",", "'type'", "=>", "$", "this", "->", "type", ",", "'service'", "=>", "$", "this", "->", "service", ",", "'parameters'", "=>", "$", "this", "->", "parameters", ",", "'request'", "=>", "$", "this", "->", "request", ",", "'query'", "=>", "$", "this", "->", "query", "]", ")", ";", "}" ]
Return the serialized data @return string
[ "Return", "the", "serialized", "data" ]
5093297dcb7441a8d8f79cbb2429c93232e16d1c
https://github.com/comodojo/dispatcher.framework/blob/5093297dcb7441a8d8f79cbb2429c93232e16d1c/src/Comodojo/Dispatcher/Router/Route.php#L387-L398
16,106
comodojo/dispatcher.framework
src/Comodojo/Dispatcher/Router/Route.php
Route.unserialize
public function unserialize($data) { $parts = unserialize($data); $this->classname = $parts->classname; $this->type = $parts->type; $this->service = $parts->service; $this->parameters = $parts->parameters; $this->request = $parts->request; $this->query = $parts->query; }
php
public function unserialize($data) { $parts = unserialize($data); $this->classname = $parts->classname; $this->type = $parts->type; $this->service = $parts->service; $this->parameters = $parts->parameters; $this->request = $parts->request; $this->query = $parts->query; }
[ "public", "function", "unserialize", "(", "$", "data", ")", "{", "$", "parts", "=", "unserialize", "(", "$", "data", ")", ";", "$", "this", "->", "classname", "=", "$", "parts", "->", "classname", ";", "$", "this", "->", "type", "=", "$", "parts", "->", "type", ";", "$", "this", "->", "service", "=", "$", "parts", "->", "service", ";", "$", "this", "->", "parameters", "=", "$", "parts", "->", "parameters", ";", "$", "this", "->", "request", "=", "$", "parts", "->", "request", ";", "$", "this", "->", "query", "=", "$", "parts", "->", "query", ";", "}" ]
Return the unserialized object @param string $data Serialized data
[ "Return", "the", "unserialized", "object" ]
5093297dcb7441a8d8f79cbb2429c93232e16d1c
https://github.com/comodojo/dispatcher.framework/blob/5093297dcb7441a8d8f79cbb2429c93232e16d1c/src/Comodojo/Dispatcher/Router/Route.php#L406-L417
16,107
jpuck/color-mixer
src/CanonicalNames.php
CanonicalNames.hex
public static function hex(string $name = null) { if ( empty($name) ) { return static::$hexmap; } return static::$hexmap[$name] ?? false; }
php
public static function hex(string $name = null) { if ( empty($name) ) { return static::$hexmap; } return static::$hexmap[$name] ?? false; }
[ "public", "static", "function", "hex", "(", "string", "$", "name", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "return", "static", "::", "$", "hexmap", ";", "}", "return", "static", "::", "$", "hexmap", "[", "$", "name", "]", "??", "false", ";", "}" ]
Returns the hexadecimal CSS color given the canonical name. @param string Optional canonical color name. @return mixed Default returns array of all canonical keys and hex values. Given a name, returns string hexadecimal color or false if color does not exist.
[ "Returns", "the", "hexadecimal", "CSS", "color", "given", "the", "canonical", "name", "." ]
cea01c3082a921a35e00ae0a287c795d9fd73ada
https://github.com/jpuck/color-mixer/blob/cea01c3082a921a35e00ae0a287c795d9fd73ada/src/CanonicalNames.php#L165-L172
16,108
constant-null/backstubber
src/FileGenerator.php
FileGenerator.generate
public function generate($outputPath) { // do content replacement $this->process(); // check if directory exist, if not create it $baseDir = dirname($outputPath); if (!is_dir($baseDir)) { mkdir($baseDir, 700, true); } return (bool)file_put_contents($outputPath, $this->getContent()); }
php
public function generate($outputPath) { // do content replacement $this->process(); // check if directory exist, if not create it $baseDir = dirname($outputPath); if (!is_dir($baseDir)) { mkdir($baseDir, 700, true); } return (bool)file_put_contents($outputPath, $this->getContent()); }
[ "public", "function", "generate", "(", "$", "outputPath", ")", "{", "// do content replacement", "$", "this", "->", "process", "(", ")", ";", "// check if directory exist, if not create it", "$", "baseDir", "=", "dirname", "(", "$", "outputPath", ")", ";", "if", "(", "!", "is_dir", "(", "$", "baseDir", ")", ")", "{", "mkdir", "(", "$", "baseDir", ",", "700", ",", "true", ")", ";", "}", "return", "(", "bool", ")", "file_put_contents", "(", "$", "outputPath", ",", "$", "this", "->", "getContent", "(", ")", ")", ";", "}" ]
save generated file to path returns true if file was successfully created false otherwise @param $outputPath string @return bool
[ "save", "generated", "file", "to", "path", "returns", "true", "if", "file", "was", "successfully", "created", "false", "otherwise" ]
1e7ee66091bae4e6b709642467609a8566dae479
https://github.com/constant-null/backstubber/blob/1e7ee66091bae4e6b709642467609a8566dae479/src/FileGenerator.php#L100-L112
16,109
constant-null/backstubber
src/FileGenerator.php
FileGenerator.formatValue
protected function formatValue($value) { if (is_array($value)) { return Formatter::formatArray($value); } return Formatter::formatScalar($value); }
php
protected function formatValue($value) { if (is_array($value)) { return Formatter::formatArray($value); } return Formatter::formatScalar($value); }
[ "protected", "function", "formatValue", "(", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "return", "Formatter", "::", "formatArray", "(", "$", "value", ")", ";", "}", "return", "Formatter", "::", "formatScalar", "(", "$", "value", ")", ";", "}" ]
Format a value before processing. @param array|string $value @return array|string
[ "Format", "a", "value", "before", "processing", "." ]
1e7ee66091bae4e6b709642467609a8566dae479
https://github.com/constant-null/backstubber/blob/1e7ee66091bae4e6b709642467609a8566dae479/src/FileGenerator.php#L120-L127
16,110
stubbles/stubbles-webapp-core
src/main/php/UriPath.php
UriPath.hasArgument
public function hasArgument(string $name): bool { $this->parsePathArguments(); return isset($this->arguments[$name]); }
php
public function hasArgument(string $name): bool { $this->parsePathArguments(); return isset($this->arguments[$name]); }
[ "public", "function", "hasArgument", "(", "string", "$", "name", ")", ":", "bool", "{", "$", "this", "->", "parsePathArguments", "(", ")", ";", "return", "isset", "(", "$", "this", "->", "arguments", "[", "$", "name", "]", ")", ";", "}" ]
checks if path contains argument with given name @param string $name @return bool
[ "checks", "if", "path", "contains", "argument", "with", "given", "name" ]
7705f129011a81d5cc3c76b4b150fab3dadac6a3
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/UriPath.php#L99-L103
16,111
stubbles/stubbles-webapp-core
src/main/php/UriPath.php
UriPath.readArgument
public function readArgument(string $name): ValueReader { $this->parsePathArguments(); if (isset($this->arguments[$name])) { return ValueReader::forValue($this->arguments[$name]); } return ValueReader::forValue(null); }
php
public function readArgument(string $name): ValueReader { $this->parsePathArguments(); if (isset($this->arguments[$name])) { return ValueReader::forValue($this->arguments[$name]); } return ValueReader::forValue(null); }
[ "public", "function", "readArgument", "(", "string", "$", "name", ")", ":", "ValueReader", "{", "$", "this", "->", "parsePathArguments", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "arguments", "[", "$", "name", "]", ")", ")", "{", "return", "ValueReader", "::", "forValue", "(", "$", "this", "->", "arguments", "[", "$", "name", "]", ")", ";", "}", "return", "ValueReader", "::", "forValue", "(", "null", ")", ";", "}" ]
returns argument with given name or default if not set @param string $name @return \stubbles\input\ValueReader @since 3.3.0
[ "returns", "argument", "with", "given", "name", "or", "default", "if", "not", "set" ]
7705f129011a81d5cc3c76b4b150fab3dadac6a3
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/UriPath.php#L112-L120
16,112
stubbles/stubbles-webapp-core
src/main/php/UriPath.php
UriPath.parsePathArguments
private function parsePathArguments() { if (null !== $this->arguments) { return; } $arguments = []; preg_match('/^' . self::pattern($this->configuredPath) . '/', $this->calledPath, $arguments); array_shift($arguments); $names = []; $this->arguments = []; preg_match_all('/[{][^}]*[}]/', str_replace('/', '\/', $this->configuredPath), $names); foreach ($names[0] as $key => $name) { if (isset($arguments[$key])) { $this->arguments[str_replace(['{', '}'], '', $name)] = $arguments[$key]; } } }
php
private function parsePathArguments() { if (null !== $this->arguments) { return; } $arguments = []; preg_match('/^' . self::pattern($this->configuredPath) . '/', $this->calledPath, $arguments); array_shift($arguments); $names = []; $this->arguments = []; preg_match_all('/[{][^}]*[}]/', str_replace('/', '\/', $this->configuredPath), $names); foreach ($names[0] as $key => $name) { if (isset($arguments[$key])) { $this->arguments[str_replace(['{', '}'], '', $name)] = $arguments[$key]; } } }
[ "private", "function", "parsePathArguments", "(", ")", "{", "if", "(", "null", "!==", "$", "this", "->", "arguments", ")", "{", "return", ";", "}", "$", "arguments", "=", "[", "]", ";", "preg_match", "(", "'/^'", ".", "self", "::", "pattern", "(", "$", "this", "->", "configuredPath", ")", ".", "'/'", ",", "$", "this", "->", "calledPath", ",", "$", "arguments", ")", ";", "array_shift", "(", "$", "arguments", ")", ";", "$", "names", "=", "[", "]", ";", "$", "this", "->", "arguments", "=", "[", "]", ";", "preg_match_all", "(", "'/[{][^}]*[}]/'", ",", "str_replace", "(", "'/'", ",", "'\\/'", ",", "$", "this", "->", "configuredPath", ")", ",", "$", "names", ")", ";", "foreach", "(", "$", "names", "[", "0", "]", "as", "$", "key", "=>", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "arguments", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "arguments", "[", "str_replace", "(", "[", "'{'", ",", "'}'", "]", ",", "''", ",", "$", "name", ")", "]", "=", "$", "arguments", "[", "$", "key", "]", ";", "}", "}", "}" ]
parses path arguments from called path
[ "parses", "path", "arguments", "from", "called", "path" ]
7705f129011a81d5cc3c76b4b150fab3dadac6a3
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/UriPath.php#L125-L142
16,113
stubbles/stubbles-webapp-core
src/main/php/UriPath.php
UriPath.remaining
public function remaining(string $default = null) { $matches = []; preg_match('/(' . self::pattern($this->configuredPath) . ')([^?]*)?/', $this->calledPath, $matches); $last = count($matches) - 1; if (2 > $last) { return $default; } if (isset($matches[$last]) && !empty($matches[$last])) { return $matches[$last]; } return $default; }
php
public function remaining(string $default = null) { $matches = []; preg_match('/(' . self::pattern($this->configuredPath) . ')([^?]*)?/', $this->calledPath, $matches); $last = count($matches) - 1; if (2 > $last) { return $default; } if (isset($matches[$last]) && !empty($matches[$last])) { return $matches[$last]; } return $default; }
[ "public", "function", "remaining", "(", "string", "$", "default", "=", "null", ")", "{", "$", "matches", "=", "[", "]", ";", "preg_match", "(", "'/('", ".", "self", "::", "pattern", "(", "$", "this", "->", "configuredPath", ")", ".", "')([^?]*)?/'", ",", "$", "this", "->", "calledPath", ",", "$", "matches", ")", ";", "$", "last", "=", "count", "(", "$", "matches", ")", "-", "1", ";", "if", "(", "2", ">", "$", "last", ")", "{", "return", "$", "default", ";", "}", "if", "(", "isset", "(", "$", "matches", "[", "$", "last", "]", ")", "&&", "!", "empty", "(", "$", "matches", "[", "$", "last", "]", ")", ")", "{", "return", "$", "matches", "[", "$", "last", "]", ";", "}", "return", "$", "default", ";", "}" ]
returns remaining path that was not matched by original path @param string $default @return string
[ "returns", "remaining", "path", "that", "was", "not", "matched", "by", "original", "path" ]
7705f129011a81d5cc3c76b4b150fab3dadac6a3
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/UriPath.php#L150-L164
16,114
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getTemplate
public function getTemplate($entityType) { $params = [ 'fields' => 'attributes.title', 'limit' => 1, ]; $definition = $this->search('EntityType', ['title' => $entityType], $params); return array_fill_keys(array_merge(['_id'], array_column($definition[0]['attributes'], 'title')), null); }
php
public function getTemplate($entityType) { $params = [ 'fields' => 'attributes.title', 'limit' => 1, ]; $definition = $this->search('EntityType', ['title' => $entityType], $params); return array_fill_keys(array_merge(['_id'], array_column($definition[0]['attributes'], 'title')), null); }
[ "public", "function", "getTemplate", "(", "$", "entityType", ")", "{", "$", "params", "=", "[", "'fields'", "=>", "'attributes.title'", ",", "'limit'", "=>", "1", ",", "]", ";", "$", "definition", "=", "$", "this", "->", "search", "(", "'EntityType'", ",", "[", "'title'", "=>", "$", "entityType", "]", ",", "$", "params", ")", ";", "return", "array_fill_keys", "(", "array_merge", "(", "[", "'_id'", "]", ",", "array_column", "(", "$", "definition", "[", "0", "]", "[", "'attributes'", "]", ",", "'title'", ")", ")", ",", "null", ")", ";", "}" ]
Returns an array that has all the fields according to the definition in Communibase. @param string $entityType @return array @throws Exception
[ "Returns", "an", "array", "that", "has", "all", "the", "fields", "according", "to", "the", "definition", "in", "Communibase", "." ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L88-L97
16,115
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getById
public function getById($entityType, $id, array $params = [], $version = null) { if (empty($id)) { throw new Exception('Id is empty'); } if (!static::isIdValid($id)) { throw new Exception('Id is invalid, please use a correctly formatted id'); } return ($version === null) ? $this->doGet($entityType . '.json/crud/' . $id, $params) : $this->doGet($entityType . '.json/history/' . $id . '/' . $version, $params); }
php
public function getById($entityType, $id, array $params = [], $version = null) { if (empty($id)) { throw new Exception('Id is empty'); } if (!static::isIdValid($id)) { throw new Exception('Id is invalid, please use a correctly formatted id'); } return ($version === null) ? $this->doGet($entityType . '.json/crud/' . $id, $params) : $this->doGet($entityType . '.json/history/' . $id . '/' . $version, $params); }
[ "public", "function", "getById", "(", "$", "entityType", ",", "$", "id", ",", "array", "$", "params", "=", "[", "]", ",", "$", "version", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "id", ")", ")", "{", "throw", "new", "Exception", "(", "'Id is empty'", ")", ";", "}", "if", "(", "!", "static", "::", "isIdValid", "(", "$", "id", ")", ")", "{", "throw", "new", "Exception", "(", "'Id is invalid, please use a correctly formatted id'", ")", ";", "}", "return", "(", "$", "version", "===", "null", ")", "?", "$", "this", "->", "doGet", "(", "$", "entityType", ".", "'.json/crud/'", ".", "$", "id", ",", "$", "params", ")", ":", "$", "this", "->", "doGet", "(", "$", "entityType", ".", "'.json/history/'", ".", "$", "id", ".", "'/'", ".", "$", "version", ",", "$", "params", ")", ";", "}" ]
Get a single Entity by its id @param string $entityType @param string $id @param array $params (optional) @param string|null $version @return array entity @throws Exception
[ "Get", "a", "single", "Entity", "by", "its", "id" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L111-L124
16,116
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getByRef
public function getByRef(array $ref, array $parentEntity = []) { $document = $parentEntity; if (strpos($ref['rootDocumentEntityType'], 'parent') === false) { if (empty($document['_id']) || $document['_id'] !== $ref['rootDocumentId']) { $document = $this->getById($ref['rootDocumentEntityType'], $ref['rootDocumentId']); } if (count($document) === 0) { throw new Exception('Invalid document reference (document cannot be found by Id)'); } } $container = $document; foreach ($ref['path'] as $pathInDocument) { if (!array_key_exists($pathInDocument['field'], $container)) { throw new Exception('Could not find the path in document'); } $container = $container[$pathInDocument['field']]; if (empty($pathInDocument['objectId'])) { continue; } if (!is_array($container)) { throw new Exception('Invalid value for path in document'); } $result = array_filter($container, function ($item) use ($pathInDocument) { return $item['_id'] === $pathInDocument['objectId']; }); if (count($result) === 0) { throw new Exception('Empty result of reference'); } $container = reset($result); } return $container; }
php
public function getByRef(array $ref, array $parentEntity = []) { $document = $parentEntity; if (strpos($ref['rootDocumentEntityType'], 'parent') === false) { if (empty($document['_id']) || $document['_id'] !== $ref['rootDocumentId']) { $document = $this->getById($ref['rootDocumentEntityType'], $ref['rootDocumentId']); } if (count($document) === 0) { throw new Exception('Invalid document reference (document cannot be found by Id)'); } } $container = $document; foreach ($ref['path'] as $pathInDocument) { if (!array_key_exists($pathInDocument['field'], $container)) { throw new Exception('Could not find the path in document'); } $container = $container[$pathInDocument['field']]; if (empty($pathInDocument['objectId'])) { continue; } if (!is_array($container)) { throw new Exception('Invalid value for path in document'); } $result = array_filter($container, function ($item) use ($pathInDocument) { return $item['_id'] === $pathInDocument['objectId']; }); if (count($result) === 0) { throw new Exception('Empty result of reference'); } $container = reset($result); } return $container; }
[ "public", "function", "getByRef", "(", "array", "$", "ref", ",", "array", "$", "parentEntity", "=", "[", "]", ")", "{", "$", "document", "=", "$", "parentEntity", ";", "if", "(", "strpos", "(", "$", "ref", "[", "'rootDocumentEntityType'", "]", ",", "'parent'", ")", "===", "false", ")", "{", "if", "(", "empty", "(", "$", "document", "[", "'_id'", "]", ")", "||", "$", "document", "[", "'_id'", "]", "!==", "$", "ref", "[", "'rootDocumentId'", "]", ")", "{", "$", "document", "=", "$", "this", "->", "getById", "(", "$", "ref", "[", "'rootDocumentEntityType'", "]", ",", "$", "ref", "[", "'rootDocumentId'", "]", ")", ";", "}", "if", "(", "count", "(", "$", "document", ")", "===", "0", ")", "{", "throw", "new", "Exception", "(", "'Invalid document reference (document cannot be found by Id)'", ")", ";", "}", "}", "$", "container", "=", "$", "document", ";", "foreach", "(", "$", "ref", "[", "'path'", "]", "as", "$", "pathInDocument", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "pathInDocument", "[", "'field'", "]", ",", "$", "container", ")", ")", "{", "throw", "new", "Exception", "(", "'Could not find the path in document'", ")", ";", "}", "$", "container", "=", "$", "container", "[", "$", "pathInDocument", "[", "'field'", "]", "]", ";", "if", "(", "empty", "(", "$", "pathInDocument", "[", "'objectId'", "]", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "is_array", "(", "$", "container", ")", ")", "{", "throw", "new", "Exception", "(", "'Invalid value for path in document'", ")", ";", "}", "$", "result", "=", "array_filter", "(", "$", "container", ",", "function", "(", "$", "item", ")", "use", "(", "$", "pathInDocument", ")", "{", "return", "$", "item", "[", "'_id'", "]", "===", "$", "pathInDocument", "[", "'objectId'", "]", ";", "}", ")", ";", "if", "(", "count", "(", "$", "result", ")", "===", "0", ")", "{", "throw", "new", "Exception", "(", "'Empty result of reference'", ")", ";", "}", "$", "container", "=", "reset", "(", "$", "result", ")", ";", "}", "return", "$", "container", ";", "}" ]
Get a single Entity by a ref-string @todo if the ref is a parent.parent.parent the code would need further improvement. @param array $ref @param array $parentEntity (optional) @return array the referred Entity data @throws Exception
[ "Get", "a", "single", "Entity", "by", "a", "ref", "-", "string" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L138-L173
16,117
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getByIds
public function getByIds($entityType, array $ids, array $params = []) { $validIds = array_values(array_unique(array_filter($ids, [__CLASS__, 'isIdValid']))); if (count($validIds) === 0) { return []; } $doSortByIds = empty($params['sort']); $results = $this->search($entityType, ['_id' => ['$in' => $validIds]], $params); if (!$doSortByIds) { return $results; } $flipped = array_flip($validIds); foreach ($results as $result) { $flipped[$result['_id']] = $result; } return array_filter(array_values($flipped), function ($result) { return is_array($result) && count($result) > 0; }); }
php
public function getByIds($entityType, array $ids, array $params = []) { $validIds = array_values(array_unique(array_filter($ids, [__CLASS__, 'isIdValid']))); if (count($validIds) === 0) { return []; } $doSortByIds = empty($params['sort']); $results = $this->search($entityType, ['_id' => ['$in' => $validIds]], $params); if (!$doSortByIds) { return $results; } $flipped = array_flip($validIds); foreach ($results as $result) { $flipped[$result['_id']] = $result; } return array_filter(array_values($flipped), function ($result) { return is_array($result) && count($result) > 0; }); }
[ "public", "function", "getByIds", "(", "$", "entityType", ",", "array", "$", "ids", ",", "array", "$", "params", "=", "[", "]", ")", "{", "$", "validIds", "=", "array_values", "(", "array_unique", "(", "array_filter", "(", "$", "ids", ",", "[", "__CLASS__", ",", "'isIdValid'", "]", ")", ")", ")", ";", "if", "(", "count", "(", "$", "validIds", ")", "===", "0", ")", "{", "return", "[", "]", ";", "}", "$", "doSortByIds", "=", "empty", "(", "$", "params", "[", "'sort'", "]", ")", ";", "$", "results", "=", "$", "this", "->", "search", "(", "$", "entityType", ",", "[", "'_id'", "=>", "[", "'$in'", "=>", "$", "validIds", "]", "]", ",", "$", "params", ")", ";", "if", "(", "!", "$", "doSortByIds", ")", "{", "return", "$", "results", ";", "}", "$", "flipped", "=", "array_flip", "(", "$", "validIds", ")", ";", "foreach", "(", "$", "results", "as", "$", "result", ")", "{", "$", "flipped", "[", "$", "result", "[", "'_id'", "]", "]", "=", "$", "result", ";", "}", "return", "array_filter", "(", "array_values", "(", "$", "flipped", ")", ",", "function", "(", "$", "result", ")", "{", "return", "is_array", "(", "$", "result", ")", "&&", "count", "(", "$", "result", ")", ">", "0", ";", "}", ")", ";", "}" ]
Get an array of entities by their ids @param string $entityType @param array $ids @param array $params (optional) @return array entities @throws Exception
[ "Get", "an", "array", "of", "entities", "by", "their", "ids" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L186-L208
16,118
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getIds
public function getIds($entityType, array $selector = [], array $params = []) { $params['fields'] = '_id'; return array_column($this->search($entityType, $selector, $params), '_id'); }
php
public function getIds($entityType, array $selector = [], array $params = []) { $params['fields'] = '_id'; return array_column($this->search($entityType, $selector, $params), '_id'); }
[ "public", "function", "getIds", "(", "$", "entityType", ",", "array", "$", "selector", "=", "[", "]", ",", "array", "$", "params", "=", "[", "]", ")", "{", "$", "params", "[", "'fields'", "]", "=", "'_id'", ";", "return", "array_column", "(", "$", "this", "->", "search", "(", "$", "entityType", ",", "$", "selector", ",", "$", "params", ")", ",", "'_id'", ")", ";", "}" ]
Get result entityIds of a certain search @param string $entityType @param array $selector (optional) @param array $params (optional) @return array @throws Exception
[ "Get", "result", "entityIds", "of", "a", "certain", "search" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L236-L241
16,119
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getId
public function getId($entityType, array $selector = []) { $params = ['limit' => 1]; $ids = (array)$this->getIds($entityType, $selector, $params); return array_shift($ids); }
php
public function getId($entityType, array $selector = []) { $params = ['limit' => 1]; $ids = (array)$this->getIds($entityType, $selector, $params); return array_shift($ids); }
[ "public", "function", "getId", "(", "$", "entityType", ",", "array", "$", "selector", "=", "[", "]", ")", "{", "$", "params", "=", "[", "'limit'", "=>", "1", "]", ";", "$", "ids", "=", "(", "array", ")", "$", "this", "->", "getIds", "(", "$", "entityType", ",", "$", "selector", ",", "$", "params", ")", ";", "return", "array_shift", "(", "$", "ids", ")", ";", "}" ]
Get the id of an entity based on a search @param string $entityType i.e. Person @param array $selector (optional) i.e. ['firstName' => 'Henk'] @return array resultData @throws Exception
[ "Get", "the", "id", "of", "an", "entity", "based", "on", "a", "search" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L253-L259
16,120
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.update
public function update($entityType, array $properties) { if (empty($properties['_id'])) { return $this->doPost($entityType . '.json/crud/', [], $properties); } return $this->doPut($entityType . '.json/crud/' . $properties['_id'], [], $properties); }
php
public function update($entityType, array $properties) { if (empty($properties['_id'])) { return $this->doPost($entityType . '.json/crud/', [], $properties); } return $this->doPut($entityType . '.json/crud/' . $properties['_id'], [], $properties); }
[ "public", "function", "update", "(", "$", "entityType", ",", "array", "$", "properties", ")", "{", "if", "(", "empty", "(", "$", "properties", "[", "'_id'", "]", ")", ")", "{", "return", "$", "this", "->", "doPost", "(", "$", "entityType", ".", "'.json/crud/'", ",", "[", "]", ",", "$", "properties", ")", ";", "}", "return", "$", "this", "->", "doPut", "(", "$", "entityType", ".", "'.json/crud/'", ".", "$", "properties", "[", "'_id'", "]", ",", "[", "]", ",", "$", "properties", ")", ";", "}" ]
This will save an entity in Communibase. When a _id-field is found, this entity will be updated NOTE: When updating, depending on the Entity, you may need to include all fields. @param string $entityType @param array $properties - the to-be-saved entity data @return array resultData @throws Exception
[ "This", "will", "save", "an", "entity", "in", "Communibase", ".", "When", "a", "_id", "-", "field", "is", "found", "this", "entity", "will", "be", "updated" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L336-L342
16,121
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.finalize
public function finalize($entityType, $id) { if ($entityType !== 'Invoice') { throw new Exception('Cannot call finalize on ' . $entityType); } return $this->doPost($entityType . '.json/finalize/' . $id); }
php
public function finalize($entityType, $id) { if ($entityType !== 'Invoice') { throw new Exception('Cannot call finalize on ' . $entityType); } return $this->doPost($entityType . '.json/finalize/' . $id); }
[ "public", "function", "finalize", "(", "$", "entityType", ",", "$", "id", ")", "{", "if", "(", "$", "entityType", "!==", "'Invoice'", ")", "{", "throw", "new", "Exception", "(", "'Cannot call finalize on '", ".", "$", "entityType", ")", ";", "}", "return", "$", "this", "->", "doPost", "(", "$", "entityType", ".", "'.json/finalize/'", ".", "$", "id", ")", ";", "}" ]
Finalize an invoice by adding an invoiceNumber to it. Besides, invoice items will receive a 'generalLedgerAccountNumber'. This number will be unique and sequential within the 'daybook' of the invoice. NOTE: this is Invoice specific @param string $entityType @param string $id @return array @throws Exception
[ "Finalize", "an", "invoice", "by", "adding", "an", "invoiceNumber", "to", "it", ".", "Besides", "invoice", "items", "will", "receive", "a", "generalLedgerAccountNumber", ".", "This", "number", "will", "be", "unique", "and", "sequential", "within", "the", "daybook", "of", "the", "invoice", "." ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L358-L365
16,122
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.doGet
protected function doGet($path, array $params = null, array $data = null) { return $this->getResult('GET', $path, $params, $data); }
php
protected function doGet($path, array $params = null, array $data = null) { return $this->getResult('GET', $path, $params, $data); }
[ "protected", "function", "doGet", "(", "$", "path", ",", "array", "$", "params", "=", "null", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "getResult", "(", "'GET'", ",", "$", "path", ",", "$", "params", ",", "$", "data", ")", ";", "}" ]
Perform the actual GET @param string $path @param array $params @param array $data @return array @throws Exception
[ "Perform", "the", "actual", "GET" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L462-L465
16,123
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.doPost
protected function doPost($path, array $params = null, array $data = null) { return $this->getResult('POST', $path, $params, $data); }
php
protected function doPost($path, array $params = null, array $data = null) { return $this->getResult('POST', $path, $params, $data); }
[ "protected", "function", "doPost", "(", "$", "path", ",", "array", "$", "params", "=", "null", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "getResult", "(", "'POST'", ",", "$", "path", ",", "$", "params", ",", "$", "data", ")", ";", "}" ]
Perform the actual POST @param string $path @param array $params @param array $data @return array @throws Exception
[ "Perform", "the", "actual", "POST" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L478-L481
16,124
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.doPut
protected function doPut($path, array $params = null, array $data = null) { return $this->getResult('PUT', $path, $params, $data); }
php
protected function doPut($path, array $params = null, array $data = null) { return $this->getResult('PUT', $path, $params, $data); }
[ "protected", "function", "doPut", "(", "$", "path", ",", "array", "$", "params", "=", "null", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "getResult", "(", "'PUT'", ",", "$", "path", ",", "$", "params", ",", "$", "data", ")", ";", "}" ]
Perform the actual PUT @param string $path @param array $params @param array $data @return array @throws Exception
[ "Perform", "the", "actual", "PUT" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L494-L497
16,125
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.doDelete
protected function doDelete($path, array $params = null, array $data = null) { return $this->getResult('DELETE', $path, $params, $data); }
php
protected function doDelete($path, array $params = null, array $data = null) { return $this->getResult('DELETE', $path, $params, $data); }
[ "protected", "function", "doDelete", "(", "$", "path", ",", "array", "$", "params", "=", "null", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "getResult", "(", "'DELETE'", ",", "$", "path", ",", "$", "params", ",", "$", "data", ")", ";", "}" ]
Perform the actual DELETE @param string $path @param array $params @param array $data @return array @throws Exception
[ "Perform", "the", "actual", "DELETE" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L510-L513
16,126
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.parseResult
private function parseResult($response, $httpCode) { $result = json_decode($response, true); if (is_array($result)) { return $result; } throw new Exception('"' . $this->getLastJsonError() . '" in ' . $response, $httpCode); }
php
private function parseResult($response, $httpCode) { $result = json_decode($response, true); if (is_array($result)) { return $result; } throw new Exception('"' . $this->getLastJsonError() . '" in ' . $response, $httpCode); }
[ "private", "function", "parseResult", "(", "$", "response", ",", "$", "httpCode", ")", "{", "$", "result", "=", "json_decode", "(", "$", "response", ",", "true", ")", ";", "if", "(", "is_array", "(", "$", "result", ")", ")", "{", "return", "$", "result", ";", "}", "throw", "new", "Exception", "(", "'\"'", ".", "$", "this", "->", "getLastJsonError", "(", ")", ".", "'\" in '", ".", "$", "response", ",", "$", "httpCode", ")", ";", "}" ]
Parse the Communibase result and if necessary throw an exception @param string $response @param int $httpCode @return array @throws Exception
[ "Parse", "the", "Communibase", "result", "and", "if", "necessary", "throw", "an", "exception" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L597-L606
16,127
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getLastJsonError
private function getLastJsonError() { static $messages = [ JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', ]; $jsonLastError = json_last_error(); return array_key_exists($jsonLastError, $messages) ? $messages[$jsonLastError] : 'Empty response received'; }
php
private function getLastJsonError() { static $messages = [ JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', ]; $jsonLastError = json_last_error(); return array_key_exists($jsonLastError, $messages) ? $messages[$jsonLastError] : 'Empty response received'; }
[ "private", "function", "getLastJsonError", "(", ")", "{", "static", "$", "messages", "=", "[", "JSON_ERROR_DEPTH", "=>", "'Maximum stack depth exceeded'", ",", "JSON_ERROR_STATE_MISMATCH", "=>", "'Underflow or the modes mismatch'", ",", "JSON_ERROR_CTRL_CHAR", "=>", "'Unexpected control character found'", ",", "JSON_ERROR_SYNTAX", "=>", "'Syntax error, malformed JSON'", ",", "JSON_ERROR_UTF8", "=>", "'Malformed UTF-8 characters, possibly incorrectly encoded'", ",", "]", ";", "$", "jsonLastError", "=", "json_last_error", "(", ")", ";", "return", "array_key_exists", "(", "$", "jsonLastError", ",", "$", "messages", ")", "?", "$", "messages", "[", "$", "jsonLastError", "]", ":", "'Empty response received'", ";", "}" ]
Error message based on the most recent JSON error. @see http://nl1.php.net/manual/en/function.json-last-error.php @return string
[ "Error", "message", "based", "on", "the", "most", "recent", "JSON", "error", "." ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L615-L627
16,128
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.call
private function call($method, array $arguments) { try { /** * Due to GuzzleHttp not passing a default host header given to the client to _every_ request made by the * client we manually check to see if we need to add a hostheader to requests. * When the issue is resolved the foreach can be removed (as the function might even?) * * @see https://github.com/guzzle/guzzle/issues/1297 */ if (isset($this->extraHeaders['host'])) { $arguments[1]['headers']['Host'] = $this->extraHeaders['host']; } if ($this->logger) { $this->logger->startQuery($method . ' ' . reset($arguments), $arguments); } $response = call_user_func_array([$this->getClient(), $method], $arguments); if ($this->logger) { $this->logger->stopQuery(); } return $response; // try to catch the Guzzle client exception (404's, validation errors etc) and wrap them into a CB exception } catch (ClientException $e) { $response = $e->getResponse(); $response = json_decode($response === null ? '' : $response->getBody(), true); throw new Exception( $response['message'], $response['code'], $e, (($_ =& $response['errors']) ?: []) ); } catch (ConnectException $e) { throw new Exception('Can not connect', 500, $e, []); } }
php
private function call($method, array $arguments) { try { /** * Due to GuzzleHttp not passing a default host header given to the client to _every_ request made by the * client we manually check to see if we need to add a hostheader to requests. * When the issue is resolved the foreach can be removed (as the function might even?) * * @see https://github.com/guzzle/guzzle/issues/1297 */ if (isset($this->extraHeaders['host'])) { $arguments[1]['headers']['Host'] = $this->extraHeaders['host']; } if ($this->logger) { $this->logger->startQuery($method . ' ' . reset($arguments), $arguments); } $response = call_user_func_array([$this->getClient(), $method], $arguments); if ($this->logger) { $this->logger->stopQuery(); } return $response; // try to catch the Guzzle client exception (404's, validation errors etc) and wrap them into a CB exception } catch (ClientException $e) { $response = $e->getResponse(); $response = json_decode($response === null ? '' : $response->getBody(), true); throw new Exception( $response['message'], $response['code'], $e, (($_ =& $response['errors']) ?: []) ); } catch (ConnectException $e) { throw new Exception('Can not connect', 500, $e, []); } }
[ "private", "function", "call", "(", "$", "method", ",", "array", "$", "arguments", ")", "{", "try", "{", "/**\n * Due to GuzzleHttp not passing a default host header given to the client to _every_ request made by the\n * client we manually check to see if we need to add a hostheader to requests.\n * When the issue is resolved the foreach can be removed (as the function might even?)\n *\n * @see https://github.com/guzzle/guzzle/issues/1297\n */", "if", "(", "isset", "(", "$", "this", "->", "extraHeaders", "[", "'host'", "]", ")", ")", "{", "$", "arguments", "[", "1", "]", "[", "'headers'", "]", "[", "'Host'", "]", "=", "$", "this", "->", "extraHeaders", "[", "'host'", "]", ";", "}", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "startQuery", "(", "$", "method", ".", "' '", ".", "reset", "(", "$", "arguments", ")", ",", "$", "arguments", ")", ";", "}", "$", "response", "=", "call_user_func_array", "(", "[", "$", "this", "->", "getClient", "(", ")", ",", "$", "method", "]", ",", "$", "arguments", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "stopQuery", "(", ")", ";", "}", "return", "$", "response", ";", "// try to catch the Guzzle client exception (404's, validation errors etc) and wrap them into a CB exception", "}", "catch", "(", "ClientException", "$", "e", ")", "{", "$", "response", "=", "$", "e", "->", "getResponse", "(", ")", ";", "$", "response", "=", "json_decode", "(", "$", "response", "===", "null", "?", "''", ":", "$", "response", "->", "getBody", "(", ")", ",", "true", ")", ";", "throw", "new", "Exception", "(", "$", "response", "[", "'message'", "]", ",", "$", "response", "[", "'code'", "]", ",", "$", "e", ",", "(", "(", "$", "_", "=", "&", "$", "response", "[", "'errors'", "]", ")", "?", ":", "[", "]", ")", ")", ";", "}", "catch", "(", "ConnectException", "$", "e", ")", "{", "throw", "new", "Exception", "(", "'Can not connect'", ",", "500", ",", "$", "e", ",", "[", "]", ")", ";", "}", "}" ]
Perform the actual call to Communibase @param string $method @param array $arguments @return \Psr\Http\Message\ResponseInterface @throws Exception
[ "Perform", "the", "actual", "call", "to", "Communibase" ]
f1f9699e1a8acf066fab308f1e86cb8b5548e2db
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L743-L788
16,129
weavephp/weave
src/Middleware/Dispatch.php
Dispatch.run
protected function run(Request $request) { // If there's nothing to dispatch, continue along the middleware pipeline $handler = $request->getAttribute('dispatch.handler', false); if ($handler === false) { return $this->chain($request); } // Setup any remaining chained parts of the dispatch for future dispatch $request = $request->withAttribute('dispatch.handler', $this->resolver->shift($handler)); // Resolve the handler into something callable $dispatchable = $this->resolver->resolve($handler, $resolutionType); // Dispatch $parameters = [ $dispatchable, $resolutionType, DispatchAdaptorInterface::SOURCE_DISPATCH_MIDDLEWARE, $request ]; $response = $this->getResponseObject(); if ($response !== null) { $parameters[] = $response; } return $this->dispatcher->dispatch(...$parameters) ?: $this->chain($request); }
php
protected function run(Request $request) { // If there's nothing to dispatch, continue along the middleware pipeline $handler = $request->getAttribute('dispatch.handler', false); if ($handler === false) { return $this->chain($request); } // Setup any remaining chained parts of the dispatch for future dispatch $request = $request->withAttribute('dispatch.handler', $this->resolver->shift($handler)); // Resolve the handler into something callable $dispatchable = $this->resolver->resolve($handler, $resolutionType); // Dispatch $parameters = [ $dispatchable, $resolutionType, DispatchAdaptorInterface::SOURCE_DISPATCH_MIDDLEWARE, $request ]; $response = $this->getResponseObject(); if ($response !== null) { $parameters[] = $response; } return $this->dispatcher->dispatch(...$parameters) ?: $this->chain($request); }
[ "protected", "function", "run", "(", "Request", "$", "request", ")", "{", "// If there's nothing to dispatch, continue along the middleware pipeline", "$", "handler", "=", "$", "request", "->", "getAttribute", "(", "'dispatch.handler'", ",", "false", ")", ";", "if", "(", "$", "handler", "===", "false", ")", "{", "return", "$", "this", "->", "chain", "(", "$", "request", ")", ";", "}", "// Setup any remaining chained parts of the dispatch for future dispatch", "$", "request", "=", "$", "request", "->", "withAttribute", "(", "'dispatch.handler'", ",", "$", "this", "->", "resolver", "->", "shift", "(", "$", "handler", ")", ")", ";", "// Resolve the handler into something callable", "$", "dispatchable", "=", "$", "this", "->", "resolver", "->", "resolve", "(", "$", "handler", ",", "$", "resolutionType", ")", ";", "// Dispatch", "$", "parameters", "=", "[", "$", "dispatchable", ",", "$", "resolutionType", ",", "DispatchAdaptorInterface", "::", "SOURCE_DISPATCH_MIDDLEWARE", ",", "$", "request", "]", ";", "$", "response", "=", "$", "this", "->", "getResponseObject", "(", ")", ";", "if", "(", "$", "response", "!==", "null", ")", "{", "$", "parameters", "[", "]", "=", "$", "response", ";", "}", "return", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "...", "$", "parameters", ")", "?", ":", "$", "this", "->", "chain", "(", "$", "request", ")", ";", "}" ]
Handle a dispatch. @param Request $request The request. @return Response
[ "Handle", "a", "dispatch", "." ]
44183a5bcb9e3ed3754cc76aa9e0724d718caeec
https://github.com/weavephp/weave/blob/44183a5bcb9e3ed3754cc76aa9e0724d718caeec/src/Middleware/Dispatch.php#L56-L82
16,130
rinvex/obsolete-module
src/ModuleManager.php
ModuleManager.sort
public function sort() { if ($this->modules) { $modules = []; $sorter = new StringSort(); foreach ($this->modules as $slug => $module) { $sorter->add($slug, array_intersect(array_keys($module->getAttribute('require')), array_keys($this->modules))); } foreach ($sorter->sort() as $slug) { $modules[$slug] = $this->modules[$slug]; } // Override modules array $this->modules = $modules; } return $this; }
php
public function sort() { if ($this->modules) { $modules = []; $sorter = new StringSort(); foreach ($this->modules as $slug => $module) { $sorter->add($slug, array_intersect(array_keys($module->getAttribute('require')), array_keys($this->modules))); } foreach ($sorter->sort() as $slug) { $modules[$slug] = $this->modules[$slug]; } // Override modules array $this->modules = $modules; } return $this; }
[ "public", "function", "sort", "(", ")", "{", "if", "(", "$", "this", "->", "modules", ")", "{", "$", "modules", "=", "[", "]", ";", "$", "sorter", "=", "new", "StringSort", "(", ")", ";", "foreach", "(", "$", "this", "->", "modules", "as", "$", "slug", "=>", "$", "module", ")", "{", "$", "sorter", "->", "add", "(", "$", "slug", ",", "array_intersect", "(", "array_keys", "(", "$", "module", "->", "getAttribute", "(", "'require'", ")", ")", ",", "array_keys", "(", "$", "this", "->", "modules", ")", ")", ")", ";", "}", "foreach", "(", "$", "sorter", "->", "sort", "(", ")", "as", "$", "slug", ")", "{", "$", "modules", "[", "$", "slug", "]", "=", "$", "this", "->", "modules", "[", "$", "slug", "]", ";", "}", "// Override modules array", "$", "this", "->", "modules", "=", "$", "modules", ";", "}", "return", "$", "this", ";", "}" ]
Sort modules by their dependencies. @return $this
[ "Sort", "modules", "by", "their", "dependencies", "." ]
95e372ae97ecbe7071c3da397b0afd57f327361f
https://github.com/rinvex/obsolete-module/blob/95e372ae97ecbe7071c3da397b0afd57f327361f/src/ModuleManager.php#L81-L100
16,131
rinvex/obsolete-module
src/ModuleManager.php
ModuleManager.register
public function register() { foreach ($this->modules as $module) { if ($aggregator = $module->getAttribute('aggregator')) { $this->container->register($aggregator); } } return $this; }
php
public function register() { foreach ($this->modules as $module) { if ($aggregator = $module->getAttribute('aggregator')) { $this->container->register($aggregator); } } return $this; }
[ "public", "function", "register", "(", ")", "{", "foreach", "(", "$", "this", "->", "modules", "as", "$", "module", ")", "{", "if", "(", "$", "aggregator", "=", "$", "module", "->", "getAttribute", "(", "'aggregator'", ")", ")", "{", "$", "this", "->", "container", "->", "register", "(", "$", "aggregator", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Register modules with service container. @return $this
[ "Register", "modules", "with", "service", "container", "." ]
95e372ae97ecbe7071c3da397b0afd57f327361f
https://github.com/rinvex/obsolete-module/blob/95e372ae97ecbe7071c3da397b0afd57f327361f/src/ModuleManager.php#L107-L116
16,132
WellCommerce/OrderBundle
Form/DataTransformer/ShippingCostCollectionToArrayTransformer.php
ShippingCostCollectionToArrayTransformer.getRangeData
private function getRangeData(ShippingMethodCost $cost) { return [ 'min' => $cost->getRangeFrom(), 'max' => $cost->getRangeTo(), 'price' => $cost->getCost()->getGrossAmount(), ]; }
php
private function getRangeData(ShippingMethodCost $cost) { return [ 'min' => $cost->getRangeFrom(), 'max' => $cost->getRangeTo(), 'price' => $cost->getCost()->getGrossAmount(), ]; }
[ "private", "function", "getRangeData", "(", "ShippingMethodCost", "$", "cost", ")", "{", "return", "[", "'min'", "=>", "$", "cost", "->", "getRangeFrom", "(", ")", ",", "'max'", "=>", "$", "cost", "->", "getRangeTo", "(", ")", ",", "'price'", "=>", "$", "cost", "->", "getCost", "(", ")", "->", "getGrossAmount", "(", ")", ",", "]", ";", "}" ]
Returns costs data as an array @param ShippingMethodCost $cost @return array
[ "Returns", "costs", "data", "as", "an", "array" ]
d72cfb51eab7a1f66f186900d1e2d533a822c424
https://github.com/WellCommerce/OrderBundle/blob/d72cfb51eab7a1f66f186900d1e2d533a822c424/Form/DataTransformer/ShippingCostCollectionToArrayTransformer.php#L54-L61
16,133
EcomDev/phpspec-magento-di-adapter
src/Extension.php
Extension.load
public function load(ServiceContainer $container, array $params) { $container->define( 'ecomdev.phpspec.magento_di_adapter.vfs', $this->vfsFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.code_generator.io', $this->ioFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes', $this->simplifiedDefinedClassesFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.parameter_validator', $this->parameterValidatorFactory() ); $container->define( 'runner.maintainers.ecomdev_magento_collaborator', $this->collaboratorMaintainerFactory(), ['runner.maintainers'] ); }
php
public function load(ServiceContainer $container, array $params) { $container->define( 'ecomdev.phpspec.magento_di_adapter.vfs', $this->vfsFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.code_generator.io', $this->ioFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes', $this->simplifiedDefinedClassesFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.parameter_validator', $this->parameterValidatorFactory() ); $container->define( 'runner.maintainers.ecomdev_magento_collaborator', $this->collaboratorMaintainerFactory(), ['runner.maintainers'] ); }
[ "public", "function", "load", "(", "ServiceContainer", "$", "container", ",", "array", "$", "params", ")", "{", "$", "container", "->", "define", "(", "'ecomdev.phpspec.magento_di_adapter.vfs'", ",", "$", "this", "->", "vfsFactory", "(", ")", ")", ";", "$", "container", "->", "define", "(", "'ecomdev.phpspec.magento_di_adapter.code_generator.io'", ",", "$", "this", "->", "ioFactory", "(", ")", ")", ";", "$", "container", "->", "define", "(", "'ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes'", ",", "$", "this", "->", "simplifiedDefinedClassesFactory", "(", ")", ")", ";", "$", "container", "->", "define", "(", "'ecomdev.phpspec.magento_di_adapter.parameter_validator'", ",", "$", "this", "->", "parameterValidatorFactory", "(", ")", ")", ";", "$", "container", "->", "define", "(", "'runner.maintainers.ecomdev_magento_collaborator'", ",", "$", "this", "->", "collaboratorMaintainerFactory", "(", ")", ",", "[", "'runner.maintainers'", "]", ")", ";", "}" ]
Load collaborator into PHPSpec ServiceContainer @param ServiceContainer $container
[ "Load", "collaborator", "into", "PHPSpec", "ServiceContainer" ]
b39f6f0afbb837dbf0eb4c71e6cdb318b8c9de37
https://github.com/EcomDev/phpspec-magento-di-adapter/blob/b39f6f0afbb837dbf0eb4c71e6cdb318b8c9de37/src/Extension.php#L33-L60
16,134
EcomDev/phpspec-magento-di-adapter
src/Extension.php
Extension.parameterValidatorFactory
public function parameterValidatorFactory() { return function (ServiceContainer $container) { $parameterValidator = new ParameterValidator( $container->get('ecomdev.phpspec.magento_di_adapter.code_generator.io'), $container->get('ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes'), $container->get('loader.transformer.typehintindex') ); $parameterValidator ->addGenerator(Generator\Factory::class, Generator\Factory::ENTITY_TYPE) ->addGenerator(Generator\Repository::class, Generator\Repository::ENTITY_TYPE) ->addGenerator(Generator\Converter::class, Generator\Converter::ENTITY_TYPE) ->addGenerator(Generator\Persistor::class, Generator\Persistor::ENTITY_TYPE) ->addGenerator(MapperGenerator::class, MapperGenerator::ENTITY_TYPE) ->addGenerator(SearchResults::class, SearchResults::ENTITY_TYPE) ; return $parameterValidator; }; }
php
public function parameterValidatorFactory() { return function (ServiceContainer $container) { $parameterValidator = new ParameterValidator( $container->get('ecomdev.phpspec.magento_di_adapter.code_generator.io'), $container->get('ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes'), $container->get('loader.transformer.typehintindex') ); $parameterValidator ->addGenerator(Generator\Factory::class, Generator\Factory::ENTITY_TYPE) ->addGenerator(Generator\Repository::class, Generator\Repository::ENTITY_TYPE) ->addGenerator(Generator\Converter::class, Generator\Converter::ENTITY_TYPE) ->addGenerator(Generator\Persistor::class, Generator\Persistor::ENTITY_TYPE) ->addGenerator(MapperGenerator::class, MapperGenerator::ENTITY_TYPE) ->addGenerator(SearchResults::class, SearchResults::ENTITY_TYPE) ; return $parameterValidator; }; }
[ "public", "function", "parameterValidatorFactory", "(", ")", "{", "return", "function", "(", "ServiceContainer", "$", "container", ")", "{", "$", "parameterValidator", "=", "new", "ParameterValidator", "(", "$", "container", "->", "get", "(", "'ecomdev.phpspec.magento_di_adapter.code_generator.io'", ")", ",", "$", "container", "->", "get", "(", "'ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes'", ")", ",", "$", "container", "->", "get", "(", "'loader.transformer.typehintindex'", ")", ")", ";", "$", "parameterValidator", "->", "addGenerator", "(", "Generator", "\\", "Factory", "::", "class", ",", "Generator", "\\", "Factory", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "Generator", "\\", "Repository", "::", "class", ",", "Generator", "\\", "Repository", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "Generator", "\\", "Converter", "::", "class", ",", "Generator", "\\", "Converter", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "Generator", "\\", "Persistor", "::", "class", ",", "Generator", "\\", "Persistor", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "MapperGenerator", "::", "class", ",", "MapperGenerator", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "SearchResults", "::", "class", ",", "SearchResults", "::", "ENTITY_TYPE", ")", ";", "return", "$", "parameterValidator", ";", "}", ";", "}" ]
Factory for instantiation of parameter validator @return \Closure
[ "Factory", "for", "instantiation", "of", "parameter", "validator" ]
b39f6f0afbb837dbf0eb4c71e6cdb318b8c9de37
https://github.com/EcomDev/phpspec-magento-di-adapter/blob/b39f6f0afbb837dbf0eb4c71e6cdb318b8c9de37/src/Extension.php#L67-L87
16,135
datasift/datasift-php
lib/DataSift/HistoricPreview.php
DataSift_HistoricPreview.fromResponse
public function fromResponse(array $data) { $map = array( 'id' => 'setId', 'start' => 'setStart', 'end' => 'setEnd', 'hash' => 'setHash', 'parameters' => 'setParameters', 'created_at' => 'setCreatedAt', //only present in responses 'progress' => 'setProgress', 'status' => 'setStatus', 'feeds' => 'setFeeds', 'sample' => 'setSample', 'data' => 'setData', ); foreach ($map as $key => $setter) { if (isset($data[$key])) { $this->$setter($data[$key]); } } return $this; }
php
public function fromResponse(array $data) { $map = array( 'id' => 'setId', 'start' => 'setStart', 'end' => 'setEnd', 'hash' => 'setHash', 'parameters' => 'setParameters', 'created_at' => 'setCreatedAt', //only present in responses 'progress' => 'setProgress', 'status' => 'setStatus', 'feeds' => 'setFeeds', 'sample' => 'setSample', 'data' => 'setData', ); foreach ($map as $key => $setter) { if (isset($data[$key])) { $this->$setter($data[$key]); } } return $this; }
[ "public", "function", "fromResponse", "(", "array", "$", "data", ")", "{", "$", "map", "=", "array", "(", "'id'", "=>", "'setId'", ",", "'start'", "=>", "'setStart'", ",", "'end'", "=>", "'setEnd'", ",", "'hash'", "=>", "'setHash'", ",", "'parameters'", "=>", "'setParameters'", ",", "'created_at'", "=>", "'setCreatedAt'", ",", "//only present in responses", "'progress'", "=>", "'setProgress'", ",", "'status'", "=>", "'setStatus'", ",", "'feeds'", "=>", "'setFeeds'", ",", "'sample'", "=>", "'setSample'", ",", "'data'", "=>", "'setData'", ",", ")", ";", "foreach", "(", "$", "map", "as", "$", "key", "=>", "$", "setter", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "$", "setter", "(", "$", "data", "[", "$", "key", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Hydrates this preview from an array of API responses @param array $data @return DataSift_HistoricPreview
[ "Hydrates", "this", "preview", "from", "an", "array", "of", "API", "responses" ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/HistoricPreview.php#L265-L289
16,136
datasift/datasift-php
lib/DataSift/HistoricPreview.php
DataSift_HistoricPreview.create
public function create() { $params = array( 'start' => $this->getStart(), 'hash' => $this->getHash(), 'parameters' => implode(',', $this->getParameters()) ); if (is_int($this->end)) { $params['end'] = $this->getEnd(); } $this->fromResponse($this->getUser()->post('preview/create', $params)); }
php
public function create() { $params = array( 'start' => $this->getStart(), 'hash' => $this->getHash(), 'parameters' => implode(',', $this->getParameters()) ); if (is_int($this->end)) { $params['end'] = $this->getEnd(); } $this->fromResponse($this->getUser()->post('preview/create', $params)); }
[ "public", "function", "create", "(", ")", "{", "$", "params", "=", "array", "(", "'start'", "=>", "$", "this", "->", "getStart", "(", ")", ",", "'hash'", "=>", "$", "this", "->", "getHash", "(", ")", ",", "'parameters'", "=>", "implode", "(", "','", ",", "$", "this", "->", "getParameters", "(", ")", ")", ")", ";", "if", "(", "is_int", "(", "$", "this", "->", "end", ")", ")", "{", "$", "params", "[", "'end'", "]", "=", "$", "this", "->", "getEnd", "(", ")", ";", "}", "$", "this", "->", "fromResponse", "(", "$", "this", "->", "getUser", "(", ")", "->", "post", "(", "'preview/create'", ",", "$", "params", ")", ")", ";", "}" ]
Create the preview represented by the parameters in this object @return DataSift_HistoricPreview @throws DataSift_Exception_APIError @throws DataSift_Exception_AccessDenied
[ "Create", "the", "preview", "represented", "by", "the", "parameters", "in", "this", "object" ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/HistoricPreview.php#L322-L333
16,137
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.listHistorics
public static function listHistorics($user, $page = 1, $per_page = 20) { try { $res = $user->post( 'historics/get', array( 'page' => $page, 'max' => $page, ) ); $retval = array('count' => $res['count'], 'historics' => array()); foreach ($res['data'] as $historic) { $retval['historics'][] = new self($user, $historic); } return $retval; } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public static function listHistorics($user, $page = 1, $per_page = 20) { try { $res = $user->post( 'historics/get', array( 'page' => $page, 'max' => $page, ) ); $retval = array('count' => $res['count'], 'historics' => array()); foreach ($res['data'] as $historic) { $retval['historics'][] = new self($user, $historic); } return $retval; } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "static", "function", "listHistorics", "(", "$", "user", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "20", ")", "{", "try", "{", "$", "res", "=", "$", "user", "->", "post", "(", "'historics/get'", ",", "array", "(", "'page'", "=>", "$", "page", ",", "'max'", "=>", "$", "page", ",", ")", ")", ";", "$", "retval", "=", "array", "(", "'count'", "=>", "$", "res", "[", "'count'", "]", ",", "'historics'", "=>", "array", "(", ")", ")", ";", "foreach", "(", "$", "res", "[", "'data'", "]", "as", "$", "historic", ")", "{", "$", "retval", "[", "'historics'", "]", "[", "]", "=", "new", "self", "(", "$", "user", ",", "$", "historic", ")", ";", "}", "return", "$", "retval", ";", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
List Historics queries. @param DataSift_User $user The user object. @param int $page The start page. @param int $per_page The start page. @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError
[ "List", "Historics", "queries", "." ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L36-L66
16,138
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.reloadData
public function reloadData() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot reload the data for a deleted Historic.'); } if ($this->_playback_id === false) { throw new DataSift_Exception_InvalidData('Cannot reload the data for a Historic with no playback ID.'); } try { $this->initFromArray($this->_user->post('historics/get', array('id' => $this->_playback_id))); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public function reloadData() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot reload the data for a deleted Historic.'); } if ($this->_playback_id === false) { throw new DataSift_Exception_InvalidData('Cannot reload the data for a Historic with no playback ID.'); } try { $this->initFromArray($this->_user->post('historics/get', array('id' => $this->_playback_id))); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "function", "reloadData", "(", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot reload the data for a deleted Historic.'", ")", ";", "}", "if", "(", "$", "this", "->", "_playback_id", "===", "false", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot reload the data for a Historic with no playback ID.'", ")", ";", "}", "try", "{", "$", "this", "->", "initFromArray", "(", "$", "this", "->", "_user", "->", "post", "(", "'historics/get'", ",", "array", "(", "'id'", "=>", "$", "this", "->", "_playback_id", ")", ")", ")", ";", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
Reload the data for this object from the API. @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError @throws DataSift_Exception_AccessDenied
[ "Reload", "the", "data", "for", "this", "object", "from", "the", "API", "." ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L243-L267
16,139
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.initFromArray
protected function initFromArray($data) { if (! isset($data['id'])) { throw new DataSift_Exception_APIError('No playback ID in the response'); } if ($data['id'] != $this->_playback_id) { throw new DataSift_Exception_APIError('Incorrect playback ID in the response'); } if (! isset($data['definition_id'])) { throw new DataSift_Exception_APIError('No definition hash in the response'); } $this->_hash = $data['definition_id']; if (! isset($data['name'])) { throw new DataSift_Exception_APIError('No name in the response'); } $this->_name = $data['name']; if (! isset($data['start'])) { throw new DataSift_Exception_APIError('No start timestamp in the response'); } $this->_start = $data['start']; if (! isset($data['end'])) { throw new DataSift_Exception_APIError('No end timestamp in the response'); } $this->_end = $data['end']; if (! isset($data['created_at'])) { throw new DataSift_Exception_APIError('No created at timestamp in the response'); } $this->_created_at = $data['created_at']; if (! isset($data['status'])) { throw new DataSift_Exception_APIError('No status in the response'); } $this->_status = $data['status']; if (! isset($data['progress'])) { throw new DataSift_Exception_APIError('No progress in the response'); } $this->_progress = $data['progress']; if (! isset($data['sources'])) { throw new DataSift_Exception_APIError('No sources in the response'); } $this->_sources = $data['sources']; if (! isset($data['sample'])) { throw new DataSift_Exception_APIError('No smaple in the response'); } $this->_sample = $data['sample']; if (isset($data['estimated_completion'])) { $this->_estimated_completion = $data['estimated_completion']; } if ($this->_status == 'deleted') { $this->_deleted = true; } }
php
protected function initFromArray($data) { if (! isset($data['id'])) { throw new DataSift_Exception_APIError('No playback ID in the response'); } if ($data['id'] != $this->_playback_id) { throw new DataSift_Exception_APIError('Incorrect playback ID in the response'); } if (! isset($data['definition_id'])) { throw new DataSift_Exception_APIError('No definition hash in the response'); } $this->_hash = $data['definition_id']; if (! isset($data['name'])) { throw new DataSift_Exception_APIError('No name in the response'); } $this->_name = $data['name']; if (! isset($data['start'])) { throw new DataSift_Exception_APIError('No start timestamp in the response'); } $this->_start = $data['start']; if (! isset($data['end'])) { throw new DataSift_Exception_APIError('No end timestamp in the response'); } $this->_end = $data['end']; if (! isset($data['created_at'])) { throw new DataSift_Exception_APIError('No created at timestamp in the response'); } $this->_created_at = $data['created_at']; if (! isset($data['status'])) { throw new DataSift_Exception_APIError('No status in the response'); } $this->_status = $data['status']; if (! isset($data['progress'])) { throw new DataSift_Exception_APIError('No progress in the response'); } $this->_progress = $data['progress']; if (! isset($data['sources'])) { throw new DataSift_Exception_APIError('No sources in the response'); } $this->_sources = $data['sources']; if (! isset($data['sample'])) { throw new DataSift_Exception_APIError('No smaple in the response'); } $this->_sample = $data['sample']; if (isset($data['estimated_completion'])) { $this->_estimated_completion = $data['estimated_completion']; } if ($this->_status == 'deleted') { $this->_deleted = true; } }
[ "protected", "function", "initFromArray", "(", "$", "data", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'id'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No playback ID in the response'", ")", ";", "}", "if", "(", "$", "data", "[", "'id'", "]", "!=", "$", "this", "->", "_playback_id", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'Incorrect playback ID in the response'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "data", "[", "'definition_id'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No definition hash in the response'", ")", ";", "}", "$", "this", "->", "_hash", "=", "$", "data", "[", "'definition_id'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'name'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No name in the response'", ")", ";", "}", "$", "this", "->", "_name", "=", "$", "data", "[", "'name'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'start'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No start timestamp in the response'", ")", ";", "}", "$", "this", "->", "_start", "=", "$", "data", "[", "'start'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'end'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No end timestamp in the response'", ")", ";", "}", "$", "this", "->", "_end", "=", "$", "data", "[", "'end'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'created_at'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No created at timestamp in the response'", ")", ";", "}", "$", "this", "->", "_created_at", "=", "$", "data", "[", "'created_at'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'status'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No status in the response'", ")", ";", "}", "$", "this", "->", "_status", "=", "$", "data", "[", "'status'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'progress'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No progress in the response'", ")", ";", "}", "$", "this", "->", "_progress", "=", "$", "data", "[", "'progress'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'sources'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No sources in the response'", ")", ";", "}", "$", "this", "->", "_sources", "=", "$", "data", "[", "'sources'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'sample'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No smaple in the response'", ")", ";", "}", "$", "this", "->", "_sample", "=", "$", "data", "[", "'sample'", "]", ";", "if", "(", "isset", "(", "$", "data", "[", "'estimated_completion'", "]", ")", ")", "{", "$", "this", "->", "_estimated_completion", "=", "$", "data", "[", "'estimated_completion'", "]", ";", "}", "if", "(", "$", "this", "->", "_status", "==", "'deleted'", ")", "{", "$", "this", "->", "_deleted", "=", "true", ";", "}", "}" ]
Initialise this object from the data in the given array. @param array $data The array of data. @throws DataSift_Exception_InvalidData
[ "Initialise", "this", "object", "from", "the", "data", "in", "the", "given", "array", "." ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L276-L337
16,140
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.prepare
public function prepare() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot prepare a deleted Historic.'); } if ($this->_playback_id !== false) { throw new DataSift_Exception_InvalidData('This historic query has already been prepared.'); } try { $res = $this->_user->post( 'historics/prepare', array( 'hash' => $this->_hash, 'start' => $this->_start, 'end' => $this->_end, 'name' => $this->_name, 'sources' => implode(',', $this->_sources), 'sample' => $this->_sample, ) ); if (isset($res['id'])) { $this->_playback_id = $res['id']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no playback ID in the response'); } if (isset($res['dpus'])) { $this->_dpus = $res['dpus']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no DPU cost in the response'); } if (isset($res['availability'])) { $this->_availability = $res['availability']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no availability in the response'); } } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public function prepare() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot prepare a deleted Historic.'); } if ($this->_playback_id !== false) { throw new DataSift_Exception_InvalidData('This historic query has already been prepared.'); } try { $res = $this->_user->post( 'historics/prepare', array( 'hash' => $this->_hash, 'start' => $this->_start, 'end' => $this->_end, 'name' => $this->_name, 'sources' => implode(',', $this->_sources), 'sample' => $this->_sample, ) ); if (isset($res['id'])) { $this->_playback_id = $res['id']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no playback ID in the response'); } if (isset($res['dpus'])) { $this->_dpus = $res['dpus']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no DPU cost in the response'); } if (isset($res['availability'])) { $this->_availability = $res['availability']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no availability in the response'); } } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "function", "prepare", "(", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot prepare a deleted Historic.'", ")", ";", "}", "if", "(", "$", "this", "->", "_playback_id", "!==", "false", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'This historic query has already been prepared.'", ")", ";", "}", "try", "{", "$", "res", "=", "$", "this", "->", "_user", "->", "post", "(", "'historics/prepare'", ",", "array", "(", "'hash'", "=>", "$", "this", "->", "_hash", ",", "'start'", "=>", "$", "this", "->", "_start", ",", "'end'", "=>", "$", "this", "->", "_end", ",", "'name'", "=>", "$", "this", "->", "_name", ",", "'sources'", "=>", "implode", "(", "','", ",", "$", "this", "->", "_sources", ")", ",", "'sample'", "=>", "$", "this", "->", "_sample", ",", ")", ")", ";", "if", "(", "isset", "(", "$", "res", "[", "'id'", "]", ")", ")", "{", "$", "this", "->", "_playback_id", "=", "$", "res", "[", "'id'", "]", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'Prepared successfully but no playback ID in the response'", ")", ";", "}", "if", "(", "isset", "(", "$", "res", "[", "'dpus'", "]", ")", ")", "{", "$", "this", "->", "_dpus", "=", "$", "res", "[", "'dpus'", "]", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'Prepared successfully but no DPU cost in the response'", ")", ";", "}", "if", "(", "isset", "(", "$", "res", "[", "'availability'", "]", ")", ")", "{", "$", "this", "->", "_availability", "=", "$", "res", "[", "'availability'", "]", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'Prepared successfully but no availability in the response'", ")", ";", "}", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
Call the DataSift API to prepare this historic query. @return void @throws DataSift_Exception_APIError @throws DataSift_Exception_InvalidData
[ "Call", "the", "DataSift", "API", "to", "prepare", "this", "historic", "query", "." ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L530-L582
16,141
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.stop
public function stop() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot stop a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot stop a historic query that hasn\'t been prepared.'); } try { $res = $this->_user->post( 'historics/stop', array( 'id' => $this->_playback_id, ) ); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); case 404: // Historic query not found throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public function stop() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot stop a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot stop a historic query that hasn\'t been prepared.'); } try { $res = $this->_user->post( 'historics/stop', array( 'id' => $this->_playback_id, ) ); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); case 404: // Historic query not found throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "function", "stop", "(", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot stop a deleted Historic.'", ")", ";", "}", "if", "(", "$", "this", "->", "_playback_id", "===", "false", "||", "strlen", "(", "$", "this", "->", "_playback_id", ")", "==", "0", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot stop a historic query that hasn\\'t been prepared.'", ")", ";", "}", "try", "{", "$", "res", "=", "$", "this", "->", "_user", "->", "post", "(", "'historics/stop'", ",", "array", "(", "'id'", "=>", "$", "this", "->", "_playback_id", ",", ")", ")", ";", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "case", "404", ":", "// Historic query not found", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
Stop this historic query. @return void @throws DataSift_Exception_APIError @throws DataSift_Exception_InvalidData
[ "Stop", "this", "historic", "query", "." ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L633-L666
16,142
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.pause
public function pause($reason = false) { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot pause a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot pause a historic query that hasn\'t been prepared.'); } try { $params = array('id' => $this->_playback_id); if ($reason) { $params['reason'] = $reason; } $res = $this->_user->post('historics/pause', $params); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); case 404: // Historic query not found throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public function pause($reason = false) { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot pause a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot pause a historic query that hasn\'t been prepared.'); } try { $params = array('id' => $this->_playback_id); if ($reason) { $params['reason'] = $reason; } $res = $this->_user->post('historics/pause', $params); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); case 404: // Historic query not found throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "function", "pause", "(", "$", "reason", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot pause a deleted Historic.'", ")", ";", "}", "if", "(", "$", "this", "->", "_playback_id", "===", "false", "||", "strlen", "(", "$", "this", "->", "_playback_id", ")", "==", "0", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot pause a historic query that hasn\\'t been prepared.'", ")", ";", "}", "try", "{", "$", "params", "=", "array", "(", "'id'", "=>", "$", "this", "->", "_playback_id", ")", ";", "if", "(", "$", "reason", ")", "{", "$", "params", "[", "'reason'", "]", "=", "$", "reason", ";", "}", "$", "res", "=", "$", "this", "->", "_user", "->", "post", "(", "'historics/pause'", ",", "$", "params", ")", ";", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "case", "404", ":", "// Historic query not found", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
Pause this historic query. @param string $reason Your reason for pausing the Historics query. @return void @throws DataSift_Exception_APIError @throws DataSift_Exception_InvalidData
[ "Pause", "this", "historic", "query", "." ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L677-L707
16,143
Nayjest/Tree
src/ChildNodeTrait.php
ChildNodeTrait.internalSetParent
final public function internalSetParent(ParentNodeInterface $parent) { $this->emit('parent.change', [$parent, $this]); $this->parentNode = $parent; }
php
final public function internalSetParent(ParentNodeInterface $parent) { $this->emit('parent.change', [$parent, $this]); $this->parentNode = $parent; }
[ "final", "public", "function", "internalSetParent", "(", "ParentNodeInterface", "$", "parent", ")", "{", "$", "this", "->", "emit", "(", "'parent.change'", ",", "[", "$", "parent", ",", "$", "this", "]", ")", ";", "$", "this", "->", "parentNode", "=", "$", "parent", ";", "}" ]
Attaches component to registry. @param ParentNodeInterface $parent @return null
[ "Attaches", "component", "to", "registry", "." ]
e73da75f939e207b1c25065e9466c28300e7113c
https://github.com/Nayjest/Tree/blob/e73da75f939e207b1c25065e9466c28300e7113c/src/ChildNodeTrait.php#L37-L41
16,144
discophp/framework
core/classes/PDO.class.php
PDO.create
public function create($table, $data){ $keys = array_keys($data); $values = ':' . implode(',:', $keys); $keys = implode(',', $keys); return $this->query($this->set("INSERT INTO {$table} ({$keys}) VALUES({$values})", $data)); }
php
public function create($table, $data){ $keys = array_keys($data); $values = ':' . implode(',:', $keys); $keys = implode(',', $keys); return $this->query($this->set("INSERT INTO {$table} ({$keys}) VALUES({$values})", $data)); }
[ "public", "function", "create", "(", "$", "table", ",", "$", "data", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "data", ")", ";", "$", "values", "=", "':'", ".", "implode", "(", "',:'", ",", "$", "keys", ")", ";", "$", "keys", "=", "implode", "(", "','", ",", "$", "keys", ")", ";", "return", "$", "this", "->", "query", "(", "$", "this", "->", "set", "(", "\"INSERT INTO {$table} ({$keys}) VALUES({$values})\"", ",", "$", "data", ")", ")", ";", "}" ]
Perform an INSERT statement. @param string $table The name of the table to insert into. @param array $data The data to insert into the table, must be an associative array. @return mixed @throws \Disco\exceptions\DBQuery
[ "Perform", "an", "INSERT", "statement", "." ]
40ff3ea5225810534195494dc6c21083da4d1356
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L239-L244
16,145
discophp/framework
core/classes/PDO.class.php
PDO.delete
public function delete($table, $data, $conjunction = 'AND'){ $keys = array_keys($data); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=:{$key}"; }//foreach $pairs = implode(" {$conjunction} ", $pairs); return $this->query($this->set("DELETE FROM {$table} WHERE {$pairs}",$data)); }
php
public function delete($table, $data, $conjunction = 'AND'){ $keys = array_keys($data); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=:{$key}"; }//foreach $pairs = implode(" {$conjunction} ", $pairs); return $this->query($this->set("DELETE FROM {$table} WHERE {$pairs}",$data)); }
[ "public", "function", "delete", "(", "$", "table", ",", "$", "data", ",", "$", "conjunction", "=", "'AND'", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "data", ")", ";", "$", "pairs", "=", "Array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "pairs", "[", "]", "=", "\"{$key}=:{$key}\"", ";", "}", "//foreach", "$", "pairs", "=", "implode", "(", "\" {$conjunction} \"", ",", "$", "pairs", ")", ";", "return", "$", "this", "->", "query", "(", "$", "this", "->", "set", "(", "\"DELETE FROM {$table} WHERE {$pairs}\"", ",", "$", "data", ")", ")", ";", "}" ]
Perform a DELETE statement. @param string $table The name of the table to delete from. @param array $data The conditions specifying what rows to delete from the table, must be an associative array. @param string $conjunction The conjunction used to form the where condition of the delete statement. Default is `AND`. @return mixed @throws \Disco\exceptions\DBQuery
[ "Perform", "a", "DELETE", "statement", "." ]
40ff3ea5225810534195494dc6c21083da4d1356
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L259-L267
16,146
discophp/framework
core/classes/PDO.class.php
PDO.update
public function update($table, $data, $where, $conjunction = 'AND'){ $values = array_merge(array_values($data),array_values($where)); $keys = array_keys($data); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=?"; }//foreach $pairs = implode(',',$pairs); $keys = array_keys($where); $condition = Array(); foreach($keys as $key){ $condition[] = "{$key}=?"; }//foreach $condition = implode(" {$conjunction} ",$condition); return $this->query($this->set("UPDATE {$table} SET {$pairs} WHERE {$condition}",$values)); }
php
public function update($table, $data, $where, $conjunction = 'AND'){ $values = array_merge(array_values($data),array_values($where)); $keys = array_keys($data); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=?"; }//foreach $pairs = implode(',',$pairs); $keys = array_keys($where); $condition = Array(); foreach($keys as $key){ $condition[] = "{$key}=?"; }//foreach $condition = implode(" {$conjunction} ",$condition); return $this->query($this->set("UPDATE {$table} SET {$pairs} WHERE {$condition}",$values)); }
[ "public", "function", "update", "(", "$", "table", ",", "$", "data", ",", "$", "where", ",", "$", "conjunction", "=", "'AND'", ")", "{", "$", "values", "=", "array_merge", "(", "array_values", "(", "$", "data", ")", ",", "array_values", "(", "$", "where", ")", ")", ";", "$", "keys", "=", "array_keys", "(", "$", "data", ")", ";", "$", "pairs", "=", "Array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "pairs", "[", "]", "=", "\"{$key}=?\"", ";", "}", "//foreach", "$", "pairs", "=", "implode", "(", "','", ",", "$", "pairs", ")", ";", "$", "keys", "=", "array_keys", "(", "$", "where", ")", ";", "$", "condition", "=", "Array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "condition", "[", "]", "=", "\"{$key}=?\"", ";", "}", "//foreach", "$", "condition", "=", "implode", "(", "\" {$conjunction} \"", ",", "$", "condition", ")", ";", "return", "$", "this", "->", "query", "(", "$", "this", "->", "set", "(", "\"UPDATE {$table} SET {$pairs} WHERE {$condition}\"", ",", "$", "values", ")", ")", ";", "}" ]
Perform an UPDATE statement . @param string $table The name of the table to update. @param array $data The data to update the table with, must be an associative array. @param array $where The conditions specifying what rows should be updated in the table, must be an associative array. @param string $conjunction The conjunction used to form the where condition of the update statement. Default is `AND`. @return mixed @throws \Disco\exceptions\DBQuery
[ "Perform", "an", "UPDATE", "statement", "." ]
40ff3ea5225810534195494dc6c21083da4d1356
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L283-L301
16,147
discophp/framework
core/classes/PDO.class.php
PDO.select
public function select($table, $select, $where, $conjunction = 'AND'){ $keys = array_keys($where); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=:{$key}"; }//foreach $pairs = implode(" {$conjunction} ",$pairs); if(is_array($select)){ $select = implode(',',$select); }//if return $this->query($this->set("SELECT {$select} FROM {$table} WHERE {$pairs}",$where)); }
php
public function select($table, $select, $where, $conjunction = 'AND'){ $keys = array_keys($where); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=:{$key}"; }//foreach $pairs = implode(" {$conjunction} ",$pairs); if(is_array($select)){ $select = implode(',',$select); }//if return $this->query($this->set("SELECT {$select} FROM {$table} WHERE {$pairs}",$where)); }
[ "public", "function", "select", "(", "$", "table", ",", "$", "select", ",", "$", "where", ",", "$", "conjunction", "=", "'AND'", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "where", ")", ";", "$", "pairs", "=", "Array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "pairs", "[", "]", "=", "\"{$key}=:{$key}\"", ";", "}", "//foreach", "$", "pairs", "=", "implode", "(", "\" {$conjunction} \"", ",", "$", "pairs", ")", ";", "if", "(", "is_array", "(", "$", "select", ")", ")", "{", "$", "select", "=", "implode", "(", "','", ",", "$", "select", ")", ";", "}", "//if", "return", "$", "this", "->", "query", "(", "$", "this", "->", "set", "(", "\"SELECT {$select} FROM {$table} WHERE {$pairs}\"", ",", "$", "where", ")", ")", ";", "}" ]
Perform a SELECT statement . @param string $table The name of the table to select from. @param string|array $select The fields to select from the table, can be a string of field or an array of fields. @param array $where The conditions specifying what rows should be selected from the table, must be an associative array. @param string $conjunction The conjunction used to form the where condition of the select statement. Default is `AND`. @return mixed @throws \Disco\exceptions\DBQuery
[ "Perform", "a", "SELECT", "statement", "." ]
40ff3ea5225810534195494dc6c21083da4d1356
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L318-L333
16,148
discophp/framework
core/classes/PDO.class.php
PDO.set
public function set($q, $args){ if(is_array($args) && isset($args['raw'])){ $q = implode($args['raw'],explode('?',$q,2));; }//if else if(is_array($args)){ $first = array_keys($args); $first = array_shift($first); if(!is_numeric($first)){ return $this->setAssociativeArrayPlaceHolders($q,$args); }//if return $this->setQuestionMarkPlaceHolders($q,$args); }//if else { $q = implode($this->prepareType($args), explode('?', $q, 2)); }//el return $q; }
php
public function set($q, $args){ if(is_array($args) && isset($args['raw'])){ $q = implode($args['raw'],explode('?',$q,2));; }//if else if(is_array($args)){ $first = array_keys($args); $first = array_shift($first); if(!is_numeric($first)){ return $this->setAssociativeArrayPlaceHolders($q,$args); }//if return $this->setQuestionMarkPlaceHolders($q,$args); }//if else { $q = implode($this->prepareType($args), explode('?', $q, 2)); }//el return $q; }
[ "public", "function", "set", "(", "$", "q", ",", "$", "args", ")", "{", "if", "(", "is_array", "(", "$", "args", ")", "&&", "isset", "(", "$", "args", "[", "'raw'", "]", ")", ")", "{", "$", "q", "=", "implode", "(", "$", "args", "[", "'raw'", "]", ",", "explode", "(", "'?'", ",", "$", "q", ",", "2", ")", ")", ";", ";", "}", "//if", "else", "if", "(", "is_array", "(", "$", "args", ")", ")", "{", "$", "first", "=", "array_keys", "(", "$", "args", ")", ";", "$", "first", "=", "array_shift", "(", "$", "first", ")", ";", "if", "(", "!", "is_numeric", "(", "$", "first", ")", ")", "{", "return", "$", "this", "->", "setAssociativeArrayPlaceHolders", "(", "$", "q", ",", "$", "args", ")", ";", "}", "//if", "return", "$", "this", "->", "setQuestionMarkPlaceHolders", "(", "$", "q", ",", "$", "args", ")", ";", "}", "//if", "else", "{", "$", "q", "=", "implode", "(", "$", "this", "->", "prepareType", "(", "$", "args", ")", ",", "explode", "(", "'?'", ",", "$", "q", ",", "2", ")", ")", ";", "}", "//el", "return", "$", "q", ";", "}" ]
Bind passed variables into a query string and do proper type checking and escaping before binding. @param string $q The query string. @param string|array $args The variables to bind to the $q. @return string The $q with $args bound into it. @throws \Disco\exceptions\DBQuery When the number of arguements doesn't match the numebr of `?` placeholders.
[ "Bind", "passed", "variables", "into", "a", "query", "string", "and", "do", "proper", "type", "checking", "and", "escaping", "before", "binding", "." ]
40ff3ea5225810534195494dc6c21083da4d1356
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L362-L385
16,149
discophp/framework
core/classes/PDO.class.php
PDO.setQuestionMarkPlaceHolders
private function setQuestionMarkPlaceHolders($q, $args){ foreach($args as $k=>$a){ if(is_array($a) && isset($a['raw'])){ $args[$k] = $a['raw']; }//if else { $args[$k] = $this->prepareType($a); }//el }//foreach $positions = Array(); $p = -1; while(($p = strpos($q, '?', $p + 1)) !== false){ $positions[] = $p; }//while if(count($args) != count($positions)){ throw new \Disco\exceptions\DBQuery('Number of passed arguements does not match the number of `?` placeholders'); }//if //reverse em so when we do replacements we dont have //to keep track of the change in length to positions $args = array_reverse($args); $positions = array_reverse($positions); foreach($positions as $k=>$pos){ $q = substr_replace($q,$args[$k],$pos,1); }//foreach return $q; }
php
private function setQuestionMarkPlaceHolders($q, $args){ foreach($args as $k=>$a){ if(is_array($a) && isset($a['raw'])){ $args[$k] = $a['raw']; }//if else { $args[$k] = $this->prepareType($a); }//el }//foreach $positions = Array(); $p = -1; while(($p = strpos($q, '?', $p + 1)) !== false){ $positions[] = $p; }//while if(count($args) != count($positions)){ throw new \Disco\exceptions\DBQuery('Number of passed arguements does not match the number of `?` placeholders'); }//if //reverse em so when we do replacements we dont have //to keep track of the change in length to positions $args = array_reverse($args); $positions = array_reverse($positions); foreach($positions as $k=>$pos){ $q = substr_replace($q,$args[$k],$pos,1); }//foreach return $q; }
[ "private", "function", "setQuestionMarkPlaceHolders", "(", "$", "q", ",", "$", "args", ")", "{", "foreach", "(", "$", "args", "as", "$", "k", "=>", "$", "a", ")", "{", "if", "(", "is_array", "(", "$", "a", ")", "&&", "isset", "(", "$", "a", "[", "'raw'", "]", ")", ")", "{", "$", "args", "[", "$", "k", "]", "=", "$", "a", "[", "'raw'", "]", ";", "}", "//if", "else", "{", "$", "args", "[", "$", "k", "]", "=", "$", "this", "->", "prepareType", "(", "$", "a", ")", ";", "}", "//el", "}", "//foreach", "$", "positions", "=", "Array", "(", ")", ";", "$", "p", "=", "-", "1", ";", "while", "(", "(", "$", "p", "=", "strpos", "(", "$", "q", ",", "'?'", ",", "$", "p", "+", "1", ")", ")", "!==", "false", ")", "{", "$", "positions", "[", "]", "=", "$", "p", ";", "}", "//while", "if", "(", "count", "(", "$", "args", ")", "!=", "count", "(", "$", "positions", ")", ")", "{", "throw", "new", "\\", "Disco", "\\", "exceptions", "\\", "DBQuery", "(", "'Number of passed arguements does not match the number of `?` placeholders'", ")", ";", "}", "//if", "//reverse em so when we do replacements we dont have ", "//to keep track of the change in length to positions", "$", "args", "=", "array_reverse", "(", "$", "args", ")", ";", "$", "positions", "=", "array_reverse", "(", "$", "positions", ")", ";", "foreach", "(", "$", "positions", "as", "$", "k", "=>", "$", "pos", ")", "{", "$", "q", "=", "substr_replace", "(", "$", "q", ",", "$", "args", "[", "$", "k", "]", ",", "$", "pos", ",", "1", ")", ";", "}", "//foreach", "return", "$", "q", ";", "}" ]
Set `?` mark value placeholders with the values passed in args in the order they are set in the query and the args. @param string $q The query string. @param string|array $args The variables to bind to the $q. @return string The $q with $args bound into it. @throws \Disco\exceptions\DBQuery When the number of arguements doesn't match the numebr of `?` placeholders.
[ "Set", "?", "mark", "value", "placeholders", "with", "the", "values", "passed", "in", "args", "in", "the", "order", "they", "are", "set", "in", "the", "query", "and", "the", "args", "." ]
40ff3ea5225810534195494dc6c21083da4d1356
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L448-L482
16,150
discophp/framework
core/classes/PDO.class.php
PDO.prepareType
private function prepareType($arg){ if(($arg===null || $arg=='null') && $arg !== 0){ return 'NULL'; }//if if(!is_numeric($arg)){ return $this->quote($arg); }//if return $arg; }
php
private function prepareType($arg){ if(($arg===null || $arg=='null') && $arg !== 0){ return 'NULL'; }//if if(!is_numeric($arg)){ return $this->quote($arg); }//if return $arg; }
[ "private", "function", "prepareType", "(", "$", "arg", ")", "{", "if", "(", "(", "$", "arg", "===", "null", "||", "$", "arg", "==", "'null'", ")", "&&", "$", "arg", "!==", "0", ")", "{", "return", "'NULL'", ";", "}", "//if", "if", "(", "!", "is_numeric", "(", "$", "arg", ")", ")", "{", "return", "$", "this", "->", "quote", "(", "$", "arg", ")", ";", "}", "//if", "return", "$", "arg", ";", "}" ]
Determine the type of variable being bound into the query, either a String or Numeric. @param string|int|float $arg The variable to prepare. @return string|int|float The $arg prepared.
[ "Determine", "the", "type", "of", "variable", "being", "bound", "into", "the", "query", "either", "a", "String", "or", "Numeric", "." ]
40ff3ea5225810534195494dc6c21083da4d1356
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L493-L501
16,151
pipelinersales/pipeliner-php-sdk
src/PipelinerSales/ApiClient/PipelinerClient.php
PipelinerClient.create
public static function create($url, $pipelineId, $apiToken, $password) { $baseUrl = $url . '/rest_services/v1/' . $pipelineId; $httpClient = new CurlHttpClient(); $httpClient->setUserCredentials($apiToken, $password); $dateTimeFormat = Defaults::DATE_FORMAT; $repoFactory = new RestRepositoryFactory($baseUrl, $httpClient, $dateTimeFormat); $infoMethods = new RestInfoMethods($baseUrl, $httpClient); $entityTypes = array_flip($infoMethods->fetchEntityPublic()); $client = new PipelinerClient($entityTypes, $repoFactory, $infoMethods); return $client; }
php
public static function create($url, $pipelineId, $apiToken, $password) { $baseUrl = $url . '/rest_services/v1/' . $pipelineId; $httpClient = new CurlHttpClient(); $httpClient->setUserCredentials($apiToken, $password); $dateTimeFormat = Defaults::DATE_FORMAT; $repoFactory = new RestRepositoryFactory($baseUrl, $httpClient, $dateTimeFormat); $infoMethods = new RestInfoMethods($baseUrl, $httpClient); $entityTypes = array_flip($infoMethods->fetchEntityPublic()); $client = new PipelinerClient($entityTypes, $repoFactory, $infoMethods); return $client; }
[ "public", "static", "function", "create", "(", "$", "url", ",", "$", "pipelineId", ",", "$", "apiToken", ",", "$", "password", ")", "{", "$", "baseUrl", "=", "$", "url", ".", "'/rest_services/v1/'", ".", "$", "pipelineId", ";", "$", "httpClient", "=", "new", "CurlHttpClient", "(", ")", ";", "$", "httpClient", "->", "setUserCredentials", "(", "$", "apiToken", ",", "$", "password", ")", ";", "$", "dateTimeFormat", "=", "Defaults", "::", "DATE_FORMAT", ";", "$", "repoFactory", "=", "new", "RestRepositoryFactory", "(", "$", "baseUrl", ",", "$", "httpClient", ",", "$", "dateTimeFormat", ")", ";", "$", "infoMethods", "=", "new", "RestInfoMethods", "(", "$", "baseUrl", ",", "$", "httpClient", ")", ";", "$", "entityTypes", "=", "array_flip", "(", "$", "infoMethods", "->", "fetchEntityPublic", "(", ")", ")", ";", "$", "client", "=", "new", "PipelinerClient", "(", "$", "entityTypes", ",", "$", "repoFactory", ",", "$", "infoMethods", ")", ";", "return", "$", "client", ";", "}" ]
Creates a PipelinerClient object with sensible default configuration. Will perform a HTTP request to fetch the existing entity types for the pipeline. @param string $url base url of the REST server, without the trailing slash @param string $pipelineId the unique team pipeline id @param string $apiToken API token @param string $password API password @return PipelinerClient @throws PipelinerClientException when trying to use an unsupported pipeline version @throws PipelinerHttpException if fetching the pipeline version fails
[ "Creates", "a", "PipelinerClient", "object", "with", "sensible", "default", "configuration", ".", "Will", "perform", "a", "HTTP", "request", "to", "fetch", "the", "existing", "entity", "types", "for", "the", "pipeline", "." ]
a020149ffde815be17634542010814cf854c3d5f
https://github.com/pipelinersales/pipeliner-php-sdk/blob/a020149ffde815be17634542010814cf854c3d5f/src/PipelinerSales/ApiClient/PipelinerClient.php#L97-L112
16,152
pipelinersales/pipeliner-php-sdk
src/PipelinerSales/ApiClient/PipelinerClient.php
PipelinerClient.getRepository
public function getRepository($entityName) { if ($entityName instanceof Entity) { $entityName = $entityName->getType(); } if (!isset($this->repositories[$entityName])) { $plural = $this->getCollectionName($entityName); $this->repositories[$entityName] = $this->repositoryFactory->createRepository( $entityName, $plural ); } return $this->repositories[$entityName]; }
php
public function getRepository($entityName) { if ($entityName instanceof Entity) { $entityName = $entityName->getType(); } if (!isset($this->repositories[$entityName])) { $plural = $this->getCollectionName($entityName); $this->repositories[$entityName] = $this->repositoryFactory->createRepository( $entityName, $plural ); } return $this->repositories[$entityName]; }
[ "public", "function", "getRepository", "(", "$", "entityName", ")", "{", "if", "(", "$", "entityName", "instanceof", "Entity", ")", "{", "$", "entityName", "=", "$", "entityName", "->", "getType", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "repositories", "[", "$", "entityName", "]", ")", ")", "{", "$", "plural", "=", "$", "this", "->", "getCollectionName", "(", "$", "entityName", ")", ";", "$", "this", "->", "repositories", "[", "$", "entityName", "]", "=", "$", "this", "->", "repositoryFactory", "->", "createRepository", "(", "$", "entityName", ",", "$", "plural", ")", ";", "}", "return", "$", "this", "->", "repositories", "[", "$", "entityName", "]", ";", "}" ]
Returns a repository for the specified entity. @param mixed $entityName an {@see Entity} object or entity name, can be both singular (Account) and plural (Accounts) @return RepositoryInterface
[ "Returns", "a", "repository", "for", "the", "specified", "entity", "." ]
a020149ffde815be17634542010814cf854c3d5f
https://github.com/pipelinersales/pipeliner-php-sdk/blob/a020149ffde815be17634542010814cf854c3d5f/src/PipelinerSales/ApiClient/PipelinerClient.php#L152-L167
16,153
discophp/framework
core/twig/tag/PageTokenParser.php
PageTokenParser.parse
public function parse(\Twig_Token $token) { $lineno = $token->getLine(); $nodes['criteria'] = $this->parser->getExpressionParser()->parseExpression(); $this->parser->getStream()->expect('as'); $targets = $this->parser->getExpressionParser()->parseAssignmentExpression(); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $nodes['body'] = $this->parser->subparse(array($this, 'endOfTag'), true); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $elementsTarget = $targets->getNode(0); $nodes['elementsTarget'] = new \Twig_Node_Expression_AssignName($elementsTarget->getAttribute('name'), $elementsTarget->getLine()); return new PageNode($nodes, array(), $lineno, $this->getTag()); }
php
public function parse(\Twig_Token $token) { $lineno = $token->getLine(); $nodes['criteria'] = $this->parser->getExpressionParser()->parseExpression(); $this->parser->getStream()->expect('as'); $targets = $this->parser->getExpressionParser()->parseAssignmentExpression(); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $nodes['body'] = $this->parser->subparse(array($this, 'endOfTag'), true); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $elementsTarget = $targets->getNode(0); $nodes['elementsTarget'] = new \Twig_Node_Expression_AssignName($elementsTarget->getAttribute('name'), $elementsTarget->getLine()); return new PageNode($nodes, array(), $lineno, $this->getTag()); }
[ "public", "function", "parse", "(", "\\", "Twig_Token", "$", "token", ")", "{", "$", "lineno", "=", "$", "token", "->", "getLine", "(", ")", ";", "$", "nodes", "[", "'criteria'", "]", "=", "$", "this", "->", "parser", "->", "getExpressionParser", "(", ")", "->", "parseExpression", "(", ")", ";", "$", "this", "->", "parser", "->", "getStream", "(", ")", "->", "expect", "(", "'as'", ")", ";", "$", "targets", "=", "$", "this", "->", "parser", "->", "getExpressionParser", "(", ")", "->", "parseAssignmentExpression", "(", ")", ";", "$", "this", "->", "parser", "->", "getStream", "(", ")", "->", "expect", "(", "\\", "Twig_Token", "::", "BLOCK_END_TYPE", ")", ";", "$", "nodes", "[", "'body'", "]", "=", "$", "this", "->", "parser", "->", "subparse", "(", "array", "(", "$", "this", ",", "'endOfTag'", ")", ",", "true", ")", ";", "$", "this", "->", "parser", "->", "getStream", "(", ")", "->", "expect", "(", "\\", "Twig_Token", "::", "BLOCK_END_TYPE", ")", ";", "$", "elementsTarget", "=", "$", "targets", "->", "getNode", "(", "0", ")", ";", "$", "nodes", "[", "'elementsTarget'", "]", "=", "new", "\\", "Twig_Node_Expression_AssignName", "(", "$", "elementsTarget", "->", "getAttribute", "(", "'name'", ")", ",", "$", "elementsTarget", "->", "getLine", "(", ")", ")", ";", "return", "new", "PageNode", "(", "$", "nodes", ",", "array", "(", ")", ",", "$", "lineno", ",", "$", "this", "->", "getTag", "(", ")", ")", ";", "}" ]
Define how our page tag should be parsed. @param \Twig_Token $token An instance of a \Twig_Token. @return \Disco\twig\PageNode
[ "Define", "how", "our", "page", "tag", "should", "be", "parsed", "." ]
40ff3ea5225810534195494dc6c21083da4d1356
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/twig/tag/PageTokenParser.php#L20-L37
16,154
datasift/datasift-php
lib/DataSift/ApiClient.php
DataSift_ApiClient.initialize
private static function initialize($method, $ssl, $url, $headers, $params, $userAgent, $qs, $raw = false) { $ch = curl_init(); switch (strtolower($method)) { case 'post': curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, ($raw ? $params : json_encode($params))); break; case 'get': curl_setopt($ch, CURLOPT_HTTPGET, true); break; case 'put': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); break; case 'delete': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; default: throw new DataSift_Exception_NotYetImplemented('Method not of valid type'); } $url = self::appendQueryString($url, $qs); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); if ($ssl) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2'); } return $ch; }
php
private static function initialize($method, $ssl, $url, $headers, $params, $userAgent, $qs, $raw = false) { $ch = curl_init(); switch (strtolower($method)) { case 'post': curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, ($raw ? $params : json_encode($params))); break; case 'get': curl_setopt($ch, CURLOPT_HTTPGET, true); break; case 'put': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); break; case 'delete': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; default: throw new DataSift_Exception_NotYetImplemented('Method not of valid type'); } $url = self::appendQueryString($url, $qs); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); if ($ssl) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2'); } return $ch; }
[ "private", "static", "function", "initialize", "(", "$", "method", ",", "$", "ssl", ",", "$", "url", ",", "$", "headers", ",", "$", "params", ",", "$", "userAgent", ",", "$", "qs", ",", "$", "raw", "=", "false", ")", "{", "$", "ch", "=", "curl_init", "(", ")", ";", "switch", "(", "strtolower", "(", "$", "method", ")", ")", "{", "case", "'post'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "(", "$", "raw", "?", "$", "params", ":", "json_encode", "(", "$", "params", ")", ")", ")", ";", "break", ";", "case", "'get'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPGET", ",", "true", ")", ";", "break", ";", "case", "'put'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "'PUT'", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "json_encode", "(", "$", "params", ")", ")", ";", "break", ";", "case", "'delete'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "'DELETE'", ")", ";", "break", ";", "default", ":", "throw", "new", "DataSift_Exception_NotYetImplemented", "(", "'Method not of valid type'", ")", ";", "}", "$", "url", "=", "self", "::", "appendQueryString", "(", "$", "url", ",", "$", "qs", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "$", "headers", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "$", "userAgent", ")", ";", "if", "(", "$", "ssl", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYHOST", ",", "2", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSLVERSION", ",", "'CURL_SSLVERSION_TLSv1_2'", ")", ";", "}", "return", "$", "ch", ";", "}" ]
Initalize the cURL connection. @param string $method The HTTP method to use. @param boolean $ssl Is SSL Enabled. @param string $url The URL of the call. @param array $headers The headers to be sent. @param array $params The parameters to be passed along with the request. @param string $userAgent The HTTP User-Agent header. @return resource The cURL resource @throws DataSift_Exception_NotYetImplemented
[ "Initalize", "the", "cURL", "connection", "." ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/ApiClient.php#L117-L155
16,155
datasift/datasift-php
lib/DataSift/ApiClient.php
DataSift_ApiClient.decodeBody
protected static function decodeBody(array $res) { $format = isset($res['headers']['x-datasift-format']) ? $res['headers']['x-datasift-format'] : $res['headers']['content-type']; $retval = array(); if (strtolower($format) == 'json_new_line') { foreach (explode("\n", $res['body']) as $json_string) { $retval[] = json_decode($json_string, true); } } else { $retval = json_decode($res['body'], true); } return $retval; }
php
protected static function decodeBody(array $res) { $format = isset($res['headers']['x-datasift-format']) ? $res['headers']['x-datasift-format'] : $res['headers']['content-type']; $retval = array(); if (strtolower($format) == 'json_new_line') { foreach (explode("\n", $res['body']) as $json_string) { $retval[] = json_decode($json_string, true); } } else { $retval = json_decode($res['body'], true); } return $retval; }
[ "protected", "static", "function", "decodeBody", "(", "array", "$", "res", ")", "{", "$", "format", "=", "isset", "(", "$", "res", "[", "'headers'", "]", "[", "'x-datasift-format'", "]", ")", "?", "$", "res", "[", "'headers'", "]", "[", "'x-datasift-format'", "]", ":", "$", "res", "[", "'headers'", "]", "[", "'content-type'", "]", ";", "$", "retval", "=", "array", "(", ")", ";", "if", "(", "strtolower", "(", "$", "format", ")", "==", "'json_new_line'", ")", "{", "foreach", "(", "explode", "(", "\"\\n\"", ",", "$", "res", "[", "'body'", "]", ")", "as", "$", "json_string", ")", "{", "$", "retval", "[", "]", "=", "json_decode", "(", "$", "json_string", ",", "true", ")", ";", "}", "}", "else", "{", "$", "retval", "=", "json_decode", "(", "$", "res", "[", "'body'", "]", ",", "true", ")", ";", "}", "return", "$", "retval", ";", "}" ]
Decode the JSON response depending on the format. @param array $res The parsed HTTP response. @return array An array of the decoded JSON response
[ "Decode", "the", "JSON", "response", "depending", "on", "the", "format", "." ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/ApiClient.php#L173-L189
16,156
datasift/datasift-php
lib/DataSift/ApiClient.php
DataSift_ApiClient.parseHTTPResponse
private static function parseHTTPResponse($str) { $retval = array( 'headers' => array(), 'body' => '', ); $lastfield = false; $fields = explode("\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $str)); foreach ($fields as $field) { if (strlen(trim($field)) == 0) { $lastfield = ':body'; } elseif ($lastfield == ':body') { $retval['body'] .= $field . "\n"; } else { if (($field[0] == ' ' or $field[0] == "\t") and $lastfield !== false) { $retval['headers'][$lastfield] .= ' ' . $field; } elseif (preg_match('/([^:]+): (.+)/m', $field, $match)) { $match[1] = strtolower($match[1]); if (isset($retval['headers'][$match[1]])) { if (is_array($retval['headers'][$match[1]])) { $retval['headers'][$match[1]][] = $match[2]; } else { $retval['headers'][$match[1]] = array($retval['headers'][$match[1]], $match[2]); } } else { $retval['headers'][$match[1]] = trim($match[2]); } } } } return $retval; }
php
private static function parseHTTPResponse($str) { $retval = array( 'headers' => array(), 'body' => '', ); $lastfield = false; $fields = explode("\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $str)); foreach ($fields as $field) { if (strlen(trim($field)) == 0) { $lastfield = ':body'; } elseif ($lastfield == ':body') { $retval['body'] .= $field . "\n"; } else { if (($field[0] == ' ' or $field[0] == "\t") and $lastfield !== false) { $retval['headers'][$lastfield] .= ' ' . $field; } elseif (preg_match('/([^:]+): (.+)/m', $field, $match)) { $match[1] = strtolower($match[1]); if (isset($retval['headers'][$match[1]])) { if (is_array($retval['headers'][$match[1]])) { $retval['headers'][$match[1]][] = $match[2]; } else { $retval['headers'][$match[1]] = array($retval['headers'][$match[1]], $match[2]); } } else { $retval['headers'][$match[1]] = trim($match[2]); } } } } return $retval; }
[ "private", "static", "function", "parseHTTPResponse", "(", "$", "str", ")", "{", "$", "retval", "=", "array", "(", "'headers'", "=>", "array", "(", ")", ",", "'body'", "=>", "''", ",", ")", ";", "$", "lastfield", "=", "false", ";", "$", "fields", "=", "explode", "(", "\"\\n\"", ",", "preg_replace", "(", "'/\\x0D\\x0A[\\x09\\x20]+/'", ",", "' '", ",", "$", "str", ")", ")", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "if", "(", "strlen", "(", "trim", "(", "$", "field", ")", ")", "==", "0", ")", "{", "$", "lastfield", "=", "':body'", ";", "}", "elseif", "(", "$", "lastfield", "==", "':body'", ")", "{", "$", "retval", "[", "'body'", "]", ".=", "$", "field", ".", "\"\\n\"", ";", "}", "else", "{", "if", "(", "(", "$", "field", "[", "0", "]", "==", "' '", "or", "$", "field", "[", "0", "]", "==", "\"\\t\"", ")", "and", "$", "lastfield", "!==", "false", ")", "{", "$", "retval", "[", "'headers'", "]", "[", "$", "lastfield", "]", ".=", "' '", ".", "$", "field", ";", "}", "elseif", "(", "preg_match", "(", "'/([^:]+): (.+)/m'", ",", "$", "field", ",", "$", "match", ")", ")", "{", "$", "match", "[", "1", "]", "=", "strtolower", "(", "$", "match", "[", "1", "]", ")", ";", "if", "(", "isset", "(", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", ")", ")", "{", "if", "(", "is_array", "(", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", ")", ")", "{", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", "[", "]", "=", "$", "match", "[", "2", "]", ";", "}", "else", "{", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", "=", "array", "(", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", ",", "$", "match", "[", "2", "]", ")", ";", "}", "}", "else", "{", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", "=", "trim", "(", "$", "match", "[", "2", "]", ")", ";", "}", "}", "}", "}", "return", "$", "retval", ";", "}" ]
Parse an HTTP response. Separates the headers from the body and puts the headers into an associative array. @param string $str The HTTP response to be parsed. @return array An array containing headers => array(header => value), and body.
[ "Parse", "an", "HTTP", "response", ".", "Separates", "the", "headers", "from", "the", "body", "and", "puts", "the", "headers", "into", "an", "associative", "array", "." ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/ApiClient.php#L199-L231
16,157
ftrrtf/FtrrtfRollbarBundle
EventListener/RollbarListener.php
RollbarListener.onKernelRequest
public function onKernelRequest(GetResponseEvent $event) { $this->errorHandler->registerErrorHandler($this->notifier); $this->errorHandler->registerShutdownHandler($this->notifier); }
php
public function onKernelRequest(GetResponseEvent $event) { $this->errorHandler->registerErrorHandler($this->notifier); $this->errorHandler->registerShutdownHandler($this->notifier); }
[ "public", "function", "onKernelRequest", "(", "GetResponseEvent", "$", "event", ")", "{", "$", "this", "->", "errorHandler", "->", "registerErrorHandler", "(", "$", "this", "->", "notifier", ")", ";", "$", "this", "->", "errorHandler", "->", "registerShutdownHandler", "(", "$", "this", "->", "notifier", ")", ";", "}" ]
Register error handler. @param GetResponseEvent $event
[ "Register", "error", "handler", "." ]
64c75862b80a4a1ed9e98c0d217003e84df40dd7
https://github.com/ftrrtf/FtrrtfRollbarBundle/blob/64c75862b80a4a1ed9e98c0d217003e84df40dd7/EventListener/RollbarListener.php#L88-L92
16,158
ftrrtf/FtrrtfRollbarBundle
EventListener/RollbarListener.php
RollbarListener.onKernelException
public function onKernelException(GetResponseForExceptionEvent $event) { // Skip HTTP exception if ($event->getException() instanceof HttpException) { return; } $this->setException($event->getException()); }
php
public function onKernelException(GetResponseForExceptionEvent $event) { // Skip HTTP exception if ($event->getException() instanceof HttpException) { return; } $this->setException($event->getException()); }
[ "public", "function", "onKernelException", "(", "GetResponseForExceptionEvent", "$", "event", ")", "{", "// Skip HTTP exception", "if", "(", "$", "event", "->", "getException", "(", ")", "instanceof", "HttpException", ")", "{", "return", ";", "}", "$", "this", "->", "setException", "(", "$", "event", "->", "getException", "(", ")", ")", ";", "}" ]
Save exception. @param GetResponseForExceptionEvent $event
[ "Save", "exception", "." ]
64c75862b80a4a1ed9e98c0d217003e84df40dd7
https://github.com/ftrrtf/FtrrtfRollbarBundle/blob/64c75862b80a4a1ed9e98c0d217003e84df40dd7/EventListener/RollbarListener.php#L99-L107
16,159
ftrrtf/FtrrtfRollbarBundle
EventListener/RollbarListener.php
RollbarListener.onKernelResponse
public function onKernelResponse(FilterResponseEvent $event) { if ($this->getException()) { $this->notifier->reportException($this->getException()); $this->setException(null); } }
php
public function onKernelResponse(FilterResponseEvent $event) { if ($this->getException()) { $this->notifier->reportException($this->getException()); $this->setException(null); } }
[ "public", "function", "onKernelResponse", "(", "FilterResponseEvent", "$", "event", ")", "{", "if", "(", "$", "this", "->", "getException", "(", ")", ")", "{", "$", "this", "->", "notifier", "->", "reportException", "(", "$", "this", "->", "getException", "(", ")", ")", ";", "$", "this", "->", "setException", "(", "null", ")", ";", "}", "}" ]
Wrap exception with additional info. @param FilterResponseEvent $event
[ "Wrap", "exception", "with", "additional", "info", "." ]
64c75862b80a4a1ed9e98c0d217003e84df40dd7
https://github.com/ftrrtf/FtrrtfRollbarBundle/blob/64c75862b80a4a1ed9e98c0d217003e84df40dd7/EventListener/RollbarListener.php#L130-L136
16,160
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.setTheme
public function setTheme(DataSourceViewInterface $dataSource, $theme, array $vars = []) { $this->themes[$dataSource->getName()] = ($theme instanceof Twig_Template) ? $theme : $this->environment->loadTemplate($theme); $this->themesVars[$dataSource->getName()] = $vars; }
php
public function setTheme(DataSourceViewInterface $dataSource, $theme, array $vars = []) { $this->themes[$dataSource->getName()] = ($theme instanceof Twig_Template) ? $theme : $this->environment->loadTemplate($theme); $this->themesVars[$dataSource->getName()] = $vars; }
[ "public", "function", "setTheme", "(", "DataSourceViewInterface", "$", "dataSource", ",", "$", "theme", ",", "array", "$", "vars", "=", "[", "]", ")", "{", "$", "this", "->", "themes", "[", "$", "dataSource", "->", "getName", "(", ")", "]", "=", "(", "$", "theme", "instanceof", "Twig_Template", ")", "?", "$", "theme", ":", "$", "this", "->", "environment", "->", "loadTemplate", "(", "$", "theme", ")", ";", "$", "this", "->", "themesVars", "[", "$", "dataSource", "->", "getName", "(", ")", "]", "=", "$", "vars", ";", "}" ]
Set theme for specific DataSource. Theme is nothing more than twig template that contains some or all of blocks required to render DataSource. @param DataSourceViewInterface $dataSource @param $theme @param array $vars
[ "Set", "theme", "for", "specific", "DataSource", ".", "Theme", "is", "nothing", "more", "than", "twig", "template", "that", "contains", "some", "or", "all", "of", "blocks", "required", "to", "render", "DataSource", "." ]
06964672c838af9f4125065e3a90b2df4e8aa077
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L118-L124
16,161
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.setRoute
public function setRoute(DataSourceViewInterface $dataSource, $route, array $additional_parameters = []) { $this->routes[$dataSource->getName()] = $route; $this->additional_parameters[$dataSource->getName()] = $additional_parameters; }
php
public function setRoute(DataSourceViewInterface $dataSource, $route, array $additional_parameters = []) { $this->routes[$dataSource->getName()] = $route; $this->additional_parameters[$dataSource->getName()] = $additional_parameters; }
[ "public", "function", "setRoute", "(", "DataSourceViewInterface", "$", "dataSource", ",", "$", "route", ",", "array", "$", "additional_parameters", "=", "[", "]", ")", "{", "$", "this", "->", "routes", "[", "$", "dataSource", "->", "getName", "(", ")", "]", "=", "$", "route", ";", "$", "this", "->", "additional_parameters", "[", "$", "dataSource", "->", "getName", "(", ")", "]", "=", "$", "additional_parameters", ";", "}" ]
Set route and optionally additional parameters for specific DataSource. @param DataSourceViewInterface $dataSource @param $route @param array $additional_parameters
[ "Set", "route", "and", "optionally", "additional", "parameters", "for", "specific", "DataSource", "." ]
06964672c838af9f4125065e3a90b2df4e8aa077
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L133-L137
16,162
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.resolveMaxResultsOptions
private function resolveMaxResultsOptions(array $options, DataSourceViewInterface $dataSource) { $optionsResolver = new OptionsResolver(); $optionsResolver ->setDefaults([ 'route' => $this->getCurrentRoute($dataSource), 'active_class' => 'active', 'additional_parameters' => [], 'results' => [5, 10, 20, 50, 100] ]) ->setAllowedTypes('route', 'string') ->setAllowedTypes('active_class', 'string') ->setAllowedTypes('additional_parameters', 'array') ->setAllowedTypes('results', 'array'); return $optionsResolver->resolve($options); }
php
private function resolveMaxResultsOptions(array $options, DataSourceViewInterface $dataSource) { $optionsResolver = new OptionsResolver(); $optionsResolver ->setDefaults([ 'route' => $this->getCurrentRoute($dataSource), 'active_class' => 'active', 'additional_parameters' => [], 'results' => [5, 10, 20, 50, 100] ]) ->setAllowedTypes('route', 'string') ->setAllowedTypes('active_class', 'string') ->setAllowedTypes('additional_parameters', 'array') ->setAllowedTypes('results', 'array'); return $optionsResolver->resolve($options); }
[ "private", "function", "resolveMaxResultsOptions", "(", "array", "$", "options", ",", "DataSourceViewInterface", "$", "dataSource", ")", "{", "$", "optionsResolver", "=", "new", "OptionsResolver", "(", ")", ";", "$", "optionsResolver", "->", "setDefaults", "(", "[", "'route'", "=>", "$", "this", "->", "getCurrentRoute", "(", "$", "dataSource", ")", ",", "'active_class'", "=>", "'active'", ",", "'additional_parameters'", "=>", "[", "]", ",", "'results'", "=>", "[", "5", ",", "10", ",", "20", ",", "50", ",", "100", "]", "]", ")", "->", "setAllowedTypes", "(", "'route'", ",", "'string'", ")", "->", "setAllowedTypes", "(", "'active_class'", ",", "'string'", ")", "->", "setAllowedTypes", "(", "'additional_parameters'", ",", "'array'", ")", "->", "setAllowedTypes", "(", "'results'", ",", "'array'", ")", ";", "return", "$", "optionsResolver", "->", "resolve", "(", "$", "options", ")", ";", "}" ]
Validate and resolve options passed in Twig to datasource_results_per_page_widget @param array $options @return array
[ "Validate", "and", "resolve", "options", "passed", "in", "Twig", "to", "datasource_results_per_page_widget" ]
06964672c838af9f4125065e3a90b2df4e8aa077
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L333-L349
16,163
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.getTemplates
private function getTemplates(DataSourceViewInterface $dataSource) { $templates = []; if (isset($this->themes[$dataSource->getName()])) { $templates[] = $this->themes[$dataSource->getName()]; } $templates[] = $this->themes[self::DEFAULT_THEME]; return $templates; }
php
private function getTemplates(DataSourceViewInterface $dataSource) { $templates = []; if (isset($this->themes[$dataSource->getName()])) { $templates[] = $this->themes[$dataSource->getName()]; } $templates[] = $this->themes[self::DEFAULT_THEME]; return $templates; }
[ "private", "function", "getTemplates", "(", "DataSourceViewInterface", "$", "dataSource", ")", "{", "$", "templates", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "themes", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ")", ")", "{", "$", "templates", "[", "]", "=", "$", "this", "->", "themes", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ";", "}", "$", "templates", "[", "]", "=", "$", "this", "->", "themes", "[", "self", "::", "DEFAULT_THEME", "]", ";", "return", "$", "templates", ";", "}" ]
Return list of templates that might be useful to render DataSourceView. Always the last template will be default one. @param DataSourceViewInterface $dataSource @return array
[ "Return", "list", "of", "templates", "that", "might", "be", "useful", "to", "render", "DataSourceView", ".", "Always", "the", "last", "template", "will", "be", "default", "one", "." ]
06964672c838af9f4125065e3a90b2df4e8aa077
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L409-L420
16,164
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.getVars
private function getVars(DataSourceViewInterface $dataSource) { return isset($this->themesVars[$dataSource->getName()]) ? $this->themesVars[$dataSource->getName()] : [] ; }
php
private function getVars(DataSourceViewInterface $dataSource) { return isset($this->themesVars[$dataSource->getName()]) ? $this->themesVars[$dataSource->getName()] : [] ; }
[ "private", "function", "getVars", "(", "DataSourceViewInterface", "$", "dataSource", ")", "{", "return", "isset", "(", "$", "this", "->", "themesVars", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ")", "?", "$", "this", "->", "themesVars", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ":", "[", "]", ";", "}" ]
Return vars passed to theme. Those vars will be added to block context. @param DataSourceViewInterface $dataSource @return array
[ "Return", "vars", "passed", "to", "theme", ".", "Those", "vars", "will", "be", "added", "to", "block", "context", "." ]
06964672c838af9f4125065e3a90b2df4e8aa077
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L428-L434
16,165
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.getUrl
private function getUrl(DataSourceViewInterface $dataSource, array $options = [], array $parameters = []) { $router = $this->container->get('router'); return $router->generate( $options['route'], array_merge( isset($this->additional_parameters[$dataSource->getName()]) ? $this->additional_parameters[$dataSource->getName()] : [], isset($options['additional_parameters']) ? $options['additional_parameters'] : [], $parameters ) ); }
php
private function getUrl(DataSourceViewInterface $dataSource, array $options = [], array $parameters = []) { $router = $this->container->get('router'); return $router->generate( $options['route'], array_merge( isset($this->additional_parameters[$dataSource->getName()]) ? $this->additional_parameters[$dataSource->getName()] : [], isset($options['additional_parameters']) ? $options['additional_parameters'] : [], $parameters ) ); }
[ "private", "function", "getUrl", "(", "DataSourceViewInterface", "$", "dataSource", ",", "array", "$", "options", "=", "[", "]", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "$", "router", "=", "$", "this", "->", "container", "->", "get", "(", "'router'", ")", ";", "return", "$", "router", "->", "generate", "(", "$", "options", "[", "'route'", "]", ",", "array_merge", "(", "isset", "(", "$", "this", "->", "additional_parameters", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ")", "?", "$", "this", "->", "additional_parameters", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ":", "[", "]", ",", "isset", "(", "$", "options", "[", "'additional_parameters'", "]", ")", "?", "$", "options", "[", "'additional_parameters'", "]", ":", "[", "]", ",", "$", "parameters", ")", ")", ";", "}" ]
Return additional parameters that should be passed to the URL generation for specified datasource. @param DataSourceViewInterface $dataSource @return array
[ "Return", "additional", "parameters", "that", "should", "be", "passed", "to", "the", "URL", "generation", "for", "specified", "datasource", "." ]
06964672c838af9f4125065e3a90b2df4e8aa077
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L442-L458
16,166
drpdigital/json-api-parser
src/Str.php
Str.snakeCase
public static function snakeCase($value) { if (! ctype_lower($value)) { $value = preg_replace('/\s+/u', '', ucwords($value)); $value = preg_replace('/-/u', '_', $value); $value = mb_strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1_', $value), 'UTF-8'); } return $value; }
php
public static function snakeCase($value) { if (! ctype_lower($value)) { $value = preg_replace('/\s+/u', '', ucwords($value)); $value = preg_replace('/-/u', '_', $value); $value = mb_strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1_', $value), 'UTF-8'); } return $value; }
[ "public", "static", "function", "snakeCase", "(", "$", "value", ")", "{", "if", "(", "!", "ctype_lower", "(", "$", "value", ")", ")", "{", "$", "value", "=", "preg_replace", "(", "'/\\s+/u'", ",", "''", ",", "ucwords", "(", "$", "value", ")", ")", ";", "$", "value", "=", "preg_replace", "(", "'/-/u'", ",", "'_'", ",", "$", "value", ")", ";", "$", "value", "=", "mb_strtolower", "(", "preg_replace", "(", "'/(.)(?=[A-Z])/u'", ",", "'$1_'", ",", "$", "value", ")", ",", "'UTF-8'", ")", ";", "}", "return", "$", "value", ";", "}" ]
Convert given input into snake case. @param string $value @return string
[ "Convert", "given", "input", "into", "snake", "case", "." ]
b1ceefc0c19ec326129126253114c121e97ca943
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/Str.php#L13-L23
16,167
jasny/router
src/Router/Helper/NotFound.php
NotFound.notFound
protected function notFound(ServerRequestInterface $request, ResponseInterface $response) { $finalResponse = $response ->withProtocolVersion($request->getProtocolVersion()) ->withStatus(404) ->withHeader('Content-Type', 'text/plain'); $finalResponse->getBody()->write("Not found"); return $finalResponse; }
php
protected function notFound(ServerRequestInterface $request, ResponseInterface $response) { $finalResponse = $response ->withProtocolVersion($request->getProtocolVersion()) ->withStatus(404) ->withHeader('Content-Type', 'text/plain'); $finalResponse->getBody()->write("Not found"); return $finalResponse; }
[ "protected", "function", "notFound", "(", "ServerRequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "finalResponse", "=", "$", "response", "->", "withProtocolVersion", "(", "$", "request", "->", "getProtocolVersion", "(", ")", ")", "->", "withStatus", "(", "404", ")", "->", "withHeader", "(", "'Content-Type'", ",", "'text/plain'", ")", ";", "$", "finalResponse", "->", "getBody", "(", ")", "->", "write", "(", "\"Not found\"", ")", ";", "return", "$", "finalResponse", ";", "}" ]
Return with a 404 not found response @param ServerRequestInterface $request @param ResponseInterface $response @return ResponseInterface
[ "Return", "with", "a", "404", "not", "found", "response" ]
4c776665ba343150b442c21893946e3d54190896
https://github.com/jasny/router/blob/4c776665ba343150b442c21893946e3d54190896/src/Router/Helper/NotFound.php#L20-L30
16,168
chriswoodford/foursquare-php
lib/TheTwelve/Foursquare/AuthenticationGateway.php
AuthenticationGateway.initiateLogin
public function initiateLogin() { if (!$this->canInitiateLogin()) { throw new \RuntimeException( 'Unable to initiate login' ); } $uri = $this->getAuthenticationUri(); return $this->redirector->redirect($uri); }
php
public function initiateLogin() { if (!$this->canInitiateLogin()) { throw new \RuntimeException( 'Unable to initiate login' ); } $uri = $this->getAuthenticationUri(); return $this->redirector->redirect($uri); }
[ "public", "function", "initiateLogin", "(", ")", "{", "if", "(", "!", "$", "this", "->", "canInitiateLogin", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to initiate login'", ")", ";", "}", "$", "uri", "=", "$", "this", "->", "getAuthenticationUri", "(", ")", ";", "return", "$", "this", "->", "redirector", "->", "redirect", "(", "$", "uri", ")", ";", "}" ]
initiate the login process @see https://developer.foursquare.com/overview/auth.html @throws \RuntimeException @return mixed
[ "initiate", "the", "login", "process" ]
edbfcba2993a101ead8f381394742a4689aec398
https://github.com/chriswoodford/foursquare-php/blob/edbfcba2993a101ead8f381394742a4689aec398/lib/TheTwelve/Foursquare/AuthenticationGateway.php#L78-L90
16,169
chriswoodford/foursquare-php
lib/TheTwelve/Foursquare/AuthenticationGateway.php
AuthenticationGateway.getAuthenticationUri
public function getAuthenticationUri() { if (!$this->canBuildAuthenticationUri()) { throw new \RuntimeException( 'Cannot build authentication uri, dependencies are missing' ); } $uriParams = array( 'client_id' => $this->clientId, 'response_type' => 'code', 'redirect_uri' => $this->redirectUri, ); return $this->authorizeUri . '?' . http_build_query($uriParams); }
php
public function getAuthenticationUri() { if (!$this->canBuildAuthenticationUri()) { throw new \RuntimeException( 'Cannot build authentication uri, dependencies are missing' ); } $uriParams = array( 'client_id' => $this->clientId, 'response_type' => 'code', 'redirect_uri' => $this->redirectUri, ); return $this->authorizeUri . '?' . http_build_query($uriParams); }
[ "public", "function", "getAuthenticationUri", "(", ")", "{", "if", "(", "!", "$", "this", "->", "canBuildAuthenticationUri", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot build authentication uri, dependencies are missing'", ")", ";", "}", "$", "uriParams", "=", "array", "(", "'client_id'", "=>", "$", "this", "->", "clientId", ",", "'response_type'", "=>", "'code'", ",", "'redirect_uri'", "=>", "$", "this", "->", "redirectUri", ",", ")", ";", "return", "$", "this", "->", "authorizeUri", ".", "'?'", ".", "http_build_query", "(", "$", "uriParams", ")", ";", "}" ]
build the foursquare authentication uri that users are forwarded to for authentication @see https://developer.foursquare.com/overview/auth.html @return string
[ "build", "the", "foursquare", "authentication", "uri", "that", "users", "are", "forwarded", "to", "for", "authentication" ]
edbfcba2993a101ead8f381394742a4689aec398
https://github.com/chriswoodford/foursquare-php/blob/edbfcba2993a101ead8f381394742a4689aec398/lib/TheTwelve/Foursquare/AuthenticationGateway.php#L98-L115
16,170
chriswoodford/foursquare-php
lib/TheTwelve/Foursquare/AuthenticationGateway.php
AuthenticationGateway.authenticateUser
public function authenticateUser($code) { if (!$this->canAuthenticateUser()) { throw new \RuntimeException( 'Cannot authenticate user, dependencies are missing' ); } if (!$this->codeIsValid($code)) { throw new \InvalidArgumentException('Foursquare code is invalid'); } $response = json_decode($this->httpClient->get($this->accessTokenUri, array( 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'grant_type' => 'authorization_code', 'redirect_uri' => $this->redirectUri, 'code' => $code, ))); $this->token = isset($response->access_token) ? $response->access_token : null; return $this->token; }
php
public function authenticateUser($code) { if (!$this->canAuthenticateUser()) { throw new \RuntimeException( 'Cannot authenticate user, dependencies are missing' ); } if (!$this->codeIsValid($code)) { throw new \InvalidArgumentException('Foursquare code is invalid'); } $response = json_decode($this->httpClient->get($this->accessTokenUri, array( 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'grant_type' => 'authorization_code', 'redirect_uri' => $this->redirectUri, 'code' => $code, ))); $this->token = isset($response->access_token) ? $response->access_token : null; return $this->token; }
[ "public", "function", "authenticateUser", "(", "$", "code", ")", "{", "if", "(", "!", "$", "this", "->", "canAuthenticateUser", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot authenticate user, dependencies are missing'", ")", ";", "}", "if", "(", "!", "$", "this", "->", "codeIsValid", "(", "$", "code", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Foursquare code is invalid'", ")", ";", "}", "$", "response", "=", "json_decode", "(", "$", "this", "->", "httpClient", "->", "get", "(", "$", "this", "->", "accessTokenUri", ",", "array", "(", "'client_id'", "=>", "$", "this", "->", "clientId", ",", "'client_secret'", "=>", "$", "this", "->", "clientSecret", ",", "'grant_type'", "=>", "'authorization_code'", ",", "'redirect_uri'", "=>", "$", "this", "->", "redirectUri", ",", "'code'", "=>", "$", "code", ",", ")", ")", ")", ";", "$", "this", "->", "token", "=", "isset", "(", "$", "response", "->", "access_token", ")", "?", "$", "response", "->", "access_token", ":", "null", ";", "return", "$", "this", "->", "token", ";", "}" ]
authenticate the user with the response code @see https://developer.foursquare.com/overview/auth.html @param string $code @throws \RuntimeException @throws \InvalidArgumentException @return string
[ "authenticate", "the", "user", "with", "the", "response", "code" ]
edbfcba2993a101ead8f381394742a4689aec398
https://github.com/chriswoodford/foursquare-php/blob/edbfcba2993a101ead8f381394742a4689aec398/lib/TheTwelve/Foursquare/AuthenticationGateway.php#L125-L151
16,171
cronario/cronario
src/Producer.php
Producer.cleanManagerSet
protected function cleanManagerSet() { foreach ($this->managerSet as $managerKey => $manager) { /** @var $manager \Thread */ if (!$manager->isRunning()) { $this->getLogger()->debug("Daemon clean old manager : {$managerKey}", [__NAMESPACE__]); unset($this->managerSet[$managerKey]); } } return $this; }
php
protected function cleanManagerSet() { foreach ($this->managerSet as $managerKey => $manager) { /** @var $manager \Thread */ if (!$manager->isRunning()) { $this->getLogger()->debug("Daemon clean old manager : {$managerKey}", [__NAMESPACE__]); unset($this->managerSet[$managerKey]); } } return $this; }
[ "protected", "function", "cleanManagerSet", "(", ")", "{", "foreach", "(", "$", "this", "->", "managerSet", "as", "$", "managerKey", "=>", "$", "manager", ")", "{", "/** @var $manager \\Thread */", "if", "(", "!", "$", "manager", "->", "isRunning", "(", ")", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "debug", "(", "\"Daemon clean old manager : {$managerKey}\"", ",", "[", "__NAMESPACE__", "]", ")", ";", "unset", "(", "$", "this", "->", "managerSet", "[", "$", "managerKey", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Clean Manager SET Checking each manager in ManagerSet and delete manager that done theirs work @return $this
[ "Clean", "Manager", "SET" ]
954df60e95efd3085269331d435e8ce6f4980441
https://github.com/cronario/cronario/blob/954df60e95efd3085269331d435e8ce6f4980441/src/Producer.php#L428-L440
16,172
cronario/cronario
src/Producer.php
Producer.updateManagerSet
protected function updateManagerSet() { $queueStatsServer = $this->getQueue()->getStats(); if (!isset($queueStatsServer[Queue::STATS_QUEUES]) || count($queueStatsServer[Queue::STATS_QUEUES]) == 0) { return $this; } /** * filter if queue not stopped * filter if queue has jobs */ $managerOptionsSet = []; foreach ($queueStatsServer[Queue::STATS_QUEUES] as $workerClass => $queueStats) { if (in_array($workerClass, $this->managerIgnoreSet)) { continue; } if (!class_exists($workerClass)) { $this->managerIgnoreSet[] = $workerClass; continue; } if ($queueStats[Queue::STATS_QUEUE_STOP]) { continue; } if ($queueStats[Queue::STATS_JOBS_READY] == 0) { continue; } try { /** @var AbstractWorker $workerClass */ $workerConfig = $workerClass::getConfig(); // we need threads .. $managerCount = $this->calcManagerSize( $queueStats[Queue::STATS_JOBS_READY], $workerConfig[AbstractWorker::CONFIG_P_MANAGER_POOL_SIZE], $workerConfig[AbstractWorker::CONFIG_P_MANAGERS_LIMIT] ); /** @var string $workerClass */ $managerOptionsSet[$workerClass] = $managerCount; } catch (WorkerException $ex) { $this->managerIgnoreSet[] = $workerClass; $this->getLogger()->warning($ex->getMessage(), [__NAMESPACE__]); $this->getLogger() ->warning("Daemon {$this->getAppId()} will ignore worker class {$workerClass}", [__NAMESPACE__]); continue; } catch (\Exception $ex) { $this->getLogger()->warning($ex->getMessage(), [__NAMESPACE__]); continue; } } if (count($managerOptionsSet) == 0) { return $this; } $appId = $this->getAppId(); $bootstrapFile = $this->getConfig(self::CONFIG_BOOTSTRAP_FILE); foreach ($managerOptionsSet as $workerClass => $managerCount) { while ($managerCount--) { $managerId = $this->buildManagerId($workerClass, $managerCount); if (array_key_exists($managerId, $this->managerSet)) { continue; } $this->getLogger()->debug("Daemon create manager : {$managerId}", [__NAMESPACE__]); $this->managerSet[$managerId] = new Manager($managerId, $appId, $workerClass, $bootstrapFile); } } return $this; }
php
protected function updateManagerSet() { $queueStatsServer = $this->getQueue()->getStats(); if (!isset($queueStatsServer[Queue::STATS_QUEUES]) || count($queueStatsServer[Queue::STATS_QUEUES]) == 0) { return $this; } /** * filter if queue not stopped * filter if queue has jobs */ $managerOptionsSet = []; foreach ($queueStatsServer[Queue::STATS_QUEUES] as $workerClass => $queueStats) { if (in_array($workerClass, $this->managerIgnoreSet)) { continue; } if (!class_exists($workerClass)) { $this->managerIgnoreSet[] = $workerClass; continue; } if ($queueStats[Queue::STATS_QUEUE_STOP]) { continue; } if ($queueStats[Queue::STATS_JOBS_READY] == 0) { continue; } try { /** @var AbstractWorker $workerClass */ $workerConfig = $workerClass::getConfig(); // we need threads .. $managerCount = $this->calcManagerSize( $queueStats[Queue::STATS_JOBS_READY], $workerConfig[AbstractWorker::CONFIG_P_MANAGER_POOL_SIZE], $workerConfig[AbstractWorker::CONFIG_P_MANAGERS_LIMIT] ); /** @var string $workerClass */ $managerOptionsSet[$workerClass] = $managerCount; } catch (WorkerException $ex) { $this->managerIgnoreSet[] = $workerClass; $this->getLogger()->warning($ex->getMessage(), [__NAMESPACE__]); $this->getLogger() ->warning("Daemon {$this->getAppId()} will ignore worker class {$workerClass}", [__NAMESPACE__]); continue; } catch (\Exception $ex) { $this->getLogger()->warning($ex->getMessage(), [__NAMESPACE__]); continue; } } if (count($managerOptionsSet) == 0) { return $this; } $appId = $this->getAppId(); $bootstrapFile = $this->getConfig(self::CONFIG_BOOTSTRAP_FILE); foreach ($managerOptionsSet as $workerClass => $managerCount) { while ($managerCount--) { $managerId = $this->buildManagerId($workerClass, $managerCount); if (array_key_exists($managerId, $this->managerSet)) { continue; } $this->getLogger()->debug("Daemon create manager : {$managerId}", [__NAMESPACE__]); $this->managerSet[$managerId] = new Manager($managerId, $appId, $workerClass, $bootstrapFile); } } return $this; }
[ "protected", "function", "updateManagerSet", "(", ")", "{", "$", "queueStatsServer", "=", "$", "this", "->", "getQueue", "(", ")", "->", "getStats", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "queueStatsServer", "[", "Queue", "::", "STATS_QUEUES", "]", ")", "||", "count", "(", "$", "queueStatsServer", "[", "Queue", "::", "STATS_QUEUES", "]", ")", "==", "0", ")", "{", "return", "$", "this", ";", "}", "/**\n * filter if queue not stopped\n * filter if queue has jobs\n */", "$", "managerOptionsSet", "=", "[", "]", ";", "foreach", "(", "$", "queueStatsServer", "[", "Queue", "::", "STATS_QUEUES", "]", "as", "$", "workerClass", "=>", "$", "queueStats", ")", "{", "if", "(", "in_array", "(", "$", "workerClass", ",", "$", "this", "->", "managerIgnoreSet", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "class_exists", "(", "$", "workerClass", ")", ")", "{", "$", "this", "->", "managerIgnoreSet", "[", "]", "=", "$", "workerClass", ";", "continue", ";", "}", "if", "(", "$", "queueStats", "[", "Queue", "::", "STATS_QUEUE_STOP", "]", ")", "{", "continue", ";", "}", "if", "(", "$", "queueStats", "[", "Queue", "::", "STATS_JOBS_READY", "]", "==", "0", ")", "{", "continue", ";", "}", "try", "{", "/** @var AbstractWorker $workerClass */", "$", "workerConfig", "=", "$", "workerClass", "::", "getConfig", "(", ")", ";", "// we need threads ..", "$", "managerCount", "=", "$", "this", "->", "calcManagerSize", "(", "$", "queueStats", "[", "Queue", "::", "STATS_JOBS_READY", "]", ",", "$", "workerConfig", "[", "AbstractWorker", "::", "CONFIG_P_MANAGER_POOL_SIZE", "]", ",", "$", "workerConfig", "[", "AbstractWorker", "::", "CONFIG_P_MANAGERS_LIMIT", "]", ")", ";", "/** @var string $workerClass */", "$", "managerOptionsSet", "[", "$", "workerClass", "]", "=", "$", "managerCount", ";", "}", "catch", "(", "WorkerException", "$", "ex", ")", "{", "$", "this", "->", "managerIgnoreSet", "[", "]", "=", "$", "workerClass", ";", "$", "this", "->", "getLogger", "(", ")", "->", "warning", "(", "$", "ex", "->", "getMessage", "(", ")", ",", "[", "__NAMESPACE__", "]", ")", ";", "$", "this", "->", "getLogger", "(", ")", "->", "warning", "(", "\"Daemon {$this->getAppId()} will ignore worker class {$workerClass}\"", ",", "[", "__NAMESPACE__", "]", ")", ";", "continue", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "warning", "(", "$", "ex", "->", "getMessage", "(", ")", ",", "[", "__NAMESPACE__", "]", ")", ";", "continue", ";", "}", "}", "if", "(", "count", "(", "$", "managerOptionsSet", ")", "==", "0", ")", "{", "return", "$", "this", ";", "}", "$", "appId", "=", "$", "this", "->", "getAppId", "(", ")", ";", "$", "bootstrapFile", "=", "$", "this", "->", "getConfig", "(", "self", "::", "CONFIG_BOOTSTRAP_FILE", ")", ";", "foreach", "(", "$", "managerOptionsSet", "as", "$", "workerClass", "=>", "$", "managerCount", ")", "{", "while", "(", "$", "managerCount", "--", ")", "{", "$", "managerId", "=", "$", "this", "->", "buildManagerId", "(", "$", "workerClass", ",", "$", "managerCount", ")", ";", "if", "(", "array_key_exists", "(", "$", "managerId", ",", "$", "this", "->", "managerSet", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "getLogger", "(", ")", "->", "debug", "(", "\"Daemon create manager : {$managerId}\"", ",", "[", "__NAMESPACE__", "]", ")", ";", "$", "this", "->", "managerSet", "[", "$", "managerId", "]", "=", "new", "Manager", "(", "$", "managerId", ",", "$", "appId", ",", "$", "workerClass", ",", "$", "bootstrapFile", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Update Manager SET REMEMBER queueName === workerClass (cause we have relation one queue name for one type of worker) 1) get Queue stats for all queues on server 2) filter queues (stopping flag / existing ready job in it) 3) get worker configuration (to know what manager balance should do later) - if worker have problems with config we will add him to ignore manager set 4) then we try to create manager depend on exists managerSet and current balance @return $this
[ "Update", "Manager", "SET" ]
954df60e95efd3085269331d435e8ce6f4980441
https://github.com/cronario/cronario/blob/954df60e95efd3085269331d435e8ce6f4980441/src/Producer.php#L456-L538
16,173
WellCommerce/CoreBundle
Form/DataTransformer/AbstractDataTransformer.php
AbstractDataTransformer.getClassMetadata
protected function getClassMetadata(string $class): ClassMetadata { $factory = $this->getDoctrineHelper()->getMetadataFactory(); if (!$factory->hasMetadataFor($class)) { throw new \InvalidArgumentException(sprintf('No metadata found for class "%s"', $class)); } return $factory->getMetadataFor($class); }
php
protected function getClassMetadata(string $class): ClassMetadata { $factory = $this->getDoctrineHelper()->getMetadataFactory(); if (!$factory->hasMetadataFor($class)) { throw new \InvalidArgumentException(sprintf('No metadata found for class "%s"', $class)); } return $factory->getMetadataFor($class); }
[ "protected", "function", "getClassMetadata", "(", "string", "$", "class", ")", ":", "ClassMetadata", "{", "$", "factory", "=", "$", "this", "->", "getDoctrineHelper", "(", ")", "->", "getMetadataFactory", "(", ")", ";", "if", "(", "!", "$", "factory", "->", "hasMetadataFor", "(", "$", "class", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'No metadata found for class \"%s\"'", ",", "$", "class", ")", ")", ";", "}", "return", "$", "factory", "->", "getMetadataFor", "(", "$", "class", ")", ";", "}" ]
Returns mapping information for class @param string $class @return ClassMetadata
[ "Returns", "mapping", "information", "for", "class" ]
984fbd544d4b10cf11e54e0f3c304d100deb6842
https://github.com/WellCommerce/CoreBundle/blob/984fbd544d4b10cf11e54e0f3c304d100deb6842/Form/DataTransformer/AbstractDataTransformer.php#L96-L104
16,174
verschoof/bunq-api
src/Token/TokenType.php
TokenType.protect
private function protect() { if (!in_array($this->type, self::allAsString(), true)) { throw new \InvalidArgumentException(sprintf('Invalid token type "%s"', $this->type)); } }
php
private function protect() { if (!in_array($this->type, self::allAsString(), true)) { throw new \InvalidArgumentException(sprintf('Invalid token type "%s"', $this->type)); } }
[ "private", "function", "protect", "(", ")", "{", "if", "(", "!", "in_array", "(", "$", "this", "->", "type", ",", "self", "::", "allAsString", "(", ")", ",", "true", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Invalid token type \"%s\"'", ",", "$", "this", "->", "type", ")", ")", ";", "}", "}" ]
Check if the tokenType exists in our list
[ "Check", "if", "the", "tokenType", "exists", "in", "our", "list" ]
df9aa19f384275f4f0deb26de0cb5e5f8b45ffcd
https://github.com/verschoof/bunq-api/blob/df9aa19f384275f4f0deb26de0cb5e5f8b45ffcd/src/Token/TokenType.php#L102-L107
16,175
tonicospinelli/class-generation
src/ClassGeneration/ConstantCollection.php
ConstantCollection.add
public function add($constant) { if (!$constant instanceof ConstantInterface) { throw new \InvalidArgumentException( 'This Constant must be a instance of \ClassGeneration\ConstantInterface' ); } if ($constant->getName() === null) { $constant->setName('constant' . ($this->count() + 1)); } return parent::add($constant); }
php
public function add($constant) { if (!$constant instanceof ConstantInterface) { throw new \InvalidArgumentException( 'This Constant must be a instance of \ClassGeneration\ConstantInterface' ); } if ($constant->getName() === null) { $constant->setName('constant' . ($this->count() + 1)); } return parent::add($constant); }
[ "public", "function", "add", "(", "$", "constant", ")", "{", "if", "(", "!", "$", "constant", "instanceof", "ConstantInterface", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'This Constant must be a instance of \\ClassGeneration\\ConstantInterface'", ")", ";", "}", "if", "(", "$", "constant", "->", "getName", "(", ")", "===", "null", ")", "{", "$", "constant", "->", "setName", "(", "'constant'", ".", "(", "$", "this", "->", "count", "(", ")", "+", "1", ")", ")", ";", "}", "return", "parent", "::", "add", "(", "$", "constant", ")", ";", "}" ]
Adds a new Constant at ConstantCollection. @param ConstantInterface $constant @throws \InvalidArgumentException @return bool
[ "Adds", "a", "new", "Constant", "at", "ConstantCollection", "." ]
eee63bdb68c066b25b885b57b23656e809381a76
https://github.com/tonicospinelli/class-generation/blob/eee63bdb68c066b25b885b57b23656e809381a76/src/ClassGeneration/ConstantCollection.php#L31-L44
16,176
tonicospinelli/class-generation
src/ClassGeneration/ConstantCollection.php
ConstantCollection.toString
public function toString() { $string = ''; $constants = $this->getIterator(); foreach ($constants as $constant) { $string .= $constant->toString(); } return $string; }
php
public function toString() { $string = ''; $constants = $this->getIterator(); foreach ($constants as $constant) { $string .= $constant->toString(); } return $string; }
[ "public", "function", "toString", "(", ")", "{", "$", "string", "=", "''", ";", "$", "constants", "=", "$", "this", "->", "getIterator", "(", ")", ";", "foreach", "(", "$", "constants", "as", "$", "constant", ")", "{", "$", "string", ".=", "$", "constant", "->", "toString", "(", ")", ";", "}", "return", "$", "string", ";", "}" ]
Parse the Constant Collection to string. @return string
[ "Parse", "the", "Constant", "Collection", "to", "string", "." ]
eee63bdb68c066b25b885b57b23656e809381a76
https://github.com/tonicospinelli/class-generation/blob/eee63bdb68c066b25b885b57b23656e809381a76/src/ClassGeneration/ConstantCollection.php#L68-L77
16,177
jan-dolata/crude-crud
src/Engine/CrudeSetupTrait/SelectOptions.php
SelectOptions.setSelectOptions
public function setSelectOptions($attr, $options = null) { $optionsList = is_array($attr) ? $attr : [$attr => $options]; foreach ($optionsList as $key => $value) $this->selectOptions[$key] = $value; return $this; }
php
public function setSelectOptions($attr, $options = null) { $optionsList = is_array($attr) ? $attr : [$attr => $options]; foreach ($optionsList as $key => $value) $this->selectOptions[$key] = $value; return $this; }
[ "public", "function", "setSelectOptions", "(", "$", "attr", ",", "$", "options", "=", "null", ")", "{", "$", "optionsList", "=", "is_array", "(", "$", "attr", ")", "?", "$", "attr", ":", "[", "$", "attr", "=>", "$", "options", "]", ";", "foreach", "(", "$", "optionsList", "as", "$", "key", "=>", "$", "value", ")", "$", "this", "->", "selectOptions", "[", "$", "key", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Sets the Select options. @param string|array $attr @param array $options = null @return self
[ "Sets", "the", "Select", "options", "." ]
9129ea08278835cf5cecfd46a90369226ae6bdd7
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Engine/CrudeSetupTrait/SelectOptions.php#L32-L42
16,178
datasift/datasift-php
lib/DataSift/ODP.php
DataSift_ODP.ingest
public function ingest($data_set) { if (strlen($this->_source_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot make request without a source ID'); } if (empty($data_set)) { throw new DataSift_Exception_InvalidData('Cannot make request without a valid data set'); } return $this->_user->post($this->getSourceId(), $data_set, array(), true); }
php
public function ingest($data_set) { if (strlen($this->_source_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot make request without a source ID'); } if (empty($data_set)) { throw new DataSift_Exception_InvalidData('Cannot make request without a valid data set'); } return $this->_user->post($this->getSourceId(), $data_set, array(), true); }
[ "public", "function", "ingest", "(", "$", "data_set", ")", "{", "if", "(", "strlen", "(", "$", "this", "->", "_source_id", ")", "==", "0", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot make request without a source ID'", ")", ";", "}", "if", "(", "empty", "(", "$", "data_set", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot make request without a valid data set'", ")", ";", "}", "return", "$", "this", "->", "_user", "->", "post", "(", "$", "this", "->", "getSourceId", "(", ")", ",", "$", "data_set", ",", "array", "(", ")", ",", "true", ")", ";", "}" ]
Generates a curl request to the Ingestion Endpoint
[ "Generates", "a", "curl", "request", "to", "the", "Ingestion", "Endpoint" ]
35282461ad3e54880e5940bb5afce26c75dc4bb9
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/ODP.php#L67-L78
16,179
JoffreyPoreeCoding/MongoDB-ODM
src/ObjectManager.php
ObjectManager.addObject
public function addObject($object, $state, $repository) { $data = $repository->getHydrator()->unhydrate($object); $oid = spl_object_hash($object); $id = isset($data['_id']) ? serialize($data['_id']) . $repository->getCollection() : $oid; if (!isset($this->objectStates[$id])) { $this->objectStates[$id] = $state; } $this->objects[$id] = $object; $this->objectsRepository[$oid] = $repository; }
php
public function addObject($object, $state, $repository) { $data = $repository->getHydrator()->unhydrate($object); $oid = spl_object_hash($object); $id = isset($data['_id']) ? serialize($data['_id']) . $repository->getCollection() : $oid; if (!isset($this->objectStates[$id])) { $this->objectStates[$id] = $state; } $this->objects[$id] = $object; $this->objectsRepository[$oid] = $repository; }
[ "public", "function", "addObject", "(", "$", "object", ",", "$", "state", ",", "$", "repository", ")", "{", "$", "data", "=", "$", "repository", "->", "getHydrator", "(", ")", "->", "unhydrate", "(", "$", "object", ")", ";", "$", "oid", "=", "spl_object_hash", "(", "$", "object", ")", ";", "$", "id", "=", "isset", "(", "$", "data", "[", "'_id'", "]", ")", "?", "serialize", "(", "$", "data", "[", "'_id'", "]", ")", ".", "$", "repository", "->", "getCollection", "(", ")", ":", "$", "oid", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "objectStates", "[", "$", "id", "]", ")", ")", "{", "$", "this", "->", "objectStates", "[", "$", "id", "]", "=", "$", "state", ";", "}", "$", "this", "->", "objects", "[", "$", "id", "]", "=", "$", "object", ";", "$", "this", "->", "objectsRepository", "[", "$", "oid", "]", "=", "$", "repository", ";", "}" ]
Add an object @param mixed $object Object to add @param int $state State of this object @return void
[ "Add", "an", "object" ]
56fd7ab28c22f276573a89d56bb93c8d74ad7f74
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/ObjectManager.php#L43-L54
16,180
JoffreyPoreeCoding/MongoDB-ODM
src/ObjectManager.php
ObjectManager.setObjectState
public function setObjectState($object, $state) { if (is_object($object)) { $oid = spl_object_hash($object); $repository = $this->objectsRepository[$oid]; $data = $repository->getHydrator()->unhydrate($object); $id = isset($data['_id']) ? serialize($data['_id']) . $repository->getCollection() : $oid; } else { return false; } if (!isset($this->objectStates[$id]) && !isset($this->objectStates[$oid])) { throw new Exception\StateException(); } if (!in_array($state, [self::OBJ_MANAGED, self::OBJ_NEW, self::OBJ_REMOVED])) { throw new Exception\StateException("Invalid state '$state'"); } if ($state == self::OBJ_REMOVED && isset($this->objectStates[$oid]) && $this->objectStates[$oid] == self::OBJ_NEW) { throw new Exception\StateException("Can't change state to removed because object is not managed. Insert it in database before"); } if (isset($this->objectStates[$oid])) { unset($this->objectStates[$oid]); unset($this->objects[$oid]); } $this->objectStates[$id] = $state; $this->objects[$id] = $object; return true; }
php
public function setObjectState($object, $state) { if (is_object($object)) { $oid = spl_object_hash($object); $repository = $this->objectsRepository[$oid]; $data = $repository->getHydrator()->unhydrate($object); $id = isset($data['_id']) ? serialize($data['_id']) . $repository->getCollection() : $oid; } else { return false; } if (!isset($this->objectStates[$id]) && !isset($this->objectStates[$oid])) { throw new Exception\StateException(); } if (!in_array($state, [self::OBJ_MANAGED, self::OBJ_NEW, self::OBJ_REMOVED])) { throw new Exception\StateException("Invalid state '$state'"); } if ($state == self::OBJ_REMOVED && isset($this->objectStates[$oid]) && $this->objectStates[$oid] == self::OBJ_NEW) { throw new Exception\StateException("Can't change state to removed because object is not managed. Insert it in database before"); } if (isset($this->objectStates[$oid])) { unset($this->objectStates[$oid]); unset($this->objects[$oid]); } $this->objectStates[$id] = $state; $this->objects[$id] = $object; return true; }
[ "public", "function", "setObjectState", "(", "$", "object", ",", "$", "state", ")", "{", "if", "(", "is_object", "(", "$", "object", ")", ")", "{", "$", "oid", "=", "spl_object_hash", "(", "$", "object", ")", ";", "$", "repository", "=", "$", "this", "->", "objectsRepository", "[", "$", "oid", "]", ";", "$", "data", "=", "$", "repository", "->", "getHydrator", "(", ")", "->", "unhydrate", "(", "$", "object", ")", ";", "$", "id", "=", "isset", "(", "$", "data", "[", "'_id'", "]", ")", "?", "serialize", "(", "$", "data", "[", "'_id'", "]", ")", ".", "$", "repository", "->", "getCollection", "(", ")", ":", "$", "oid", ";", "}", "else", "{", "return", "false", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "objectStates", "[", "$", "id", "]", ")", "&&", "!", "isset", "(", "$", "this", "->", "objectStates", "[", "$", "oid", "]", ")", ")", "{", "throw", "new", "Exception", "\\", "StateException", "(", ")", ";", "}", "if", "(", "!", "in_array", "(", "$", "state", ",", "[", "self", "::", "OBJ_MANAGED", ",", "self", "::", "OBJ_NEW", ",", "self", "::", "OBJ_REMOVED", "]", ")", ")", "{", "throw", "new", "Exception", "\\", "StateException", "(", "\"Invalid state '$state'\"", ")", ";", "}", "if", "(", "$", "state", "==", "self", "::", "OBJ_REMOVED", "&&", "isset", "(", "$", "this", "->", "objectStates", "[", "$", "oid", "]", ")", "&&", "$", "this", "->", "objectStates", "[", "$", "oid", "]", "==", "self", "::", "OBJ_NEW", ")", "{", "throw", "new", "Exception", "\\", "StateException", "(", "\"Can't change state to removed because object is not managed. Insert it in database before\"", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "objectStates", "[", "$", "oid", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "objectStates", "[", "$", "oid", "]", ")", ";", "unset", "(", "$", "this", "->", "objects", "[", "$", "oid", "]", ")", ";", "}", "$", "this", "->", "objectStates", "[", "$", "id", "]", "=", "$", "state", ";", "$", "this", "->", "objects", "[", "$", "id", "]", "=", "$", "object", ";", "return", "true", ";", "}" ]
Update object state @param mixed $object Object to change state @param int $state New state @return void
[ "Update", "object", "state" ]
56fd7ab28c22f276573a89d56bb93c8d74ad7f74
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/ObjectManager.php#L91-L123
16,181
JoffreyPoreeCoding/MongoDB-ODM
src/ObjectManager.php
ObjectManager.getObjectState
public function getObjectState($object) { $oid = spl_object_hash($object); if (isset($this->objectsRepository[$oid])) { $repository = $this->objectsRepository[$oid]; $data = $repository->getHydrator()->unhydrate($object); $id = isset($data['_id']) ? serialize($data['_id']) . $repository->getCollection() : $oid; if (isset($this->objectStates[$id])) { return $this->objectStates[$id]; } } return null; }
php
public function getObjectState($object) { $oid = spl_object_hash($object); if (isset($this->objectsRepository[$oid])) { $repository = $this->objectsRepository[$oid]; $data = $repository->getHydrator()->unhydrate($object); $id = isset($data['_id']) ? serialize($data['_id']) . $repository->getCollection() : $oid; if (isset($this->objectStates[$id])) { return $this->objectStates[$id]; } } return null; }
[ "public", "function", "getObjectState", "(", "$", "object", ")", "{", "$", "oid", "=", "spl_object_hash", "(", "$", "object", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "objectsRepository", "[", "$", "oid", "]", ")", ")", "{", "$", "repository", "=", "$", "this", "->", "objectsRepository", "[", "$", "oid", "]", ";", "$", "data", "=", "$", "repository", "->", "getHydrator", "(", ")", "->", "unhydrate", "(", "$", "object", ")", ";", "$", "id", "=", "isset", "(", "$", "data", "[", "'_id'", "]", ")", "?", "serialize", "(", "$", "data", "[", "'_id'", "]", ")", ".", "$", "repository", "->", "getCollection", "(", ")", ":", "$", "oid", ";", "if", "(", "isset", "(", "$", "this", "->", "objectStates", "[", "$", "id", "]", ")", ")", "{", "return", "$", "this", "->", "objectStates", "[", "$", "id", "]", ";", "}", "}", "return", "null", ";", "}" ]
Get object state @param mixed $object @return void
[ "Get", "object", "state" ]
56fd7ab28c22f276573a89d56bb93c8d74ad7f74
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/ObjectManager.php#L131-L145
16,182
JoffreyPoreeCoding/MongoDB-ODM
src/ObjectManager.php
ObjectManager.getObjects
public function getObjects($state = null) { if (!isset($state)) { return $this->objects; } $objectList = []; foreach ($this->objects as $id => $object) { if ($this->objectStates[$id] == $state) { $objectList[$id] = $object; } } return $objectList; }
php
public function getObjects($state = null) { if (!isset($state)) { return $this->objects; } $objectList = []; foreach ($this->objects as $id => $object) { if ($this->objectStates[$id] == $state) { $objectList[$id] = $object; } } return $objectList; }
[ "public", "function", "getObjects", "(", "$", "state", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "state", ")", ")", "{", "return", "$", "this", "->", "objects", ";", "}", "$", "objectList", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "objects", "as", "$", "id", "=>", "$", "object", ")", "{", "if", "(", "$", "this", "->", "objectStates", "[", "$", "id", "]", "==", "$", "state", ")", "{", "$", "objectList", "[", "$", "id", "]", "=", "$", "object", ";", "}", "}", "return", "$", "objectList", ";", "}" ]
Get object with specified state @param int $state State to search @return array
[ "Get", "object", "with", "specified", "state" ]
56fd7ab28c22f276573a89d56bb93c8d74ad7f74
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/ObjectManager.php#L153-L167
16,183
JoffreyPoreeCoding/MongoDB-ODM
src/ObjectManager.php
ObjectManager.hasObject
public function hasObject($object) { $oid = spl_object_hash($object); if (!isset($this->objectsRepository[$oid])) { return false; } $repository = $this->objectsRepository[$oid]; $data = $repository->getHydrator()->unhydrate($object); $id = isset($data['_id']) ? serialize($data['_id']) . $repository->getCollection() : $oid; return isset($this->objects[$oid]) || isset($this->objects[$id]); }
php
public function hasObject($object) { $oid = spl_object_hash($object); if (!isset($this->objectsRepository[$oid])) { return false; } $repository = $this->objectsRepository[$oid]; $data = $repository->getHydrator()->unhydrate($object); $id = isset($data['_id']) ? serialize($data['_id']) . $repository->getCollection() : $oid; return isset($this->objects[$oid]) || isset($this->objects[$id]); }
[ "public", "function", "hasObject", "(", "$", "object", ")", "{", "$", "oid", "=", "spl_object_hash", "(", "$", "object", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "objectsRepository", "[", "$", "oid", "]", ")", ")", "{", "return", "false", ";", "}", "$", "repository", "=", "$", "this", "->", "objectsRepository", "[", "$", "oid", "]", ";", "$", "data", "=", "$", "repository", "->", "getHydrator", "(", ")", "->", "unhydrate", "(", "$", "object", ")", ";", "$", "id", "=", "isset", "(", "$", "data", "[", "'_id'", "]", ")", "?", "serialize", "(", "$", "data", "[", "'_id'", "]", ")", ".", "$", "repository", "->", "getCollection", "(", ")", ":", "$", "oid", ";", "return", "isset", "(", "$", "this", "->", "objects", "[", "$", "oid", "]", ")", "||", "isset", "(", "$", "this", "->", "objects", "[", "$", "id", "]", ")", ";", "}" ]
Check if object is managed @param mixed $object Object to search @return boolean
[ "Check", "if", "object", "is", "managed" ]
56fd7ab28c22f276573a89d56bb93c8d74ad7f74
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/ObjectManager.php#L188-L199
16,184
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/UserQuery.php
UserQuery.filterByRole
public function filterByRole($role, $comparison = Criteria::EQUAL) { return $this ->useUserRoleQuery() ->filterByRole($role, $comparison) ->endUse(); }
php
public function filterByRole($role, $comparison = Criteria::EQUAL) { return $this ->useUserRoleQuery() ->filterByRole($role, $comparison) ->endUse(); }
[ "public", "function", "filterByRole", "(", "$", "role", ",", "$", "comparison", "=", "Criteria", "::", "EQUAL", ")", "{", "return", "$", "this", "->", "useUserRoleQuery", "(", ")", "->", "filterByRole", "(", "$", "role", ",", "$", "comparison", ")", "->", "endUse", "(", ")", ";", "}" ]
Filter the query by a related Role object using the user_role table as cross reference @param Role $role the related object to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return ChildUserQuery The current query, for fluid interface
[ "Filter", "the", "query", "by", "a", "related", "Role", "object", "using", "the", "user_role", "table", "as", "cross", "reference" ]
3424a360c9bded71eb5b570bc114a7759cb23ec6
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/UserQuery.php#L605-L611
16,185
sulu/SuluSalesShippingBundle
src/Sulu/Bundle/Sales/OrderBundle/Widgets/FlowOfDocuments.php
FlowOfDocuments.fetchDocumentData
protected function fetchDocumentData($options) { $documents = $this->dependencyManager->getDocuments($options['orderId'], $options['locale']); if (!empty($documents)) { /* @var SalesDocument $document */ foreach ($documents as $document) { $data = $document->getSalesDocumentData(); parent::addEntry( $data['id'], $data['number'], $data['type'], $data['date'], parent::getRoute($data['id'], $data['type'], 'details'), $data['pdfBaseUrl'] ); } } }
php
protected function fetchDocumentData($options) { $documents = $this->dependencyManager->getDocuments($options['orderId'], $options['locale']); if (!empty($documents)) { /* @var SalesDocument $document */ foreach ($documents as $document) { $data = $document->getSalesDocumentData(); parent::addEntry( $data['id'], $data['number'], $data['type'], $data['date'], parent::getRoute($data['id'], $data['type'], 'details'), $data['pdfBaseUrl'] ); } } }
[ "protected", "function", "fetchDocumentData", "(", "$", "options", ")", "{", "$", "documents", "=", "$", "this", "->", "dependencyManager", "->", "getDocuments", "(", "$", "options", "[", "'orderId'", "]", ",", "$", "options", "[", "'locale'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "documents", ")", ")", "{", "/* @var SalesDocument $document */", "foreach", "(", "$", "documents", "as", "$", "document", ")", "{", "$", "data", "=", "$", "document", "->", "getSalesDocumentData", "(", ")", ";", "parent", "::", "addEntry", "(", "$", "data", "[", "'id'", "]", ",", "$", "data", "[", "'number'", "]", ",", "$", "data", "[", "'type'", "]", ",", "$", "data", "[", "'date'", "]", ",", "parent", "::", "getRoute", "(", "$", "data", "[", "'id'", "]", ",", "$", "data", "[", "'type'", "]", ",", "'details'", ")", ",", "$", "data", "[", "'pdfBaseUrl'", "]", ")", ";", "}", "}", "}" ]
Retrieves document data for a specific order and adds it to the entries @param $options @throws \Sulu\Bundle\AdminBundle\Widgets\WidgetParameterException
[ "Retrieves", "document", "data", "for", "a", "specific", "order", "and", "adds", "it", "to", "the", "entries" ]
0d39de262d58579e5679db99a77dbf717d600b5e
https://github.com/sulu/SuluSalesShippingBundle/blob/0d39de262d58579e5679db99a77dbf717d600b5e/src/Sulu/Bundle/Sales/OrderBundle/Widgets/FlowOfDocuments.php#L93-L110
16,186
withfatpanda/illuminate-wordpress
src/WordPress/Plugin.php
Plugin.getInstance
static function getInstance($name = null) { if (empty($name)) { $name = get_called_class(); } if (!empty(static::$plugins[$name])) { return static::$plugins[$name]; } return false; }
php
static function getInstance($name = null) { if (empty($name)) { $name = get_called_class(); } if (!empty(static::$plugins[$name])) { return static::$plugins[$name]; } return false; }
[ "static", "function", "getInstance", "(", "$", "name", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "$", "name", "=", "get_called_class", "(", ")", ";", "}", "if", "(", "!", "empty", "(", "static", "::", "$", "plugins", "[", "$", "name", "]", ")", ")", "{", "return", "static", "::", "$", "plugins", "[", "$", "name", "]", ";", "}", "return", "false", ";", "}" ]
Get the existing instance of this Plugin. @param string Optionally, the name or classname of the Plugin to retrieve @return Plugin instance if bootstrapped, otherwise false
[ "Get", "the", "existing", "instance", "of", "this", "Plugin", "." ]
b426ca81a55367459430c974932ee5a941d759d8
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Plugin.php#L157-L166
16,187
withfatpanda/illuminate-wordpress
src/WordPress/Plugin.php
Plugin.registerRequestBindings
protected function registerRequestBindings() { $this->singleton('Illuminate\Http\Request', function () { // create a new request object $request = Request::capture(); // create an arbitrary response object $this->response = new Response; // get a SessionManager from the container $manager = $this['session']; // startup the StartSession middleware $middleware = new StartSession($manager); $middleware->handle($request, function() { return $this->response; }); // print out any cookies created by the session system foreach($this->response->headers->getCookies() as $cookie) { @header('Set-Cookie: '.$cookie); } return $request; }); }
php
protected function registerRequestBindings() { $this->singleton('Illuminate\Http\Request', function () { // create a new request object $request = Request::capture(); // create an arbitrary response object $this->response = new Response; // get a SessionManager from the container $manager = $this['session']; // startup the StartSession middleware $middleware = new StartSession($manager); $middleware->handle($request, function() { return $this->response; }); // print out any cookies created by the session system foreach($this->response->headers->getCookies() as $cookie) { @header('Set-Cookie: '.$cookie); } return $request; }); }
[ "protected", "function", "registerRequestBindings", "(", ")", "{", "$", "this", "->", "singleton", "(", "'Illuminate\\Http\\Request'", ",", "function", "(", ")", "{", "// create a new request object", "$", "request", "=", "Request", "::", "capture", "(", ")", ";", "// create an arbitrary response object", "$", "this", "->", "response", "=", "new", "Response", ";", "// get a SessionManager from the container", "$", "manager", "=", "$", "this", "[", "'session'", "]", ";", "// startup the StartSession middleware", "$", "middleware", "=", "new", "StartSession", "(", "$", "manager", ")", ";", "$", "middleware", "->", "handle", "(", "$", "request", ",", "function", "(", ")", "{", "return", "$", "this", "->", "response", ";", "}", ")", ";", "// print out any cookies created by the session system", "foreach", "(", "$", "this", "->", "response", "->", "headers", "->", "getCookies", "(", ")", "as", "$", "cookie", ")", "{", "@", "header", "(", "'Set-Cookie: '", ".", "$", "cookie", ")", ";", "}", "return", "$", "request", ";", "}", ")", ";", "}" ]
Register container bindings for the plugin. @return void
[ "Register", "container", "bindings", "for", "the", "plugin", "." ]
b426ca81a55367459430c974932ee5a941d759d8
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Plugin.php#L244-L264
16,188
withfatpanda/illuminate-wordpress
src/WordPress/Plugin.php
Plugin.bootstrap
static function bootstrap($bootstrap) { $basepath = realpath(dirname($bootstrap)); $fs = new Filesystem; $pluginSrcFile = $basepath.'/src/plugin.php'; require_once $pluginSrcFile; $source = $fs->get($pluginSrcFile); $pluginClass = static::getFirstPluginClassName($source); // now check to see if we've been here before... if (!empty(static::$plugins[$pluginClass])) { return static::$plugins[$pluginClass]; } // the plugin will have already been bootstrapped by // the time we get here IF the autoload file exists; // if it doesn't, setup a fallback class loader if (!file_exists($composer = $basepath.'/vendor/autoload.php')) { spl_autoload_register(function($name) use ($fs, $basepath) { $src = $basepath.'/src'; $files = $fs->glob($src.'/**/*.php'); static $classmap; // build the classmap if ($classmap === null) { $classmap = []; foreach($files as $file) { $contents = $fs->get($file); $namespace = ''; if (preg_match('/namespace\s+(.*?);/i', $contents, $matches)) { $namespace = $matches[1]; } if (preg_match_all('/class\s+([\w\_]+).*?{/i', $contents, $matches)) { foreach($matches[1] as $className) { $classmap["{$namespace}\\{$className}"] = $file; } } } } // if we found a match, load it if (!empty($classmap[$name])) { require_once $classmap[$name]; } }); } $plugin = new $pluginClass($bootstrap); static::$plugins[$pluginClass] = $plugin; static::$plugins[$plugin->getSlug()] = $plugin; return static::$plugins[$pluginClass]; }
php
static function bootstrap($bootstrap) { $basepath = realpath(dirname($bootstrap)); $fs = new Filesystem; $pluginSrcFile = $basepath.'/src/plugin.php'; require_once $pluginSrcFile; $source = $fs->get($pluginSrcFile); $pluginClass = static::getFirstPluginClassName($source); // now check to see if we've been here before... if (!empty(static::$plugins[$pluginClass])) { return static::$plugins[$pluginClass]; } // the plugin will have already been bootstrapped by // the time we get here IF the autoload file exists; // if it doesn't, setup a fallback class loader if (!file_exists($composer = $basepath.'/vendor/autoload.php')) { spl_autoload_register(function($name) use ($fs, $basepath) { $src = $basepath.'/src'; $files = $fs->glob($src.'/**/*.php'); static $classmap; // build the classmap if ($classmap === null) { $classmap = []; foreach($files as $file) { $contents = $fs->get($file); $namespace = ''; if (preg_match('/namespace\s+(.*?);/i', $contents, $matches)) { $namespace = $matches[1]; } if (preg_match_all('/class\s+([\w\_]+).*?{/i', $contents, $matches)) { foreach($matches[1] as $className) { $classmap["{$namespace}\\{$className}"] = $file; } } } } // if we found a match, load it if (!empty($classmap[$name])) { require_once $classmap[$name]; } }); } $plugin = new $pluginClass($bootstrap); static::$plugins[$pluginClass] = $plugin; static::$plugins[$plugin->getSlug()] = $plugin; return static::$plugins[$pluginClass]; }
[ "static", "function", "bootstrap", "(", "$", "bootstrap", ")", "{", "$", "basepath", "=", "realpath", "(", "dirname", "(", "$", "bootstrap", ")", ")", ";", "$", "fs", "=", "new", "Filesystem", ";", "$", "pluginSrcFile", "=", "$", "basepath", ".", "'/src/plugin.php'", ";", "require_once", "$", "pluginSrcFile", ";", "$", "source", "=", "$", "fs", "->", "get", "(", "$", "pluginSrcFile", ")", ";", "$", "pluginClass", "=", "static", "::", "getFirstPluginClassName", "(", "$", "source", ")", ";", "// now check to see if we've been here before...", "if", "(", "!", "empty", "(", "static", "::", "$", "plugins", "[", "$", "pluginClass", "]", ")", ")", "{", "return", "static", "::", "$", "plugins", "[", "$", "pluginClass", "]", ";", "}", "// the plugin will have already been bootstrapped by", "// the time we get here IF the autoload file exists;", "// if it doesn't, setup a fallback class loader", "if", "(", "!", "file_exists", "(", "$", "composer", "=", "$", "basepath", ".", "'/vendor/autoload.php'", ")", ")", "{", "spl_autoload_register", "(", "function", "(", "$", "name", ")", "use", "(", "$", "fs", ",", "$", "basepath", ")", "{", "$", "src", "=", "$", "basepath", ".", "'/src'", ";", "$", "files", "=", "$", "fs", "->", "glob", "(", "$", "src", ".", "'/**/*.php'", ")", ";", "static", "$", "classmap", ";", "// build the classmap", "if", "(", "$", "classmap", "===", "null", ")", "{", "$", "classmap", "=", "[", "]", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "contents", "=", "$", "fs", "->", "get", "(", "$", "file", ")", ";", "$", "namespace", "=", "''", ";", "if", "(", "preg_match", "(", "'/namespace\\s+(.*?);/i'", ",", "$", "contents", ",", "$", "matches", ")", ")", "{", "$", "namespace", "=", "$", "matches", "[", "1", "]", ";", "}", "if", "(", "preg_match_all", "(", "'/class\\s+([\\w\\_]+).*?{/i'", ",", "$", "contents", ",", "$", "matches", ")", ")", "{", "foreach", "(", "$", "matches", "[", "1", "]", "as", "$", "className", ")", "{", "$", "classmap", "[", "\"{$namespace}\\\\{$className}\"", "]", "=", "$", "file", ";", "}", "}", "}", "}", "// if we found a match, load it", "if", "(", "!", "empty", "(", "$", "classmap", "[", "$", "name", "]", ")", ")", "{", "require_once", "$", "classmap", "[", "$", "name", "]", ";", "}", "}", ")", ";", "}", "$", "plugin", "=", "new", "$", "pluginClass", "(", "$", "bootstrap", ")", ";", "static", "::", "$", "plugins", "[", "$", "pluginClass", "]", "=", "$", "plugin", ";", "static", "::", "$", "plugins", "[", "$", "plugin", "->", "getSlug", "(", ")", "]", "=", "$", "plugin", ";", "return", "static", "::", "$", "plugins", "[", "$", "pluginClass", "]", ";", "}" ]
Bootstrap a plugin found in the given bootstrap file. @param string The full path to a Plugin's bootstrap file @return Plugin
[ "Bootstrap", "a", "plugin", "found", "in", "the", "given", "bootstrap", "file", "." ]
b426ca81a55367459430c974932ee5a941d759d8
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Plugin.php#L538-L600
16,189
withfatpanda/illuminate-wordpress
src/WordPress/Plugin.php
Plugin.getDefaultDatabaseConnectionConfig
protected function getDefaultDatabaseConnectionConfig() { global $table_prefix; $default = [ 'driver' => 'mysql', 'host' => getenv('DB_HOST'), 'port' => getenv('DB_PORT'), 'database' => getenv('DB_NAME'), 'username' => getenv('DB_USER'), 'password' => getenv('DB_PASSWORD'), 'charset' => getenv('DB_CHARSET'), 'collation' => getenv('DB_COLLATE'), 'prefix' => getenv('DB_PREFIX') ?: $table_prefix, 'timezone' => getenv('DB_TIMEZONE') ?: '+00:00', 'strict' => getenv('DB_STRICT_MODE') ?: false, ]; if (empty($default['database']) && defined('DB_NAME')) { $default['database'] = DB_NAME; } if (empty($default['username']) && defined('DB_USER')) { $default['username'] = DB_USER; } if (empty($default['password']) && defined('DB_PASSWORD')) { $default['password'] = DB_PASSWORD; } if (empty($default['host']) && defined('DB_HOST')) { $default['host'] = DB_HOST; } if (empty($default['charset']) && defined('DB_CHARSET')) { $default['charset'] = DB_CHARSET; } if (empty($default['collation'])) { if (defined('DB_COLLATE') && DB_COLLATE) { $default['collation'] = DB_COLLATE; } else { $default['collation'] = 'utf8_unicode_ci'; } } return $default; }
php
protected function getDefaultDatabaseConnectionConfig() { global $table_prefix; $default = [ 'driver' => 'mysql', 'host' => getenv('DB_HOST'), 'port' => getenv('DB_PORT'), 'database' => getenv('DB_NAME'), 'username' => getenv('DB_USER'), 'password' => getenv('DB_PASSWORD'), 'charset' => getenv('DB_CHARSET'), 'collation' => getenv('DB_COLLATE'), 'prefix' => getenv('DB_PREFIX') ?: $table_prefix, 'timezone' => getenv('DB_TIMEZONE') ?: '+00:00', 'strict' => getenv('DB_STRICT_MODE') ?: false, ]; if (empty($default['database']) && defined('DB_NAME')) { $default['database'] = DB_NAME; } if (empty($default['username']) && defined('DB_USER')) { $default['username'] = DB_USER; } if (empty($default['password']) && defined('DB_PASSWORD')) { $default['password'] = DB_PASSWORD; } if (empty($default['host']) && defined('DB_HOST')) { $default['host'] = DB_HOST; } if (empty($default['charset']) && defined('DB_CHARSET')) { $default['charset'] = DB_CHARSET; } if (empty($default['collation'])) { if (defined('DB_COLLATE') && DB_COLLATE) { $default['collation'] = DB_COLLATE; } else { $default['collation'] = 'utf8_unicode_ci'; } } return $default; }
[ "protected", "function", "getDefaultDatabaseConnectionConfig", "(", ")", "{", "global", "$", "table_prefix", ";", "$", "default", "=", "[", "'driver'", "=>", "'mysql'", ",", "'host'", "=>", "getenv", "(", "'DB_HOST'", ")", ",", "'port'", "=>", "getenv", "(", "'DB_PORT'", ")", ",", "'database'", "=>", "getenv", "(", "'DB_NAME'", ")", ",", "'username'", "=>", "getenv", "(", "'DB_USER'", ")", ",", "'password'", "=>", "getenv", "(", "'DB_PASSWORD'", ")", ",", "'charset'", "=>", "getenv", "(", "'DB_CHARSET'", ")", ",", "'collation'", "=>", "getenv", "(", "'DB_COLLATE'", ")", ",", "'prefix'", "=>", "getenv", "(", "'DB_PREFIX'", ")", "?", ":", "$", "table_prefix", ",", "'timezone'", "=>", "getenv", "(", "'DB_TIMEZONE'", ")", "?", ":", "'+00:00'", ",", "'strict'", "=>", "getenv", "(", "'DB_STRICT_MODE'", ")", "?", ":", "false", ",", "]", ";", "if", "(", "empty", "(", "$", "default", "[", "'database'", "]", ")", "&&", "defined", "(", "'DB_NAME'", ")", ")", "{", "$", "default", "[", "'database'", "]", "=", "DB_NAME", ";", "}", "if", "(", "empty", "(", "$", "default", "[", "'username'", "]", ")", "&&", "defined", "(", "'DB_USER'", ")", ")", "{", "$", "default", "[", "'username'", "]", "=", "DB_USER", ";", "}", "if", "(", "empty", "(", "$", "default", "[", "'password'", "]", ")", "&&", "defined", "(", "'DB_PASSWORD'", ")", ")", "{", "$", "default", "[", "'password'", "]", "=", "DB_PASSWORD", ";", "}", "if", "(", "empty", "(", "$", "default", "[", "'host'", "]", ")", "&&", "defined", "(", "'DB_HOST'", ")", ")", "{", "$", "default", "[", "'host'", "]", "=", "DB_HOST", ";", "}", "if", "(", "empty", "(", "$", "default", "[", "'charset'", "]", ")", "&&", "defined", "(", "'DB_CHARSET'", ")", ")", "{", "$", "default", "[", "'charset'", "]", "=", "DB_CHARSET", ";", "}", "if", "(", "empty", "(", "$", "default", "[", "'collation'", "]", ")", ")", "{", "if", "(", "defined", "(", "'DB_COLLATE'", ")", "&&", "DB_COLLATE", ")", "{", "$", "default", "[", "'collation'", "]", "=", "DB_COLLATE", ";", "}", "else", "{", "$", "default", "[", "'collation'", "]", "=", "'utf8_unicode_ci'", ";", "}", "}", "return", "$", "default", ";", "}" ]
Try to load the database configuration from the environment first using getenv; finding none, look to the traditional constants typically defined in wp-config.php @return array
[ "Try", "to", "load", "the", "database", "configuration", "from", "the", "environment", "first", "using", "getenv", ";", "finding", "none", "look", "to", "the", "traditional", "constants", "typically", "defined", "in", "wp", "-", "config", ".", "php" ]
b426ca81a55367459430c974932ee5a941d759d8
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Plugin.php#L608-L655
16,190
withfatpanda/illuminate-wordpress
src/WordPress/Plugin.php
Plugin.bootstrapContainer
protected function bootstrapContainer() { $this->instance('app', $this); $this->instance('Illuminate\Container\Container', $this); $this->instance('path', $this->path()); $this->configure('app'); $this->configure('scout'); $this->configure('services'); $this->configure('session'); $this->configure('mail'); $this->registerContainerAliases(); $this->bindActionsAndFilters(); $this->register(\Illuminate\Session\SessionServiceProvider::class); $this->register(\FatPanda\Illuminate\WordPress\Providers\Mail\MailServiceProvider::class); $this->register(Providers\Session\WordPressSessionServiceProvider::class); $this->register(Providers\Scout\ScoutServiceProvider::class); $this->singleton(\Illuminate\Contracts\Console\Kernel::class, WordPressConsoleKernel::class); $this->singleton(\Illuminate\Contracts\Debug\ExceptionHandler::class, WordPressExceptionHandler::class); }
php
protected function bootstrapContainer() { $this->instance('app', $this); $this->instance('Illuminate\Container\Container', $this); $this->instance('path', $this->path()); $this->configure('app'); $this->configure('scout'); $this->configure('services'); $this->configure('session'); $this->configure('mail'); $this->registerContainerAliases(); $this->bindActionsAndFilters(); $this->register(\Illuminate\Session\SessionServiceProvider::class); $this->register(\FatPanda\Illuminate\WordPress\Providers\Mail\MailServiceProvider::class); $this->register(Providers\Session\WordPressSessionServiceProvider::class); $this->register(Providers\Scout\ScoutServiceProvider::class); $this->singleton(\Illuminate\Contracts\Console\Kernel::class, WordPressConsoleKernel::class); $this->singleton(\Illuminate\Contracts\Debug\ExceptionHandler::class, WordPressExceptionHandler::class); }
[ "protected", "function", "bootstrapContainer", "(", ")", "{", "$", "this", "->", "instance", "(", "'app'", ",", "$", "this", ")", ";", "$", "this", "->", "instance", "(", "'Illuminate\\Container\\Container'", ",", "$", "this", ")", ";", "$", "this", "->", "instance", "(", "'path'", ",", "$", "this", "->", "path", "(", ")", ")", ";", "$", "this", "->", "configure", "(", "'app'", ")", ";", "$", "this", "->", "configure", "(", "'scout'", ")", ";", "$", "this", "->", "configure", "(", "'services'", ")", ";", "$", "this", "->", "configure", "(", "'session'", ")", ";", "$", "this", "->", "configure", "(", "'mail'", ")", ";", "$", "this", "->", "registerContainerAliases", "(", ")", ";", "$", "this", "->", "bindActionsAndFilters", "(", ")", ";", "$", "this", "->", "register", "(", "\\", "Illuminate", "\\", "Session", "\\", "SessionServiceProvider", "::", "class", ")", ";", "$", "this", "->", "register", "(", "\\", "FatPanda", "\\", "Illuminate", "\\", "WordPress", "\\", "Providers", "\\", "Mail", "\\", "MailServiceProvider", "::", "class", ")", ";", "$", "this", "->", "register", "(", "Providers", "\\", "Session", "\\", "WordPressSessionServiceProvider", "::", "class", ")", ";", "$", "this", "->", "register", "(", "Providers", "\\", "Scout", "\\", "ScoutServiceProvider", "::", "class", ")", ";", "$", "this", "->", "singleton", "(", "\\", "Illuminate", "\\", "Contracts", "\\", "Console", "\\", "Kernel", "::", "class", ",", "WordPressConsoleKernel", "::", "class", ")", ";", "$", "this", "->", "singleton", "(", "\\", "Illuminate", "\\", "Contracts", "\\", "Debug", "\\", "ExceptionHandler", "::", "class", ",", "WordPressExceptionHandler", "::", "class", ")", ";", "}" ]
Bootstrap the plugin container. @return void
[ "Bootstrap", "the", "plugin", "container", "." ]
b426ca81a55367459430c974932ee5a941d759d8
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Plugin.php#L662-L686
16,191
withfatpanda/illuminate-wordpress
src/WordPress/Plugin.php
Plugin.storagePath
public function storagePath($path = null) { return WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . Str::slug($this->getNamespaceName()) . DIRECTORY_SEPARATOR . ( $path ? DIRECTORY_SEPARATOR . $path : $path ); }
php
public function storagePath($path = null) { return WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . Str::slug($this->getNamespaceName()) . DIRECTORY_SEPARATOR . ( $path ? DIRECTORY_SEPARATOR . $path : $path ); }
[ "public", "function", "storagePath", "(", "$", "path", "=", "null", ")", "{", "return", "WP_CONTENT_DIR", ".", "DIRECTORY_SEPARATOR", ".", "'storage'", ".", "DIRECTORY_SEPARATOR", ".", "Str", "::", "slug", "(", "$", "this", "->", "getNamespaceName", "(", ")", ")", ".", "DIRECTORY_SEPARATOR", ".", "(", "$", "path", "?", "DIRECTORY_SEPARATOR", ".", "$", "path", ":", "$", "path", ")", ";", "}" ]
Get the storage path for the plugin @param string|null $path @return string
[ "Get", "the", "storage", "path", "for", "the", "plugin" ]
b426ca81a55367459430c974932ee5a941d759d8
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Plugin.php#L747-L750
16,192
withfatpanda/illuminate-wordpress
src/WordPress/Plugin.php
Plugin.register
public function register($provider, $options = [], $force = false) { if (is_string($provider) || is_class($provider)) { $implements = class_implements($provider); if (isset($implements['FatPanda\Illuminate\WordPress\Concerns\CustomSchema'])) { $this->customSchema[] = $provider; return $this; } if (isset($implements['FatPanda\Illuminate\WordPress\Concerns\CanShortcode'])) { // we have to do this right away call_user_func_array($provider . '::register', [ $this ]); return $this; } } if (!$provider instanceof ServiceProvider) { $provider = new $provider($this); } if (array_key_exists($providerName = get_class($provider), $this->loadedProviders)) { return $this; } $this->loadedProviders[$providerName] = true; if (method_exists($provider, 'register')) { $provider->register(); } if (method_exists($provider, 'boot')) { return $this->call([$provider, 'boot']); } return $this; }
php
public function register($provider, $options = [], $force = false) { if (is_string($provider) || is_class($provider)) { $implements = class_implements($provider); if (isset($implements['FatPanda\Illuminate\WordPress\Concerns\CustomSchema'])) { $this->customSchema[] = $provider; return $this; } if (isset($implements['FatPanda\Illuminate\WordPress\Concerns\CanShortcode'])) { // we have to do this right away call_user_func_array($provider . '::register', [ $this ]); return $this; } } if (!$provider instanceof ServiceProvider) { $provider = new $provider($this); } if (array_key_exists($providerName = get_class($provider), $this->loadedProviders)) { return $this; } $this->loadedProviders[$providerName] = true; if (method_exists($provider, 'register')) { $provider->register(); } if (method_exists($provider, 'boot')) { return $this->call([$provider, 'boot']); } return $this; }
[ "public", "function", "register", "(", "$", "provider", ",", "$", "options", "=", "[", "]", ",", "$", "force", "=", "false", ")", "{", "if", "(", "is_string", "(", "$", "provider", ")", "||", "is_class", "(", "$", "provider", ")", ")", "{", "$", "implements", "=", "class_implements", "(", "$", "provider", ")", ";", "if", "(", "isset", "(", "$", "implements", "[", "'FatPanda\\Illuminate\\WordPress\\Concerns\\CustomSchema'", "]", ")", ")", "{", "$", "this", "->", "customSchema", "[", "]", "=", "$", "provider", ";", "return", "$", "this", ";", "}", "if", "(", "isset", "(", "$", "implements", "[", "'FatPanda\\Illuminate\\WordPress\\Concerns\\CanShortcode'", "]", ")", ")", "{", "// we have to do this right away", "call_user_func_array", "(", "$", "provider", ".", "'::register'", ",", "[", "$", "this", "]", ")", ";", "return", "$", "this", ";", "}", "}", "if", "(", "!", "$", "provider", "instanceof", "ServiceProvider", ")", "{", "$", "provider", "=", "new", "$", "provider", "(", "$", "this", ")", ";", "}", "if", "(", "array_key_exists", "(", "$", "providerName", "=", "get_class", "(", "$", "provider", ")", ",", "$", "this", "->", "loadedProviders", ")", ")", "{", "return", "$", "this", ";", "}", "$", "this", "->", "loadedProviders", "[", "$", "providerName", "]", "=", "true", ";", "if", "(", "method_exists", "(", "$", "provider", ",", "'register'", ")", ")", "{", "$", "provider", "->", "register", "(", ")", ";", "}", "if", "(", "method_exists", "(", "$", "provider", ",", "'boot'", ")", ")", "{", "return", "$", "this", "->", "call", "(", "[", "$", "provider", ",", "'boot'", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
Register a service provider or a CustomSchema with the plugin. @param mixed $provider @param array $options @param bool $force @return Plugin
[ "Register", "a", "service", "provider", "or", "a", "CustomSchema", "with", "the", "plugin", "." ]
b426ca81a55367459430c974932ee5a941d759d8
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Plugin.php#L998-L1034
16,193
withfatpanda/illuminate-wordpress
src/WordPress/Plugin.php
Plugin.registerArtisanCommand
protected function registerArtisanCommand() { if (!class_exists('WP_CLI')) { return false; } /** * Run Laravel Artisan for this plugin */ \WP_CLI::add_command($this->getCLICommandName(), function() { $args = []; // rebuild args, because WP_CLI does stuff to it... if (!empty($_SERVER['argv'])) { $args = array_slice($_SERVER['argv'], 2); array_unshift($args, $_SERVER['argv'][0]); } $this->artisan->handle( new \Symfony\Component\Console\Input\ArgvInput($args), new \Symfony\Component\Console\Output\ConsoleOutput ); }); }
php
protected function registerArtisanCommand() { if (!class_exists('WP_CLI')) { return false; } /** * Run Laravel Artisan for this plugin */ \WP_CLI::add_command($this->getCLICommandName(), function() { $args = []; // rebuild args, because WP_CLI does stuff to it... if (!empty($_SERVER['argv'])) { $args = array_slice($_SERVER['argv'], 2); array_unshift($args, $_SERVER['argv'][0]); } $this->artisan->handle( new \Symfony\Component\Console\Input\ArgvInput($args), new \Symfony\Component\Console\Output\ConsoleOutput ); }); }
[ "protected", "function", "registerArtisanCommand", "(", ")", "{", "if", "(", "!", "class_exists", "(", "'WP_CLI'", ")", ")", "{", "return", "false", ";", "}", "/**\n * Run Laravel Artisan for this plugin\n */", "\\", "WP_CLI", "::", "add_command", "(", "$", "this", "->", "getCLICommandName", "(", ")", ",", "function", "(", ")", "{", "$", "args", "=", "[", "]", ";", "// rebuild args, because WP_CLI does stuff to it...", "if", "(", "!", "empty", "(", "$", "_SERVER", "[", "'argv'", "]", ")", ")", "{", "$", "args", "=", "array_slice", "(", "$", "_SERVER", "[", "'argv'", "]", ",", "2", ")", ";", "array_unshift", "(", "$", "args", ",", "$", "_SERVER", "[", "'argv'", "]", "[", "0", "]", ")", ";", "}", "$", "this", "->", "artisan", "->", "handle", "(", "new", "\\", "Symfony", "\\", "Component", "\\", "Console", "\\", "Input", "\\", "ArgvInput", "(", "$", "args", ")", ",", "new", "\\", "Symfony", "\\", "Component", "\\", "Console", "\\", "Output", "\\", "ConsoleOutput", ")", ";", "}", ")", ";", "}" ]
Create a WP-CLI command for running Artisan.
[ "Create", "a", "WP", "-", "CLI", "command", "for", "running", "Artisan", "." ]
b426ca81a55367459430c974932ee5a941d759d8
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Plugin.php#L1083-L1106
16,194
withfatpanda/illuminate-wordpress
src/WordPress/Plugin.php
Plugin.registerRestRouter
protected function registerRestRouter() { $this->singleton('FatPanda\Illuminate\WordPress\Http\Router', function() { // create the router $router = new Router($this); $router->setNamespace($this->getRestNamespace()); $router->setVersion($this->getRestVersion()); $router->setControllerClasspath($this->getNamespaceName() . '\\Http\\Controllers'); // load the routes $plugin = $this; require $this->basePath('src/routes.php'); return $router; }); }
php
protected function registerRestRouter() { $this->singleton('FatPanda\Illuminate\WordPress\Http\Router', function() { // create the router $router = new Router($this); $router->setNamespace($this->getRestNamespace()); $router->setVersion($this->getRestVersion()); $router->setControllerClasspath($this->getNamespaceName() . '\\Http\\Controllers'); // load the routes $plugin = $this; require $this->basePath('src/routes.php'); return $router; }); }
[ "protected", "function", "registerRestRouter", "(", ")", "{", "$", "this", "->", "singleton", "(", "'FatPanda\\Illuminate\\WordPress\\Http\\Router'", ",", "function", "(", ")", "{", "// create the router", "$", "router", "=", "new", "Router", "(", "$", "this", ")", ";", "$", "router", "->", "setNamespace", "(", "$", "this", "->", "getRestNamespace", "(", ")", ")", ";", "$", "router", "->", "setVersion", "(", "$", "this", "->", "getRestVersion", "(", ")", ")", ";", "$", "router", "->", "setControllerClasspath", "(", "$", "this", "->", "getNamespaceName", "(", ")", ".", "'\\\\Http\\\\Controllers'", ")", ";", "// load the routes", "$", "plugin", "=", "$", "this", ";", "require", "$", "this", "->", "basePath", "(", "'src/routes.php'", ")", ";", "return", "$", "router", ";", "}", ")", ";", "}" ]
Create router instance and load routes
[ "Create", "router", "instance", "and", "load", "routes" ]
b426ca81a55367459430c974932ee5a941d759d8
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Plugin.php#L1156-L1170
16,195
FrenchFrogs/framework
src/Table/Table/Export.php
Export.toCsv
public function toCsv($filename = null) { // on set le nom du fichier if (!is_null($filename)) { $this->setFilename($filename); } // si pas de nom de fichier setté, on met celui par default if (!$this->hasFilename()) { $this->setFilename($this->filenameDefault); } // backup du renderer $renderer = $this->getRenderer(); // render export $this->setRenderer(new Csv()); // appel du collback if ($this->hasExport()){ call_user_func($this->export, $this); } // rendu $this->render(); // restore renderer $this->setRenderer($renderer); return $this; }
php
public function toCsv($filename = null) { // on set le nom du fichier if (!is_null($filename)) { $this->setFilename($filename); } // si pas de nom de fichier setté, on met celui par default if (!$this->hasFilename()) { $this->setFilename($this->filenameDefault); } // backup du renderer $renderer = $this->getRenderer(); // render export $this->setRenderer(new Csv()); // appel du collback if ($this->hasExport()){ call_user_func($this->export, $this); } // rendu $this->render(); // restore renderer $this->setRenderer($renderer); return $this; }
[ "public", "function", "toCsv", "(", "$", "filename", "=", "null", ")", "{", "// on set le nom du fichier", "if", "(", "!", "is_null", "(", "$", "filename", ")", ")", "{", "$", "this", "->", "setFilename", "(", "$", "filename", ")", ";", "}", "// si pas de nom de fichier setté, on met celui par default", "if", "(", "!", "$", "this", "->", "hasFilename", "(", ")", ")", "{", "$", "this", "->", "setFilename", "(", "$", "this", "->", "filenameDefault", ")", ";", "}", "// backup du renderer", "$", "renderer", "=", "$", "this", "->", "getRenderer", "(", ")", ";", "// render export", "$", "this", "->", "setRenderer", "(", "new", "Csv", "(", ")", ")", ";", "// appel du collback", "if", "(", "$", "this", "->", "hasExport", "(", ")", ")", "{", "call_user_func", "(", "$", "this", "->", "export", ",", "$", "this", ")", ";", "}", "// rendu", "$", "this", "->", "render", "(", ")", ";", "// restore renderer", "$", "this", "->", "setRenderer", "(", "$", "renderer", ")", ";", "return", "$", "this", ";", "}" ]
Export dans un fichier CSV @param $filename @param bool $download @return $this
[ "Export", "dans", "un", "fichier", "CSV" ]
a4838c698a5600437e87dac6d35ba8ebe32c4395
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Table/Table/Export.php#L119-L150
16,196
Graphiques-Digitale/silverstripe-seo-metadata
code/SEO_Metadata_SiteTree_DataExtension.php
SEO_Metadata_SiteTree_DataExtension.getSEOFields
public function getSEOFields() { // Variables $config = SiteConfig::current_site_config(); $SEO = []; // Canonical if ($config->CanonicalEnabled()) { $SEO[] = ReadonlyField::create('ReadonlyMetaCanonical', 'link rel="canonical"', $this->owner->AbsoluteLink()); } // Title if ($config->TitleEnabled()) { $SEO[] = TextField::create('MetaTitle', 'meta title') ->setAttribute('placeholder', $this->owner->GenerateTitle()); } // Description $SEO[] = TextareaField::create('MetaDescription', 'meta description') ->setAttribute('placeholder', $this->owner->GenerateDescriptionFromContent()); // ExtraMeta if ($config->ExtraMetaEnabled()) { $SEO[] = TextareaField::create('ExtraMeta', 'Custom Metadata'); } return $SEO; }
php
public function getSEOFields() { // Variables $config = SiteConfig::current_site_config(); $SEO = []; // Canonical if ($config->CanonicalEnabled()) { $SEO[] = ReadonlyField::create('ReadonlyMetaCanonical', 'link rel="canonical"', $this->owner->AbsoluteLink()); } // Title if ($config->TitleEnabled()) { $SEO[] = TextField::create('MetaTitle', 'meta title') ->setAttribute('placeholder', $this->owner->GenerateTitle()); } // Description $SEO[] = TextareaField::create('MetaDescription', 'meta description') ->setAttribute('placeholder', $this->owner->GenerateDescriptionFromContent()); // ExtraMeta if ($config->ExtraMetaEnabled()) { $SEO[] = TextareaField::create('ExtraMeta', 'Custom Metadata'); } return $SEO; }
[ "public", "function", "getSEOFields", "(", ")", "{", "// Variables", "$", "config", "=", "SiteConfig", "::", "current_site_config", "(", ")", ";", "$", "SEO", "=", "[", "]", ";", "// Canonical", "if", "(", "$", "config", "->", "CanonicalEnabled", "(", ")", ")", "{", "$", "SEO", "[", "]", "=", "ReadonlyField", "::", "create", "(", "'ReadonlyMetaCanonical'", ",", "'link rel=\"canonical\"'", ",", "$", "this", "->", "owner", "->", "AbsoluteLink", "(", ")", ")", ";", "}", "// Title", "if", "(", "$", "config", "->", "TitleEnabled", "(", ")", ")", "{", "$", "SEO", "[", "]", "=", "TextField", "::", "create", "(", "'MetaTitle'", ",", "'meta title'", ")", "->", "setAttribute", "(", "'placeholder'", ",", "$", "this", "->", "owner", "->", "GenerateTitle", "(", ")", ")", ";", "}", "// Description", "$", "SEO", "[", "]", "=", "TextareaField", "::", "create", "(", "'MetaDescription'", ",", "'meta description'", ")", "->", "setAttribute", "(", "'placeholder'", ",", "$", "this", "->", "owner", "->", "GenerateDescriptionFromContent", "(", ")", ")", ";", "// ExtraMeta", "if", "(", "$", "config", "->", "ExtraMetaEnabled", "(", ")", ")", "{", "$", "SEO", "[", "]", "=", "TextareaField", "::", "create", "(", "'ExtraMeta'", ",", "'Custom Metadata'", ")", ";", "}", "return", "$", "SEO", ";", "}" ]
Gets SEO fields. @return array
[ "Gets", "SEO", "fields", "." ]
f92128688a60b6c6b514b6efb1486ac60f4a8e03
https://github.com/Graphiques-Digitale/silverstripe-seo-metadata/blob/f92128688a60b6c6b514b6efb1486ac60f4a8e03/code/SEO_Metadata_SiteTree_DataExtension.php#L51-L73
16,197
Graphiques-Digitale/silverstripe-seo-metadata
code/SEO_Metadata_SiteTree_DataExtension.php
SEO_Metadata_SiteTree_DataExtension.getFullOutput
public function getFullOutput() { return array( LiteralField::create('HeaderMetadata', '<pre class="bold">$Metadata()</pre>'), LiteralField::create('LiteralMetadata', '<pre>' . nl2br(htmlentities(trim($this->owner->Metadata()), ENT_QUOTES)) . '</pre>') ); }
php
public function getFullOutput() { return array( LiteralField::create('HeaderMetadata', '<pre class="bold">$Metadata()</pre>'), LiteralField::create('LiteralMetadata', '<pre>' . nl2br(htmlentities(trim($this->owner->Metadata()), ENT_QUOTES)) . '</pre>') ); }
[ "public", "function", "getFullOutput", "(", ")", "{", "return", "array", "(", "LiteralField", "::", "create", "(", "'HeaderMetadata'", ",", "'<pre class=\"bold\">$Metadata()</pre>'", ")", ",", "LiteralField", "::", "create", "(", "'LiteralMetadata'", ",", "'<pre>'", ".", "nl2br", "(", "htmlentities", "(", "trim", "(", "$", "this", "->", "owner", "->", "Metadata", "(", ")", ")", ",", "ENT_QUOTES", ")", ")", ".", "'</pre>'", ")", ")", ";", "}" ]
Gets the full output. @return array
[ "Gets", "the", "full", "output", "." ]
f92128688a60b6c6b514b6efb1486ac60f4a8e03
https://github.com/Graphiques-Digitale/silverstripe-seo-metadata/blob/f92128688a60b6c6b514b6efb1486ac60f4a8e03/code/SEO_Metadata_SiteTree_DataExtension.php#L80-L86
16,198
Graphiques-Digitale/silverstripe-seo-metadata
code/SEO_Metadata_SiteTree_DataExtension.php
SEO_Metadata_SiteTree_DataExtension.Metadata
public function Metadata() { // variables $config = SiteConfig::current_site_config(); // begin SEO $metadata = PHP_EOL . $this->owner->MarkupComment('SEO'); // register extension update hook $this->owner->extend('updateMetadata', $config, $this->owner, $metadata); // end $metadata .= $this->owner->MarkupComment('END SEO'); // return return $metadata; }
php
public function Metadata() { // variables $config = SiteConfig::current_site_config(); // begin SEO $metadata = PHP_EOL . $this->owner->MarkupComment('SEO'); // register extension update hook $this->owner->extend('updateMetadata', $config, $this->owner, $metadata); // end $metadata .= $this->owner->MarkupComment('END SEO'); // return return $metadata; }
[ "public", "function", "Metadata", "(", ")", "{", "// variables", "$", "config", "=", "SiteConfig", "::", "current_site_config", "(", ")", ";", "// begin SEO", "$", "metadata", "=", "PHP_EOL", ".", "$", "this", "->", "owner", "->", "MarkupComment", "(", "'SEO'", ")", ";", "// register extension update hook", "$", "this", "->", "owner", "->", "extend", "(", "'updateMetadata'", ",", "$", "config", ",", "$", "this", "->", "owner", ",", "$", "metadata", ")", ";", "// end", "$", "metadata", ".=", "$", "this", "->", "owner", "->", "MarkupComment", "(", "'END SEO'", ")", ";", "// return", "return", "$", "metadata", ";", "}" ]
Main function to format & output metadata as an HTML string. Use the `updateMetadata($config, $owner, $metadata)` update hook when extending `DataExtension`s. @return string
[ "Main", "function", "to", "format", "&", "output", "metadata", "as", "an", "HTML", "string", "." ]
f92128688a60b6c6b514b6efb1486ac60f4a8e03
https://github.com/Graphiques-Digitale/silverstripe-seo-metadata/blob/f92128688a60b6c6b514b6efb1486ac60f4a8e03/code/SEO_Metadata_SiteTree_DataExtension.php#L95-L107
16,199
Graphiques-Digitale/silverstripe-seo-metadata
code/SEO_Metadata_SiteTree_DataExtension.php
SEO_Metadata_SiteTree_DataExtension.updateMetadata
public function updateMetadata(SiteConfig $config, SiteTree $owner, &$metadata) { // metadata $metadata .= $owner->MarkupComment('Metadata'); // charset if ($config->CharsetEnabled()) { $metadata .= '<meta charset="' . $config->Charset() . '" />' . PHP_EOL; } // canonical if ($config->CanonicalEnabled()) { $metadata .= $owner->MarkupLink('canonical', $owner->AbsoluteLink()); } // title if ($config->TitleEnabled()) { $metadata .= '<title>' . $owner->encodeContent($owner->GenerateTitle(), $config->Charset()) . '</title>' . PHP_EOL; } // description if ($description = $owner->GenerateDescription()) { $metadata .= $owner->MarkupMeta('description', $description, $config->Charset()); } // extra metadata if ($config->ExtraMetaEnabled()) { $metadata .= $owner->MarkupComment('Extra Metadata'); $metadata .= $owner->GenerateExtraMeta(); } }
php
public function updateMetadata(SiteConfig $config, SiteTree $owner, &$metadata) { // metadata $metadata .= $owner->MarkupComment('Metadata'); // charset if ($config->CharsetEnabled()) { $metadata .= '<meta charset="' . $config->Charset() . '" />' . PHP_EOL; } // canonical if ($config->CanonicalEnabled()) { $metadata .= $owner->MarkupLink('canonical', $owner->AbsoluteLink()); } // title if ($config->TitleEnabled()) { $metadata .= '<title>' . $owner->encodeContent($owner->GenerateTitle(), $config->Charset()) . '</title>' . PHP_EOL; } // description if ($description = $owner->GenerateDescription()) { $metadata .= $owner->MarkupMeta('description', $description, $config->Charset()); } // extra metadata if ($config->ExtraMetaEnabled()) { $metadata .= $owner->MarkupComment('Extra Metadata'); $metadata .= $owner->GenerateExtraMeta(); } }
[ "public", "function", "updateMetadata", "(", "SiteConfig", "$", "config", ",", "SiteTree", "$", "owner", ",", "&", "$", "metadata", ")", "{", "// metadata", "$", "metadata", ".=", "$", "owner", "->", "MarkupComment", "(", "'Metadata'", ")", ";", "// charset", "if", "(", "$", "config", "->", "CharsetEnabled", "(", ")", ")", "{", "$", "metadata", ".=", "'<meta charset=\"'", ".", "$", "config", "->", "Charset", "(", ")", ".", "'\" />'", ".", "PHP_EOL", ";", "}", "// canonical", "if", "(", "$", "config", "->", "CanonicalEnabled", "(", ")", ")", "{", "$", "metadata", ".=", "$", "owner", "->", "MarkupLink", "(", "'canonical'", ",", "$", "owner", "->", "AbsoluteLink", "(", ")", ")", ";", "}", "// title", "if", "(", "$", "config", "->", "TitleEnabled", "(", ")", ")", "{", "$", "metadata", ".=", "'<title>'", ".", "$", "owner", "->", "encodeContent", "(", "$", "owner", "->", "GenerateTitle", "(", ")", ",", "$", "config", "->", "Charset", "(", ")", ")", ".", "'</title>'", ".", "PHP_EOL", ";", "}", "// description", "if", "(", "$", "description", "=", "$", "owner", "->", "GenerateDescription", "(", ")", ")", "{", "$", "metadata", ".=", "$", "owner", "->", "MarkupMeta", "(", "'description'", ",", "$", "description", ",", "$", "config", "->", "Charset", "(", ")", ")", ";", "}", "// extra metadata", "if", "(", "$", "config", "->", "ExtraMetaEnabled", "(", ")", ")", "{", "$", "metadata", ".=", "$", "owner", "->", "MarkupComment", "(", "'Extra Metadata'", ")", ";", "$", "metadata", ".=", "$", "owner", "->", "GenerateExtraMeta", "(", ")", ";", "}", "}" ]
Updates metadata fields. @param SiteConfig $config @param SiteTree $owner @param string $metadata @return void
[ "Updates", "metadata", "fields", "." ]
f92128688a60b6c6b514b6efb1486ac60f4a8e03
https://github.com/Graphiques-Digitale/silverstripe-seo-metadata/blob/f92128688a60b6c6b514b6efb1486ac60f4a8e03/code/SEO_Metadata_SiteTree_DataExtension.php#L122-L147