repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
superfaktura/apiclient
SFAPIclient/Requests/Transport/cURL.php
Requests_Transport_cURL.stream_headers
protected function stream_headers($handle, $headers) { // Why do we do this? cURL will send both the final response and any // interim responses, such as a 100 Continue. We don't need that. // (We may want to keep this somewhere just in case) if ($this->done_headers) { $this->headers = ''; $this->done_headers = false; } $this->headers .= $headers; if ($headers === "\r\n") { $this->done_headers = true; } return strlen($headers); }
php
protected function stream_headers($handle, $headers) { // Why do we do this? cURL will send both the final response and any // interim responses, such as a 100 Continue. We don't need that. // (We may want to keep this somewhere just in case) if ($this->done_headers) { $this->headers = ''; $this->done_headers = false; } $this->headers .= $headers; if ($headers === "\r\n") { $this->done_headers = true; } return strlen($headers); }
[ "protected", "function", "stream_headers", "(", "$", "handle", ",", "$", "headers", ")", "{", "// Why do we do this? cURL will send both the final response and any", "// interim responses, such as a 100 Continue. We don't need that.", "// (We may want to keep this somewhere just in case)", "if", "(", "$", "this", "->", "done_headers", ")", "{", "$", "this", "->", "headers", "=", "''", ";", "$", "this", "->", "done_headers", "=", "false", ";", "}", "$", "this", "->", "headers", ".=", "$", "headers", ";", "if", "(", "$", "headers", "===", "\"\\r\\n\"", ")", "{", "$", "this", "->", "done_headers", "=", "true", ";", "}", "return", "strlen", "(", "$", "headers", ")", ";", "}" ]
Collect the headers as they are received @param resource $handle cURL resource @param string $headers Header string @return integer Length of provided header
[ "Collect", "the", "headers", "as", "they", "are", "received" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/Transport/cURL.php#L155-L169
train
doctrine/KeyValueStore
lib/Doctrine/KeyValueStore/Storage/MongoDbStorage.php
MongoDbStorage.initialize
public function initialize() { if (null !== $this->collection) { return; } if (empty($this->dbOptions['database'])) { throw new \RuntimeException('The option "database" must be set'); } if (empty($this->dbOptions['collection'])) { throw new \RuntimeException('The option "collection" must be set'); } $this->collection = $this ->mongo ->selectDB($this->dbOptions['database']) ->selectCollection($this->dbOptions['collection']); }
php
public function initialize() { if (null !== $this->collection) { return; } if (empty($this->dbOptions['database'])) { throw new \RuntimeException('The option "database" must be set'); } if (empty($this->dbOptions['collection'])) { throw new \RuntimeException('The option "collection" must be set'); } $this->collection = $this ->mongo ->selectDB($this->dbOptions['database']) ->selectCollection($this->dbOptions['collection']); }
[ "public", "function", "initialize", "(", ")", "{", "if", "(", "null", "!==", "$", "this", "->", "collection", ")", "{", "return", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "dbOptions", "[", "'database'", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'The option \"database\" must be set'", ")", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "dbOptions", "[", "'collection'", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'The option \"collection\" must be set'", ")", ";", "}", "$", "this", "->", "collection", "=", "$", "this", "->", "mongo", "->", "selectDB", "(", "$", "this", "->", "dbOptions", "[", "'database'", "]", ")", "->", "selectCollection", "(", "$", "this", "->", "dbOptions", "[", "'collection'", "]", ")", ";", "}" ]
Initialize the mongodb collection @throws \RuntimeException
[ "Initialize", "the", "mongodb", "collection" ]
8ba3db4ce7727f19cdb91519968ba4259b588277
https://github.com/doctrine/KeyValueStore/blob/8ba3db4ce7727f19cdb91519968ba4259b588277/lib/Doctrine/KeyValueStore/Storage/MongoDbStorage.php#L67-L84
train
doctrine/KeyValueStore
lib/Doctrine/KeyValueStore/Storage/ArrayStorage.php
ArrayStorage.update
public function update($storageName, $key, array $data) { if (!isset($this->data[$storageName])) { $this->data[$storageName] = []; } $this->data[$storageName][serialize($key)] = $data; }
php
public function update($storageName, $key, array $data) { if (!isset($this->data[$storageName])) { $this->data[$storageName] = []; } $this->data[$storageName][serialize($key)] = $data; }
[ "public", "function", "update", "(", "$", "storageName", ",", "$", "key", ",", "array", "$", "data", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "data", "[", "$", "storageName", "]", ")", ")", "{", "$", "this", "->", "data", "[", "$", "storageName", "]", "=", "[", "]", ";", "}", "$", "this", "->", "data", "[", "$", "storageName", "]", "[", "serialize", "(", "$", "key", ")", "]", "=", "$", "data", ";", "}" ]
Update data into the given key. @param array|string $key @param array $data
[ "Update", "data", "into", "the", "given", "key", "." ]
8ba3db4ce7727f19cdb91519968ba4259b588277
https://github.com/doctrine/KeyValueStore/blob/8ba3db4ce7727f19cdb91519968ba4259b588277/lib/Doctrine/KeyValueStore/Storage/ArrayStorage.php#L80-L87
train
superfaktura/apiclient
SFAPIclient/Requests/Auth/Basic.php
Requests_Auth_Basic.curl_before_send
public function curl_before_send(&$handle) { curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString()); }
php
public function curl_before_send(&$handle) { curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString()); }
[ "public", "function", "curl_before_send", "(", "&", "$", "handle", ")", "{", "curl_setopt", "(", "$", "handle", ",", "CURLOPT_HTTPAUTH", ",", "CURLAUTH_BASIC", ")", ";", "curl_setopt", "(", "$", "handle", ",", "CURLOPT_USERPWD", ",", "$", "this", "->", "getAuthString", "(", ")", ")", ";", "}" ]
Set cURL parameters before the data is sent @param resource $handle cURL resource
[ "Set", "cURL", "parameters", "before", "the", "data", "is", "sent" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/Auth/Basic.php#L66-L69
train
yiisoft/view
src/widgets/ActiveForm.php
ActiveForm.run
public function run() { if (!empty($this->_fields)) { throw new InvalidCallException('Each beginField() should have a matching endField() call.'); } $content = ob_get_clean(); $html = Html::beginForm($this->action, $this->method, $this->options); $html .= $content; $html .= Html::endForm(); return $html; }
php
public function run() { if (!empty($this->_fields)) { throw new InvalidCallException('Each beginField() should have a matching endField() call.'); } $content = ob_get_clean(); $html = Html::beginForm($this->action, $this->method, $this->options); $html .= $content; $html .= Html::endForm(); return $html; }
[ "public", "function", "run", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "_fields", ")", ")", "{", "throw", "new", "InvalidCallException", "(", "'Each beginField() should have a matching endField() call.'", ")", ";", "}", "$", "content", "=", "ob_get_clean", "(", ")", ";", "$", "html", "=", "Html", "::", "beginForm", "(", "$", "this", "->", "action", ",", "$", "this", "->", "method", ",", "$", "this", "->", "options", ")", ";", "$", "html", ".=", "$", "content", ";", "$", "html", ".=", "Html", "::", "endForm", "(", ")", ";", "return", "$", "html", ";", "}" ]
Runs the widget. This registers the necessary JavaScript code and renders the form open and close tags. @throws InvalidCallException if `beginField()` and `endField()` calls are not matching.
[ "Runs", "the", "widget", ".", "This", "registers", "the", "necessary", "JavaScript", "code", "and", "renders", "the", "form", "open", "and", "close", "tags", "." ]
206f58f0c33a7a861984e4c67de470529b19ebb5
https://github.com/yiisoft/view/blob/206f58f0c33a7a861984e4c67de470529b19ebb5/src/widgets/ActiveForm.php#L202-L214
train
doctrine/KeyValueStore
lib/Doctrine/KeyValueStore/Query/RangeQuery.php
RangeQuery.execute
public function execute() { $storage = $this->em->unwrap(); if (! $storage instanceof RangeQueryStorage) { throw new \RuntimeException( 'The storage backend ' . $storage->getName() . ' does not support range queries.' ); } $uow = $this->em->getUnitOfWork(); $class = $this->em->getClassMetadata($this->className); $rowHydration = function ($row) use ($uow, $class) { $key = []; foreach ($class->identifier as $id) { $key[$id] = $row[$id]; } return $uow->createEntity($class, $key, $row); }; return $storage->executeRangeQuery($this, $class->storageName, $class->identifier, $rowHydration); }
php
public function execute() { $storage = $this->em->unwrap(); if (! $storage instanceof RangeQueryStorage) { throw new \RuntimeException( 'The storage backend ' . $storage->getName() . ' does not support range queries.' ); } $uow = $this->em->getUnitOfWork(); $class = $this->em->getClassMetadata($this->className); $rowHydration = function ($row) use ($uow, $class) { $key = []; foreach ($class->identifier as $id) { $key[$id] = $row[$id]; } return $uow->createEntity($class, $key, $row); }; return $storage->executeRangeQuery($this, $class->storageName, $class->identifier, $rowHydration); }
[ "public", "function", "execute", "(", ")", "{", "$", "storage", "=", "$", "this", "->", "em", "->", "unwrap", "(", ")", ";", "if", "(", "!", "$", "storage", "instanceof", "RangeQueryStorage", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'The storage backend '", ".", "$", "storage", "->", "getName", "(", ")", ".", "' does not support range queries.'", ")", ";", "}", "$", "uow", "=", "$", "this", "->", "em", "->", "getUnitOfWork", "(", ")", ";", "$", "class", "=", "$", "this", "->", "em", "->", "getClassMetadata", "(", "$", "this", "->", "className", ")", ";", "$", "rowHydration", "=", "function", "(", "$", "row", ")", "use", "(", "$", "uow", ",", "$", "class", ")", "{", "$", "key", "=", "[", "]", ";", "foreach", "(", "$", "class", "->", "identifier", "as", "$", "id", ")", "{", "$", "key", "[", "$", "id", "]", "=", "$", "row", "[", "$", "id", "]", ";", "}", "return", "$", "uow", "->", "createEntity", "(", "$", "class", ",", "$", "key", ",", "$", "row", ")", ";", "}", ";", "return", "$", "storage", "->", "executeRangeQuery", "(", "$", "this", ",", "$", "class", "->", "storageName", ",", "$", "class", "->", "identifier", ",", "$", "rowHydration", ")", ";", "}" ]
Execute query and return a result iterator. @return ResultIterator
[ "Execute", "query", "and", "return", "a", "result", "iterator", "." ]
8ba3db4ce7727f19cdb91519968ba4259b588277
https://github.com/doctrine/KeyValueStore/blob/8ba3db4ce7727f19cdb91519968ba4259b588277/lib/Doctrine/KeyValueStore/Query/RangeQuery.php#L207-L229
train
superfaktura/apiclient
SFAPIclient/Requests/IRI.php
Requests_IRI.remove_dot_segments
private function remove_dot_segments($input) { $output = ''; while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input === '.' || $input === '..') { // A: If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise, if (strpos($input, '../') === 0) { $input = substr($input, 3); } elseif (strpos($input, './') === 0) { $input = substr($input, 2); } // B: if the input buffer begins with a prefix of "/./" or "/.", where "." is a complete path segment, then replace that prefix with "/" in the input buffer; otherwise, elseif (strpos($input, '/./') === 0) { $input = substr($input, 2); } elseif ($input === '/.') { $input = '/'; } // C: if the input buffer begins with a prefix of "/../" or "/..", where ".." is a complete path segment, then replace that prefix with "/" in the input buffer and remove the last segment and its preceding "/" (if any) from the output buffer; otherwise, elseif (strpos($input, '/../') === 0) { $input = substr($input, 3); $output = substr_replace($output, '', strrpos($output, '/')); } elseif ($input === '/..') { $input = '/'; $output = substr_replace($output, '', strrpos($output, '/')); } // D: if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise, elseif ($input === '.' || $input === '..') { $input = ''; } // E: move the first path segment in the input buffer to the end of the output buffer, including the initial "/" character (if any) and any subsequent characters up to, but not including, the next "/" character or the end of the input buffer elseif (($pos = strpos($input, '/', 1)) !== false) { $output .= substr($input, 0, $pos); $input = substr_replace($input, '', 0, $pos); } else { $output .= $input; $input = ''; } } return $output . $input; }
php
private function remove_dot_segments($input) { $output = ''; while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input === '.' || $input === '..') { // A: If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise, if (strpos($input, '../') === 0) { $input = substr($input, 3); } elseif (strpos($input, './') === 0) { $input = substr($input, 2); } // B: if the input buffer begins with a prefix of "/./" or "/.", where "." is a complete path segment, then replace that prefix with "/" in the input buffer; otherwise, elseif (strpos($input, '/./') === 0) { $input = substr($input, 2); } elseif ($input === '/.') { $input = '/'; } // C: if the input buffer begins with a prefix of "/../" or "/..", where ".." is a complete path segment, then replace that prefix with "/" in the input buffer and remove the last segment and its preceding "/" (if any) from the output buffer; otherwise, elseif (strpos($input, '/../') === 0) { $input = substr($input, 3); $output = substr_replace($output, '', strrpos($output, '/')); } elseif ($input === '/..') { $input = '/'; $output = substr_replace($output, '', strrpos($output, '/')); } // D: if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise, elseif ($input === '.' || $input === '..') { $input = ''; } // E: move the first path segment in the input buffer to the end of the output buffer, including the initial "/" character (if any) and any subsequent characters up to, but not including, the next "/" character or the end of the input buffer elseif (($pos = strpos($input, '/', 1)) !== false) { $output .= substr($input, 0, $pos); $input = substr_replace($input, '', 0, $pos); } else { $output .= $input; $input = ''; } } return $output . $input; }
[ "private", "function", "remove_dot_segments", "(", "$", "input", ")", "{", "$", "output", "=", "''", ";", "while", "(", "strpos", "(", "$", "input", ",", "'./'", ")", "!==", "false", "||", "strpos", "(", "$", "input", ",", "'/.'", ")", "!==", "false", "||", "$", "input", "===", "'.'", "||", "$", "input", "===", "'..'", ")", "{", "// A: If the input buffer begins with a prefix of \"../\" or \"./\", then remove that prefix from the input buffer; otherwise,", "if", "(", "strpos", "(", "$", "input", ",", "'../'", ")", "===", "0", ")", "{", "$", "input", "=", "substr", "(", "$", "input", ",", "3", ")", ";", "}", "elseif", "(", "strpos", "(", "$", "input", ",", "'./'", ")", "===", "0", ")", "{", "$", "input", "=", "substr", "(", "$", "input", ",", "2", ")", ";", "}", "// B: if the input buffer begins with a prefix of \"/./\" or \"/.\", where \".\" is a complete path segment, then replace that prefix with \"/\" in the input buffer; otherwise,", "elseif", "(", "strpos", "(", "$", "input", ",", "'/./'", ")", "===", "0", ")", "{", "$", "input", "=", "substr", "(", "$", "input", ",", "2", ")", ";", "}", "elseif", "(", "$", "input", "===", "'/.'", ")", "{", "$", "input", "=", "'/'", ";", "}", "// C: if the input buffer begins with a prefix of \"/../\" or \"/..\", where \"..\" is a complete path segment, then replace that prefix with \"/\" in the input buffer and remove the last segment and its preceding \"/\" (if any) from the output buffer; otherwise,", "elseif", "(", "strpos", "(", "$", "input", ",", "'/../'", ")", "===", "0", ")", "{", "$", "input", "=", "substr", "(", "$", "input", ",", "3", ")", ";", "$", "output", "=", "substr_replace", "(", "$", "output", ",", "''", ",", "strrpos", "(", "$", "output", ",", "'/'", ")", ")", ";", "}", "elseif", "(", "$", "input", "===", "'/..'", ")", "{", "$", "input", "=", "'/'", ";", "$", "output", "=", "substr_replace", "(", "$", "output", ",", "''", ",", "strrpos", "(", "$", "output", ",", "'/'", ")", ")", ";", "}", "// D: if the input buffer consists only of \".\" or \"..\", then remove that from the input buffer; otherwise,", "elseif", "(", "$", "input", "===", "'.'", "||", "$", "input", "===", "'..'", ")", "{", "$", "input", "=", "''", ";", "}", "// E: move the first path segment in the input buffer to the end of the output buffer, including the initial \"/\" character (if any) and any subsequent characters up to, but not including, the next \"/\" character or the end of the input buffer", "elseif", "(", "(", "$", "pos", "=", "strpos", "(", "$", "input", ",", "'/'", ",", "1", ")", ")", "!==", "false", ")", "{", "$", "output", ".=", "substr", "(", "$", "input", ",", "0", ",", "$", "pos", ")", ";", "$", "input", "=", "substr_replace", "(", "$", "input", ",", "''", ",", "0", ",", "$", "pos", ")", ";", "}", "else", "{", "$", "output", ".=", "$", "input", ";", "$", "input", "=", "''", ";", "}", "}", "return", "$", "output", ".", "$", "input", ";", "}" ]
Remove dot segments from a path @param string $input @return string
[ "Remove", "dot", "segments", "from", "a", "path" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IRI.php#L395-L447
train
superfaktura/apiclient
SFAPIclient/Requests/IRI.php
Requests_IRI.is_valid
public function is_valid() { $isauthority = $this->iuserinfo !== null || $this->ihost !== null || $this->port !== null; if ($this->ipath !== '' && ( $isauthority && ( $this->ipath[0] !== '/' || substr($this->ipath, 0, 2) === '//' ) || ( $this->scheme === null && !$isauthority && strpos($this->ipath, ':') !== false && (strpos($this->ipath, '/') === false ? true : strpos($this->ipath, ':') < strpos($this->ipath, '/')) ) ) ) { return false; } return true; }
php
public function is_valid() { $isauthority = $this->iuserinfo !== null || $this->ihost !== null || $this->port !== null; if ($this->ipath !== '' && ( $isauthority && ( $this->ipath[0] !== '/' || substr($this->ipath, 0, 2) === '//' ) || ( $this->scheme === null && !$isauthority && strpos($this->ipath, ':') !== false && (strpos($this->ipath, '/') === false ? true : strpos($this->ipath, ':') < strpos($this->ipath, '/')) ) ) ) { return false; } return true; }
[ "public", "function", "is_valid", "(", ")", "{", "$", "isauthority", "=", "$", "this", "->", "iuserinfo", "!==", "null", "||", "$", "this", "->", "ihost", "!==", "null", "||", "$", "this", "->", "port", "!==", "null", ";", "if", "(", "$", "this", "->", "ipath", "!==", "''", "&&", "(", "$", "isauthority", "&&", "(", "$", "this", "->", "ipath", "[", "0", "]", "!==", "'/'", "||", "substr", "(", "$", "this", "->", "ipath", ",", "0", ",", "2", ")", "===", "'//'", ")", "||", "(", "$", "this", "->", "scheme", "===", "null", "&&", "!", "$", "isauthority", "&&", "strpos", "(", "$", "this", "->", "ipath", ",", "':'", ")", "!==", "false", "&&", "(", "strpos", "(", "$", "this", "->", "ipath", ",", "'/'", ")", "===", "false", "?", "true", ":", "strpos", "(", "$", "this", "->", "ipath", ",", "':'", ")", "<", "strpos", "(", "$", "this", "->", "ipath", ",", "'/'", ")", ")", ")", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if the object represents a valid IRI. This needs to be done on each call as some things change depending on another part of the IRI. @return bool
[ "Check", "if", "the", "object", "represents", "a", "valid", "IRI", ".", "This", "needs", "to", "be", "done", "on", "each", "call", "as", "some", "things", "change", "depending", "on", "another", "part", "of", "the", "IRI", "." ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IRI.php#L760-L782
train
superfaktura/apiclient
SFAPIclient/Requests/IRI.php
Requests_IRI.set_userinfo
private function set_userinfo($iuserinfo) { if ($iuserinfo === null) { $this->iuserinfo = null; } else { $this->iuserinfo = $this->replace_invalid_with_pct_encoding($iuserinfo, '!$&\'()*+,;=:'); $this->scheme_normalization(); } return true; }
php
private function set_userinfo($iuserinfo) { if ($iuserinfo === null) { $this->iuserinfo = null; } else { $this->iuserinfo = $this->replace_invalid_with_pct_encoding($iuserinfo, '!$&\'()*+,;=:'); $this->scheme_normalization(); } return true; }
[ "private", "function", "set_userinfo", "(", "$", "iuserinfo", ")", "{", "if", "(", "$", "iuserinfo", "===", "null", ")", "{", "$", "this", "->", "iuserinfo", "=", "null", ";", "}", "else", "{", "$", "this", "->", "iuserinfo", "=", "$", "this", "->", "replace_invalid_with_pct_encoding", "(", "$", "iuserinfo", ",", "'!$&\\'()*+,;=:'", ")", ";", "$", "this", "->", "scheme_normalization", "(", ")", ";", "}", "return", "true", ";", "}" ]
Set the iuserinfo. @param string $iuserinfo @return bool
[ "Set", "the", "iuserinfo", "." ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IRI.php#L935-L948
train
superfaktura/apiclient
SFAPIclient/Requests/IRI.php
Requests_IRI.set_path
private function set_path($ipath) { static $cache; if (!$cache) { $cache = array(); } $ipath = (string) $ipath; if (isset($cache[$ipath])) { $this->ipath = $cache[$ipath][(int) ($this->scheme !== null)]; } else { $valid = $this->replace_invalid_with_pct_encoding($ipath, '!$&\'()*+,;=@:/'); $removed = $this->remove_dot_segments($valid); $cache[$ipath] = array($valid, $removed); $this->ipath = ($this->scheme !== null) ? $removed : $valid; } $this->scheme_normalization(); return true; }
php
private function set_path($ipath) { static $cache; if (!$cache) { $cache = array(); } $ipath = (string) $ipath; if (isset($cache[$ipath])) { $this->ipath = $cache[$ipath][(int) ($this->scheme !== null)]; } else { $valid = $this->replace_invalid_with_pct_encoding($ipath, '!$&\'()*+,;=@:/'); $removed = $this->remove_dot_segments($valid); $cache[$ipath] = array($valid, $removed); $this->ipath = ($this->scheme !== null) ? $removed : $valid; } $this->scheme_normalization(); return true; }
[ "private", "function", "set_path", "(", "$", "ipath", ")", "{", "static", "$", "cache", ";", "if", "(", "!", "$", "cache", ")", "{", "$", "cache", "=", "array", "(", ")", ";", "}", "$", "ipath", "=", "(", "string", ")", "$", "ipath", ";", "if", "(", "isset", "(", "$", "cache", "[", "$", "ipath", "]", ")", ")", "{", "$", "this", "->", "ipath", "=", "$", "cache", "[", "$", "ipath", "]", "[", "(", "int", ")", "(", "$", "this", "->", "scheme", "!==", "null", ")", "]", ";", "}", "else", "{", "$", "valid", "=", "$", "this", "->", "replace_invalid_with_pct_encoding", "(", "$", "ipath", ",", "'!$&\\'()*+,;=@:/'", ")", ";", "$", "removed", "=", "$", "this", "->", "remove_dot_segments", "(", "$", "valid", ")", ";", "$", "cache", "[", "$", "ipath", "]", "=", "array", "(", "$", "valid", ",", "$", "removed", ")", ";", "$", "this", "->", "ipath", "=", "(", "$", "this", "->", "scheme", "!==", "null", ")", "?", "$", "removed", ":", "$", "valid", ";", "}", "$", "this", "->", "scheme_normalization", "(", ")", ";", "return", "true", ";", "}" ]
Set the ipath. @param string $ipath @return bool
[ "Set", "the", "ipath", "." ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IRI.php#L1039-L1064
train
superfaktura/apiclient
SFAPIclient/Requests/IRI.php
Requests_IRI.set_query
private function set_query($iquery) { if ($iquery === null) { $this->iquery = null; } else { $this->iquery = $this->replace_invalid_with_pct_encoding($iquery, '!$&\'()*+,;=:@/?', true); $this->scheme_normalization(); } return true; }
php
private function set_query($iquery) { if ($iquery === null) { $this->iquery = null; } else { $this->iquery = $this->replace_invalid_with_pct_encoding($iquery, '!$&\'()*+,;=:@/?', true); $this->scheme_normalization(); } return true; }
[ "private", "function", "set_query", "(", "$", "iquery", ")", "{", "if", "(", "$", "iquery", "===", "null", ")", "{", "$", "this", "->", "iquery", "=", "null", ";", "}", "else", "{", "$", "this", "->", "iquery", "=", "$", "this", "->", "replace_invalid_with_pct_encoding", "(", "$", "iquery", ",", "'!$&\\'()*+,;=:@/?'", ",", "true", ")", ";", "$", "this", "->", "scheme_normalization", "(", ")", ";", "}", "return", "true", ";", "}" ]
Set the iquery. @param string $iquery @return bool
[ "Set", "the", "iquery", "." ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IRI.php#L1072-L1084
train
superfaktura/apiclient
SFAPIclient/Requests/IRI.php
Requests_IRI.set_fragment
private function set_fragment($ifragment) { if ($ifragment === null) { $this->ifragment = null; } else { $this->ifragment = $this->replace_invalid_with_pct_encoding($ifragment, '!$&\'()*+,;=:@/?'); $this->scheme_normalization(); } return true; }
php
private function set_fragment($ifragment) { if ($ifragment === null) { $this->ifragment = null; } else { $this->ifragment = $this->replace_invalid_with_pct_encoding($ifragment, '!$&\'()*+,;=:@/?'); $this->scheme_normalization(); } return true; }
[ "private", "function", "set_fragment", "(", "$", "ifragment", ")", "{", "if", "(", "$", "ifragment", "===", "null", ")", "{", "$", "this", "->", "ifragment", "=", "null", ";", "}", "else", "{", "$", "this", "->", "ifragment", "=", "$", "this", "->", "replace_invalid_with_pct_encoding", "(", "$", "ifragment", ",", "'!$&\\'()*+,;=:@/?'", ")", ";", "$", "this", "->", "scheme_normalization", "(", ")", ";", "}", "return", "true", ";", "}" ]
Set the ifragment. @param string $ifragment @return bool
[ "Set", "the", "ifragment", "." ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IRI.php#L1092-L1104
train
yiisoft/view
src/widgets/ActiveFormClientScript.php
ActiveFormClientScript.buildClientValidator
protected function buildClientValidator($validator, $model, $attribute, $view) { foreach ($this->getClientValidatorMap() as $serverSideValidatorClass => $clientSideValidator) { if ($clientSideValidator !== false && $validator instanceof $serverSideValidatorClass) { /* @var $clientValidator \yii\validators\client\ClientValidator */ $clientValidator = $this->app->createObject($clientSideValidator); return $clientValidator->build($validator, $model, $attribute, $view); } } }
php
protected function buildClientValidator($validator, $model, $attribute, $view) { foreach ($this->getClientValidatorMap() as $serverSideValidatorClass => $clientSideValidator) { if ($clientSideValidator !== false && $validator instanceof $serverSideValidatorClass) { /* @var $clientValidator \yii\validators\client\ClientValidator */ $clientValidator = $this->app->createObject($clientSideValidator); return $clientValidator->build($validator, $model, $attribute, $view); } } }
[ "protected", "function", "buildClientValidator", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ",", "$", "view", ")", "{", "foreach", "(", "$", "this", "->", "getClientValidatorMap", "(", ")", "as", "$", "serverSideValidatorClass", "=>", "$", "clientSideValidator", ")", "{", "if", "(", "$", "clientSideValidator", "!==", "false", "&&", "$", "validator", "instanceof", "$", "serverSideValidatorClass", ")", "{", "/* @var $clientValidator \\yii\\validators\\client\\ClientValidator */", "$", "clientValidator", "=", "$", "this", "->", "app", "->", "createObject", "(", "$", "clientSideValidator", ")", ";", "return", "$", "clientValidator", "->", "build", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ",", "$", "view", ")", ";", "}", "}", "}" ]
Builds the JavaScript needed for performing client-side validation for given validator. @param \yii\validators\Validator $validator validator to be built. @param \yii\base\Model $model the data model being validated. @param string $attribute the name of the attribute to be validated. @param \yii\view\View $view the view object that is going to be used to render views or view files containing a model form with validator applied. @return string|null client-side validation JavaScript code, `null` - if given validator is not supported.
[ "Builds", "the", "JavaScript", "needed", "for", "performing", "client", "-", "side", "validation", "for", "given", "validator", "." ]
206f58f0c33a7a861984e4c67de470529b19ebb5
https://github.com/yiisoft/view/blob/206f58f0c33a7a861984e4c67de470529b19ebb5/src/widgets/ActiveFormClientScript.php#L251-L261
train
doctrine/KeyValueStore
lib/Doctrine/KeyValueStore/Storage/DBALStorage.php
DBALStorage.insert
public function insert($storageName, $key, array $data) { try { $this->conn->insert($this->table, [ $this->keyColumn => $key, $this->dataColumn => serialize($data), ]); } catch (\Exception $e) { } }
php
public function insert($storageName, $key, array $data) { try { $this->conn->insert($this->table, [ $this->keyColumn => $key, $this->dataColumn => serialize($data), ]); } catch (\Exception $e) { } }
[ "public", "function", "insert", "(", "$", "storageName", ",", "$", "key", ",", "array", "$", "data", ")", "{", "try", "{", "$", "this", "->", "conn", "->", "insert", "(", "$", "this", "->", "table", ",", "[", "$", "this", "->", "keyColumn", "=>", "$", "key", ",", "$", "this", "->", "dataColumn", "=>", "serialize", "(", "$", "data", ")", ",", "]", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "}" ]
Insert data into the storage key specified. @param array|string $key @param array $data
[ "Insert", "data", "into", "the", "storage", "key", "specified", "." ]
8ba3db4ce7727f19cdb91519968ba4259b588277
https://github.com/doctrine/KeyValueStore/blob/8ba3db4ce7727f19cdb91519968ba4259b588277/lib/Doctrine/KeyValueStore/Storage/DBALStorage.php#L83-L92
train
superfaktura/apiclient
SFAPIclient/Requests/IDNAEncoder.php
Requests_IDNAEncoder.encode
public static function encode($string) { $parts = explode('.', $string); foreach ($parts as &$part) { $part = self::to_ascii($part); } return implode('.', $parts); }
php
public static function encode($string) { $parts = explode('.', $string); foreach ($parts as &$part) { $part = self::to_ascii($part); } return implode('.', $parts); }
[ "public", "static", "function", "encode", "(", "$", "string", ")", "{", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "string", ")", ";", "foreach", "(", "$", "parts", "as", "&", "$", "part", ")", "{", "$", "part", "=", "self", "::", "to_ascii", "(", "$", "part", ")", ";", "}", "return", "implode", "(", "'.'", ",", "$", "parts", ")", ";", "}" ]
Encode a hostname using Punycode @param string $string Hostname @return string Punycode-encoded hostname
[ "Encode", "a", "hostname", "using", "Punycode" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IDNAEncoder.php#L43-L49
train
superfaktura/apiclient
SFAPIclient/Requests/IDNAEncoder.php
Requests_IDNAEncoder.to_ascii
public static function to_ascii($string) { // Step 1: Check if the string is already ASCII if (self::is_ascii($string)) { // Skip to step 7 if (strlen($string) < 64) { return $string; } throw new Requests_Exception('Provided string is too long', 'idna.provided_too_long', $string); } // Step 2: nameprep $string = self::nameprep($string); // Step 3: UseSTD3ASCIIRules is false, continue // Step 4: Check if it's ASCII now if (self::is_ascii($string)) { // Skip to step 7 if (strlen($string) < 64) { return $string; } throw new Requests_Exception('Prepared string is too long', 'idna.prepared_too_long', $string); } // Step 5: Check ACE prefix if (strpos($string, self::ACE_PREFIX) === 0) { throw new Requests_Exception('Provided string begins with ACE prefix', 'idna.provided_is_prefixed', $string); } // Step 6: Encode with Punycode $string = self::punycode_encode($string); // Step 7: Prepend ACE prefix $string = self::ACE_PREFIX . $string; // Step 8: Check size if (strlen($string) < 64) { return $string; } throw new Requests_Exception('Encoded string is too long', 'idna.encoded_too_long', $string); }
php
public static function to_ascii($string) { // Step 1: Check if the string is already ASCII if (self::is_ascii($string)) { // Skip to step 7 if (strlen($string) < 64) { return $string; } throw new Requests_Exception('Provided string is too long', 'idna.provided_too_long', $string); } // Step 2: nameprep $string = self::nameprep($string); // Step 3: UseSTD3ASCIIRules is false, continue // Step 4: Check if it's ASCII now if (self::is_ascii($string)) { // Skip to step 7 if (strlen($string) < 64) { return $string; } throw new Requests_Exception('Prepared string is too long', 'idna.prepared_too_long', $string); } // Step 5: Check ACE prefix if (strpos($string, self::ACE_PREFIX) === 0) { throw new Requests_Exception('Provided string begins with ACE prefix', 'idna.provided_is_prefixed', $string); } // Step 6: Encode with Punycode $string = self::punycode_encode($string); // Step 7: Prepend ACE prefix $string = self::ACE_PREFIX . $string; // Step 8: Check size if (strlen($string) < 64) { return $string; } throw new Requests_Exception('Encoded string is too long', 'idna.encoded_too_long', $string); }
[ "public", "static", "function", "to_ascii", "(", "$", "string", ")", "{", "// Step 1: Check if the string is already ASCII", "if", "(", "self", "::", "is_ascii", "(", "$", "string", ")", ")", "{", "// Skip to step 7", "if", "(", "strlen", "(", "$", "string", ")", "<", "64", ")", "{", "return", "$", "string", ";", "}", "throw", "new", "Requests_Exception", "(", "'Provided string is too long'", ",", "'idna.provided_too_long'", ",", "$", "string", ")", ";", "}", "// Step 2: nameprep", "$", "string", "=", "self", "::", "nameprep", "(", "$", "string", ")", ";", "// Step 3: UseSTD3ASCIIRules is false, continue", "// Step 4: Check if it's ASCII now", "if", "(", "self", "::", "is_ascii", "(", "$", "string", ")", ")", "{", "// Skip to step 7", "if", "(", "strlen", "(", "$", "string", ")", "<", "64", ")", "{", "return", "$", "string", ";", "}", "throw", "new", "Requests_Exception", "(", "'Prepared string is too long'", ",", "'idna.prepared_too_long'", ",", "$", "string", ")", ";", "}", "// Step 5: Check ACE prefix", "if", "(", "strpos", "(", "$", "string", ",", "self", "::", "ACE_PREFIX", ")", "===", "0", ")", "{", "throw", "new", "Requests_Exception", "(", "'Provided string begins with ACE prefix'", ",", "'idna.provided_is_prefixed'", ",", "$", "string", ")", ";", "}", "// Step 6: Encode with Punycode", "$", "string", "=", "self", "::", "punycode_encode", "(", "$", "string", ")", ";", "// Step 7: Prepend ACE prefix", "$", "string", "=", "self", "::", "ACE_PREFIX", ".", "$", "string", ";", "// Step 8: Check size", "if", "(", "strlen", "(", "$", "string", ")", "<", "64", ")", "{", "return", "$", "string", ";", "}", "throw", "new", "Requests_Exception", "(", "'Encoded string is too long'", ",", "'idna.encoded_too_long'", ",", "$", "string", ")", ";", "}" ]
Convert a UTF-8 string to an ASCII string using Punycode @throws Requests_Exception Provided string longer than 64 ASCII characters (`idna.provided_too_long`) @throws Requests_Exception Prepared string longer than 64 ASCII characters (`idna.prepared_too_long`) @throws Requests_Exception Provided string already begins with xn-- (`idna.provided_is_prefixed`) @throws Requests_Exception Encded string longer than 64 ASCII characters (`idna.encoded_too_long`) @param string $string ASCII or UTF-8 string (max length 64 characters) @return string ASCII string
[ "Convert", "a", "UTF", "-", "8", "string", "to", "an", "ASCII", "string", "using", "Punycode" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IDNAEncoder.php#L62-L104
train
superfaktura/apiclient
SFAPIclient/Requests/IDNAEncoder.php
Requests_IDNAEncoder.utf8_to_codepoints
protected static function utf8_to_codepoints($input) { $codepoints = array(); // Get number of bytes $strlen = strlen($input); for ($position = 0; $position < $strlen; $position++) { $value = ord($input[$position]); // One byte sequence: if ((~$value & 0x80) === 0x80) { $character = $value; $length = 1; $remaining = 0; } // Two byte sequence: elseif (($value & 0xE0) === 0xC0) { $character = ($value & 0x1F) << 6; $length = 2; $remaining = 1; } // Three byte sequence: elseif (($value & 0xF0) === 0xE0) { $character = ($value & 0x0F) << 12; $length = 3; $remaining = 2; } // Four byte sequence: elseif (($value & 0xF8) === 0xF0) { $character = ($value & 0x07) << 18; $length = 4; $remaining = 3; } // Invalid byte: else { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $value); } if ($remaining > 0) { if ($position + $length > $strlen) { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character); } for ($position++; $remaining > 0; $position++) { $value = ord($input[$position]); // If it is invalid, count the sequence as invalid and reprocess the current byte: if (($value & 0xC0) !== 0x80) { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character); } $character |= ($value & 0x3F) << (--$remaining * 6); } $position--; } if ( // Non-shortest form sequences are invalid $length > 1 && $character <= 0x7F || $length > 2 && $character <= 0x7FF || $length > 3 && $character <= 0xFFFF // Outside of range of ucschar codepoints // Noncharacters || ($character & 0xFFFE) === 0xFFFE || $character >= 0xFDD0 && $character <= 0xFDEF || ( // Everything else not in ucschar $character > 0xD7FF && $character < 0xF900 || $character < 0x20 || $character > 0x7E && $character < 0xA0 || $character > 0xEFFFD ) ) { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character); } $codepoints[] = $character; } return $codepoints; }
php
protected static function utf8_to_codepoints($input) { $codepoints = array(); // Get number of bytes $strlen = strlen($input); for ($position = 0; $position < $strlen; $position++) { $value = ord($input[$position]); // One byte sequence: if ((~$value & 0x80) === 0x80) { $character = $value; $length = 1; $remaining = 0; } // Two byte sequence: elseif (($value & 0xE0) === 0xC0) { $character = ($value & 0x1F) << 6; $length = 2; $remaining = 1; } // Three byte sequence: elseif (($value & 0xF0) === 0xE0) { $character = ($value & 0x0F) << 12; $length = 3; $remaining = 2; } // Four byte sequence: elseif (($value & 0xF8) === 0xF0) { $character = ($value & 0x07) << 18; $length = 4; $remaining = 3; } // Invalid byte: else { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $value); } if ($remaining > 0) { if ($position + $length > $strlen) { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character); } for ($position++; $remaining > 0; $position++) { $value = ord($input[$position]); // If it is invalid, count the sequence as invalid and reprocess the current byte: if (($value & 0xC0) !== 0x80) { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character); } $character |= ($value & 0x3F) << (--$remaining * 6); } $position--; } if ( // Non-shortest form sequences are invalid $length > 1 && $character <= 0x7F || $length > 2 && $character <= 0x7FF || $length > 3 && $character <= 0xFFFF // Outside of range of ucschar codepoints // Noncharacters || ($character & 0xFFFE) === 0xFFFE || $character >= 0xFDD0 && $character <= 0xFDEF || ( // Everything else not in ucschar $character > 0xD7FF && $character < 0xF900 || $character < 0x20 || $character > 0x7E && $character < 0xA0 || $character > 0xEFFFD ) ) { throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character); } $codepoints[] = $character; } return $codepoints; }
[ "protected", "static", "function", "utf8_to_codepoints", "(", "$", "input", ")", "{", "$", "codepoints", "=", "array", "(", ")", ";", "// Get number of bytes", "$", "strlen", "=", "strlen", "(", "$", "input", ")", ";", "for", "(", "$", "position", "=", "0", ";", "$", "position", "<", "$", "strlen", ";", "$", "position", "++", ")", "{", "$", "value", "=", "ord", "(", "$", "input", "[", "$", "position", "]", ")", ";", "// One byte sequence:", "if", "(", "(", "~", "$", "value", "&", "0x80", ")", "===", "0x80", ")", "{", "$", "character", "=", "$", "value", ";", "$", "length", "=", "1", ";", "$", "remaining", "=", "0", ";", "}", "// Two byte sequence:", "elseif", "(", "(", "$", "value", "&", "0xE0", ")", "===", "0xC0", ")", "{", "$", "character", "=", "(", "$", "value", "&", "0x1F", ")", "<<", "6", ";", "$", "length", "=", "2", ";", "$", "remaining", "=", "1", ";", "}", "// Three byte sequence:", "elseif", "(", "(", "$", "value", "&", "0xF0", ")", "===", "0xE0", ")", "{", "$", "character", "=", "(", "$", "value", "&", "0x0F", ")", "<<", "12", ";", "$", "length", "=", "3", ";", "$", "remaining", "=", "2", ";", "}", "// Four byte sequence:", "elseif", "(", "(", "$", "value", "&", "0xF8", ")", "===", "0xF0", ")", "{", "$", "character", "=", "(", "$", "value", "&", "0x07", ")", "<<", "18", ";", "$", "length", "=", "4", ";", "$", "remaining", "=", "3", ";", "}", "// Invalid byte:", "else", "{", "throw", "new", "Requests_Exception", "(", "'Invalid Unicode codepoint'", ",", "'idna.invalidcodepoint'", ",", "$", "value", ")", ";", "}", "if", "(", "$", "remaining", ">", "0", ")", "{", "if", "(", "$", "position", "+", "$", "length", ">", "$", "strlen", ")", "{", "throw", "new", "Requests_Exception", "(", "'Invalid Unicode codepoint'", ",", "'idna.invalidcodepoint'", ",", "$", "character", ")", ";", "}", "for", "(", "$", "position", "++", ";", "$", "remaining", ">", "0", ";", "$", "position", "++", ")", "{", "$", "value", "=", "ord", "(", "$", "input", "[", "$", "position", "]", ")", ";", "// If it is invalid, count the sequence as invalid and reprocess the current byte:", "if", "(", "(", "$", "value", "&", "0xC0", ")", "!==", "0x80", ")", "{", "throw", "new", "Requests_Exception", "(", "'Invalid Unicode codepoint'", ",", "'idna.invalidcodepoint'", ",", "$", "character", ")", ";", "}", "$", "character", "|=", "(", "$", "value", "&", "0x3F", ")", "<<", "(", "--", "$", "remaining", "*", "6", ")", ";", "}", "$", "position", "--", ";", "}", "if", "(", "// Non-shortest form sequences are invalid", "$", "length", ">", "1", "&&", "$", "character", "<=", "0x7F", "||", "$", "length", ">", "2", "&&", "$", "character", "<=", "0x7FF", "||", "$", "length", ">", "3", "&&", "$", "character", "<=", "0xFFFF", "// Outside of range of ucschar codepoints", "// Noncharacters", "||", "(", "$", "character", "&", "0xFFFE", ")", "===", "0xFFFE", "||", "$", "character", ">=", "0xFDD0", "&&", "$", "character", "<=", "0xFDEF", "||", "(", "// Everything else not in ucschar", "$", "character", ">", "0xD7FF", "&&", "$", "character", "<", "0xF900", "||", "$", "character", "<", "0x20", "||", "$", "character", ">", "0x7E", "&&", "$", "character", "<", "0xA0", "||", "$", "character", ">", "0xEFFFD", ")", ")", "{", "throw", "new", "Requests_Exception", "(", "'Invalid Unicode codepoint'", ",", "'idna.invalidcodepoint'", ",", "$", "character", ")", ";", "}", "$", "codepoints", "[", "]", "=", "$", "character", ";", "}", "return", "$", "codepoints", ";", "}" ]
Convert a UTF-8 string to a UCS-4 codepoint array Based on Requests_IRI::replace_invalid_with_pct_encoding() @throws Requests_Exception Invalid UTF-8 codepoint (`idna.invalidcodepoint`) @param string $input @return array Unicode code points
[ "Convert", "a", "UTF", "-", "8", "string", "to", "a", "UCS", "-", "4", "codepoint", "array" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IDNAEncoder.php#L138-L217
train
superfaktura/apiclient
SFAPIclient/Requests/IDNAEncoder.php
Requests_IDNAEncoder.punycode_encode
public static function punycode_encode($input) { $output = ''; # let n = initial_n $n = self::BOOTSTRAP_INITIAL_N; # let delta = 0 $delta = 0; # let bias = initial_bias $bias = self::BOOTSTRAP_INITIAL_BIAS; # let h = b = the number of basic code points in the input $h = $b = 0; // see loop # copy them to the output in order $codepoints = self::utf8_to_codepoints($input); foreach ($codepoints as $char) { if ($char < 128) { // Character is valid ASCII // TODO: this should also check if it's valid for a URL $output .= chr($char); $h++; } // Check if the character is non-ASCII, but below initial n // This never occurs for Punycode, so ignore in coverage // @codeCoverageIgnoreStart elseif ($char < $n) { throw new Requests_Exception('Invalid character', 'idna.character_outside_domain', $char); } // @codeCoverageIgnoreEnd else { $extended[$char] = true; } } $extended = array_keys($extended); sort($extended); $b = $h; # [copy them] followed by a delimiter if b > 0 if (strlen($output) > 0) { $output .= '-'; } # {if the input contains a non-basic code point < n then fail} # while h < length(input) do begin while ($h < count($codepoints)) { # let m = the minimum code point >= n in the input $m = array_shift($extended); //printf('next code point to insert is %s' . PHP_EOL, dechex($m)); # let delta = delta + (m - n) * (h + 1), fail on overflow $delta += ($m - $n) * ($h + 1); # let n = m $n = $m; # for each code point c in the input (in order) do begin for ($num = 0; $num < count($codepoints); $num++) { $c = $codepoints[$num]; # if c < n then increment delta, fail on overflow if ($c < $n) { $delta++; } # if c == n then begin elseif ($c === $n) { # let q = delta $q = $delta; # for k = base to infinity in steps of base do begin for ($k = self::BOOTSTRAP_BASE; ; $k += self::BOOTSTRAP_BASE) { # let t = tmin if k <= bias {+ tmin}, or # tmax if k >= bias + tmax, or k - bias otherwise if ($k <= ($bias + self::BOOTSTRAP_TMIN)) { $t = self::BOOTSTRAP_TMIN; } elseif ($k >= ($bias + self::BOOTSTRAP_TMAX)) { $t = self::BOOTSTRAP_TMAX; } else { $t = $k - $bias; } # if q < t then break if ($q < $t) { break; } # output the code point for digit t + ((q - t) mod (base - t)) $digit = $t + (($q - $t) % (self::BOOTSTRAP_BASE - $t)); //printf('needed delta is %d, encodes as "%s"' . PHP_EOL, $delta, self::digit_to_char($digit)); $output .= self::digit_to_char($digit); # let q = (q - t) div (base - t) $q = floor(($q - $t) / (self::BOOTSTRAP_BASE - $t)); # end } # output the code point for digit q $output .= self::digit_to_char($q); //printf('needed delta is %d, encodes as "%s"' . PHP_EOL, $delta, self::digit_to_char($q)); # let bias = adapt(delta, h + 1, test h equals b?) $bias = self::adapt($delta, $h + 1, $h === $b); //printf('bias becomes %d' . PHP_EOL, $bias); # let delta = 0 $delta = 0; # increment h $h++; # end } # end } # increment delta and n $delta++; $n++; # end } return $output; }
php
public static function punycode_encode($input) { $output = ''; # let n = initial_n $n = self::BOOTSTRAP_INITIAL_N; # let delta = 0 $delta = 0; # let bias = initial_bias $bias = self::BOOTSTRAP_INITIAL_BIAS; # let h = b = the number of basic code points in the input $h = $b = 0; // see loop # copy them to the output in order $codepoints = self::utf8_to_codepoints($input); foreach ($codepoints as $char) { if ($char < 128) { // Character is valid ASCII // TODO: this should also check if it's valid for a URL $output .= chr($char); $h++; } // Check if the character is non-ASCII, but below initial n // This never occurs for Punycode, so ignore in coverage // @codeCoverageIgnoreStart elseif ($char < $n) { throw new Requests_Exception('Invalid character', 'idna.character_outside_domain', $char); } // @codeCoverageIgnoreEnd else { $extended[$char] = true; } } $extended = array_keys($extended); sort($extended); $b = $h; # [copy them] followed by a delimiter if b > 0 if (strlen($output) > 0) { $output .= '-'; } # {if the input contains a non-basic code point < n then fail} # while h < length(input) do begin while ($h < count($codepoints)) { # let m = the minimum code point >= n in the input $m = array_shift($extended); //printf('next code point to insert is %s' . PHP_EOL, dechex($m)); # let delta = delta + (m - n) * (h + 1), fail on overflow $delta += ($m - $n) * ($h + 1); # let n = m $n = $m; # for each code point c in the input (in order) do begin for ($num = 0; $num < count($codepoints); $num++) { $c = $codepoints[$num]; # if c < n then increment delta, fail on overflow if ($c < $n) { $delta++; } # if c == n then begin elseif ($c === $n) { # let q = delta $q = $delta; # for k = base to infinity in steps of base do begin for ($k = self::BOOTSTRAP_BASE; ; $k += self::BOOTSTRAP_BASE) { # let t = tmin if k <= bias {+ tmin}, or # tmax if k >= bias + tmax, or k - bias otherwise if ($k <= ($bias + self::BOOTSTRAP_TMIN)) { $t = self::BOOTSTRAP_TMIN; } elseif ($k >= ($bias + self::BOOTSTRAP_TMAX)) { $t = self::BOOTSTRAP_TMAX; } else { $t = $k - $bias; } # if q < t then break if ($q < $t) { break; } # output the code point for digit t + ((q - t) mod (base - t)) $digit = $t + (($q - $t) % (self::BOOTSTRAP_BASE - $t)); //printf('needed delta is %d, encodes as "%s"' . PHP_EOL, $delta, self::digit_to_char($digit)); $output .= self::digit_to_char($digit); # let q = (q - t) div (base - t) $q = floor(($q - $t) / (self::BOOTSTRAP_BASE - $t)); # end } # output the code point for digit q $output .= self::digit_to_char($q); //printf('needed delta is %d, encodes as "%s"' . PHP_EOL, $delta, self::digit_to_char($q)); # let bias = adapt(delta, h + 1, test h equals b?) $bias = self::adapt($delta, $h + 1, $h === $b); //printf('bias becomes %d' . PHP_EOL, $bias); # let delta = 0 $delta = 0; # increment h $h++; # end } # end } # increment delta and n $delta++; $n++; # end } return $output; }
[ "public", "static", "function", "punycode_encode", "(", "$", "input", ")", "{", "$", "output", "=", "''", ";", "#\t\tlet n = initial_n", "$", "n", "=", "self", "::", "BOOTSTRAP_INITIAL_N", ";", "#\t\tlet delta = 0", "$", "delta", "=", "0", ";", "#\t\tlet bias = initial_bias", "$", "bias", "=", "self", "::", "BOOTSTRAP_INITIAL_BIAS", ";", "#\t\tlet h = b = the number of basic code points in the input", "$", "h", "=", "$", "b", "=", "0", ";", "// see loop", "#\t\tcopy them to the output in order", "$", "codepoints", "=", "self", "::", "utf8_to_codepoints", "(", "$", "input", ")", ";", "foreach", "(", "$", "codepoints", "as", "$", "char", ")", "{", "if", "(", "$", "char", "<", "128", ")", "{", "// Character is valid ASCII", "// TODO: this should also check if it's valid for a URL", "$", "output", ".=", "chr", "(", "$", "char", ")", ";", "$", "h", "++", ";", "}", "// Check if the character is non-ASCII, but below initial n", "// This never occurs for Punycode, so ignore in coverage", "// @codeCoverageIgnoreStart", "elseif", "(", "$", "char", "<", "$", "n", ")", "{", "throw", "new", "Requests_Exception", "(", "'Invalid character'", ",", "'idna.character_outside_domain'", ",", "$", "char", ")", ";", "}", "// @codeCoverageIgnoreEnd", "else", "{", "$", "extended", "[", "$", "char", "]", "=", "true", ";", "}", "}", "$", "extended", "=", "array_keys", "(", "$", "extended", ")", ";", "sort", "(", "$", "extended", ")", ";", "$", "b", "=", "$", "h", ";", "#\t\t[copy them] followed by a delimiter if b > 0", "if", "(", "strlen", "(", "$", "output", ")", ">", "0", ")", "{", "$", "output", ".=", "'-'", ";", "}", "#\t\t{if the input contains a non-basic code point < n then fail}", "#\t\twhile h < length(input) do begin", "while", "(", "$", "h", "<", "count", "(", "$", "codepoints", ")", ")", "{", "#\t\t\tlet m = the minimum code point >= n in the input", "$", "m", "=", "array_shift", "(", "$", "extended", ")", ";", "//printf('next code point to insert is %s' . PHP_EOL, dechex($m));", "#\t\t\tlet delta = delta + (m - n) * (h + 1), fail on overflow", "$", "delta", "+=", "(", "$", "m", "-", "$", "n", ")", "*", "(", "$", "h", "+", "1", ")", ";", "#\t\t\tlet n = m", "$", "n", "=", "$", "m", ";", "#\t\t\tfor each code point c in the input (in order) do begin", "for", "(", "$", "num", "=", "0", ";", "$", "num", "<", "count", "(", "$", "codepoints", ")", ";", "$", "num", "++", ")", "{", "$", "c", "=", "$", "codepoints", "[", "$", "num", "]", ";", "#\t\t\t\tif c < n then increment delta, fail on overflow", "if", "(", "$", "c", "<", "$", "n", ")", "{", "$", "delta", "++", ";", "}", "#\t\t\t\tif c == n then begin", "elseif", "(", "$", "c", "===", "$", "n", ")", "{", "#\t\t\t\t\tlet q = delta", "$", "q", "=", "$", "delta", ";", "#\t\t\t\t\tfor k = base to infinity in steps of base do begin", "for", "(", "$", "k", "=", "self", "::", "BOOTSTRAP_BASE", ";", ";", "$", "k", "+=", "self", "::", "BOOTSTRAP_BASE", ")", "{", "#\t\t\t\t\t\tlet t = tmin if k <= bias {+ tmin}, or", "#\t\t\t\t\t\t\t\ttmax if k >= bias + tmax, or k - bias otherwise", "if", "(", "$", "k", "<=", "(", "$", "bias", "+", "self", "::", "BOOTSTRAP_TMIN", ")", ")", "{", "$", "t", "=", "self", "::", "BOOTSTRAP_TMIN", ";", "}", "elseif", "(", "$", "k", ">=", "(", "$", "bias", "+", "self", "::", "BOOTSTRAP_TMAX", ")", ")", "{", "$", "t", "=", "self", "::", "BOOTSTRAP_TMAX", ";", "}", "else", "{", "$", "t", "=", "$", "k", "-", "$", "bias", ";", "}", "#\t\t\t\t\t\tif q < t then break", "if", "(", "$", "q", "<", "$", "t", ")", "{", "break", ";", "}", "#\t\t\t\t\t\toutput the code point for digit t + ((q - t) mod (base - t))", "$", "digit", "=", "$", "t", "+", "(", "(", "$", "q", "-", "$", "t", ")", "%", "(", "self", "::", "BOOTSTRAP_BASE", "-", "$", "t", ")", ")", ";", "//printf('needed delta is %d, encodes as \"%s\"' . PHP_EOL, $delta, self::digit_to_char($digit));", "$", "output", ".=", "self", "::", "digit_to_char", "(", "$", "digit", ")", ";", "#\t\t\t\t\t\tlet q = (q - t) div (base - t)", "$", "q", "=", "floor", "(", "(", "$", "q", "-", "$", "t", ")", "/", "(", "self", "::", "BOOTSTRAP_BASE", "-", "$", "t", ")", ")", ";", "#\t\t\t\t\tend", "}", "#\t\t\t\t\toutput the code point for digit q", "$", "output", ".=", "self", "::", "digit_to_char", "(", "$", "q", ")", ";", "//printf('needed delta is %d, encodes as \"%s\"' . PHP_EOL, $delta, self::digit_to_char($q));", "#\t\t\t\t\tlet bias = adapt(delta, h + 1, test h equals b?)", "$", "bias", "=", "self", "::", "adapt", "(", "$", "delta", ",", "$", "h", "+", "1", ",", "$", "h", "===", "$", "b", ")", ";", "//printf('bias becomes %d' . PHP_EOL, $bias);", "#\t\t\t\t\tlet delta = 0", "$", "delta", "=", "0", ";", "#\t\t\t\t\tincrement h", "$", "h", "++", ";", "#\t\t\t\tend", "}", "#\t\t\tend", "}", "#\t\t\tincrement delta and n", "$", "delta", "++", ";", "$", "n", "++", ";", "#\t\tend", "}", "return", "$", "output", ";", "}" ]
RFC3492-compliant encoder @internal Pseudo-code from Section 6.3 is commented with "#" next to relevant code @throws Requests_Exception On character outside of the domain (never happens with Punycode) (`idna.character_outside_domain`) @param string $input UTF-8 encoded string to encode @return string Punycode-encoded string
[ "RFC3492", "-", "compliant", "encoder" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IDNAEncoder.php#L228-L333
train
superfaktura/apiclient
SFAPIclient/Requests/IDNAEncoder.php
Requests_IDNAEncoder.digit_to_char
protected static function digit_to_char($digit) { if ($digit < 0 || $digit > 35) { throw new Requests_Exception(sprintf('Invalid digit %d', $digit), 'idna.invalid_digit', $digit); } $digits = 'abcdefghijklmnopqrstuvwxyz0123456789'; return $digits[$digit]; }
php
protected static function digit_to_char($digit) { if ($digit < 0 || $digit > 35) { throw new Requests_Exception(sprintf('Invalid digit %d', $digit), 'idna.invalid_digit', $digit); } $digits = 'abcdefghijklmnopqrstuvwxyz0123456789'; return $digits[$digit]; }
[ "protected", "static", "function", "digit_to_char", "(", "$", "digit", ")", "{", "if", "(", "$", "digit", "<", "0", "||", "$", "digit", ">", "35", ")", "{", "throw", "new", "Requests_Exception", "(", "sprintf", "(", "'Invalid digit %d'", ",", "$", "digit", ")", ",", "'idna.invalid_digit'", ",", "$", "digit", ")", ";", "}", "$", "digits", "=", "'abcdefghijklmnopqrstuvwxyz0123456789'", ";", "return", "$", "digits", "[", "$", "digit", "]", ";", "}" ]
Convert a digit to its respective character @see http://tools.ietf.org/html/rfc3492#section-5 @throws Requests_Exception On invalid digit (`idna.invalid_digit`) @param int $digit Digit in the range 0-35 @return string Single character corresponding to digit
[ "Convert", "a", "digit", "to", "its", "respective", "character" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IDNAEncoder.php#L344-L350
train
superfaktura/apiclient
SFAPIclient/Requests/IDNAEncoder.php
Requests_IDNAEncoder.adapt
protected static function adapt($delta, $numpoints, $firsttime) { # function adapt(delta,numpoints,firsttime): # if firsttime then let delta = delta div damp if ($firsttime) { $delta = floor($delta / self::BOOTSTRAP_DAMP); } # else let delta = delta div 2 else { $delta = floor($delta / 2); } # let delta = delta + (delta div numpoints) $delta += floor($delta / $numpoints); # let k = 0 $k = 0; # while delta > ((base - tmin) * tmax) div 2 do begin $max = floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN) * self::BOOTSTRAP_TMAX) / 2); while ($delta > $max) { # let delta = delta div (base - tmin) $delta = floor($delta / (self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN)); # let k = k + base $k += self::BOOTSTRAP_BASE; # end } # return k + (((base - tmin + 1) * delta) div (delta + skew)) return $k + floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN + 1) * $delta) / ($delta + self::BOOTSTRAP_SKEW)); }
php
protected static function adapt($delta, $numpoints, $firsttime) { # function adapt(delta,numpoints,firsttime): # if firsttime then let delta = delta div damp if ($firsttime) { $delta = floor($delta / self::BOOTSTRAP_DAMP); } # else let delta = delta div 2 else { $delta = floor($delta / 2); } # let delta = delta + (delta div numpoints) $delta += floor($delta / $numpoints); # let k = 0 $k = 0; # while delta > ((base - tmin) * tmax) div 2 do begin $max = floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN) * self::BOOTSTRAP_TMAX) / 2); while ($delta > $max) { # let delta = delta div (base - tmin) $delta = floor($delta / (self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN)); # let k = k + base $k += self::BOOTSTRAP_BASE; # end } # return k + (((base - tmin + 1) * delta) div (delta + skew)) return $k + floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN + 1) * $delta) / ($delta + self::BOOTSTRAP_SKEW)); }
[ "protected", "static", "function", "adapt", "(", "$", "delta", ",", "$", "numpoints", ",", "$", "firsttime", ")", "{", "#\tfunction adapt(delta,numpoints,firsttime):", "#\t\tif firsttime then let delta = delta div damp", "if", "(", "$", "firsttime", ")", "{", "$", "delta", "=", "floor", "(", "$", "delta", "/", "self", "::", "BOOTSTRAP_DAMP", ")", ";", "}", "#\t\telse let delta = delta div 2", "else", "{", "$", "delta", "=", "floor", "(", "$", "delta", "/", "2", ")", ";", "}", "#\t\tlet delta = delta + (delta div numpoints)", "$", "delta", "+=", "floor", "(", "$", "delta", "/", "$", "numpoints", ")", ";", "#\t\tlet k = 0", "$", "k", "=", "0", ";", "#\t\twhile delta > ((base - tmin) * tmax) div 2 do begin", "$", "max", "=", "floor", "(", "(", "(", "self", "::", "BOOTSTRAP_BASE", "-", "self", "::", "BOOTSTRAP_TMIN", ")", "*", "self", "::", "BOOTSTRAP_TMAX", ")", "/", "2", ")", ";", "while", "(", "$", "delta", ">", "$", "max", ")", "{", "#\t\t\tlet delta = delta div (base - tmin)", "$", "delta", "=", "floor", "(", "$", "delta", "/", "(", "self", "::", "BOOTSTRAP_BASE", "-", "self", "::", "BOOTSTRAP_TMIN", ")", ")", ";", "#\t\t\tlet k = k + base", "$", "k", "+=", "self", "::", "BOOTSTRAP_BASE", ";", "#\t\tend", "}", "#\t\treturn k + (((base - tmin + 1) * delta) div (delta + skew))", "return", "$", "k", "+", "floor", "(", "(", "(", "self", "::", "BOOTSTRAP_BASE", "-", "self", "::", "BOOTSTRAP_TMIN", "+", "1", ")", "*", "$", "delta", ")", "/", "(", "$", "delta", "+", "self", "::", "BOOTSTRAP_SKEW", ")", ")", ";", "}" ]
Adapt the bias @see http://tools.ietf.org/html/rfc3492#section-6.1 @param int $delta @param int $numpoints @param bool $firsttime @return int New bias
[ "Adapt", "the", "bias" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/IDNAEncoder.php#L361-L386
train
superfaktura/apiclient
SFAPIclient/SFAPIclient.php
SFAPIclient.addTag
public function addTag(array $data) { try { $response = Requests::post( $this->getConstant('SFAPI_URL') . '/tags/add', $this->headers, array('data' => json_encode($data)), array('timeout' => $this->timeout) ); $response_data = json_decode($response->body); return $response_data; } catch (Exception $e) { return $this->exceptionHandling($e); } }
php
public function addTag(array $data) { try { $response = Requests::post( $this->getConstant('SFAPI_URL') . '/tags/add', $this->headers, array('data' => json_encode($data)), array('timeout' => $this->timeout) ); $response_data = json_decode($response->body); return $response_data; } catch (Exception $e) { return $this->exceptionHandling($e); } }
[ "public", "function", "addTag", "(", "array", "$", "data", ")", "{", "try", "{", "$", "response", "=", "Requests", "::", "post", "(", "$", "this", "->", "getConstant", "(", "'SFAPI_URL'", ")", ".", "'/tags/add'", ",", "$", "this", "->", "headers", ",", "array", "(", "'data'", "=>", "json_encode", "(", "$", "data", ")", ")", ",", "array", "(", "'timeout'", "=>", "$", "this", "->", "timeout", ")", ")", ";", "$", "response_data", "=", "json_decode", "(", "$", "response", "->", "body", ")", ";", "return", "$", "response_data", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "$", "this", "->", "exceptionHandling", "(", "$", "e", ")", ";", "}", "}" ]
Create new tag. @param array $data @return mixed|stdClass
[ "Create", "new", "tag", "." ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/SFAPIclient.php#L809-L824
train
superfaktura/apiclient
SFAPIclient/Requests/Hooks.php
Requests_Hooks.register
public function register($hook, $callback, $priority = 0) { if (!isset($this->hooks[$hook])) { $this->hooks[$hook] = array(); } if (!isset($this->hooks[$hook][$priority])) { $this->hooks[$hook][$priority] = array(); } $this->hooks[$hook][$priority][] = $callback; }
php
public function register($hook, $callback, $priority = 0) { if (!isset($this->hooks[$hook])) { $this->hooks[$hook] = array(); } if (!isset($this->hooks[$hook][$priority])) { $this->hooks[$hook][$priority] = array(); } $this->hooks[$hook][$priority][] = $callback; }
[ "public", "function", "register", "(", "$", "hook", ",", "$", "callback", ",", "$", "priority", "=", "0", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "hooks", "[", "$", "hook", "]", ")", ")", "{", "$", "this", "->", "hooks", "[", "$", "hook", "]", "=", "array", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "hooks", "[", "$", "hook", "]", "[", "$", "priority", "]", ")", ")", "{", "$", "this", "->", "hooks", "[", "$", "hook", "]", "[", "$", "priority", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "hooks", "[", "$", "hook", "]", "[", "$", "priority", "]", "[", "]", "=", "$", "callback", ";", "}" ]
Register a callback for a hook @param string $hook Hook name @param callback $callback Function/method to call on event @param int $priority Priority number. <0 is executed earlier, >0 is executed later
[ "Register", "a", "callback", "for", "a", "hook" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/Hooks.php#L30-L39
train
superfaktura/apiclient
SFAPIclient/Requests/Hooks.php
Requests_Hooks.dispatch
public function dispatch($hook, $parameters = array()) { if (empty($this->hooks[$hook])) { return false; } foreach ($this->hooks[$hook] as $priority => $hooked) { foreach ($hooked as $callback) { call_user_func_array($callback, $parameters); } } return true; }
php
public function dispatch($hook, $parameters = array()) { if (empty($this->hooks[$hook])) { return false; } foreach ($this->hooks[$hook] as $priority => $hooked) { foreach ($hooked as $callback) { call_user_func_array($callback, $parameters); } } return true; }
[ "public", "function", "dispatch", "(", "$", "hook", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "hooks", "[", "$", "hook", "]", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "this", "->", "hooks", "[", "$", "hook", "]", "as", "$", "priority", "=>", "$", "hooked", ")", "{", "foreach", "(", "$", "hooked", "as", "$", "callback", ")", "{", "call_user_func_array", "(", "$", "callback", ",", "$", "parameters", ")", ";", "}", "}", "return", "true", ";", "}" ]
Dispatch a message @param string $hook Hook name @param array $parameters Parameters to pass to callbacks @return boolean Successfulness
[ "Dispatch", "a", "message" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/Hooks.php#L48-L60
train
yiisoft/view
src/widgets/ContentDecorator.php
ContentDecorator.init
public function init(): void { parent::init(); if ($this->viewFile === null) { throw new InvalidConfigException('ContentDecorator::viewFile must be set.'); } ob_start(); ob_implicit_flush(false); }
php
public function init(): void { parent::init(); if ($this->viewFile === null) { throw new InvalidConfigException('ContentDecorator::viewFile must be set.'); } ob_start(); ob_implicit_flush(false); }
[ "public", "function", "init", "(", ")", ":", "void", "{", "parent", "::", "init", "(", ")", ";", "if", "(", "$", "this", "->", "viewFile", "===", "null", ")", "{", "throw", "new", "InvalidConfigException", "(", "'ContentDecorator::viewFile must be set.'", ")", ";", "}", "ob_start", "(", ")", ";", "ob_implicit_flush", "(", "false", ")", ";", "}" ]
Starts recording a clip.
[ "Starts", "recording", "a", "clip", "." ]
206f58f0c33a7a861984e4c67de470529b19ebb5
https://github.com/yiisoft/view/blob/206f58f0c33a7a861984e4c67de470529b19ebb5/src/widgets/ContentDecorator.php#L57-L66
train
superfaktura/apiclient
SFAPIclient/Requests/Response/Headers.php
Requests_Response_Headers.offsetGet
public function offsetGet($key) { $key = strtolower($key); return isset($this->data[$key]) ? $this->data[$key] : null; }
php
public function offsetGet($key) { $key = strtolower($key); return isset($this->data[$key]) ? $this->data[$key] : null; }
[ "public", "function", "offsetGet", "(", "$", "key", ")", "{", "$", "key", "=", "strtolower", "(", "$", "key", ")", ";", "return", "isset", "(", "$", "this", "->", "data", "[", "$", "key", "]", ")", "?", "$", "this", "->", "data", "[", "$", "key", "]", ":", "null", ";", "}" ]
Get the given header @param string $key @return string Header value
[ "Get", "the", "given", "header" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/Response/Headers.php#L38-L41
train
superfaktura/apiclient
SFAPIclient/Requests/Response/Headers.php
Requests_Response_Headers.offsetSet
public function offsetSet($key, $value) { if (is_null($key)) { throw new Requests_Exception('Headers is a dictionary, not a list', 'invalidset'); } $key = strtolower($key); if (isset($this->data[$key])) { // RFC2616 notes that multiple headers must be able to // be combined like this. We should use a smarter way though (arrays // internally, e.g.) $value = $this->data[$key] . ',' . $value; } $this->data[$key] = $value; }
php
public function offsetSet($key, $value) { if (is_null($key)) { throw new Requests_Exception('Headers is a dictionary, not a list', 'invalidset'); } $key = strtolower($key); if (isset($this->data[$key])) { // RFC2616 notes that multiple headers must be able to // be combined like this. We should use a smarter way though (arrays // internally, e.g.) $value = $this->data[$key] . ',' . $value; } $this->data[$key] = $value; }
[ "public", "function", "offsetSet", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "is_null", "(", "$", "key", ")", ")", "{", "throw", "new", "Requests_Exception", "(", "'Headers is a dictionary, not a list'", ",", "'invalidset'", ")", ";", "}", "$", "key", "=", "strtolower", "(", "$", "key", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "data", "[", "$", "key", "]", ")", ")", "{", "// RFC2616 notes that multiple headers must be able to", "// be combined like this. We should use a smarter way though (arrays", "// internally, e.g.)", "$", "value", "=", "$", "this", "->", "data", "[", "$", "key", "]", ".", "','", ".", "$", "value", ";", "}", "$", "this", "->", "data", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
Set the given header @throws Requests_Exception On attempting to use headers dictionary as list (`invalidset`) @param string $key Header name @param string $value Header value
[ "Set", "the", "given", "header" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests/Response/Headers.php#L51-L66
train
superfaktura/apiclient
SFAPIclient/Requests.php
Requests.autoloader
public static function autoloader($class) { // Check that the class starts with "Requests" if (strpos($class, 'Requests') !== 0) { return; } $file = str_replace('_', '/', $class); if (file_exists(dirname(__FILE__) . '/' . $file . '.php')) { require_once(dirname(__FILE__) . '/' . $file . '.php'); } }
php
public static function autoloader($class) { // Check that the class starts with "Requests" if (strpos($class, 'Requests') !== 0) { return; } $file = str_replace('_', '/', $class); if (file_exists(dirname(__FILE__) . '/' . $file . '.php')) { require_once(dirname(__FILE__) . '/' . $file . '.php'); } }
[ "public", "static", "function", "autoloader", "(", "$", "class", ")", "{", "// Check that the class starts with \"Requests\"", "if", "(", "strpos", "(", "$", "class", ",", "'Requests'", ")", "!==", "0", ")", "{", "return", ";", "}", "$", "file", "=", "str_replace", "(", "'_'", ",", "'/'", ",", "$", "class", ")", ";", "if", "(", "file_exists", "(", "dirname", "(", "__FILE__", ")", ".", "'/'", ".", "$", "file", ".", "'.php'", ")", ")", "{", "require_once", "(", "dirname", "(", "__FILE__", ")", ".", "'/'", ".", "$", "file", ".", "'.php'", ")", ";", "}", "}" ]
Autoloader for Requests Register this with {@see register_autoloader()} if you'd like to avoid having to create your own. (You can also use `spl_autoload_register` directly if you'd prefer.) @codeCoverageIgnore @param string $class Class name to load
[ "Autoloader", "for", "Requests" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests.php#L85-L95
train
superfaktura/apiclient
SFAPIclient/Requests.php
Requests.add_transport
public static function add_transport($transport) { if (empty(self::$transports)) { self::$transports = array( 'Requests_Transport_cURL', 'Requests_Transport_fsockopen', ); } self::$transports = array_merge(self::$transports, array($transport)); }
php
public static function add_transport($transport) { if (empty(self::$transports)) { self::$transports = array( 'Requests_Transport_cURL', 'Requests_Transport_fsockopen', ); } self::$transports = array_merge(self::$transports, array($transport)); }
[ "public", "static", "function", "add_transport", "(", "$", "transport", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "transports", ")", ")", "{", "self", "::", "$", "transports", "=", "array", "(", "'Requests_Transport_cURL'", ",", "'Requests_Transport_fsockopen'", ",", ")", ";", "}", "self", "::", "$", "transports", "=", "array_merge", "(", "self", "::", "$", "transports", ",", "array", "(", "$", "transport", ")", ")", ";", "}" ]
Register a transport @param string $transport Transport class to add, must support the Requests_Transport interface
[ "Register", "a", "transport" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests.php#L111-L120
train
superfaktura/apiclient
SFAPIclient/Requests.php
Requests.get_transport
protected static function get_transport() { // Caching code, don't bother testing coverage // @codeCoverageIgnoreStart if (!is_null(self::$transport)) { return new self::$transport(); } // @codeCoverageIgnoreEnd if (empty(self::$transports)) { self::$transports = array( 'Requests_Transport_cURL', 'Requests_Transport_fsockopen', ); } // Find us a working transport foreach (self::$transports as $class) { if (!class_exists($class)) continue; $result = call_user_func(array($class, 'test')); if ($result) { self::$transport = $class; break; } } if (self::$transport === null) { throw new Requests_Exception('No working transports found', 'notransport', self::$transports); } return new self::$transport(); }
php
protected static function get_transport() { // Caching code, don't bother testing coverage // @codeCoverageIgnoreStart if (!is_null(self::$transport)) { return new self::$transport(); } // @codeCoverageIgnoreEnd if (empty(self::$transports)) { self::$transports = array( 'Requests_Transport_cURL', 'Requests_Transport_fsockopen', ); } // Find us a working transport foreach (self::$transports as $class) { if (!class_exists($class)) continue; $result = call_user_func(array($class, 'test')); if ($result) { self::$transport = $class; break; } } if (self::$transport === null) { throw new Requests_Exception('No working transports found', 'notransport', self::$transports); } return new self::$transport(); }
[ "protected", "static", "function", "get_transport", "(", ")", "{", "// Caching code, don't bother testing coverage", "// @codeCoverageIgnoreStart", "if", "(", "!", "is_null", "(", "self", "::", "$", "transport", ")", ")", "{", "return", "new", "self", "::", "$", "transport", "(", ")", ";", "}", "// @codeCoverageIgnoreEnd", "if", "(", "empty", "(", "self", "::", "$", "transports", ")", ")", "{", "self", "::", "$", "transports", "=", "array", "(", "'Requests_Transport_cURL'", ",", "'Requests_Transport_fsockopen'", ",", ")", ";", "}", "// Find us a working transport", "foreach", "(", "self", "::", "$", "transports", "as", "$", "class", ")", "{", "if", "(", "!", "class_exists", "(", "$", "class", ")", ")", "continue", ";", "$", "result", "=", "call_user_func", "(", "array", "(", "$", "class", ",", "'test'", ")", ")", ";", "if", "(", "$", "result", ")", "{", "self", "::", "$", "transport", "=", "$", "class", ";", "break", ";", "}", "}", "if", "(", "self", "::", "$", "transport", "===", "null", ")", "{", "throw", "new", "Requests_Exception", "(", "'No working transports found'", ",", "'notransport'", ",", "self", "::", "$", "transports", ")", ";", "}", "return", "new", "self", "::", "$", "transport", "(", ")", ";", "}" ]
Get a working transport @throws Requests_Exception If no valid transport is found (`notransport`) @return Requests_Transport
[ "Get", "a", "working", "transport" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests.php#L128-L159
train
superfaktura/apiclient
SFAPIclient/Requests.php
Requests.request
public static function request($url, $headers = array(), $data = array(), $type = self::GET, $options = array()) { if (!preg_match('/^http(s)?:\/\//i', $url)) { throw new Requests_Exception('Only HTTP requests are handled.', 'nonhttp', $url); } $defaults = array( 'timeout' => 10, 'useragent' => 'php-requests/' . self::VERSION, 'redirected' => 0, 'redirects' => 10, 'follow_redirects' => true, 'blocking' => true, 'type' => $type, 'filename' => false, 'auth' => false, 'idn' => true, 'hooks' => null, 'transport' => null, ); $options = array_merge($defaults, $options); if (empty($options['hooks'])) { $options['hooks'] = new Requests_Hooks(); } // Special case for simple basic auth if (is_array($options['auth'])) { $options['auth'] = new Requests_Auth_Basic($options['auth']); } if ($options['auth'] !== false) { $options['auth']->register($options['hooks']); } $options['hooks']->dispatch('requests.before_request', array(&$url, &$headers, &$data, &$type, &$options)); if ($options['idn'] !== false) { $iri = new Requests_IRI($url); $iri->host = Requests_IDNAEncoder::encode($iri->ihost); $url = $iri->uri; } if (!empty($options['transport'])) { $transport = $options['transport']; if (is_string($options['transport'])) { $transport = new $transport(); } } else { $transport = self::get_transport(); } $response = $transport->request($url, $headers, $data, $options); $options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options)); return self::parse_response($response, $url, $headers, $data, $options); }
php
public static function request($url, $headers = array(), $data = array(), $type = self::GET, $options = array()) { if (!preg_match('/^http(s)?:\/\//i', $url)) { throw new Requests_Exception('Only HTTP requests are handled.', 'nonhttp', $url); } $defaults = array( 'timeout' => 10, 'useragent' => 'php-requests/' . self::VERSION, 'redirected' => 0, 'redirects' => 10, 'follow_redirects' => true, 'blocking' => true, 'type' => $type, 'filename' => false, 'auth' => false, 'idn' => true, 'hooks' => null, 'transport' => null, ); $options = array_merge($defaults, $options); if (empty($options['hooks'])) { $options['hooks'] = new Requests_Hooks(); } // Special case for simple basic auth if (is_array($options['auth'])) { $options['auth'] = new Requests_Auth_Basic($options['auth']); } if ($options['auth'] !== false) { $options['auth']->register($options['hooks']); } $options['hooks']->dispatch('requests.before_request', array(&$url, &$headers, &$data, &$type, &$options)); if ($options['idn'] !== false) { $iri = new Requests_IRI($url); $iri->host = Requests_IDNAEncoder::encode($iri->ihost); $url = $iri->uri; } if (!empty($options['transport'])) { $transport = $options['transport']; if (is_string($options['transport'])) { $transport = new $transport(); } } else { $transport = self::get_transport(); } $response = $transport->request($url, $headers, $data, $options); $options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options)); return self::parse_response($response, $url, $headers, $data, $options); }
[ "public", "static", "function", "request", "(", "$", "url", ",", "$", "headers", "=", "array", "(", ")", ",", "$", "data", "=", "array", "(", ")", ",", "$", "type", "=", "self", "::", "GET", ",", "$", "options", "=", "array", "(", ")", ")", "{", "if", "(", "!", "preg_match", "(", "'/^http(s)?:\\/\\//i'", ",", "$", "url", ")", ")", "{", "throw", "new", "Requests_Exception", "(", "'Only HTTP requests are handled.'", ",", "'nonhttp'", ",", "$", "url", ")", ";", "}", "$", "defaults", "=", "array", "(", "'timeout'", "=>", "10", ",", "'useragent'", "=>", "'php-requests/'", ".", "self", "::", "VERSION", ",", "'redirected'", "=>", "0", ",", "'redirects'", "=>", "10", ",", "'follow_redirects'", "=>", "true", ",", "'blocking'", "=>", "true", ",", "'type'", "=>", "$", "type", ",", "'filename'", "=>", "false", ",", "'auth'", "=>", "false", ",", "'idn'", "=>", "true", ",", "'hooks'", "=>", "null", ",", "'transport'", "=>", "null", ",", ")", ";", "$", "options", "=", "array_merge", "(", "$", "defaults", ",", "$", "options", ")", ";", "if", "(", "empty", "(", "$", "options", "[", "'hooks'", "]", ")", ")", "{", "$", "options", "[", "'hooks'", "]", "=", "new", "Requests_Hooks", "(", ")", ";", "}", "// Special case for simple basic auth", "if", "(", "is_array", "(", "$", "options", "[", "'auth'", "]", ")", ")", "{", "$", "options", "[", "'auth'", "]", "=", "new", "Requests_Auth_Basic", "(", "$", "options", "[", "'auth'", "]", ")", ";", "}", "if", "(", "$", "options", "[", "'auth'", "]", "!==", "false", ")", "{", "$", "options", "[", "'auth'", "]", "->", "register", "(", "$", "options", "[", "'hooks'", "]", ")", ";", "}", "$", "options", "[", "'hooks'", "]", "->", "dispatch", "(", "'requests.before_request'", ",", "array", "(", "&", "$", "url", ",", "&", "$", "headers", ",", "&", "$", "data", ",", "&", "$", "type", ",", "&", "$", "options", ")", ")", ";", "if", "(", "$", "options", "[", "'idn'", "]", "!==", "false", ")", "{", "$", "iri", "=", "new", "Requests_IRI", "(", "$", "url", ")", ";", "$", "iri", "->", "host", "=", "Requests_IDNAEncoder", "::", "encode", "(", "$", "iri", "->", "ihost", ")", ";", "$", "url", "=", "$", "iri", "->", "uri", ";", "}", "if", "(", "!", "empty", "(", "$", "options", "[", "'transport'", "]", ")", ")", "{", "$", "transport", "=", "$", "options", "[", "'transport'", "]", ";", "if", "(", "is_string", "(", "$", "options", "[", "'transport'", "]", ")", ")", "{", "$", "transport", "=", "new", "$", "transport", "(", ")", ";", "}", "}", "else", "{", "$", "transport", "=", "self", "::", "get_transport", "(", ")", ";", "}", "$", "response", "=", "$", "transport", "->", "request", "(", "$", "url", ",", "$", "headers", ",", "$", "data", ",", "$", "options", ")", ";", "$", "options", "[", "'hooks'", "]", "->", "dispatch", "(", "'requests.before_parse'", ",", "array", "(", "&", "$", "response", ",", "$", "url", ",", "$", "headers", ",", "$", "data", ",", "$", "type", ",", "$", "options", ")", ")", ";", "return", "self", "::", "parse_response", "(", "$", "response", ",", "$", "url", ",", "$", "headers", ",", "$", "data", ",", "$", "options", ")", ";", "}" ]
Main interface for HTTP requests This method initiates a request and sends it via a transport before parsing. The `$options` parameter takes an associative array with the following options: - `timeout`: How long should we wait for a response? (integer, seconds, default: 10) - `useragent`: Useragent to send to the server (string, default: php-requests/$version) - `follow_redirects`: Should we follow 3xx redirects? (boolean, default: true) - `redirects`: How many times should we redirect before erroring? (integer, default: 10) - `blocking`: Should we block processing on this request? (boolean, default: true) - `filename`: File to stream the body to instead. (string|boolean, default: false) - `auth`: Authentication handler or array of user/password details to use for Basic authentication (Requests_Auth|array|boolean, default: false) - `idn`: Enable IDN parsing (boolean, default: true) - `transport`: Custom transport. Either a class name, or a transport object. Defaults to the first working transport from {@see getTransport()} (string|Requests_Transport, default: {@see getTransport()}) @throws Requests_Exception On invalid URLs (`nonhttp`) @param string $url URL to request @param array $headers Extra headers to send with the request @param array $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests @param string $type HTTP request type (use Requests constants) @param array $options Options for the request (see description for more information) @return Requests_Response
[ "Main", "interface", "for", "HTTP", "requests" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests.php#L237-L292
train
superfaktura/apiclient
SFAPIclient/Requests.php
Requests.decode_chunked
protected static function decode_chunked($data) { if (!preg_match('/^([0-9a-f]+)[^\r\n]*\r\n/i', trim($data))) { return $data; } $decoded = ''; $encoded = $data; while (true) { $is_chunked = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $encoded, $matches ); if (!$is_chunked) { // Looks like it's not chunked after all return $data; } $length = hexdec(trim($matches[1])); if ($length === 0) { // Ignore trailer headers return $decoded; } $chunk_length = strlen($matches[0]); $decoded .= $part = substr($encoded, $chunk_length, $length); $encoded = substr($encoded, $chunk_length + $length + 2); if (trim($encoded) === '0' || empty($encoded)) { return $decoded; } } // We'll never actually get down here // @codeCoverageIgnoreStart }
php
protected static function decode_chunked($data) { if (!preg_match('/^([0-9a-f]+)[^\r\n]*\r\n/i', trim($data))) { return $data; } $decoded = ''; $encoded = $data; while (true) { $is_chunked = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $encoded, $matches ); if (!$is_chunked) { // Looks like it's not chunked after all return $data; } $length = hexdec(trim($matches[1])); if ($length === 0) { // Ignore trailer headers return $decoded; } $chunk_length = strlen($matches[0]); $decoded .= $part = substr($encoded, $chunk_length, $length); $encoded = substr($encoded, $chunk_length + $length + 2); if (trim($encoded) === '0' || empty($encoded)) { return $decoded; } } // We'll never actually get down here // @codeCoverageIgnoreStart }
[ "protected", "static", "function", "decode_chunked", "(", "$", "data", ")", "{", "if", "(", "!", "preg_match", "(", "'/^([0-9a-f]+)[^\\r\\n]*\\r\\n/i'", ",", "trim", "(", "$", "data", ")", ")", ")", "{", "return", "$", "data", ";", "}", "$", "decoded", "=", "''", ";", "$", "encoded", "=", "$", "data", ";", "while", "(", "true", ")", "{", "$", "is_chunked", "=", "(", "bool", ")", "preg_match", "(", "'/^([0-9a-f]+)[^\\r\\n]*\\r\\n/i'", ",", "$", "encoded", ",", "$", "matches", ")", ";", "if", "(", "!", "$", "is_chunked", ")", "{", "// Looks like it's not chunked after all", "return", "$", "data", ";", "}", "$", "length", "=", "hexdec", "(", "trim", "(", "$", "matches", "[", "1", "]", ")", ")", ";", "if", "(", "$", "length", "===", "0", ")", "{", "// Ignore trailer headers", "return", "$", "decoded", ";", "}", "$", "chunk_length", "=", "strlen", "(", "$", "matches", "[", "0", "]", ")", ";", "$", "decoded", ".=", "$", "part", "=", "substr", "(", "$", "encoded", ",", "$", "chunk_length", ",", "$", "length", ")", ";", "$", "encoded", "=", "substr", "(", "$", "encoded", ",", "$", "chunk_length", "+", "$", "length", "+", "2", ")", ";", "if", "(", "trim", "(", "$", "encoded", ")", "===", "'0'", "||", "empty", "(", "$", "encoded", ")", ")", "{", "return", "$", "decoded", ";", "}", "}", "// We'll never actually get down here", "// @codeCoverageIgnoreStart", "}" ]
Decoded a chunked body as per RFC 2616 @see http://tools.ietf.org/html/rfc2616#section-3.6.1 @param string $data Chunked body @return string Decoded body
[ "Decoded", "a", "chunked", "body", "as", "per", "RFC", "2616" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests.php#L388-L420
train
superfaktura/apiclient
SFAPIclient/Requests.php
Requests.decompress
protected static function decompress($data) { if (substr($data, 0, 2) !== "\x1f\x8b") { // Not actually compressed. Probably cURL ruining this for us. return $data; } if (function_exists('gzdecode') && ($decoded = gzdecode($data)) !== false) { return $decoded; } elseif (function_exists('gzinflate') && ($decoded = @gzinflate($data)) !== false) { return $decoded; } elseif (($decoded = self::compatible_gzinflate($data)) !== false) { return $decoded; } elseif (function_exists('gzuncompress') && ($decoded = @gzuncompress($data)) !== false) { return $decoded; } return $data; }
php
protected static function decompress($data) { if (substr($data, 0, 2) !== "\x1f\x8b") { // Not actually compressed. Probably cURL ruining this for us. return $data; } if (function_exists('gzdecode') && ($decoded = gzdecode($data)) !== false) { return $decoded; } elseif (function_exists('gzinflate') && ($decoded = @gzinflate($data)) !== false) { return $decoded; } elseif (($decoded = self::compatible_gzinflate($data)) !== false) { return $decoded; } elseif (function_exists('gzuncompress') && ($decoded = @gzuncompress($data)) !== false) { return $decoded; } return $data; }
[ "protected", "static", "function", "decompress", "(", "$", "data", ")", "{", "if", "(", "substr", "(", "$", "data", ",", "0", ",", "2", ")", "!==", "\"\\x1f\\x8b\"", ")", "{", "// Not actually compressed. Probably cURL ruining this for us.", "return", "$", "data", ";", "}", "if", "(", "function_exists", "(", "'gzdecode'", ")", "&&", "(", "$", "decoded", "=", "gzdecode", "(", "$", "data", ")", ")", "!==", "false", ")", "{", "return", "$", "decoded", ";", "}", "elseif", "(", "function_exists", "(", "'gzinflate'", ")", "&&", "(", "$", "decoded", "=", "@", "gzinflate", "(", "$", "data", ")", ")", "!==", "false", ")", "{", "return", "$", "decoded", ";", "}", "elseif", "(", "(", "$", "decoded", "=", "self", "::", "compatible_gzinflate", "(", "$", "data", ")", ")", "!==", "false", ")", "{", "return", "$", "decoded", ";", "}", "elseif", "(", "function_exists", "(", "'gzuncompress'", ")", "&&", "(", "$", "decoded", "=", "@", "gzuncompress", "(", "$", "data", ")", ")", "!==", "false", ")", "{", "return", "$", "decoded", ";", "}", "return", "$", "data", ";", "}" ]
Decompress an encoded body Implements gzip, compress and deflate. Guesses which it is by attempting to decode. @todo Make this smarter by defaulting to whatever the headers say first @param string $data Compressed data in one of the above formats @return string Decompressed string
[ "Decompress", "an", "encoded", "body" ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests.php#L447-L467
train
superfaktura/apiclient
SFAPIclient/Requests.php
Requests.compatible_gzinflate
protected static function compatible_gzinflate($gzData) { if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) { $i = 10; $flg = ord( substr($gzData, 3, 1) ); if ( $flg > 0 ) { if ( $flg & 4 ) { list($xlen) = unpack('v', substr($gzData, $i, 2) ); $i = $i + 2 + $xlen; } if ( $flg & 8 ) $i = strpos($gzData, "\0", $i) + 1; if ( $flg & 16 ) $i = strpos($gzData, "\0", $i) + 1; if ( $flg & 2 ) $i = $i + 2; } return gzinflate( substr($gzData, $i, -8) ); } else { return false; } }
php
protected static function compatible_gzinflate($gzData) { if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) { $i = 10; $flg = ord( substr($gzData, 3, 1) ); if ( $flg > 0 ) { if ( $flg & 4 ) { list($xlen) = unpack('v', substr($gzData, $i, 2) ); $i = $i + 2 + $xlen; } if ( $flg & 8 ) $i = strpos($gzData, "\0", $i) + 1; if ( $flg & 16 ) $i = strpos($gzData, "\0", $i) + 1; if ( $flg & 2 ) $i = $i + 2; } return gzinflate( substr($gzData, $i, -8) ); } else { return false; } }
[ "protected", "static", "function", "compatible_gzinflate", "(", "$", "gzData", ")", "{", "if", "(", "substr", "(", "$", "gzData", ",", "0", ",", "3", ")", "==", "\"\\x1f\\x8b\\x08\"", ")", "{", "$", "i", "=", "10", ";", "$", "flg", "=", "ord", "(", "substr", "(", "$", "gzData", ",", "3", ",", "1", ")", ")", ";", "if", "(", "$", "flg", ">", "0", ")", "{", "if", "(", "$", "flg", "&", "4", ")", "{", "list", "(", "$", "xlen", ")", "=", "unpack", "(", "'v'", ",", "substr", "(", "$", "gzData", ",", "$", "i", ",", "2", ")", ")", ";", "$", "i", "=", "$", "i", "+", "2", "+", "$", "xlen", ";", "}", "if", "(", "$", "flg", "&", "8", ")", "$", "i", "=", "strpos", "(", "$", "gzData", ",", "\"\\0\"", ",", "$", "i", ")", "+", "1", ";", "if", "(", "$", "flg", "&", "16", ")", "$", "i", "=", "strpos", "(", "$", "gzData", ",", "\"\\0\"", ",", "$", "i", ")", "+", "1", ";", "if", "(", "$", "flg", "&", "2", ")", "$", "i", "=", "$", "i", "+", "2", ";", "}", "return", "gzinflate", "(", "substr", "(", "$", "gzData", ",", "$", "i", ",", "-", "8", ")", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Decompress deflated string while staying compatible with the majority of servers. Certain servers will return deflated data with headers which PHP's gziniflate() function cannot handle out of the box. The following function lifted from http://au2.php.net/manual/en/function.gzinflate.php#77336 will attempt to deflate the various return forms used. @link http://au2.php.net/manual/en/function.gzinflate.php#77336 @param string $gzData String to decompress. @return string|bool False on failure.
[ "Decompress", "deflated", "string", "while", "staying", "compatible", "with", "the", "majority", "of", "servers", "." ]
a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c
https://github.com/superfaktura/apiclient/blob/a8d94eaa9a36b3bb4bdc47395e029e38c388dd1c/SFAPIclient/Requests.php#L482-L502
train
yiisoft/view
src/widgets/ActiveField.php
ActiveField.end
public function end() { $html = Html::endTag(ArrayHelper::keyExists('tag', $this->options) ? $this->options['tag'] : 'div'); $this->form->afterFieldRender($this); return $html; }
php
public function end() { $html = Html::endTag(ArrayHelper::keyExists('tag', $this->options) ? $this->options['tag'] : 'div'); $this->form->afterFieldRender($this); return $html; }
[ "public", "function", "end", "(", ")", "{", "$", "html", "=", "Html", "::", "endTag", "(", "ArrayHelper", "::", "keyExists", "(", "'tag'", ",", "$", "this", "->", "options", ")", "?", "$", "this", "->", "options", "[", "'tag'", "]", ":", "'div'", ")", ";", "$", "this", "->", "form", "->", "afterFieldRender", "(", "$", "this", ")", ";", "return", "$", "html", ";", "}" ]
Renders the closing tag of the field container. @return string the rendering result.
[ "Renders", "the", "closing", "tag", "of", "the", "field", "container", "." ]
206f58f0c33a7a861984e4c67de470529b19ebb5
https://github.com/yiisoft/view/blob/206f58f0c33a7a861984e4c67de470529b19ebb5/src/widgets/ActiveField.php#L255-L261
train
yiisoft/view
src/widgets/ActiveField.php
ActiveField.addAriaAttributes
protected function addAriaAttributes(&$options) { if ($this->addAriaAttributes) { if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) { $options['aria-required'] = 'true'; } if (!isset($options['aria-invalid'])) { if ($this->model->hasErrors($this->attribute)) { $options['aria-invalid'] = 'true'; } } } }
php
protected function addAriaAttributes(&$options) { if ($this->addAriaAttributes) { if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) { $options['aria-required'] = 'true'; } if (!isset($options['aria-invalid'])) { if ($this->model->hasErrors($this->attribute)) { $options['aria-invalid'] = 'true'; } } } }
[ "protected", "function", "addAriaAttributes", "(", "&", "$", "options", ")", "{", "if", "(", "$", "this", "->", "addAriaAttributes", ")", "{", "if", "(", "!", "isset", "(", "$", "options", "[", "'aria-required'", "]", ")", "&&", "$", "this", "->", "model", "->", "isAttributeRequired", "(", "$", "this", "->", "attribute", ")", ")", "{", "$", "options", "[", "'aria-required'", "]", "=", "'true'", ";", "}", "if", "(", "!", "isset", "(", "$", "options", "[", "'aria-invalid'", "]", ")", ")", "{", "if", "(", "$", "this", "->", "model", "->", "hasErrors", "(", "$", "this", "->", "attribute", ")", ")", "{", "$", "options", "[", "'aria-invalid'", "]", "=", "'true'", ";", "}", "}", "}", "}" ]
Adds aria attributes to the input options. @param $options array input options
[ "Adds", "aria", "attributes", "to", "the", "input", "options", "." ]
206f58f0c33a7a861984e4c67de470529b19ebb5
https://github.com/yiisoft/view/blob/206f58f0c33a7a861984e4c67de470529b19ebb5/src/widgets/ActiveField.php#L865-L877
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.queryFilter
public function queryFilter(string $filterType, $filterOptions, string $clauseType = 'must'): ElasticSearchQueryBuilder { $this->request->queryFilter($filterType, $filterOptions, $clauseType); return $this; }
php
public function queryFilter(string $filterType, $filterOptions, string $clauseType = 'must'): ElasticSearchQueryBuilder { $this->request->queryFilter($filterType, $filterOptions, $clauseType); return $this; }
[ "public", "function", "queryFilter", "(", "string", "$", "filterType", ",", "$", "filterOptions", ",", "string", "$", "clauseType", "=", "'must'", ")", ":", "ElasticSearchQueryBuilder", "{", "$", "this", "->", "request", "->", "queryFilter", "(", "$", "filterType", ",", "$", "filterOptions", ",", "$", "clauseType", ")", ";", "return", "$", "this", ";", "}" ]
Add a filter to query.filtered.filter @param string $filterType @param mixed $filterOptions @param string $clauseType one of must, should, must_not @return ElasticSearchQueryBuilder @throws QueryBuildingException @api
[ "Add", "a", "filter", "to", "query", ".", "filtered", ".", "filter" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L333-L338
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.queryFilterMultiple
public function queryFilterMultiple(array $data, $clauseType = 'must'): ElasticSearchQueryBuilder { foreach ($data as $key => $value) { if ($value !== null) { if (is_array($value)) { $this->queryFilter('terms', [$key => $value], $clauseType); } else { $this->queryFilter('term', [$key => $value], $clauseType); } } } return $this; }
php
public function queryFilterMultiple(array $data, $clauseType = 'must'): ElasticSearchQueryBuilder { foreach ($data as $key => $value) { if ($value !== null) { if (is_array($value)) { $this->queryFilter('terms', [$key => $value], $clauseType); } else { $this->queryFilter('term', [$key => $value], $clauseType); } } } return $this; }
[ "public", "function", "queryFilterMultiple", "(", "array", "$", "data", ",", "$", "clauseType", "=", "'must'", ")", ":", "ElasticSearchQueryBuilder", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "!==", "null", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "this", "->", "queryFilter", "(", "'terms'", ",", "[", "$", "key", "=>", "$", "value", "]", ",", "$", "clauseType", ")", ";", "}", "else", "{", "$", "this", "->", "queryFilter", "(", "'term'", ",", "[", "$", "key", "=>", "$", "value", "]", ",", "$", "clauseType", ")", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Add multiple filters to query.filtered.filter Example Usage: searchFilter = Neos.Fusion:RawArray { author = 'Max' tags = Neos.Fusion:RawArray { 0 = 'a' 1 = 'b' } } searchQuery = ${Search.queryFilterMultiple(this.searchFilter)} @param array $data An associative array of keys as variable names and values as variable values @param string $clauseType one of must, should, must_not @return ElasticSearchQueryBuilder @throws QueryBuildingException @api
[ "Add", "multiple", "filters", "to", "query", ".", "filtered", ".", "filter" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L378-L391
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.fieldBasedAggregation
public function fieldBasedAggregation(string $name, string $field, string $type = 'terms', string $parentPath = '', int $size = 10): ElasticSearchQueryBuilder { $aggregationDefinition = [ $type => [ 'field' => $field, 'size' => $size ] ]; $this->aggregation($name, $aggregationDefinition, $parentPath); return $this; }
php
public function fieldBasedAggregation(string $name, string $field, string $type = 'terms', string $parentPath = '', int $size = 10): ElasticSearchQueryBuilder { $aggregationDefinition = [ $type => [ 'field' => $field, 'size' => $size ] ]; $this->aggregation($name, $aggregationDefinition, $parentPath); return $this; }
[ "public", "function", "fieldBasedAggregation", "(", "string", "$", "name", ",", "string", "$", "field", ",", "string", "$", "type", "=", "'terms'", ",", "string", "$", "parentPath", "=", "''", ",", "int", "$", "size", "=", "10", ")", ":", "ElasticSearchQueryBuilder", "{", "$", "aggregationDefinition", "=", "[", "$", "type", "=>", "[", "'field'", "=>", "$", "field", ",", "'size'", "=>", "$", "size", "]", "]", ";", "$", "this", "->", "aggregation", "(", "$", "name", ",", "$", "aggregationDefinition", ",", "$", "parentPath", ")", ";", "return", "$", "this", ";", "}" ]
This method adds a field based aggregation configuration. This can be used for simple aggregations like terms Example Usage to create a terms aggregation for a property color: nodes = ${Search....fieldBasedAggregation("colors", "color").execute()} Access all aggregation data with {nodes.aggregations} in your fluid template @param string $name The name to identify the resulting aggregation @param string $field The field to aggregate by @param string $type Aggregation type @param string $parentPath @param int $size The amount of buckets to return @return ElasticSearchQueryBuilder @throws QueryBuildingException
[ "This", "method", "adds", "a", "field", "based", "aggregation", "configuration", ".", "This", "can", "be", "used", "for", "simple", "aggregations", "like", "terms" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L410-L422
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.aggregation
public function aggregation(string $name, array $aggregationDefinition, string $parentPath = ''): ElasticSearchQueryBuilder { $this->request->aggregation($name, $aggregationDefinition, $parentPath); return $this; }
php
public function aggregation(string $name, array $aggregationDefinition, string $parentPath = ''): ElasticSearchQueryBuilder { $this->request->aggregation($name, $aggregationDefinition, $parentPath); return $this; }
[ "public", "function", "aggregation", "(", "string", "$", "name", ",", "array", "$", "aggregationDefinition", ",", "string", "$", "parentPath", "=", "''", ")", ":", "ElasticSearchQueryBuilder", "{", "$", "this", "->", "request", "->", "aggregation", "(", "$", "name", ",", "$", "aggregationDefinition", ",", "$", "parentPath", ")", ";", "return", "$", "this", ";", "}" ]
This method is used to create any kind of aggregation. Example Usage to create a terms aggregation for a property color: aggregationDefinition = Neos.Fusion:RawArray { terms = Neos.Fusion:RawArray { field = "color" } } nodes = ${Search....aggregation("color", this.aggregationDefinition).execute()} Access all aggregation data with {nodes.aggregations} in your fluid template @param string $name @param array $aggregationDefinition @param string $parentPath @return ElasticSearchQueryBuilder @throws QueryBuildingException
[ "This", "method", "is", "used", "to", "create", "any", "kind", "of", "aggregation", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L445-L450
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.termSuggestions
public function termSuggestions(string $text, string $field = '_all', string $name = 'suggestions'): ElasticSearchQueryBuilder { $suggestionDefinition = [ 'text' => $text, 'term' => [ 'field' => $field ] ]; $this->suggestions($name, $suggestionDefinition); return $this; }
php
public function termSuggestions(string $text, string $field = '_all', string $name = 'suggestions'): ElasticSearchQueryBuilder { $suggestionDefinition = [ 'text' => $text, 'term' => [ 'field' => $field ] ]; $this->suggestions($name, $suggestionDefinition); return $this; }
[ "public", "function", "termSuggestions", "(", "string", "$", "text", ",", "string", "$", "field", "=", "'_all'", ",", "string", "$", "name", "=", "'suggestions'", ")", ":", "ElasticSearchQueryBuilder", "{", "$", "suggestionDefinition", "=", "[", "'text'", "=>", "$", "text", ",", "'term'", "=>", "[", "'field'", "=>", "$", "field", "]", "]", ";", "$", "this", "->", "suggestions", "(", "$", "name", ",", "$", "suggestionDefinition", ")", ";", "return", "$", "this", ";", "}" ]
This method is used to create a simple term suggestion. Example Usage of a term suggestion nodes = ${Search....termSuggestions("aTerm")} Access all suggestions data with ${Search....getSuggestions()} @param string $text @param string $field @param string $name @return ElasticSearchQueryBuilder
[ "This", "method", "is", "used", "to", "create", "a", "simple", "term", "suggestion", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L466-L478
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.suggestions
public function suggestions(string $name, array $suggestionDefinition): ElasticSearchQueryBuilder { $this->request->suggestions($name, $suggestionDefinition); return $this; }
php
public function suggestions(string $name, array $suggestionDefinition): ElasticSearchQueryBuilder { $this->request->suggestions($name, $suggestionDefinition); return $this; }
[ "public", "function", "suggestions", "(", "string", "$", "name", ",", "array", "$", "suggestionDefinition", ")", ":", "ElasticSearchQueryBuilder", "{", "$", "this", "->", "request", "->", "suggestions", "(", "$", "name", ",", "$", "suggestionDefinition", ")", ";", "return", "$", "this", ";", "}" ]
This method is used to create any kind of suggestion. Example Usage of a term suggestion for the fulltext search suggestionDefinition = Neos.Fusion:RawArray { text = "some text" terms = Neos.Fusion:RawArray { field = "body" } } nodes = ${Search....suggestion("my-suggestions", this.suggestionDefinition).execute()} Access all suggestions data with {nodes.suggestions} in your fluid template @param string $name @param array $suggestionDefinition @return ElasticSearchQueryBuilder
[ "This", "method", "is", "used", "to", "create", "any", "kind", "of", "suggestion", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L500-L505
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.log
public function log($message = null): ElasticSearchQueryBuilder { $this->logThisQuery = true; $this->logMessage = $message; return $this; }
php
public function log($message = null): ElasticSearchQueryBuilder { $this->logThisQuery = true; $this->logMessage = $message; return $this; }
[ "public", "function", "log", "(", "$", "message", "=", "null", ")", ":", "ElasticSearchQueryBuilder", "{", "$", "this", "->", "logThisQuery", "=", "true", ";", "$", "this", "->", "logMessage", "=", "$", "message", ";", "return", "$", "this", ";", "}" ]
Log the current request to the Elasticsearch log for debugging after it has been executed. @param string $message an optional message to identify the log entry @return ElasticSearchQueryBuilder @api
[ "Log", "the", "current", "request", "to", "the", "Elasticsearch", "log", "for", "debugging", "after", "it", "has", "been", "executed", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L524-L530
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.fetch
public function fetch(): array { try { $timeBefore = microtime(true); $request = $this->request->getRequestAsJson(); $response = $this->elasticSearchClient->getIndex()->request('GET', '/_search', [], $request); $timeAfterwards = microtime(true); $this->result = $response->getTreatedContent(); $searchResult = $this->evaluateResult($this->result); $this->result['nodes'] = []; $this->logThisQuery && $this->logger->log(sprintf('Query Log (%s): %s -- execution time: %s ms -- Limit: %s -- Number of results returned: %s -- Total Results: %s', $this->logMessage, $request, (($timeAfterwards - $timeBefore) * 1000), $this->limit, count($searchResult->getHits()), $searchResult->getTotal()), LOG_DEBUG); if (count($searchResult->getHits()) > 0) { $this->result['nodes'] = $this->convertHitsToNodes($searchResult->getHits()); } } catch (ApiException $exception) { $this->logger->logException($exception); $this->result['nodes'] = []; } return $this->result; }
php
public function fetch(): array { try { $timeBefore = microtime(true); $request = $this->request->getRequestAsJson(); $response = $this->elasticSearchClient->getIndex()->request('GET', '/_search', [], $request); $timeAfterwards = microtime(true); $this->result = $response->getTreatedContent(); $searchResult = $this->evaluateResult($this->result); $this->result['nodes'] = []; $this->logThisQuery && $this->logger->log(sprintf('Query Log (%s): %s -- execution time: %s ms -- Limit: %s -- Number of results returned: %s -- Total Results: %s', $this->logMessage, $request, (($timeAfterwards - $timeBefore) * 1000), $this->limit, count($searchResult->getHits()), $searchResult->getTotal()), LOG_DEBUG); if (count($searchResult->getHits()) > 0) { $this->result['nodes'] = $this->convertHitsToNodes($searchResult->getHits()); } } catch (ApiException $exception) { $this->logger->logException($exception); $this->result['nodes'] = []; } return $this->result; }
[ "public", "function", "fetch", "(", ")", ":", "array", "{", "try", "{", "$", "timeBefore", "=", "microtime", "(", "true", ")", ";", "$", "request", "=", "$", "this", "->", "request", "->", "getRequestAsJson", "(", ")", ";", "$", "response", "=", "$", "this", "->", "elasticSearchClient", "->", "getIndex", "(", ")", "->", "request", "(", "'GET'", ",", "'/_search'", ",", "[", "]", ",", "$", "request", ")", ";", "$", "timeAfterwards", "=", "microtime", "(", "true", ")", ";", "$", "this", "->", "result", "=", "$", "response", "->", "getTreatedContent", "(", ")", ";", "$", "searchResult", "=", "$", "this", "->", "evaluateResult", "(", "$", "this", "->", "result", ")", ";", "$", "this", "->", "result", "[", "'nodes'", "]", "=", "[", "]", ";", "$", "this", "->", "logThisQuery", "&&", "$", "this", "->", "logger", "->", "log", "(", "sprintf", "(", "'Query Log (%s): %s -- execution time: %s ms -- Limit: %s -- Number of results returned: %s -- Total Results: %s'", ",", "$", "this", "->", "logMessage", ",", "$", "request", ",", "(", "(", "$", "timeAfterwards", "-", "$", "timeBefore", ")", "*", "1000", ")", ",", "$", "this", "->", "limit", ",", "count", "(", "$", "searchResult", "->", "getHits", "(", ")", ")", ",", "$", "searchResult", "->", "getTotal", "(", ")", ")", ",", "LOG_DEBUG", ")", ";", "if", "(", "count", "(", "$", "searchResult", "->", "getHits", "(", ")", ")", ">", "0", ")", "{", "$", "this", "->", "result", "[", "'nodes'", "]", "=", "$", "this", "->", "convertHitsToNodes", "(", "$", "searchResult", "->", "getHits", "(", ")", ")", ";", "}", "}", "catch", "(", "ApiException", "$", "exception", ")", "{", "$", "this", "->", "logger", "->", "logException", "(", "$", "exception", ")", ";", "$", "this", "->", "result", "[", "'nodes'", "]", "=", "[", "]", ";", "}", "return", "$", "this", "->", "result", ";", "}" ]
Execute the query and return the list of nodes as result. This method is rather internal; just to be called from the ElasticSearchQueryResult. For the public API, please use execute() @return array<\Neos\ContentRepository\Domain\Model\NodeInterface> @throws \Flowpack\ElasticSearch\Exception
[ "Execute", "the", "query", "and", "return", "the", "list", "of", "nodes", "as", "result", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L575-L600
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.count
public function count() { $timeBefore = microtime(true); $request = $this->getRequest()->getCountRequestAsJson(); $response = $this->elasticSearchClient->getIndex()->request('GET', '/_count', [], $request); $timeAfterwards = microtime(true); $treatedContent = $response->getTreatedContent(); $count = $treatedContent['count']; $this->logThisQuery && $this->logger->log('Count Query Log (' . $this->logMessage . '): ' . $request . ' -- execution time: ' . (($timeAfterwards - $timeBefore) * 1000) . ' ms -- Total Results: ' . $count, LOG_DEBUG); return $count; }
php
public function count() { $timeBefore = microtime(true); $request = $this->getRequest()->getCountRequestAsJson(); $response = $this->elasticSearchClient->getIndex()->request('GET', '/_count', [], $request); $timeAfterwards = microtime(true); $treatedContent = $response->getTreatedContent(); $count = $treatedContent['count']; $this->logThisQuery && $this->logger->log('Count Query Log (' . $this->logMessage . '): ' . $request . ' -- execution time: ' . (($timeAfterwards - $timeBefore) * 1000) . ' ms -- Total Results: ' . $count, LOG_DEBUG); return $count; }
[ "public", "function", "count", "(", ")", "{", "$", "timeBefore", "=", "microtime", "(", "true", ")", ";", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getCountRequestAsJson", "(", ")", ";", "$", "response", "=", "$", "this", "->", "elasticSearchClient", "->", "getIndex", "(", ")", "->", "request", "(", "'GET'", ",", "'/_count'", ",", "[", "]", ",", "$", "request", ")", ";", "$", "timeAfterwards", "=", "microtime", "(", "true", ")", ";", "$", "treatedContent", "=", "$", "response", "->", "getTreatedContent", "(", ")", ";", "$", "count", "=", "$", "treatedContent", "[", "'count'", "]", ";", "$", "this", "->", "logThisQuery", "&&", "$", "this", "->", "logger", "->", "log", "(", "'Count Query Log ('", ".", "$", "this", "->", "logMessage", ".", "'): '", ".", "$", "request", ".", "' -- execution time: '", ".", "(", "(", "$", "timeAfterwards", "-", "$", "timeBefore", ")", "*", "1000", ")", ".", "' ms -- Total Results: '", ".", "$", "count", ",", "LOG_DEBUG", ")", ";", "return", "$", "count", ";", "}" ]
Return the total number of hits for the query. @return integer @throws \Flowpack\ElasticSearch\Exception @api
[ "Return", "the", "total", "number", "of", "hits", "for", "the", "query", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L645-L659
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.fulltext
public function fulltext($searchWord, array $options = []) { // We automatically enable result highlighting when doing fulltext searches. It is up to the user to use this information or not use it. $this->request->fulltext(trim(json_encode($searchWord), '"'), $options); $this->request->highlight(150, 2); return $this; }
php
public function fulltext($searchWord, array $options = []) { // We automatically enable result highlighting when doing fulltext searches. It is up to the user to use this information or not use it. $this->request->fulltext(trim(json_encode($searchWord), '"'), $options); $this->request->highlight(150, 2); return $this; }
[ "public", "function", "fulltext", "(", "$", "searchWord", ",", "array", "$", "options", "=", "[", "]", ")", "{", "// We automatically enable result highlighting when doing fulltext searches. It is up to the user to use this information or not use it.", "$", "this", "->", "request", "->", "fulltext", "(", "trim", "(", "json_encode", "(", "$", "searchWord", ")", ",", "'\"'", ")", ",", "$", "options", ")", ";", "$", "this", "->", "request", "->", "highlight", "(", "150", ",", "2", ")", ";", "return", "$", "this", ";", "}" ]
Match the searchword against the fulltext index @param string $searchWord @param array $options Options to configure the query_string, see https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-query-string-query.html @return QueryBuilderInterface @api
[ "Match", "the", "searchword", "against", "the", "fulltext", "index" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L669-L676
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.query
public function query(NodeInterface $contextNode) { // on indexing, the __parentPath is tokenized to contain ALL parent path parts, // e.g. /foo, /foo/bar/, /foo/bar/baz; to speed up matching.. That's why we use a simple "term" filter here. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-term-filter.html // another term filter against the path allows the context node itself to be found $this->queryFilter('bool', [ 'should' => [ [ 'term' => ['__parentPath' => $contextNode->getPath()] ], [ 'term' => ['__path' => $contextNode->getPath()] ] ] ]); // // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-terms-filter.html $this->queryFilter('terms', ['__workspace' => array_unique(['live', $contextNode->getContext()->getWorkspace()->getName()])]); // match exact dimension values for each dimension, this works because the indexing flattens the node variants for all dimension preset combinations $dimensionCombinations = $contextNode->getContext()->getDimensions(); if (is_array($dimensionCombinations)) { $this->queryFilter('term', ['__dimensionCombinationHash' => md5(json_encode($dimensionCombinations))]); } $this->contextNode = $contextNode; return $this; }
php
public function query(NodeInterface $contextNode) { // on indexing, the __parentPath is tokenized to contain ALL parent path parts, // e.g. /foo, /foo/bar/, /foo/bar/baz; to speed up matching.. That's why we use a simple "term" filter here. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-term-filter.html // another term filter against the path allows the context node itself to be found $this->queryFilter('bool', [ 'should' => [ [ 'term' => ['__parentPath' => $contextNode->getPath()] ], [ 'term' => ['__path' => $contextNode->getPath()] ] ] ]); // // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-terms-filter.html $this->queryFilter('terms', ['__workspace' => array_unique(['live', $contextNode->getContext()->getWorkspace()->getName()])]); // match exact dimension values for each dimension, this works because the indexing flattens the node variants for all dimension preset combinations $dimensionCombinations = $contextNode->getContext()->getDimensions(); if (is_array($dimensionCombinations)) { $this->queryFilter('term', ['__dimensionCombinationHash' => md5(json_encode($dimensionCombinations))]); } $this->contextNode = $contextNode; return $this; }
[ "public", "function", "query", "(", "NodeInterface", "$", "contextNode", ")", "{", "// on indexing, the __parentPath is tokenized to contain ALL parent path parts,", "// e.g. /foo, /foo/bar/, /foo/bar/baz; to speed up matching.. That's why we use a simple \"term\" filter here.", "// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-term-filter.html", "// another term filter against the path allows the context node itself to be found", "$", "this", "->", "queryFilter", "(", "'bool'", ",", "[", "'should'", "=>", "[", "[", "'term'", "=>", "[", "'__parentPath'", "=>", "$", "contextNode", "->", "getPath", "(", ")", "]", "]", ",", "[", "'term'", "=>", "[", "'__path'", "=>", "$", "contextNode", "->", "getPath", "(", ")", "]", "]", "]", "]", ")", ";", "//", "// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-terms-filter.html", "$", "this", "->", "queryFilter", "(", "'terms'", ",", "[", "'__workspace'", "=>", "array_unique", "(", "[", "'live'", ",", "$", "contextNode", "->", "getContext", "(", ")", "->", "getWorkspace", "(", ")", "->", "getName", "(", ")", "]", ")", "]", ")", ";", "// match exact dimension values for each dimension, this works because the indexing flattens the node variants for all dimension preset combinations", "$", "dimensionCombinations", "=", "$", "contextNode", "->", "getContext", "(", ")", "->", "getDimensions", "(", ")", ";", "if", "(", "is_array", "(", "$", "dimensionCombinations", ")", ")", "{", "$", "this", "->", "queryFilter", "(", "'term'", ",", "[", "'__dimensionCombinationHash'", "=>", "md5", "(", "json_encode", "(", "$", "dimensionCombinations", ")", ")", "]", ")", ";", "}", "$", "this", "->", "contextNode", "=", "$", "contextNode", ";", "return", "$", "this", ";", "}" ]
Sets the starting point for this query. Search result should only contain nodes that match the context of the given node and have it as parent node in their rootline. @param NodeInterface $contextNode @return QueryBuilderInterface @throws QueryBuildingException @throws \Neos\Flow\Persistence\Exception\IllegalObjectTypeException @api
[ "Sets", "the", "starting", "point", "for", "this", "query", ".", "Search", "result", "should", "only", "contain", "nodes", "that", "match", "the", "context", "of", "the", "given", "node", "and", "have", "it", "as", "parent", "node", "in", "their", "rootline", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L759-L789
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryBuilder.php
ElasticSearchQueryBuilder.cacheLifetime
public function cacheLifetime(): int { $minTimestamps = array_filter([ $this->getNearestFutureDate('_hiddenBeforeDateTime'), $this->getNearestFutureDate('_hiddenAfterDateTime') ], function ($value) { return $value != 0; }); if (empty($minTimestamps)) { return 0; } $minTimestamp = min($minTimestamps); return $minTimestamp - $this->now->getTimestamp(); }
php
public function cacheLifetime(): int { $minTimestamps = array_filter([ $this->getNearestFutureDate('_hiddenBeforeDateTime'), $this->getNearestFutureDate('_hiddenAfterDateTime') ], function ($value) { return $value != 0; }); if (empty($minTimestamps)) { return 0; } $minTimestamp = min($minTimestamps); return $minTimestamp - $this->now->getTimestamp(); }
[ "public", "function", "cacheLifetime", "(", ")", ":", "int", "{", "$", "minTimestamps", "=", "array_filter", "(", "[", "$", "this", "->", "getNearestFutureDate", "(", "'_hiddenBeforeDateTime'", ")", ",", "$", "this", "->", "getNearestFutureDate", "(", "'_hiddenAfterDateTime'", ")", "]", ",", "function", "(", "$", "value", ")", "{", "return", "$", "value", "!=", "0", ";", "}", ")", ";", "if", "(", "empty", "(", "$", "minTimestamps", ")", ")", "{", "return", "0", ";", "}", "$", "minTimestamp", "=", "min", "(", "$", "minTimestamps", ")", ";", "return", "$", "minTimestamp", "-", "$", "this", "->", "now", "->", "getTimestamp", "(", ")", ";", "}" ]
This method will get the minimum of all allowed cache lifetimes for the nodes that would result from the current defined query. This means it will evaluate to the nearest future value of the hiddenBeforeDateTime or hiddenAfterDateTime properties of all nodes in the result. @return int @throws QueryBuildingException @throws \Flowpack\ElasticSearch\Exception
[ "This", "method", "will", "get", "the", "minimum", "of", "all", "allowed", "cache", "lifetimes", "for", "the", "nodes", "that", "would", "result", "from", "the", "current", "defined", "query", ".", "This", "means", "it", "will", "evaluate", "to", "the", "nearest", "future", "value", "of", "the", "hiddenBeforeDateTime", "or", "hiddenAfterDateTime", "properties", "of", "all", "nodes", "in", "the", "result", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryBuilder.php#L871-L887
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryResult.php
ElasticSearchQueryResult.initialize
protected function initialize(): void { if ($this->result === null) { $queryBuilder = $this->elasticSearchQuery->getQueryBuilder(); $this->result = $queryBuilder->fetch(); $this->nodes = $this->result['nodes']; $this->count = $queryBuilder->getTotalItems(); } }
php
protected function initialize(): void { if ($this->result === null) { $queryBuilder = $this->elasticSearchQuery->getQueryBuilder(); $this->result = $queryBuilder->fetch(); $this->nodes = $this->result['nodes']; $this->count = $queryBuilder->getTotalItems(); } }
[ "protected", "function", "initialize", "(", ")", ":", "void", "{", "if", "(", "$", "this", "->", "result", "===", "null", ")", "{", "$", "queryBuilder", "=", "$", "this", "->", "elasticSearchQuery", "->", "getQueryBuilder", "(", ")", ";", "$", "this", "->", "result", "=", "$", "queryBuilder", "->", "fetch", "(", ")", ";", "$", "this", "->", "nodes", "=", "$", "this", "->", "result", "[", "'nodes'", "]", ";", "$", "this", "->", "count", "=", "$", "queryBuilder", "->", "getTotalItems", "(", ")", ";", "}", "}" ]
Initialize the results by really executing the query @return void
[ "Initialize", "the", "results", "by", "really", "executing", "the", "query" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryResult.php#L53-L61
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/ElasticSearchQueryResult.php
ElasticSearchQueryResult.getSortValuesForNode
public function getSortValuesForNode(NodeInterface $node): array { $hit = $this->searchHitForNode($node); if (is_array($hit) && array_key_exists('sort', $hit)) { return $hit['sort']; } return []; }
php
public function getSortValuesForNode(NodeInterface $node): array { $hit = $this->searchHitForNode($node); if (is_array($hit) && array_key_exists('sort', $hit)) { return $hit['sort']; } return []; }
[ "public", "function", "getSortValuesForNode", "(", "NodeInterface", "$", "node", ")", ":", "array", "{", "$", "hit", "=", "$", "this", "->", "searchHitForNode", "(", "$", "node", ")", ";", "if", "(", "is_array", "(", "$", "hit", ")", "&&", "array_key_exists", "(", "'sort'", ",", "$", "hit", ")", ")", "{", "return", "$", "hit", "[", "'sort'", "]", ";", "}", "return", "[", "]", ";", "}" ]
Returns the array with all sort values for a given node. The values are fetched from the raw content Elasticsearch returns within the hit data @param NodeInterface $node @return array
[ "Returns", "the", "array", "with", "all", "sort", "values", "for", "a", "given", "node", ".", "The", "values", "are", "fetched", "from", "the", "raw", "content", "Elasticsearch", "returns", "within", "the", "hit", "data" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/ElasticSearchQueryResult.php#L267-L275
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Command/NodeIndexCommandController.php
NodeIndexCommandController.showMappingCommand
public function showMappingCommand(): void { $nodeTypeMappingCollection = $this->nodeTypeMappingBuilder->buildMappingInformation($this->nodeIndexer->getIndex()); foreach ($nodeTypeMappingCollection as $mapping) { /** @var Mapping $mapping */ $this->output(Yaml::dump($mapping->asArray(), 5, 2)); $this->outputLine(); } $this->outputLine('------------'); $mappingErrors = $this->nodeTypeMappingBuilder->getLastMappingErrors(); if ($mappingErrors->hasErrors()) { $this->outputLine('<b>Mapping Errors</b>'); foreach ($mappingErrors->getFlattenedErrors() as $errors) { foreach ($errors as $error) { $this->outputLine($error); } } } if ($mappingErrors->hasWarnings()) { $this->outputLine('<b>Mapping Warnings</b>'); foreach ($mappingErrors->getFlattenedWarnings() as $warnings) { foreach ($warnings as $warning) { $this->outputLine($warning); } } } }
php
public function showMappingCommand(): void { $nodeTypeMappingCollection = $this->nodeTypeMappingBuilder->buildMappingInformation($this->nodeIndexer->getIndex()); foreach ($nodeTypeMappingCollection as $mapping) { /** @var Mapping $mapping */ $this->output(Yaml::dump($mapping->asArray(), 5, 2)); $this->outputLine(); } $this->outputLine('------------'); $mappingErrors = $this->nodeTypeMappingBuilder->getLastMappingErrors(); if ($mappingErrors->hasErrors()) { $this->outputLine('<b>Mapping Errors</b>'); foreach ($mappingErrors->getFlattenedErrors() as $errors) { foreach ($errors as $error) { $this->outputLine($error); } } } if ($mappingErrors->hasWarnings()) { $this->outputLine('<b>Mapping Warnings</b>'); foreach ($mappingErrors->getFlattenedWarnings() as $warnings) { foreach ($warnings as $warning) { $this->outputLine($warning); } } } }
[ "public", "function", "showMappingCommand", "(", ")", ":", "void", "{", "$", "nodeTypeMappingCollection", "=", "$", "this", "->", "nodeTypeMappingBuilder", "->", "buildMappingInformation", "(", "$", "this", "->", "nodeIndexer", "->", "getIndex", "(", ")", ")", ";", "foreach", "(", "$", "nodeTypeMappingCollection", "as", "$", "mapping", ")", "{", "/** @var Mapping $mapping */", "$", "this", "->", "output", "(", "Yaml", "::", "dump", "(", "$", "mapping", "->", "asArray", "(", ")", ",", "5", ",", "2", ")", ")", ";", "$", "this", "->", "outputLine", "(", ")", ";", "}", "$", "this", "->", "outputLine", "(", "'------------'", ")", ";", "$", "mappingErrors", "=", "$", "this", "->", "nodeTypeMappingBuilder", "->", "getLastMappingErrors", "(", ")", ";", "if", "(", "$", "mappingErrors", "->", "hasErrors", "(", ")", ")", "{", "$", "this", "->", "outputLine", "(", "'<b>Mapping Errors</b>'", ")", ";", "foreach", "(", "$", "mappingErrors", "->", "getFlattenedErrors", "(", ")", "as", "$", "errors", ")", "{", "foreach", "(", "$", "errors", "as", "$", "error", ")", "{", "$", "this", "->", "outputLine", "(", "$", "error", ")", ";", "}", "}", "}", "if", "(", "$", "mappingErrors", "->", "hasWarnings", "(", ")", ")", "{", "$", "this", "->", "outputLine", "(", "'<b>Mapping Warnings</b>'", ")", ";", "foreach", "(", "$", "mappingErrors", "->", "getFlattenedWarnings", "(", ")", "as", "$", "warnings", ")", "{", "foreach", "(", "$", "warnings", "as", "$", "warning", ")", "{", "$", "this", "->", "outputLine", "(", "$", "warning", ")", ";", "}", "}", "}", "}" ]
Show the mapping which would be sent to the ElasticSearch server @return void @throws CRAException
[ "Show", "the", "mapping", "which", "would", "be", "sent", "to", "the", "ElasticSearch", "server" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Command/NodeIndexCommandController.php#L138-L166
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Command/NodeIndexCommandController.php
NodeIndexCommandController.indexNodeCommand
public function indexNodeCommand(string $identifier, string $workspace = null): void { if ($workspace === null && $this->settings['indexAllWorkspaces'] === false) { $workspace = 'live'; } $indexNode = function ($identifier, Workspace $workspace, array $dimensions) { $context = $this->createContentContext($workspace->getName(), $dimensions); $node = $context->getNodeByIdentifier($identifier); if ($node === null) { $this->outputLine('Node with the given identifier is not found.'); $this->quit(); } $this->outputLine(); $this->outputLine('Index node "%s" (%s)', [ $node->getLabel(), $node->getIdentifier(), ]); $this->outputLine(' workspace: %s', [ $workspace->getName() ]); $this->outputLine(' node type: %s', [ $node->getNodeType()->getName() ]); $this->outputLine(' dimensions: %s', [ json_encode($dimensions) ]); $this->nodeIndexer->indexNode($node); }; $indexInWorkspace = function ($identifier, Workspace $workspace) use ($indexNode) { $combinations = $this->contentDimensionCombinator->getAllAllowedCombinations(); if ($combinations === []) { $indexNode($identifier, $workspace, []); } else { foreach ($combinations as $combination) { $indexNode($identifier, $workspace, $combination); } } }; if ($workspace === null) { foreach ($this->workspaceRepository->findAll() as $workspaceToIndex) { $indexInWorkspace($identifier, $workspaceToIndex); } } else { /** @var Workspace $workspaceInstance */ $workspaceInstance = $this->workspaceRepository->findByIdentifier($workspace); if ($workspaceInstance === null) { $this->outputLine('The given workspace (%s) does not exist.', [$workspace]); $this->quit(1); } $indexInWorkspace($identifier, $workspaceInstance); } }
php
public function indexNodeCommand(string $identifier, string $workspace = null): void { if ($workspace === null && $this->settings['indexAllWorkspaces'] === false) { $workspace = 'live'; } $indexNode = function ($identifier, Workspace $workspace, array $dimensions) { $context = $this->createContentContext($workspace->getName(), $dimensions); $node = $context->getNodeByIdentifier($identifier); if ($node === null) { $this->outputLine('Node with the given identifier is not found.'); $this->quit(); } $this->outputLine(); $this->outputLine('Index node "%s" (%s)', [ $node->getLabel(), $node->getIdentifier(), ]); $this->outputLine(' workspace: %s', [ $workspace->getName() ]); $this->outputLine(' node type: %s', [ $node->getNodeType()->getName() ]); $this->outputLine(' dimensions: %s', [ json_encode($dimensions) ]); $this->nodeIndexer->indexNode($node); }; $indexInWorkspace = function ($identifier, Workspace $workspace) use ($indexNode) { $combinations = $this->contentDimensionCombinator->getAllAllowedCombinations(); if ($combinations === []) { $indexNode($identifier, $workspace, []); } else { foreach ($combinations as $combination) { $indexNode($identifier, $workspace, $combination); } } }; if ($workspace === null) { foreach ($this->workspaceRepository->findAll() as $workspaceToIndex) { $indexInWorkspace($identifier, $workspaceToIndex); } } else { /** @var Workspace $workspaceInstance */ $workspaceInstance = $this->workspaceRepository->findByIdentifier($workspace); if ($workspaceInstance === null) { $this->outputLine('The given workspace (%s) does not exist.', [$workspace]); $this->quit(1); } $indexInWorkspace($identifier, $workspaceInstance); } }
[ "public", "function", "indexNodeCommand", "(", "string", "$", "identifier", ",", "string", "$", "workspace", "=", "null", ")", ":", "void", "{", "if", "(", "$", "workspace", "===", "null", "&&", "$", "this", "->", "settings", "[", "'indexAllWorkspaces'", "]", "===", "false", ")", "{", "$", "workspace", "=", "'live'", ";", "}", "$", "indexNode", "=", "function", "(", "$", "identifier", ",", "Workspace", "$", "workspace", ",", "array", "$", "dimensions", ")", "{", "$", "context", "=", "$", "this", "->", "createContentContext", "(", "$", "workspace", "->", "getName", "(", ")", ",", "$", "dimensions", ")", ";", "$", "node", "=", "$", "context", "->", "getNodeByIdentifier", "(", "$", "identifier", ")", ";", "if", "(", "$", "node", "===", "null", ")", "{", "$", "this", "->", "outputLine", "(", "'Node with the given identifier is not found.'", ")", ";", "$", "this", "->", "quit", "(", ")", ";", "}", "$", "this", "->", "outputLine", "(", ")", ";", "$", "this", "->", "outputLine", "(", "'Index node \"%s\" (%s)'", ",", "[", "$", "node", "->", "getLabel", "(", ")", ",", "$", "node", "->", "getIdentifier", "(", ")", ",", "]", ")", ";", "$", "this", "->", "outputLine", "(", "' workspace: %s'", ",", "[", "$", "workspace", "->", "getName", "(", ")", "]", ")", ";", "$", "this", "->", "outputLine", "(", "' node type: %s'", ",", "[", "$", "node", "->", "getNodeType", "(", ")", "->", "getName", "(", ")", "]", ")", ";", "$", "this", "->", "outputLine", "(", "' dimensions: %s'", ",", "[", "json_encode", "(", "$", "dimensions", ")", "]", ")", ";", "$", "this", "->", "nodeIndexer", "->", "indexNode", "(", "$", "node", ")", ";", "}", ";", "$", "indexInWorkspace", "=", "function", "(", "$", "identifier", ",", "Workspace", "$", "workspace", ")", "use", "(", "$", "indexNode", ")", "{", "$", "combinations", "=", "$", "this", "->", "contentDimensionCombinator", "->", "getAllAllowedCombinations", "(", ")", ";", "if", "(", "$", "combinations", "===", "[", "]", ")", "{", "$", "indexNode", "(", "$", "identifier", ",", "$", "workspace", ",", "[", "]", ")", ";", "}", "else", "{", "foreach", "(", "$", "combinations", "as", "$", "combination", ")", "{", "$", "indexNode", "(", "$", "identifier", ",", "$", "workspace", ",", "$", "combination", ")", ";", "}", "}", "}", ";", "if", "(", "$", "workspace", "===", "null", ")", "{", "foreach", "(", "$", "this", "->", "workspaceRepository", "->", "findAll", "(", ")", "as", "$", "workspaceToIndex", ")", "{", "$", "indexInWorkspace", "(", "$", "identifier", ",", "$", "workspaceToIndex", ")", ";", "}", "}", "else", "{", "/** @var Workspace $workspaceInstance */", "$", "workspaceInstance", "=", "$", "this", "->", "workspaceRepository", "->", "findByIdentifier", "(", "$", "workspace", ")", ";", "if", "(", "$", "workspaceInstance", "===", "null", ")", "{", "$", "this", "->", "outputLine", "(", "'The given workspace (%s) does not exist.'", ",", "[", "$", "workspace", "]", ")", ";", "$", "this", "->", "quit", "(", "1", ")", ";", "}", "$", "indexInWorkspace", "(", "$", "identifier", ",", "$", "workspaceInstance", ")", ";", "}", "}" ]
Index a single node by the given identifier and workspace name @param string $identifier @param string $workspace @return void @throws StopActionException
[ "Index", "a", "single", "node", "by", "the", "given", "identifier", "and", "workspace", "name" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Command/NodeIndexCommandController.php#L176-L230
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Command/NodeIndexCommandController.php
NodeIndexCommandController.buildCommand
public function buildCommand(int $limit = null, bool $update = false, string $workspace = null, string $postfix = ''): void { if ($workspace !== null && $this->workspaceRepository->findByIdentifier($workspace) === null) { $this->logger->log('The given workspace (' . $workspace . ') does not exist.', LOG_ERR); $this->quit(1); } if ($update === true) { $this->logger->log('!!! Update Mode (Development) active!'); } else { $this->createNewIndex($postfix); } $this->applyMapping(); $this->logger->log(sprintf('Indexing %snodes ... ', ($limit !== null ? 'the first ' . $limit . ' ' : ''))); $count = 0; if ($workspace === null && $this->settings['indexAllWorkspaces'] === false) { $workspace = 'live'; } $callback = function ($workspaceName, $indexedNodes, $dimensions) { if ($dimensions === []) { $this->outputLine('Workspace "' . $workspaceName . '" without dimensions done. (Indexed ' . $indexedNodes . ' nodes)'); } else { $this->outputLine('Workspace "' . $workspaceName . '" and dimensions "' . json_encode($dimensions) . '" done. (Indexed ' . $indexedNodes . ' nodes)'); } }; if ($workspace === null) { foreach ($this->workspaceRepository->findAll() as $workspaceToIndex) { $count += $this->indexWorkspace($workspaceToIndex->getName(), $limit, $callback); } } else { $count += $this->indexWorkspace($workspace, $limit, $callback); } $this->nodeIndexingManager->flushQueues(); if ($this->errorHandlingService->hasError()) { $this->outputLine(); /** @var ErrorInterface $error */ foreach ($this->errorHandlingService as $error) { $this->outputLine('<error>Error</error> ' . $error->message()); } $this->outputLine(); $this->outputLine('<error>Check your logs for more information</error>'); } else { $this->logger->log('Done. (indexed ' . $count . ' nodes)', LOG_INFO); } $this->nodeIndexer->getIndex()->refresh(); // TODO: smoke tests if ($update === false) { $this->nodeIndexer->updateIndexAlias(); } }
php
public function buildCommand(int $limit = null, bool $update = false, string $workspace = null, string $postfix = ''): void { if ($workspace !== null && $this->workspaceRepository->findByIdentifier($workspace) === null) { $this->logger->log('The given workspace (' . $workspace . ') does not exist.', LOG_ERR); $this->quit(1); } if ($update === true) { $this->logger->log('!!! Update Mode (Development) active!'); } else { $this->createNewIndex($postfix); } $this->applyMapping(); $this->logger->log(sprintf('Indexing %snodes ... ', ($limit !== null ? 'the first ' . $limit . ' ' : ''))); $count = 0; if ($workspace === null && $this->settings['indexAllWorkspaces'] === false) { $workspace = 'live'; } $callback = function ($workspaceName, $indexedNodes, $dimensions) { if ($dimensions === []) { $this->outputLine('Workspace "' . $workspaceName . '" without dimensions done. (Indexed ' . $indexedNodes . ' nodes)'); } else { $this->outputLine('Workspace "' . $workspaceName . '" and dimensions "' . json_encode($dimensions) . '" done. (Indexed ' . $indexedNodes . ' nodes)'); } }; if ($workspace === null) { foreach ($this->workspaceRepository->findAll() as $workspaceToIndex) { $count += $this->indexWorkspace($workspaceToIndex->getName(), $limit, $callback); } } else { $count += $this->indexWorkspace($workspace, $limit, $callback); } $this->nodeIndexingManager->flushQueues(); if ($this->errorHandlingService->hasError()) { $this->outputLine(); /** @var ErrorInterface $error */ foreach ($this->errorHandlingService as $error) { $this->outputLine('<error>Error</error> ' . $error->message()); } $this->outputLine(); $this->outputLine('<error>Check your logs for more information</error>'); } else { $this->logger->log('Done. (indexed ' . $count . ' nodes)', LOG_INFO); } $this->nodeIndexer->getIndex()->refresh(); // TODO: smoke tests if ($update === false) { $this->nodeIndexer->updateIndexAlias(); } }
[ "public", "function", "buildCommand", "(", "int", "$", "limit", "=", "null", ",", "bool", "$", "update", "=", "false", ",", "string", "$", "workspace", "=", "null", ",", "string", "$", "postfix", "=", "''", ")", ":", "void", "{", "if", "(", "$", "workspace", "!==", "null", "&&", "$", "this", "->", "workspaceRepository", "->", "findByIdentifier", "(", "$", "workspace", ")", "===", "null", ")", "{", "$", "this", "->", "logger", "->", "log", "(", "'The given workspace ('", ".", "$", "workspace", ".", "') does not exist.'", ",", "LOG_ERR", ")", ";", "$", "this", "->", "quit", "(", "1", ")", ";", "}", "if", "(", "$", "update", "===", "true", ")", "{", "$", "this", "->", "logger", "->", "log", "(", "'!!! Update Mode (Development) active!'", ")", ";", "}", "else", "{", "$", "this", "->", "createNewIndex", "(", "$", "postfix", ")", ";", "}", "$", "this", "->", "applyMapping", "(", ")", ";", "$", "this", "->", "logger", "->", "log", "(", "sprintf", "(", "'Indexing %snodes ... '", ",", "(", "$", "limit", "!==", "null", "?", "'the first '", ".", "$", "limit", ".", "' '", ":", "''", ")", ")", ")", ";", "$", "count", "=", "0", ";", "if", "(", "$", "workspace", "===", "null", "&&", "$", "this", "->", "settings", "[", "'indexAllWorkspaces'", "]", "===", "false", ")", "{", "$", "workspace", "=", "'live'", ";", "}", "$", "callback", "=", "function", "(", "$", "workspaceName", ",", "$", "indexedNodes", ",", "$", "dimensions", ")", "{", "if", "(", "$", "dimensions", "===", "[", "]", ")", "{", "$", "this", "->", "outputLine", "(", "'Workspace \"'", ".", "$", "workspaceName", ".", "'\" without dimensions done. (Indexed '", ".", "$", "indexedNodes", ".", "' nodes)'", ")", ";", "}", "else", "{", "$", "this", "->", "outputLine", "(", "'Workspace \"'", ".", "$", "workspaceName", ".", "'\" and dimensions \"'", ".", "json_encode", "(", "$", "dimensions", ")", ".", "'\" done. (Indexed '", ".", "$", "indexedNodes", ".", "' nodes)'", ")", ";", "}", "}", ";", "if", "(", "$", "workspace", "===", "null", ")", "{", "foreach", "(", "$", "this", "->", "workspaceRepository", "->", "findAll", "(", ")", "as", "$", "workspaceToIndex", ")", "{", "$", "count", "+=", "$", "this", "->", "indexWorkspace", "(", "$", "workspaceToIndex", "->", "getName", "(", ")", ",", "$", "limit", ",", "$", "callback", ")", ";", "}", "}", "else", "{", "$", "count", "+=", "$", "this", "->", "indexWorkspace", "(", "$", "workspace", ",", "$", "limit", ",", "$", "callback", ")", ";", "}", "$", "this", "->", "nodeIndexingManager", "->", "flushQueues", "(", ")", ";", "if", "(", "$", "this", "->", "errorHandlingService", "->", "hasError", "(", ")", ")", "{", "$", "this", "->", "outputLine", "(", ")", ";", "/** @var ErrorInterface $error */", "foreach", "(", "$", "this", "->", "errorHandlingService", "as", "$", "error", ")", "{", "$", "this", "->", "outputLine", "(", "'<error>Error</error> '", ".", "$", "error", "->", "message", "(", ")", ")", ";", "}", "$", "this", "->", "outputLine", "(", ")", ";", "$", "this", "->", "outputLine", "(", "'<error>Check your logs for more information</error>'", ")", ";", "}", "else", "{", "$", "this", "->", "logger", "->", "log", "(", "'Done. (indexed '", ".", "$", "count", ".", "' nodes)'", ",", "LOG_INFO", ")", ";", "}", "$", "this", "->", "nodeIndexer", "->", "getIndex", "(", ")", "->", "refresh", "(", ")", ";", "// TODO: smoke tests", "if", "(", "$", "update", "===", "false", ")", "{", "$", "this", "->", "nodeIndexer", "->", "updateIndexAlias", "(", ")", ";", "}", "}" ]
Index all nodes by creating a new index and when everything was completed, switch the index alias. This command (re-)indexes all nodes contained in the content repository and sets the schema beforehand. @param int $limit Amount of nodes to index at maximum @param bool $update if TRUE, do not throw away the index at the start. Should *only be used for development*. @param string $workspace name of the workspace which should be indexed @param string $postfix Index postfix, index with the same postfix will be deleted if exist @return void @throws ApiException @throws StopActionException @throws CRAException
[ "Index", "all", "nodes", "by", "creating", "a", "new", "index", "and", "when", "everything", "was", "completed", "switch", "the", "index", "alias", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Command/NodeIndexCommandController.php#L246-L302
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Command/NodeIndexCommandController.php
NodeIndexCommandController.applyMapping
protected function applyMapping(): void { $nodeTypeMappingCollection = $this->nodeTypeMappingBuilder->buildMappingInformation($this->nodeIndexer->getIndex()); foreach ($nodeTypeMappingCollection as $mapping) { /** @var Mapping $mapping */ $mapping->apply(); } $this->logger->log('Updated Mapping.'); }
php
protected function applyMapping(): void { $nodeTypeMappingCollection = $this->nodeTypeMappingBuilder->buildMappingInformation($this->nodeIndexer->getIndex()); foreach ($nodeTypeMappingCollection as $mapping) { /** @var Mapping $mapping */ $mapping->apply(); } $this->logger->log('Updated Mapping.'); }
[ "protected", "function", "applyMapping", "(", ")", ":", "void", "{", "$", "nodeTypeMappingCollection", "=", "$", "this", "->", "nodeTypeMappingBuilder", "->", "buildMappingInformation", "(", "$", "this", "->", "nodeIndexer", "->", "getIndex", "(", ")", ")", ";", "foreach", "(", "$", "nodeTypeMappingCollection", "as", "$", "mapping", ")", "{", "/** @var Mapping $mapping */", "$", "mapping", "->", "apply", "(", ")", ";", "}", "$", "this", "->", "logger", "->", "log", "(", "'Updated Mapping.'", ")", ";", "}" ]
Apply the mapping to the current index. @return void @throws CRAException
[ "Apply", "the", "mapping", "to", "the", "current", "index", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Command/NodeIndexCommandController.php#L355-L363
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Driver/AbstractQuery.php
AbstractQuery.addSubAggregation
protected function addSubAggregation(string $parentPath, string $name, array $aggregationConfiguration): void { // Find the parentPath $path =& $this->request['aggregations']; foreach (explode('.', $parentPath) as $subPart) { if ($path === null || !array_key_exists($subPart, $path)) { throw new Exception\QueryBuildingException(sprintf('The parent path segment "%s" could not be found when adding a sub aggregation to parent path "%s"', $subPart, $parentPath)); } $path =& $path[$subPart]['aggregations']; } $path[$name] = $aggregationConfiguration; }
php
protected function addSubAggregation(string $parentPath, string $name, array $aggregationConfiguration): void { // Find the parentPath $path =& $this->request['aggregations']; foreach (explode('.', $parentPath) as $subPart) { if ($path === null || !array_key_exists($subPart, $path)) { throw new Exception\QueryBuildingException(sprintf('The parent path segment "%s" could not be found when adding a sub aggregation to parent path "%s"', $subPart, $parentPath)); } $path =& $path[$subPart]['aggregations']; } $path[$name] = $aggregationConfiguration; }
[ "protected", "function", "addSubAggregation", "(", "string", "$", "parentPath", ",", "string", "$", "name", ",", "array", "$", "aggregationConfiguration", ")", ":", "void", "{", "// Find the parentPath", "$", "path", "=", "&", "$", "this", "->", "request", "[", "'aggregations'", "]", ";", "foreach", "(", "explode", "(", "'.'", ",", "$", "parentPath", ")", "as", "$", "subPart", ")", "{", "if", "(", "$", "path", "===", "null", "||", "!", "array_key_exists", "(", "$", "subPart", ",", "$", "path", ")", ")", "{", "throw", "new", "Exception", "\\", "QueryBuildingException", "(", "sprintf", "(", "'The parent path segment \"%s\" could not be found when adding a sub aggregation to parent path \"%s\"'", ",", "$", "subPart", ",", "$", "parentPath", ")", ")", ";", "}", "$", "path", "=", "&", "$", "path", "[", "$", "subPart", "]", "[", "'aggregations'", "]", ";", "}", "$", "path", "[", "$", "name", "]", "=", "$", "aggregationConfiguration", ";", "}" ]
This is an low level method for internal usage. You can add a custom $aggregationConfiguration under a given $parentPath. The $parentPath foo.bar would insert your $aggregationConfiguration under $this->request['aggregations']['foo']['aggregations']['bar']['aggregations'][$name] @param string $parentPath The parent path to add the sub aggregation to @param string $name The name to identify the resulting aggregation @param array $aggregationConfiguration @return void @throws Exception\QueryBuildingException
[ "This", "is", "an", "low", "level", "method", "for", "internal", "usage", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Driver/AbstractQuery.php#L144-L157
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Eel/SearchResultHelper.php
SearchResultHelper.didYouMean
public function didYouMean(ElasticSearchQueryResult $searchResult, float $scoreThreshold = 0.7, string $suggestionName = 'suggestions'): string { $maxScore = 0; $suggestionParts = []; foreach ($searchResult->getSuggestions()[$suggestionName] as $suggestion) { if (array_key_exists('options', $suggestion) && !empty($suggestion['options'])) { $bestSuggestion = current($suggestion['options']); $maxScore = $bestSuggestion['score'] > $maxScore ? $bestSuggestion['score'] : $maxScore; $suggestionParts[] = $bestSuggestion['text']; } else { $suggestionParts[] = $suggestion['text']; } } if ($maxScore >= $scoreThreshold) { return implode(' ', $suggestionParts); } return ''; }
php
public function didYouMean(ElasticSearchQueryResult $searchResult, float $scoreThreshold = 0.7, string $suggestionName = 'suggestions'): string { $maxScore = 0; $suggestionParts = []; foreach ($searchResult->getSuggestions()[$suggestionName] as $suggestion) { if (array_key_exists('options', $suggestion) && !empty($suggestion['options'])) { $bestSuggestion = current($suggestion['options']); $maxScore = $bestSuggestion['score'] > $maxScore ? $bestSuggestion['score'] : $maxScore; $suggestionParts[] = $bestSuggestion['text']; } else { $suggestionParts[] = $suggestion['text']; } } if ($maxScore >= $scoreThreshold) { return implode(' ', $suggestionParts); } return ''; }
[ "public", "function", "didYouMean", "(", "ElasticSearchQueryResult", "$", "searchResult", ",", "float", "$", "scoreThreshold", "=", "0.7", ",", "string", "$", "suggestionName", "=", "'suggestions'", ")", ":", "string", "{", "$", "maxScore", "=", "0", ";", "$", "suggestionParts", "=", "[", "]", ";", "foreach", "(", "$", "searchResult", "->", "getSuggestions", "(", ")", "[", "$", "suggestionName", "]", "as", "$", "suggestion", ")", "{", "if", "(", "array_key_exists", "(", "'options'", ",", "$", "suggestion", ")", "&&", "!", "empty", "(", "$", "suggestion", "[", "'options'", "]", ")", ")", "{", "$", "bestSuggestion", "=", "current", "(", "$", "suggestion", "[", "'options'", "]", ")", ";", "$", "maxScore", "=", "$", "bestSuggestion", "[", "'score'", "]", ">", "$", "maxScore", "?", "$", "bestSuggestion", "[", "'score'", "]", ":", "$", "maxScore", ";", "$", "suggestionParts", "[", "]", "=", "$", "bestSuggestion", "[", "'text'", "]", ";", "}", "else", "{", "$", "suggestionParts", "[", "]", "=", "$", "suggestion", "[", "'text'", "]", ";", "}", "}", "if", "(", "$", "maxScore", ">=", "$", "scoreThreshold", ")", "{", "return", "implode", "(", "' '", ",", "$", "suggestionParts", ")", ";", "}", "return", "''", ";", "}" ]
The "didYouMean" operation processes the previously defined suggestion by extracting and concatenating the best guess for each word given in the search term. A threshold can be given as second parameter. If none of the suggestions reaches this threshold, an empty string is returned. Example:: searchQuery = ${Search.query(site).fulltext('noes cms').termSuggestions('noes cms')} didYouMean = ${SearchResult.didYouMean(this.searchQuery.execute(), 0.5)} @param ElasticSearchQueryResult $searchResult The result of an elastic search query @param float $scoreThreshold The minimum required score to return the suggestion @param string $suggestionName The suggestion name which was given in the suggestion definition @return string
[ "The", "didYouMean", "operation", "processes", "the", "previously", "defined", "suggestion", "by", "extracting", "and", "concatenating", "the", "best", "guess", "for", "each", "word", "given", "in", "the", "search", "term", ".", "A", "threshold", "can", "be", "given", "as", "second", "parameter", ".", "If", "none", "of", "the", "suggestions", "reaches", "this", "threshold", "an", "empty", "string", "is", "returned", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Eel/SearchResultHelper.php#L41-L60
train
joomla-framework/application
src/Web/WebClient.php
WebClient.detectHeaders
protected function detectHeaders() { if (\function_exists('getallheaders')) { // If php is working under Apache, there is a special function $this->headers = getallheaders(); } else { // Else we fill headers from $_SERVER variable $this->headers = array(); foreach ($_SERVER as $name => $value) { if (substr($name, 0, 5) == 'HTTP_') { $this->headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; } } } // Mark this detection routine as run. $this->detection['headers'] = true; }
php
protected function detectHeaders() { if (\function_exists('getallheaders')) { // If php is working under Apache, there is a special function $this->headers = getallheaders(); } else { // Else we fill headers from $_SERVER variable $this->headers = array(); foreach ($_SERVER as $name => $value) { if (substr($name, 0, 5) == 'HTTP_') { $this->headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; } } } // Mark this detection routine as run. $this->detection['headers'] = true; }
[ "protected", "function", "detectHeaders", "(", ")", "{", "if", "(", "\\", "function_exists", "(", "'getallheaders'", ")", ")", "{", "// If php is working under Apache, there is a special function", "$", "this", "->", "headers", "=", "getallheaders", "(", ")", ";", "}", "else", "{", "// Else we fill headers from $_SERVER variable", "$", "this", "->", "headers", "=", "array", "(", ")", ";", "foreach", "(", "$", "_SERVER", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "substr", "(", "$", "name", ",", "0", ",", "5", ")", "==", "'HTTP_'", ")", "{", "$", "this", "->", "headers", "[", "str_replace", "(", "' '", ",", "'-'", ",", "ucwords", "(", "strtolower", "(", "str_replace", "(", "'_'", ",", "' '", ",", "substr", "(", "$", "name", ",", "5", ")", ")", ")", ")", ")", "]", "=", "$", "value", ";", "}", "}", "}", "// Mark this detection routine as run.", "$", "this", "->", "detection", "[", "'headers'", "]", "=", "true", ";", "}" ]
Fills internal array of headers @return void @since 1.3.0
[ "Fills", "internal", "array", "of", "headers" ]
134f2980575b7e58b51ef3624faac84e7a3f304d
https://github.com/joomla-framework/application/blob/134f2980575b7e58b51ef3624faac84e7a3f304d/src/Web/WebClient.php#L620-L643
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Command/NodeTypeCommandController.php
NodeTypeCommandController.showCommand
public function showCommand(string $nodeType = null): void { if ($nodeType !== null) { /** @var NodeType $nodeType */ $nodeType = $this->nodeTypeManager->getNodeType($nodeType); $configuration = $nodeType->getFullConfiguration(); } else { $nodeTypes = $this->nodeTypeManager->getNodeTypes(); $configuration = []; /** @var NodeType $nodeType */ foreach ($nodeTypes as $nodeTypeName => $nodeType) { $configuration[$nodeTypeName] = $nodeType->getFullConfiguration(); } } $this->output(Yaml::dump($configuration, 5, 2)); }
php
public function showCommand(string $nodeType = null): void { if ($nodeType !== null) { /** @var NodeType $nodeType */ $nodeType = $this->nodeTypeManager->getNodeType($nodeType); $configuration = $nodeType->getFullConfiguration(); } else { $nodeTypes = $this->nodeTypeManager->getNodeTypes(); $configuration = []; /** @var NodeType $nodeType */ foreach ($nodeTypes as $nodeTypeName => $nodeType) { $configuration[$nodeTypeName] = $nodeType->getFullConfiguration(); } } $this->output(Yaml::dump($configuration, 5, 2)); }
[ "public", "function", "showCommand", "(", "string", "$", "nodeType", "=", "null", ")", ":", "void", "{", "if", "(", "$", "nodeType", "!==", "null", ")", "{", "/** @var NodeType $nodeType */", "$", "nodeType", "=", "$", "this", "->", "nodeTypeManager", "->", "getNodeType", "(", "$", "nodeType", ")", ";", "$", "configuration", "=", "$", "nodeType", "->", "getFullConfiguration", "(", ")", ";", "}", "else", "{", "$", "nodeTypes", "=", "$", "this", "->", "nodeTypeManager", "->", "getNodeTypes", "(", ")", ";", "$", "configuration", "=", "[", "]", ";", "/** @var NodeType $nodeType */", "foreach", "(", "$", "nodeTypes", "as", "$", "nodeTypeName", "=>", "$", "nodeType", ")", "{", "$", "configuration", "[", "$", "nodeTypeName", "]", "=", "$", "nodeType", "->", "getFullConfiguration", "(", ")", ";", "}", "}", "$", "this", "->", "output", "(", "Yaml", "::", "dump", "(", "$", "configuration", ",", "5", ",", "2", ")", ")", ";", "}" ]
Show node type configuration after applying all supertypes etc @param string $nodeType the node type to optionally filter for @return void @throws NodeTypeNotFoundException
[ "Show", "node", "type", "configuration", "after", "applying", "all", "supertypes", "etc" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Command/NodeTypeCommandController.php#L46-L61
train
joomla-framework/application
src/AbstractDaemonApplication.php
AbstractDaemonApplication.fork
protected function fork() { // Attempt to fork the process. $pid = $this->pcntlFork(); // If the fork failed, throw an exception. if ($pid === -1) { throw new \RuntimeException('The process could not be forked.'); } if ($pid === 0) { // Update the process id for the child. $this->processId = (int) posix_getpid(); } else { // Log the fork in the parent. $this->getLogger()->debug('Process forked ' . $pid); } // Trigger the onFork event. $this->postFork(); return $pid; }
php
protected function fork() { // Attempt to fork the process. $pid = $this->pcntlFork(); // If the fork failed, throw an exception. if ($pid === -1) { throw new \RuntimeException('The process could not be forked.'); } if ($pid === 0) { // Update the process id for the child. $this->processId = (int) posix_getpid(); } else { // Log the fork in the parent. $this->getLogger()->debug('Process forked ' . $pid); } // Trigger the onFork event. $this->postFork(); return $pid; }
[ "protected", "function", "fork", "(", ")", "{", "// Attempt to fork the process.", "$", "pid", "=", "$", "this", "->", "pcntlFork", "(", ")", ";", "// If the fork failed, throw an exception.", "if", "(", "$", "pid", "===", "-", "1", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'The process could not be forked.'", ")", ";", "}", "if", "(", "$", "pid", "===", "0", ")", "{", "// Update the process id for the child.", "$", "this", "->", "processId", "=", "(", "int", ")", "posix_getpid", "(", ")", ";", "}", "else", "{", "// Log the fork in the parent.", "$", "this", "->", "getLogger", "(", ")", "->", "debug", "(", "'Process forked '", ".", "$", "pid", ")", ";", "}", "// Trigger the onFork event.", "$", "this", "->", "postFork", "(", ")", ";", "return", "$", "pid", ";", "}" ]
Method to fork the process. @return integer The child process id to the parent process, zero to the child process. @since 1.0 @throws \RuntimeException
[ "Method", "to", "fork", "the", "process", "." ]
134f2980575b7e58b51ef3624faac84e7a3f304d
https://github.com/joomla-framework/application/blob/134f2980575b7e58b51ef3624faac84e7a3f304d/src/AbstractDaemonApplication.php#L644-L670
train
joomla-framework/application
src/AbstractWebApplication.php
AbstractWebApplication.setHeader
public function setHeader($name, $value, $replace = false) { // Sanitize the input values. $name = (string) $name; $value = (string) $value; // If the replace flag is set, unset all known headers with the given name. if ($replace) { foreach ($this->response->headers as $key => $header) { if ($name == $header['name']) { unset($this->response->headers[$key]); } } // Clean up the array as unsetting nested arrays leaves some junk. $this->response->headers = array_values($this->response->headers); } // Add the header to the internal array. $this->response->headers[] = array('name' => $name, 'value' => $value); return $this; }
php
public function setHeader($name, $value, $replace = false) { // Sanitize the input values. $name = (string) $name; $value = (string) $value; // If the replace flag is set, unset all known headers with the given name. if ($replace) { foreach ($this->response->headers as $key => $header) { if ($name == $header['name']) { unset($this->response->headers[$key]); } } // Clean up the array as unsetting nested arrays leaves some junk. $this->response->headers = array_values($this->response->headers); } // Add the header to the internal array. $this->response->headers[] = array('name' => $name, 'value' => $value); return $this; }
[ "public", "function", "setHeader", "(", "$", "name", ",", "$", "value", ",", "$", "replace", "=", "false", ")", "{", "// Sanitize the input values.", "$", "name", "=", "(", "string", ")", "$", "name", ";", "$", "value", "=", "(", "string", ")", "$", "value", ";", "// If the replace flag is set, unset all known headers with the given name.", "if", "(", "$", "replace", ")", "{", "foreach", "(", "$", "this", "->", "response", "->", "headers", "as", "$", "key", "=>", "$", "header", ")", "{", "if", "(", "$", "name", "==", "$", "header", "[", "'name'", "]", ")", "{", "unset", "(", "$", "this", "->", "response", "->", "headers", "[", "$", "key", "]", ")", ";", "}", "}", "// Clean up the array as unsetting nested arrays leaves some junk.", "$", "this", "->", "response", "->", "headers", "=", "array_values", "(", "$", "this", "->", "response", "->", "headers", ")", ";", "}", "// Add the header to the internal array.", "$", "this", "->", "response", "->", "headers", "[", "]", "=", "array", "(", "'name'", "=>", "$", "name", ",", "'value'", "=>", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Method to set a response header. If the replace flag is set then all headers with the given name will be replaced by the new one. The headers are stored in an internal array to be sent when the site is sent to the browser. @param string $name The name of the header to set. @param string $value The value of the header to set. @param boolean $replace True to replace any headers with the same name. @return AbstractWebApplication Instance of $this to allow chaining. @since 1.0
[ "Method", "to", "set", "a", "response", "header", ".", "If", "the", "replace", "flag", "is", "set", "then", "all", "headers", "with", "the", "given", "name", "will", "be", "replaced", "by", "the", "new", "one", ".", "The", "headers", "are", "stored", "in", "an", "internal", "array", "to", "be", "sent", "when", "the", "site", "is", "sent", "to", "the", "browser", "." ]
134f2980575b7e58b51ef3624faac84e7a3f304d
https://github.com/joomla-framework/application/blob/134f2980575b7e58b51ef3624faac84e7a3f304d/src/AbstractWebApplication.php#L461-L486
train
joomla-framework/application
src/AbstractWebApplication.php
AbstractWebApplication.getHttpStatusValue
protected function getHttpStatusValue($value) { $code = (int) $value; if (array_key_exists($code, $this->responseMap)) { $value = $this->responseMap[$code]; } else { $value = 'HTTP/{version} ' . $code; } return str_replace('{version}', $this->httpVersion, $value); }
php
protected function getHttpStatusValue($value) { $code = (int) $value; if (array_key_exists($code, $this->responseMap)) { $value = $this->responseMap[$code]; } else { $value = 'HTTP/{version} ' . $code; } return str_replace('{version}', $this->httpVersion, $value); }
[ "protected", "function", "getHttpStatusValue", "(", "$", "value", ")", "{", "$", "code", "=", "(", "int", ")", "$", "value", ";", "if", "(", "array_key_exists", "(", "$", "code", ",", "$", "this", "->", "responseMap", ")", ")", "{", "$", "value", "=", "$", "this", "->", "responseMap", "[", "$", "code", "]", ";", "}", "else", "{", "$", "value", "=", "'HTTP/{version} '", ".", "$", "code", ";", "}", "return", "str_replace", "(", "'{version}'", ",", "$", "this", "->", "httpVersion", ",", "$", "value", ")", ";", "}" ]
Check if a given value can be successfully mapped to a valid http status value @param string|int $value The given status as int or string @return string @since 1.8.0
[ "Check", "if", "a", "given", "value", "can", "be", "successfully", "mapped", "to", "a", "valid", "http", "status", "value" ]
134f2980575b7e58b51ef3624faac84e7a3f304d
https://github.com/joomla-framework/application/blob/134f2980575b7e58b51ef3624faac84e7a3f304d/src/AbstractWebApplication.php#L633-L647
train
joomla-framework/application
src/AbstractWebApplication.php
AbstractWebApplication.isRedirectState
protected function isRedirectState($state) { $state = (int) $state; return $state > 299 && $state < 400 && array_key_exists($state, $this->responseMap); }
php
protected function isRedirectState($state) { $state = (int) $state; return $state > 299 && $state < 400 && array_key_exists($state, $this->responseMap); }
[ "protected", "function", "isRedirectState", "(", "$", "state", ")", "{", "$", "state", "=", "(", "int", ")", "$", "state", ";", "return", "$", "state", ">", "299", "&&", "$", "state", "<", "400", "&&", "array_key_exists", "(", "$", "state", ",", "$", "this", "->", "responseMap", ")", ";", "}" ]
Checks if a state is a redirect state @param integer $state The HTTP status code. @return boolean @since 1.8.0
[ "Checks", "if", "a", "state", "is", "a", "redirect", "state" ]
134f2980575b7e58b51ef3624faac84e7a3f304d
https://github.com/joomla-framework/application/blob/134f2980575b7e58b51ef3624faac84e7a3f304d/src/AbstractWebApplication.php#L774-L779
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Driver/AbstractIndexerDriver.php
AbstractIndexerDriver.isFulltextRoot
protected function isFulltextRoot(NodeInterface $node): bool { if ($node->getNodeType()->hasConfiguration('search')) { $elasticSearchSettingsForNode = $node->getNodeType()->getConfiguration('search'); if (isset($elasticSearchSettingsForNode['fulltext']['isRoot']) && $elasticSearchSettingsForNode['fulltext']['isRoot'] === true) { return true; } } return false; }
php
protected function isFulltextRoot(NodeInterface $node): bool { if ($node->getNodeType()->hasConfiguration('search')) { $elasticSearchSettingsForNode = $node->getNodeType()->getConfiguration('search'); if (isset($elasticSearchSettingsForNode['fulltext']['isRoot']) && $elasticSearchSettingsForNode['fulltext']['isRoot'] === true) { return true; } } return false; }
[ "protected", "function", "isFulltextRoot", "(", "NodeInterface", "$", "node", ")", ":", "bool", "{", "if", "(", "$", "node", "->", "getNodeType", "(", ")", "->", "hasConfiguration", "(", "'search'", ")", ")", "{", "$", "elasticSearchSettingsForNode", "=", "$", "node", "->", "getNodeType", "(", ")", "->", "getConfiguration", "(", "'search'", ")", ";", "if", "(", "isset", "(", "$", "elasticSearchSettingsForNode", "[", "'fulltext'", "]", "[", "'isRoot'", "]", ")", "&&", "$", "elasticSearchSettingsForNode", "[", "'fulltext'", "]", "[", "'isRoot'", "]", "===", "true", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Whether the node is configured as fulltext root. @param NodeInterface $node @return bool
[ "Whether", "the", "node", "is", "configured", "as", "fulltext", "root", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Driver/AbstractIndexerDriver.php#L37-L47
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Driver/Version5/Mapping/NodeTypeMappingBuilder.php
NodeTypeMappingBuilder.buildMappingInformation
public function buildMappingInformation(Index $index): MappingCollection { $this->lastMappingErrors = new Result(); $mappings = new MappingCollection(MappingCollection::TYPE_ENTITY); /** @var NodeType $nodeType */ foreach ($this->nodeTypeManager->getNodeTypes() as $nodeTypeName => $nodeType) { if ($nodeTypeName === 'unstructured' || $nodeType->isAbstract()) { continue; } $type = $index->findType($this->convertNodeTypeNameToMappingName($nodeTypeName)); $mapping = new Mapping($type); $fullConfiguration = $nodeType->getFullConfiguration(); if (isset($fullConfiguration['search']['elasticSearchMapping'])) { $fullMapping = $fullConfiguration['search']['elasticSearchMapping']; $this->migrateConfigurationForElasticVersion5($fullMapping); $mapping->setFullMapping($fullMapping); } // https://www.elastic.co/guide/en/elasticsearch/reference/5.4/dynamic-templates.html $mapping->addDynamicTemplate('dimensions', [ 'path_match' => '__dimensionCombinations.*', 'match_mapping_type' => 'string', 'mapping' => [ 'type' => 'text' ] ]); $mapping->setPropertyByPath('__dimensionCombinationHash', [ 'type' => 'keyword' ]); foreach ($nodeType->getProperties() as $propertyName => $propertyConfiguration) { if (isset($propertyConfiguration['search']['elasticSearchMapping'])) { if (is_array($propertyConfiguration['search']['elasticSearchMapping'])) { $propertyMapping = $propertyConfiguration['search']['elasticSearchMapping']; $this->migrateConfigurationForElasticVersion5($propertyMapping); $mapping->setPropertyByPath($propertyName, $propertyMapping); } } elseif (isset($propertyConfiguration['type'], $this->defaultConfigurationPerType[$propertyConfiguration['type']]['elasticSearchMapping'])) { if (is_array($this->defaultConfigurationPerType[$propertyConfiguration['type']]['elasticSearchMapping'])) { $mapping->setPropertyByPath($propertyName, $this->defaultConfigurationPerType[$propertyConfiguration['type']]['elasticSearchMapping']); } } else { $this->lastMappingErrors->addWarning(new Warning('Node Type "' . $nodeTypeName . '" - property "' . $propertyName . '": No ElasticSearch Mapping found.')); } } $mappings->add($mapping); } return $mappings; }
php
public function buildMappingInformation(Index $index): MappingCollection { $this->lastMappingErrors = new Result(); $mappings = new MappingCollection(MappingCollection::TYPE_ENTITY); /** @var NodeType $nodeType */ foreach ($this->nodeTypeManager->getNodeTypes() as $nodeTypeName => $nodeType) { if ($nodeTypeName === 'unstructured' || $nodeType->isAbstract()) { continue; } $type = $index->findType($this->convertNodeTypeNameToMappingName($nodeTypeName)); $mapping = new Mapping($type); $fullConfiguration = $nodeType->getFullConfiguration(); if (isset($fullConfiguration['search']['elasticSearchMapping'])) { $fullMapping = $fullConfiguration['search']['elasticSearchMapping']; $this->migrateConfigurationForElasticVersion5($fullMapping); $mapping->setFullMapping($fullMapping); } // https://www.elastic.co/guide/en/elasticsearch/reference/5.4/dynamic-templates.html $mapping->addDynamicTemplate('dimensions', [ 'path_match' => '__dimensionCombinations.*', 'match_mapping_type' => 'string', 'mapping' => [ 'type' => 'text' ] ]); $mapping->setPropertyByPath('__dimensionCombinationHash', [ 'type' => 'keyword' ]); foreach ($nodeType->getProperties() as $propertyName => $propertyConfiguration) { if (isset($propertyConfiguration['search']['elasticSearchMapping'])) { if (is_array($propertyConfiguration['search']['elasticSearchMapping'])) { $propertyMapping = $propertyConfiguration['search']['elasticSearchMapping']; $this->migrateConfigurationForElasticVersion5($propertyMapping); $mapping->setPropertyByPath($propertyName, $propertyMapping); } } elseif (isset($propertyConfiguration['type'], $this->defaultConfigurationPerType[$propertyConfiguration['type']]['elasticSearchMapping'])) { if (is_array($this->defaultConfigurationPerType[$propertyConfiguration['type']]['elasticSearchMapping'])) { $mapping->setPropertyByPath($propertyName, $this->defaultConfigurationPerType[$propertyConfiguration['type']]['elasticSearchMapping']); } } else { $this->lastMappingErrors->addWarning(new Warning('Node Type "' . $nodeTypeName . '" - property "' . $propertyName . '": No ElasticSearch Mapping found.')); } } $mappings->add($mapping); } return $mappings; }
[ "public", "function", "buildMappingInformation", "(", "Index", "$", "index", ")", ":", "MappingCollection", "{", "$", "this", "->", "lastMappingErrors", "=", "new", "Result", "(", ")", ";", "$", "mappings", "=", "new", "MappingCollection", "(", "MappingCollection", "::", "TYPE_ENTITY", ")", ";", "/** @var NodeType $nodeType */", "foreach", "(", "$", "this", "->", "nodeTypeManager", "->", "getNodeTypes", "(", ")", "as", "$", "nodeTypeName", "=>", "$", "nodeType", ")", "{", "if", "(", "$", "nodeTypeName", "===", "'unstructured'", "||", "$", "nodeType", "->", "isAbstract", "(", ")", ")", "{", "continue", ";", "}", "$", "type", "=", "$", "index", "->", "findType", "(", "$", "this", "->", "convertNodeTypeNameToMappingName", "(", "$", "nodeTypeName", ")", ")", ";", "$", "mapping", "=", "new", "Mapping", "(", "$", "type", ")", ";", "$", "fullConfiguration", "=", "$", "nodeType", "->", "getFullConfiguration", "(", ")", ";", "if", "(", "isset", "(", "$", "fullConfiguration", "[", "'search'", "]", "[", "'elasticSearchMapping'", "]", ")", ")", "{", "$", "fullMapping", "=", "$", "fullConfiguration", "[", "'search'", "]", "[", "'elasticSearchMapping'", "]", ";", "$", "this", "->", "migrateConfigurationForElasticVersion5", "(", "$", "fullMapping", ")", ";", "$", "mapping", "->", "setFullMapping", "(", "$", "fullMapping", ")", ";", "}", "// https://www.elastic.co/guide/en/elasticsearch/reference/5.4/dynamic-templates.html", "$", "mapping", "->", "addDynamicTemplate", "(", "'dimensions'", ",", "[", "'path_match'", "=>", "'__dimensionCombinations.*'", ",", "'match_mapping_type'", "=>", "'string'", ",", "'mapping'", "=>", "[", "'type'", "=>", "'text'", "]", "]", ")", ";", "$", "mapping", "->", "setPropertyByPath", "(", "'__dimensionCombinationHash'", ",", "[", "'type'", "=>", "'keyword'", "]", ")", ";", "foreach", "(", "$", "nodeType", "->", "getProperties", "(", ")", "as", "$", "propertyName", "=>", "$", "propertyConfiguration", ")", "{", "if", "(", "isset", "(", "$", "propertyConfiguration", "[", "'search'", "]", "[", "'elasticSearchMapping'", "]", ")", ")", "{", "if", "(", "is_array", "(", "$", "propertyConfiguration", "[", "'search'", "]", "[", "'elasticSearchMapping'", "]", ")", ")", "{", "$", "propertyMapping", "=", "$", "propertyConfiguration", "[", "'search'", "]", "[", "'elasticSearchMapping'", "]", ";", "$", "this", "->", "migrateConfigurationForElasticVersion5", "(", "$", "propertyMapping", ")", ";", "$", "mapping", "->", "setPropertyByPath", "(", "$", "propertyName", ",", "$", "propertyMapping", ")", ";", "}", "}", "elseif", "(", "isset", "(", "$", "propertyConfiguration", "[", "'type'", "]", ",", "$", "this", "->", "defaultConfigurationPerType", "[", "$", "propertyConfiguration", "[", "'type'", "]", "]", "[", "'elasticSearchMapping'", "]", ")", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "defaultConfigurationPerType", "[", "$", "propertyConfiguration", "[", "'type'", "]", "]", "[", "'elasticSearchMapping'", "]", ")", ")", "{", "$", "mapping", "->", "setPropertyByPath", "(", "$", "propertyName", ",", "$", "this", "->", "defaultConfigurationPerType", "[", "$", "propertyConfiguration", "[", "'type'", "]", "]", "[", "'elasticSearchMapping'", "]", ")", ";", "}", "}", "else", "{", "$", "this", "->", "lastMappingErrors", "->", "addWarning", "(", "new", "Warning", "(", "'Node Type \"'", ".", "$", "nodeTypeName", ".", "'\" - property \"'", ".", "$", "propertyName", ".", "'\": No ElasticSearch Mapping found.'", ")", ")", ";", "}", "}", "$", "mappings", "->", "add", "(", "$", "mapping", ")", ";", "}", "return", "$", "mappings", ";", "}" ]
Builds a Mapping Collection from the configured node types @param Index $index @return MappingCollection<\Flowpack\ElasticSearch\Domain\Model\Mapping>
[ "Builds", "a", "Mapping", "Collection", "from", "the", "configured", "node", "types" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Driver/Version5/Mapping/NodeTypeMappingBuilder.php#L55-L108
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Driver/Version5/Mapping/NodeTypeMappingBuilder.php
NodeTypeMappingBuilder.adjustStringTypeMapping
protected function adjustStringTypeMapping(array &$mapping): void { $adjustStringTypeMapping = function (&$item) { if (isset($item['type']) && $item['type'] === 'string') { if (isset($item['index'])) { if ($item['index'] === 'not_analyzed') { $item['type'] = 'keyword'; $item['index'] = true; unset($item['analyzer']); } elseif ($item['index'] === 'no') { $item['type'] = 'text'; $item['index'] = false; } elseif ($item['index'] === 'analyzed') { $item['type'] = 'text'; $item['index'] = true; } } else { $item['type'] = 'keyword'; $item['index'] = true; } } }; $adjustStringTypeMapping($mapping); foreach ($mapping as &$item) { if (is_array($item)) { $adjustStringTypeMapping($mapping); $this->adjustStringTypeMapping($item); } } }
php
protected function adjustStringTypeMapping(array &$mapping): void { $adjustStringTypeMapping = function (&$item) { if (isset($item['type']) && $item['type'] === 'string') { if (isset($item['index'])) { if ($item['index'] === 'not_analyzed') { $item['type'] = 'keyword'; $item['index'] = true; unset($item['analyzer']); } elseif ($item['index'] === 'no') { $item['type'] = 'text'; $item['index'] = false; } elseif ($item['index'] === 'analyzed') { $item['type'] = 'text'; $item['index'] = true; } } else { $item['type'] = 'keyword'; $item['index'] = true; } } }; $adjustStringTypeMapping($mapping); foreach ($mapping as &$item) { if (is_array($item)) { $adjustStringTypeMapping($mapping); $this->adjustStringTypeMapping($item); } } }
[ "protected", "function", "adjustStringTypeMapping", "(", "array", "&", "$", "mapping", ")", ":", "void", "{", "$", "adjustStringTypeMapping", "=", "function", "(", "&", "$", "item", ")", "{", "if", "(", "isset", "(", "$", "item", "[", "'type'", "]", ")", "&&", "$", "item", "[", "'type'", "]", "===", "'string'", ")", "{", "if", "(", "isset", "(", "$", "item", "[", "'index'", "]", ")", ")", "{", "if", "(", "$", "item", "[", "'index'", "]", "===", "'not_analyzed'", ")", "{", "$", "item", "[", "'type'", "]", "=", "'keyword'", ";", "$", "item", "[", "'index'", "]", "=", "true", ";", "unset", "(", "$", "item", "[", "'analyzer'", "]", ")", ";", "}", "elseif", "(", "$", "item", "[", "'index'", "]", "===", "'no'", ")", "{", "$", "item", "[", "'type'", "]", "=", "'text'", ";", "$", "item", "[", "'index'", "]", "=", "false", ";", "}", "elseif", "(", "$", "item", "[", "'index'", "]", "===", "'analyzed'", ")", "{", "$", "item", "[", "'type'", "]", "=", "'text'", ";", "$", "item", "[", "'index'", "]", "=", "true", ";", "}", "}", "else", "{", "$", "item", "[", "'type'", "]", "=", "'keyword'", ";", "$", "item", "[", "'index'", "]", "=", "true", ";", "}", "}", "}", ";", "$", "adjustStringTypeMapping", "(", "$", "mapping", ")", ";", "foreach", "(", "$", "mapping", "as", "&", "$", "item", ")", "{", "if", "(", "is_array", "(", "$", "item", ")", ")", "{", "$", "adjustStringTypeMapping", "(", "$", "mapping", ")", ";", "$", "this", "->", "adjustStringTypeMapping", "(", "$", "item", ")", ";", "}", "}", "}" ]
Adjust the mapping for string to text or keyword as needed. This is used to ease moving from ES 1.x and 2.x to 5.x by migrating the mapping like this: | 2.x | 5.x | |-------------------------------------------|----------------------------------| | "type": "string", "index": "no" | "type": "text", "index": false | | "type": "string", "index": "analyzed" | "type": "text", "index": true | | "type": "string", "index": "not_analyzed" | "type": "keyword", "index": true | @param array &$mapping @return void
[ "Adjust", "the", "mapping", "for", "string", "to", "text", "or", "keyword", "as", "needed", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Driver/Version5/Mapping/NodeTypeMappingBuilder.php#L134-L165
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Indexer/NodeIndexer.php
NodeIndexer.getIndexName
public function getIndexName(): string { $indexName = $this->searchClient->getIndexName(); if ($this->indexNamePostfix !== '') { $indexName .= '-' . $this->indexNamePostfix; } return $indexName; }
php
public function getIndexName(): string { $indexName = $this->searchClient->getIndexName(); if ($this->indexNamePostfix !== '') { $indexName .= '-' . $this->indexNamePostfix; } return $indexName; }
[ "public", "function", "getIndexName", "(", ")", ":", "string", "{", "$", "indexName", "=", "$", "this", "->", "searchClient", "->", "getIndexName", "(", ")", ";", "if", "(", "$", "this", "->", "indexNamePostfix", "!==", "''", ")", "{", "$", "indexName", ".=", "'-'", ".", "$", "this", "->", "indexNamePostfix", ";", "}", "return", "$", "indexName", ";", "}" ]
Returns the index name to be used for indexing, with optional indexNamePostfix appended. @return string @throws Exception
[ "Returns", "the", "index", "name", "to", "be", "used", "for", "indexing", "with", "optional", "indexNamePostfix", "appended", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Indexer/NodeIndexer.php#L139-L147
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Indexer/NodeIndexer.php
NodeIndexer.getIndex
public function getIndex(): Index { $index = $this->searchClient->findIndex($this->getIndexName()); $index->setSettingsKey($this->searchClient->getIndexName()); return $index; }
php
public function getIndex(): Index { $index = $this->searchClient->findIndex($this->getIndexName()); $index->setSettingsKey($this->searchClient->getIndexName()); return $index; }
[ "public", "function", "getIndex", "(", ")", ":", "Index", "{", "$", "index", "=", "$", "this", "->", "searchClient", "->", "findIndex", "(", "$", "this", "->", "getIndexName", "(", ")", ")", ";", "$", "index", "->", "setSettingsKey", "(", "$", "this", "->", "searchClient", "->", "getIndexName", "(", ")", ")", ";", "return", "$", "index", ";", "}" ]
Return the currently active index to be used for indexing @return Index @throws Exception
[ "Return", "the", "currently", "active", "index", "to", "be", "used", "for", "indexing" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Indexer/NodeIndexer.php#L166-L172
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Indexer/NodeIndexer.php
NodeIndexer.calculateDocumentIdentifier
protected function calculateDocumentIdentifier(NodeInterface $node, $targetWorkspaceName = null): string { $contextPath = $node->getContextPath(); if ($targetWorkspaceName !== null) { $contextPath = str_replace($node->getContext()->getWorkspace()->getName(), $targetWorkspaceName, $contextPath); } return sha1($contextPath); }
php
protected function calculateDocumentIdentifier(NodeInterface $node, $targetWorkspaceName = null): string { $contextPath = $node->getContextPath(); if ($targetWorkspaceName !== null) { $contextPath = str_replace($node->getContext()->getWorkspace()->getName(), $targetWorkspaceName, $contextPath); } return sha1($contextPath); }
[ "protected", "function", "calculateDocumentIdentifier", "(", "NodeInterface", "$", "node", ",", "$", "targetWorkspaceName", "=", "null", ")", ":", "string", "{", "$", "contextPath", "=", "$", "node", "->", "getContextPath", "(", ")", ";", "if", "(", "$", "targetWorkspaceName", "!==", "null", ")", "{", "$", "contextPath", "=", "str_replace", "(", "$", "node", "->", "getContext", "(", ")", "->", "getWorkspace", "(", ")", "->", "getName", "(", ")", ",", "$", "targetWorkspaceName", ",", "$", "contextPath", ")", ";", "}", "return", "sha1", "(", "$", "contextPath", ")", ";", "}" ]
Returns a stable identifier for the Elasticsearch document representing the node @param NodeInterface $node @param string $targetWorkspaceName @return string @throws \Neos\Flow\Persistence\Exception\IllegalObjectTypeException
[ "Returns", "a", "stable", "identifier", "for", "the", "Elasticsearch", "document", "representing", "the", "node" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Indexer/NodeIndexer.php#L279-L288
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Indexer/NodeIndexer.php
NodeIndexer.removeNode
public function removeNode(NodeInterface $node, string $targetWorkspaceName = null) { if ($this->settings['indexAllWorkspaces'] === false) { // we are only supposed to index the live workspace. // We need to check the workspace at two occasions; checking the // $targetWorkspaceName and the workspace name of the node's context as fallback if ($targetWorkspaceName !== null && $targetWorkspaceName !== 'live') { return; } if ($targetWorkspaceName === null && $node->getContext()->getWorkspaceName() !== 'live') { return; } } $documentIdentifier = $this->calculateDocumentIdentifier($node, $targetWorkspaceName); $this->currentBulkRequest[] = $this->documentDriver->delete($node, $documentIdentifier); $this->currentBulkRequest[] = $this->indexerDriver->fulltext($node, [], $targetWorkspaceName); $this->logger->log(sprintf('NodeIndexer (%s): Removed node %s (%s) from index.', $documentIdentifier, $node->getContextPath(), $node->getIdentifier()), LOG_DEBUG, null, 'ElasticSearch (CR)'); }
php
public function removeNode(NodeInterface $node, string $targetWorkspaceName = null) { if ($this->settings['indexAllWorkspaces'] === false) { // we are only supposed to index the live workspace. // We need to check the workspace at two occasions; checking the // $targetWorkspaceName and the workspace name of the node's context as fallback if ($targetWorkspaceName !== null && $targetWorkspaceName !== 'live') { return; } if ($targetWorkspaceName === null && $node->getContext()->getWorkspaceName() !== 'live') { return; } } $documentIdentifier = $this->calculateDocumentIdentifier($node, $targetWorkspaceName); $this->currentBulkRequest[] = $this->documentDriver->delete($node, $documentIdentifier); $this->currentBulkRequest[] = $this->indexerDriver->fulltext($node, [], $targetWorkspaceName); $this->logger->log(sprintf('NodeIndexer (%s): Removed node %s (%s) from index.', $documentIdentifier, $node->getContextPath(), $node->getIdentifier()), LOG_DEBUG, null, 'ElasticSearch (CR)'); }
[ "public", "function", "removeNode", "(", "NodeInterface", "$", "node", ",", "string", "$", "targetWorkspaceName", "=", "null", ")", "{", "if", "(", "$", "this", "->", "settings", "[", "'indexAllWorkspaces'", "]", "===", "false", ")", "{", "// we are only supposed to index the live workspace.", "// We need to check the workspace at two occasions; checking the", "// $targetWorkspaceName and the workspace name of the node's context as fallback", "if", "(", "$", "targetWorkspaceName", "!==", "null", "&&", "$", "targetWorkspaceName", "!==", "'live'", ")", "{", "return", ";", "}", "if", "(", "$", "targetWorkspaceName", "===", "null", "&&", "$", "node", "->", "getContext", "(", ")", "->", "getWorkspaceName", "(", ")", "!==", "'live'", ")", "{", "return", ";", "}", "}", "$", "documentIdentifier", "=", "$", "this", "->", "calculateDocumentIdentifier", "(", "$", "node", ",", "$", "targetWorkspaceName", ")", ";", "$", "this", "->", "currentBulkRequest", "[", "]", "=", "$", "this", "->", "documentDriver", "->", "delete", "(", "$", "node", ",", "$", "documentIdentifier", ")", ";", "$", "this", "->", "currentBulkRequest", "[", "]", "=", "$", "this", "->", "indexerDriver", "->", "fulltext", "(", "$", "node", ",", "[", "]", ",", "$", "targetWorkspaceName", ")", ";", "$", "this", "->", "logger", "->", "log", "(", "sprintf", "(", "'NodeIndexer (%s): Removed node %s (%s) from index.'", ",", "$", "documentIdentifier", ",", "$", "node", "->", "getContextPath", "(", ")", ",", "$", "node", "->", "getIdentifier", "(", ")", ")", ",", "LOG_DEBUG", ",", "null", ",", "'ElasticSearch (CR)'", ")", ";", "}" ]
Schedule node removal into the current bulk request. @param NodeInterface $node @param string $targetWorkspaceName @return void @throws \Neos\Flow\Persistence\Exception\IllegalObjectTypeException
[ "Schedule", "node", "removal", "into", "the", "current", "bulk", "request", "." ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Indexer/NodeIndexer.php#L298-L319
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Indexer/NodeIndexer.php
NodeIndexer.flush
public function flush() { $bulkRequest = array_filter($this->currentBulkRequest); if (count($bulkRequest) === 0) { return; } $content = ''; foreach ($bulkRequest as $bulkRequestTuple) { $tupleAsJson = ''; foreach ($bulkRequestTuple as $bulkRequestItem) { $itemAsJson = json_encode($bulkRequestItem); if ($itemAsJson === false) { $this->errorHandlingService->log( new MalformedBulkRequestError('Indexing Error: Bulk request item could not be encoded as JSON - ' . json_last_error_msg(), $bulkRequestItem) ); continue 2; } $tupleAsJson .= $itemAsJson . chr(10); } $content .= $tupleAsJson; } if ($content !== '') { $response = $this->requestDriver->bulk($this->getIndex(), $content); foreach ($response as $responseLine) { if (isset($response['errors']) && $response['errors'] !== false) { $this->errorHandlingService->log( new BulkIndexingError($this->currentBulkRequest, $responseLine) ); } } } $this->currentBulkRequest = []; }
php
public function flush() { $bulkRequest = array_filter($this->currentBulkRequest); if (count($bulkRequest) === 0) { return; } $content = ''; foreach ($bulkRequest as $bulkRequestTuple) { $tupleAsJson = ''; foreach ($bulkRequestTuple as $bulkRequestItem) { $itemAsJson = json_encode($bulkRequestItem); if ($itemAsJson === false) { $this->errorHandlingService->log( new MalformedBulkRequestError('Indexing Error: Bulk request item could not be encoded as JSON - ' . json_last_error_msg(), $bulkRequestItem) ); continue 2; } $tupleAsJson .= $itemAsJson . chr(10); } $content .= $tupleAsJson; } if ($content !== '') { $response = $this->requestDriver->bulk($this->getIndex(), $content); foreach ($response as $responseLine) { if (isset($response['errors']) && $response['errors'] !== false) { $this->errorHandlingService->log( new BulkIndexingError($this->currentBulkRequest, $responseLine) ); } } } $this->currentBulkRequest = []; }
[ "public", "function", "flush", "(", ")", "{", "$", "bulkRequest", "=", "array_filter", "(", "$", "this", "->", "currentBulkRequest", ")", ";", "if", "(", "count", "(", "$", "bulkRequest", ")", "===", "0", ")", "{", "return", ";", "}", "$", "content", "=", "''", ";", "foreach", "(", "$", "bulkRequest", "as", "$", "bulkRequestTuple", ")", "{", "$", "tupleAsJson", "=", "''", ";", "foreach", "(", "$", "bulkRequestTuple", "as", "$", "bulkRequestItem", ")", "{", "$", "itemAsJson", "=", "json_encode", "(", "$", "bulkRequestItem", ")", ";", "if", "(", "$", "itemAsJson", "===", "false", ")", "{", "$", "this", "->", "errorHandlingService", "->", "log", "(", "new", "MalformedBulkRequestError", "(", "'Indexing Error: Bulk request item could not be encoded as JSON - '", ".", "json_last_error_msg", "(", ")", ",", "$", "bulkRequestItem", ")", ")", ";", "continue", "2", ";", "}", "$", "tupleAsJson", ".=", "$", "itemAsJson", ".", "chr", "(", "10", ")", ";", "}", "$", "content", ".=", "$", "tupleAsJson", ";", "}", "if", "(", "$", "content", "!==", "''", ")", "{", "$", "response", "=", "$", "this", "->", "requestDriver", "->", "bulk", "(", "$", "this", "->", "getIndex", "(", ")", ",", "$", "content", ")", ";", "foreach", "(", "$", "response", "as", "$", "responseLine", ")", "{", "if", "(", "isset", "(", "$", "response", "[", "'errors'", "]", ")", "&&", "$", "response", "[", "'errors'", "]", "!==", "false", ")", "{", "$", "this", "->", "errorHandlingService", "->", "log", "(", "new", "BulkIndexingError", "(", "$", "this", "->", "currentBulkRequest", ",", "$", "responseLine", ")", ")", ";", "}", "}", "}", "$", "this", "->", "currentBulkRequest", "=", "[", "]", ";", "}" ]
Perform the current bulk request @return void @throws Exception
[ "Perform", "the", "current", "bulk", "request" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Indexer/NodeIndexer.php#L327-L362
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Indexer/NodeIndexer.php
NodeIndexer.updateIndexAlias
public function updateIndexAlias(): void { $aliasName = $this->searchClient->getIndexName(); // The alias name is the unprefixed index name if ($this->getIndexName() === $aliasName) { throw new Exception('UpdateIndexAlias is only allowed to be called when $this->setIndexNamePostfix has been created.', 1383649061); } if (!$this->getIndex()->exists()) { throw new Exception('The target index for updateIndexAlias does not exist. This shall never happen.', 1383649125); } $aliasActions = []; try { $indexNames = $this->indexDriver->indexesByAlias($aliasName); if ($indexNames === []) { // if there is an actual index with the name we want to use as alias, remove it now $this->indexDriver->deleteIndex($aliasName); } else { foreach ($indexNames as $indexName) { $aliasActions[] = [ 'remove' => [ 'index' => $indexName, 'alias' => $aliasName ] ]; } } } catch (ApiException $exception) { // in case of 404, do not throw an error... if ($exception->getResponse()->getStatusCode() !== 404) { throw $exception; } } $aliasActions[] = [ 'add' => [ 'index' => $this->getIndexName(), 'alias' => $aliasName ] ]; $this->indexDriver->aliasActions($aliasActions); }
php
public function updateIndexAlias(): void { $aliasName = $this->searchClient->getIndexName(); // The alias name is the unprefixed index name if ($this->getIndexName() === $aliasName) { throw new Exception('UpdateIndexAlias is only allowed to be called when $this->setIndexNamePostfix has been created.', 1383649061); } if (!$this->getIndex()->exists()) { throw new Exception('The target index for updateIndexAlias does not exist. This shall never happen.', 1383649125); } $aliasActions = []; try { $indexNames = $this->indexDriver->indexesByAlias($aliasName); if ($indexNames === []) { // if there is an actual index with the name we want to use as alias, remove it now $this->indexDriver->deleteIndex($aliasName); } else { foreach ($indexNames as $indexName) { $aliasActions[] = [ 'remove' => [ 'index' => $indexName, 'alias' => $aliasName ] ]; } } } catch (ApiException $exception) { // in case of 404, do not throw an error... if ($exception->getResponse()->getStatusCode() !== 404) { throw $exception; } } $aliasActions[] = [ 'add' => [ 'index' => $this->getIndexName(), 'alias' => $aliasName ] ]; $this->indexDriver->aliasActions($aliasActions); }
[ "public", "function", "updateIndexAlias", "(", ")", ":", "void", "{", "$", "aliasName", "=", "$", "this", "->", "searchClient", "->", "getIndexName", "(", ")", ";", "// The alias name is the unprefixed index name", "if", "(", "$", "this", "->", "getIndexName", "(", ")", "===", "$", "aliasName", ")", "{", "throw", "new", "Exception", "(", "'UpdateIndexAlias is only allowed to be called when $this->setIndexNamePostfix has been created.'", ",", "1383649061", ")", ";", "}", "if", "(", "!", "$", "this", "->", "getIndex", "(", ")", "->", "exists", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'The target index for updateIndexAlias does not exist. This shall never happen.'", ",", "1383649125", ")", ";", "}", "$", "aliasActions", "=", "[", "]", ";", "try", "{", "$", "indexNames", "=", "$", "this", "->", "indexDriver", "->", "indexesByAlias", "(", "$", "aliasName", ")", ";", "if", "(", "$", "indexNames", "===", "[", "]", ")", "{", "// if there is an actual index with the name we want to use as alias, remove it now", "$", "this", "->", "indexDriver", "->", "deleteIndex", "(", "$", "aliasName", ")", ";", "}", "else", "{", "foreach", "(", "$", "indexNames", "as", "$", "indexName", ")", "{", "$", "aliasActions", "[", "]", "=", "[", "'remove'", "=>", "[", "'index'", "=>", "$", "indexName", ",", "'alias'", "=>", "$", "aliasName", "]", "]", ";", "}", "}", "}", "catch", "(", "ApiException", "$", "exception", ")", "{", "// in case of 404, do not throw an error...", "if", "(", "$", "exception", "->", "getResponse", "(", ")", "->", "getStatusCode", "(", ")", "!==", "404", ")", "{", "throw", "$", "exception", ";", "}", "}", "$", "aliasActions", "[", "]", "=", "[", "'add'", "=>", "[", "'index'", "=>", "$", "this", "->", "getIndexName", "(", ")", ",", "'alias'", "=>", "$", "aliasName", "]", "]", ";", "$", "this", "->", "indexDriver", "->", "aliasActions", "(", "$", "aliasActions", ")", ";", "}" ]
Update the index alias @return void @throws Exception @throws ApiException
[ "Update", "the", "index", "alias" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Indexer/NodeIndexer.php#L371-L414
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/Indexer/NodeIndexer.php
NodeIndexer.withBulkProcessing
public function withBulkProcessing(callable $callback) { $bulkProcessing = $this->bulkProcessing; $this->bulkProcessing = true; try { /** @noinspection PhpUndefinedMethodInspection */ $callback->__invoke(); } catch (\Exception $exception) { $this->bulkProcessing = $bulkProcessing; throw $exception; } $this->bulkProcessing = $bulkProcessing; }
php
public function withBulkProcessing(callable $callback) { $bulkProcessing = $this->bulkProcessing; $this->bulkProcessing = true; try { /** @noinspection PhpUndefinedMethodInspection */ $callback->__invoke(); } catch (\Exception $exception) { $this->bulkProcessing = $bulkProcessing; throw $exception; } $this->bulkProcessing = $bulkProcessing; }
[ "public", "function", "withBulkProcessing", "(", "callable", "$", "callback", ")", "{", "$", "bulkProcessing", "=", "$", "this", "->", "bulkProcessing", ";", "$", "this", "->", "bulkProcessing", "=", "true", ";", "try", "{", "/** @noinspection PhpUndefinedMethodInspection */", "$", "callback", "->", "__invoke", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "exception", ")", "{", "$", "this", "->", "bulkProcessing", "=", "$", "bulkProcessing", ";", "throw", "$", "exception", ";", "}", "$", "this", "->", "bulkProcessing", "=", "$", "bulkProcessing", ";", "}" ]
Perform indexing without checking about duplication document This is used during bulk indexing to improve performance @param callable $callback @throws \Exception
[ "Perform", "indexing", "without", "checking", "about", "duplication", "document" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/Indexer/NodeIndexer.php#L463-L475
train
Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor
Classes/ElasticSearchClient.php
ElasticSearchClient.getIndexName
public function getIndexName(): string { $name = trim($this->indexNameStrategy->get()); if ($name === '') { throw new Exception('Index name can not be null'); } return $name; }
php
public function getIndexName(): string { $name = trim($this->indexNameStrategy->get()); if ($name === '') { throw new Exception('Index name can not be null'); } return $name; }
[ "public", "function", "getIndexName", "(", ")", ":", "string", "{", "$", "name", "=", "trim", "(", "$", "this", "->", "indexNameStrategy", "->", "get", "(", ")", ")", ";", "if", "(", "$", "name", "===", "''", ")", "{", "throw", "new", "Exception", "(", "'Index name can not be null'", ")", ";", "}", "return", "$", "name", ";", "}" ]
Get the index name to be used @return string @throws Exception
[ "Get", "the", "index", "name", "to", "be", "used" ]
22186096f606a7bfae283be32fcdbfb150fcfda0
https://github.com/Flowpack/Flowpack.ElasticSearch.ContentRepositoryAdaptor/blob/22186096f606a7bfae283be32fcdbfb150fcfda0/Classes/ElasticSearchClient.php#L46-L54
train
silverstripe/silverstripe-comments
src/Controllers/CommentingController.php
CommentingController.getOption
public function getOption($key) { // If possible use the current record if ($record = $this->getOwnerRecord()) { /** @var DataObject|CommentsExtension $record */ return $record->getCommentsOption($key); } // Otherwise a singleton of that record if ($class = $this->getParentClass()) { return singleton($class)->getCommentsOption($key); } // Otherwise just use the default options return singleton(CommentsExtension::class)->getCommentsOption($key); }
php
public function getOption($key) { // If possible use the current record if ($record = $this->getOwnerRecord()) { /** @var DataObject|CommentsExtension $record */ return $record->getCommentsOption($key); } // Otherwise a singleton of that record if ($class = $this->getParentClass()) { return singleton($class)->getCommentsOption($key); } // Otherwise just use the default options return singleton(CommentsExtension::class)->getCommentsOption($key); }
[ "public", "function", "getOption", "(", "$", "key", ")", "{", "// If possible use the current record", "if", "(", "$", "record", "=", "$", "this", "->", "getOwnerRecord", "(", ")", ")", "{", "/** @var DataObject|CommentsExtension $record */", "return", "$", "record", "->", "getCommentsOption", "(", "$", "key", ")", ";", "}", "// Otherwise a singleton of that record", "if", "(", "$", "class", "=", "$", "this", "->", "getParentClass", "(", ")", ")", "{", "return", "singleton", "(", "$", "class", ")", "->", "getCommentsOption", "(", "$", "key", ")", ";", "}", "// Otherwise just use the default options", "return", "singleton", "(", "CommentsExtension", "::", "class", ")", "->", "getCommentsOption", "(", "$", "key", ")", ";", "}" ]
Get the commenting option for the current state @param string $key @return mixed Result if the setting is available, or null otherwise
[ "Get", "the", "commenting", "option", "for", "the", "current", "state" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Controllers/CommentingController.php#L178-L193
train
silverstripe/silverstripe-comments
src/Controllers/CommentingController.php
CommentingController.getOptions
public function getOptions() { if ($record = $this->getOwnerRecord()) { /** @var DataObject|CommentsExtension $record */ return $record->getCommentsOptions(); } // Otherwise a singleton of that record if ($class = $this->getParentClass()) { return singleton($class)->getCommentsOptions(); } // Otherwise just use the default options return singleton(CommentsExtension::class)->getCommentsOptions(); }
php
public function getOptions() { if ($record = $this->getOwnerRecord()) { /** @var DataObject|CommentsExtension $record */ return $record->getCommentsOptions(); } // Otherwise a singleton of that record if ($class = $this->getParentClass()) { return singleton($class)->getCommentsOptions(); } // Otherwise just use the default options return singleton(CommentsExtension::class)->getCommentsOptions(); }
[ "public", "function", "getOptions", "(", ")", "{", "if", "(", "$", "record", "=", "$", "this", "->", "getOwnerRecord", "(", ")", ")", "{", "/** @var DataObject|CommentsExtension $record */", "return", "$", "record", "->", "getCommentsOptions", "(", ")", ";", "}", "// Otherwise a singleton of that record", "if", "(", "$", "class", "=", "$", "this", "->", "getParentClass", "(", ")", ")", "{", "return", "singleton", "(", "$", "class", ")", "->", "getCommentsOptions", "(", ")", ";", "}", "// Otherwise just use the default options", "return", "singleton", "(", "CommentsExtension", "::", "class", ")", "->", "getCommentsOptions", "(", ")", ";", "}" ]
Returns all the commenting options for the current instance. @return array
[ "Returns", "all", "the", "commenting", "options", "for", "the", "current", "instance", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Controllers/CommentingController.php#L200-L214
train
silverstripe/silverstripe-comments
src/Controllers/CommentingController.php
CommentingController.Link
public function Link($action = '', $id = '', $other = '') { return Controller::join_links(Director::baseURL(), 'comments', $action, $id, $other); }
php
public function Link($action = '', $id = '', $other = '') { return Controller::join_links(Director::baseURL(), 'comments', $action, $id, $other); }
[ "public", "function", "Link", "(", "$", "action", "=", "''", ",", "$", "id", "=", "''", ",", "$", "other", "=", "''", ")", "{", "return", "Controller", "::", "join_links", "(", "Director", "::", "baseURL", "(", ")", ",", "'comments'", ",", "$", "action", ",", "$", "id", ",", "$", "other", ")", ";", "}" ]
Workaround for generating the link to this controller @param string $action @param int $id @param string $other @return string
[ "Workaround", "for", "generating", "the", "link", "to", "this", "controller" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Controllers/CommentingController.php#L224-L227
train
silverstripe/silverstripe-comments
src/Controllers/CommentingController.php
CommentingController.getFeed
public function getFeed(HTTPRequest $request) { $link = $this->Link('rss'); $class = $this->decodeClassName($request->param('ID')); $id = $request->param('OtherID'); // Support old pageid param if (!$id && !$class && ($id = $request->getVar('pageid'))) { $class = SiteTree::class; } $comments = Comment::get()->filter([ 'Moderated' => 1, 'IsSpam' => 0, ]); // Check if class filter if ($class) { if (!is_subclass_of($class, DataObject::class) || !$class::has_extension(CommentsExtension::class)) { return $this->httpError(404); } $this->setParentClass($class); $comments = $comments->filter('ParentClass', $class); $link = Controller::join_links($link, $this->encodeClassName($class)); // Check if id filter if ($id) { $comments = $comments->filter('ParentID', $id); $link = Controller::join_links($link, $id); $this->setOwnerRecord(DataObject::get_by_id($class, $id)); } } $title = _t(__CLASS__ . '.RSSTITLE', "Comments RSS Feed"); $comments = PaginatedList::create($comments, $request); $comments->setPageLength($this->getOption('comments_per_page')); return RSSFeed::create( $comments, $link, $title, $link, 'Title', 'EscapedComment', 'AuthorName' ); }
php
public function getFeed(HTTPRequest $request) { $link = $this->Link('rss'); $class = $this->decodeClassName($request->param('ID')); $id = $request->param('OtherID'); // Support old pageid param if (!$id && !$class && ($id = $request->getVar('pageid'))) { $class = SiteTree::class; } $comments = Comment::get()->filter([ 'Moderated' => 1, 'IsSpam' => 0, ]); // Check if class filter if ($class) { if (!is_subclass_of($class, DataObject::class) || !$class::has_extension(CommentsExtension::class)) { return $this->httpError(404); } $this->setParentClass($class); $comments = $comments->filter('ParentClass', $class); $link = Controller::join_links($link, $this->encodeClassName($class)); // Check if id filter if ($id) { $comments = $comments->filter('ParentID', $id); $link = Controller::join_links($link, $id); $this->setOwnerRecord(DataObject::get_by_id($class, $id)); } } $title = _t(__CLASS__ . '.RSSTITLE', "Comments RSS Feed"); $comments = PaginatedList::create($comments, $request); $comments->setPageLength($this->getOption('comments_per_page')); return RSSFeed::create( $comments, $link, $title, $link, 'Title', 'EscapedComment', 'AuthorName' ); }
[ "public", "function", "getFeed", "(", "HTTPRequest", "$", "request", ")", "{", "$", "link", "=", "$", "this", "->", "Link", "(", "'rss'", ")", ";", "$", "class", "=", "$", "this", "->", "decodeClassName", "(", "$", "request", "->", "param", "(", "'ID'", ")", ")", ";", "$", "id", "=", "$", "request", "->", "param", "(", "'OtherID'", ")", ";", "// Support old pageid param", "if", "(", "!", "$", "id", "&&", "!", "$", "class", "&&", "(", "$", "id", "=", "$", "request", "->", "getVar", "(", "'pageid'", ")", ")", ")", "{", "$", "class", "=", "SiteTree", "::", "class", ";", "}", "$", "comments", "=", "Comment", "::", "get", "(", ")", "->", "filter", "(", "[", "'Moderated'", "=>", "1", ",", "'IsSpam'", "=>", "0", ",", "]", ")", ";", "// Check if class filter", "if", "(", "$", "class", ")", "{", "if", "(", "!", "is_subclass_of", "(", "$", "class", ",", "DataObject", "::", "class", ")", "||", "!", "$", "class", "::", "has_extension", "(", "CommentsExtension", "::", "class", ")", ")", "{", "return", "$", "this", "->", "httpError", "(", "404", ")", ";", "}", "$", "this", "->", "setParentClass", "(", "$", "class", ")", ";", "$", "comments", "=", "$", "comments", "->", "filter", "(", "'ParentClass'", ",", "$", "class", ")", ";", "$", "link", "=", "Controller", "::", "join_links", "(", "$", "link", ",", "$", "this", "->", "encodeClassName", "(", "$", "class", ")", ")", ";", "// Check if id filter", "if", "(", "$", "id", ")", "{", "$", "comments", "=", "$", "comments", "->", "filter", "(", "'ParentID'", ",", "$", "id", ")", ";", "$", "link", "=", "Controller", "::", "join_links", "(", "$", "link", ",", "$", "id", ")", ";", "$", "this", "->", "setOwnerRecord", "(", "DataObject", "::", "get_by_id", "(", "$", "class", ",", "$", "id", ")", ")", ";", "}", "}", "$", "title", "=", "_t", "(", "__CLASS__", ".", "'.RSSTITLE'", ",", "\"Comments RSS Feed\"", ")", ";", "$", "comments", "=", "PaginatedList", "::", "create", "(", "$", "comments", ",", "$", "request", ")", ";", "$", "comments", "->", "setPageLength", "(", "$", "this", "->", "getOption", "(", "'comments_per_page'", ")", ")", ";", "return", "RSSFeed", "::", "create", "(", "$", "comments", ",", "$", "link", ",", "$", "title", ",", "$", "link", ",", "'Title'", ",", "'EscapedComment'", ",", "'AuthorName'", ")", ";", "}" ]
Return an RSSFeed of comments for a given set of comments or all comments on the website. @param HTTPRequest @return RSSFeed
[ "Return", "an", "RSSFeed", "of", "comments", "for", "a", "given", "set", "of", "comments", "or", "all", "comments", "on", "the", "website", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Controllers/CommentingController.php#L247-L293
train
silverstripe/silverstripe-comments
src/Controllers/CommentingController.php
CommentingController.renderChangedCommentState
private function renderChangedCommentState($comment) { $referer = $this->request->getHeader('Referer'); // Render comment using AJAX if ($this->request->isAjax()) { return $comment->renderWith('Includes/CommentsInterface_singlecomment'); } // Redirect to either the comment or start of the page if (empty($referer)) { return $this->redirectBack(); } // Redirect to the comment, but check for phishing $url = $referer . '#comment-' . $comment->ID; // absolute redirection URLs not located on this site may cause phishing if (Director::is_site_url($url)) { return $this->redirect($url); } return false; }
php
private function renderChangedCommentState($comment) { $referer = $this->request->getHeader('Referer'); // Render comment using AJAX if ($this->request->isAjax()) { return $comment->renderWith('Includes/CommentsInterface_singlecomment'); } // Redirect to either the comment or start of the page if (empty($referer)) { return $this->redirectBack(); } // Redirect to the comment, but check for phishing $url = $referer . '#comment-' . $comment->ID; // absolute redirection URLs not located on this site may cause phishing if (Director::is_site_url($url)) { return $this->redirect($url); } return false; }
[ "private", "function", "renderChangedCommentState", "(", "$", "comment", ")", "{", "$", "referer", "=", "$", "this", "->", "request", "->", "getHeader", "(", "'Referer'", ")", ";", "// Render comment using AJAX", "if", "(", "$", "this", "->", "request", "->", "isAjax", "(", ")", ")", "{", "return", "$", "comment", "->", "renderWith", "(", "'Includes/CommentsInterface_singlecomment'", ")", ";", "}", "// Redirect to either the comment or start of the page", "if", "(", "empty", "(", "$", "referer", ")", ")", "{", "return", "$", "this", "->", "redirectBack", "(", ")", ";", "}", "// Redirect to the comment, but check for phishing", "$", "url", "=", "$", "referer", ".", "'#comment-'", ".", "$", "comment", "->", "ID", ";", "// absolute redirection URLs not located on this site may cause phishing", "if", "(", "Director", "::", "is_site_url", "(", "$", "url", ")", ")", "{", "return", "$", "this", "->", "redirect", "(", "$", "url", ")", ";", "}", "return", "false", ";", "}" ]
Redirect back to referer if available, ensuring that only site URLs are allowed to avoid phishing. If it's an AJAX request render the comment in it's new state @param Comment $comment @return DBHTMLText|HTTPResponse|false
[ "Redirect", "back", "to", "referer", "if", "available", "ensuring", "that", "only", "site", "URLs", "are", "allowed", "to", "avoid", "phishing", ".", "If", "it", "s", "an", "AJAX", "request", "render", "the", "comment", "in", "it", "s", "new", "state" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Controllers/CommentingController.php#L385-L407
train
silverstripe/silverstripe-comments
src/Controllers/CommentingController.php
CommentingController.ReplyForm
public function ReplyForm($comment) { // Enables multiple forms with different names to use the same handler $form = $this->CommentsForm(); $form->setName('ReplyForm_' . $comment->ID); $form->setHTMLID(null); $form->addExtraClass('reply-form'); // Load parent into reply form $form->loadDataFrom([ 'ParentCommentID' => $comment->ID ]); // Customise action $form->setFormAction($this->Link('reply', $comment->ID)); $this->extend('updateReplyForm', $form); return $form; }
php
public function ReplyForm($comment) { // Enables multiple forms with different names to use the same handler $form = $this->CommentsForm(); $form->setName('ReplyForm_' . $comment->ID); $form->setHTMLID(null); $form->addExtraClass('reply-form'); // Load parent into reply form $form->loadDataFrom([ 'ParentCommentID' => $comment->ID ]); // Customise action $form->setFormAction($this->Link('reply', $comment->ID)); $this->extend('updateReplyForm', $form); return $form; }
[ "public", "function", "ReplyForm", "(", "$", "comment", ")", "{", "// Enables multiple forms with different names to use the same handler", "$", "form", "=", "$", "this", "->", "CommentsForm", "(", ")", ";", "$", "form", "->", "setName", "(", "'ReplyForm_'", ".", "$", "comment", "->", "ID", ")", ";", "$", "form", "->", "setHTMLID", "(", "null", ")", ";", "$", "form", "->", "addExtraClass", "(", "'reply-form'", ")", ";", "// Load parent into reply form", "$", "form", "->", "loadDataFrom", "(", "[", "'ParentCommentID'", "=>", "$", "comment", "->", "ID", "]", ")", ";", "// Customise action", "$", "form", "->", "setFormAction", "(", "$", "this", "->", "Link", "(", "'reply'", ",", "$", "comment", "->", "ID", ")", ")", ";", "$", "this", "->", "extend", "(", "'updateReplyForm'", ",", "$", "form", ")", ";", "return", "$", "form", ";", "}" ]
Create a reply form for a specified comment @param Comment $comment @return Form
[ "Create", "a", "reply", "form", "for", "a", "specified", "comment" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Controllers/CommentingController.php#L437-L456
train
silverstripe/silverstripe-comments
src/Controllers/CommentingController.php
CommentingController.reply
public function reply(HTTPRequest $request) { // Extract parent comment from reply and build this way if ($parentID = $request->param('ParentCommentID')) { /** @var Comment $comment */ $comment = DataObject::get_by_id(Comment::class, $parentID, true); if ($comment) { return $this->ReplyForm($comment); } } return $this->httpError(404); }
php
public function reply(HTTPRequest $request) { // Extract parent comment from reply and build this way if ($parentID = $request->param('ParentCommentID')) { /** @var Comment $comment */ $comment = DataObject::get_by_id(Comment::class, $parentID, true); if ($comment) { return $this->ReplyForm($comment); } } return $this->httpError(404); }
[ "public", "function", "reply", "(", "HTTPRequest", "$", "request", ")", "{", "// Extract parent comment from reply and build this way", "if", "(", "$", "parentID", "=", "$", "request", "->", "param", "(", "'ParentCommentID'", ")", ")", "{", "/** @var Comment $comment */", "$", "comment", "=", "DataObject", "::", "get_by_id", "(", "Comment", "::", "class", ",", "$", "parentID", ",", "true", ")", ";", "if", "(", "$", "comment", ")", "{", "return", "$", "this", "->", "ReplyForm", "(", "$", "comment", ")", ";", "}", "}", "return", "$", "this", "->", "httpError", "(", "404", ")", ";", "}" ]
Request handler for reply form. This method will disambiguate multiple reply forms in the same method @param HTTPRequest $request @throws HTTPResponse_Exception
[ "Request", "handler", "for", "reply", "form", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Controllers/CommentingController.php#L467-L478
train
silverstripe/silverstripe-comments
src/Controllers/CommentingController.php
CommentingController.CommentsForm
public function CommentsForm() { $form = Injector::inst()->create(CommentForm::class, __FUNCTION__, $this); // hook to allow further extensions to alter the comments form $this->extend('alterCommentForm', $form); return $form; }
php
public function CommentsForm() { $form = Injector::inst()->create(CommentForm::class, __FUNCTION__, $this); // hook to allow further extensions to alter the comments form $this->extend('alterCommentForm', $form); return $form; }
[ "public", "function", "CommentsForm", "(", ")", "{", "$", "form", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "CommentForm", "::", "class", ",", "__FUNCTION__", ",", "$", "this", ")", ";", "// hook to allow further extensions to alter the comments form", "$", "this", "->", "extend", "(", "'alterCommentForm'", ",", "$", "form", ")", ";", "return", "$", "form", ";", "}" ]
Post a comment form @return Form
[ "Post", "a", "comment", "form" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Controllers/CommentingController.php#L485-L493
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.populateDefaults
public function populateDefaults() { $defaults = $this->owner->config()->get('defaults'); // Set if comments should be enabled by default if (isset($defaults['ProvideComments'])) { $this->owner->ProvideComments = $defaults['ProvideComments']; } else { $this->owner->ProvideComments = $this->owner->getCommentsOption('enabled') ? 1 : 0; } // If moderation options should be configurable via the CMS then if (isset($defaults['ModerationRequired'])) { $this->owner->ModerationRequired = $defaults['ModerationRequired']; } elseif ($this->owner->getCommentsOption('require_moderation')) { $this->owner->ModerationRequired = 'Required'; } elseif ($this->owner->getCommentsOption('require_moderation_nonmembers')) { $this->owner->ModerationRequired = 'NonMembersOnly'; } else { $this->owner->ModerationRequired = 'None'; } // Set login required if (isset($defaults['CommentsRequireLogin'])) { $this->owner->CommentsRequireLogin = $defaults['CommentsRequireLogin']; } else { $this->owner->CommentsRequireLogin = $this->owner->getCommentsOption('require_login') ? 1 : 0; } }
php
public function populateDefaults() { $defaults = $this->owner->config()->get('defaults'); // Set if comments should be enabled by default if (isset($defaults['ProvideComments'])) { $this->owner->ProvideComments = $defaults['ProvideComments']; } else { $this->owner->ProvideComments = $this->owner->getCommentsOption('enabled') ? 1 : 0; } // If moderation options should be configurable via the CMS then if (isset($defaults['ModerationRequired'])) { $this->owner->ModerationRequired = $defaults['ModerationRequired']; } elseif ($this->owner->getCommentsOption('require_moderation')) { $this->owner->ModerationRequired = 'Required'; } elseif ($this->owner->getCommentsOption('require_moderation_nonmembers')) { $this->owner->ModerationRequired = 'NonMembersOnly'; } else { $this->owner->ModerationRequired = 'None'; } // Set login required if (isset($defaults['CommentsRequireLogin'])) { $this->owner->CommentsRequireLogin = $defaults['CommentsRequireLogin']; } else { $this->owner->CommentsRequireLogin = $this->owner->getCommentsOption('require_login') ? 1 : 0; } }
[ "public", "function", "populateDefaults", "(", ")", "{", "$", "defaults", "=", "$", "this", "->", "owner", "->", "config", "(", ")", "->", "get", "(", "'defaults'", ")", ";", "// Set if comments should be enabled by default", "if", "(", "isset", "(", "$", "defaults", "[", "'ProvideComments'", "]", ")", ")", "{", "$", "this", "->", "owner", "->", "ProvideComments", "=", "$", "defaults", "[", "'ProvideComments'", "]", ";", "}", "else", "{", "$", "this", "->", "owner", "->", "ProvideComments", "=", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'enabled'", ")", "?", "1", ":", "0", ";", "}", "// If moderation options should be configurable via the CMS then", "if", "(", "isset", "(", "$", "defaults", "[", "'ModerationRequired'", "]", ")", ")", "{", "$", "this", "->", "owner", "->", "ModerationRequired", "=", "$", "defaults", "[", "'ModerationRequired'", "]", ";", "}", "elseif", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'require_moderation'", ")", ")", "{", "$", "this", "->", "owner", "->", "ModerationRequired", "=", "'Required'", ";", "}", "elseif", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'require_moderation_nonmembers'", ")", ")", "{", "$", "this", "->", "owner", "->", "ModerationRequired", "=", "'NonMembersOnly'", ";", "}", "else", "{", "$", "this", "->", "owner", "->", "ModerationRequired", "=", "'None'", ";", "}", "// Set login required", "if", "(", "isset", "(", "$", "defaults", "[", "'CommentsRequireLogin'", "]", ")", ")", "{", "$", "this", "->", "owner", "->", "CommentsRequireLogin", "=", "$", "defaults", "[", "'CommentsRequireLogin'", "]", ";", "}", "else", "{", "$", "this", "->", "owner", "->", "CommentsRequireLogin", "=", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'require_login'", ")", "?", "1", ":", "0", ";", "}", "}" ]
CMS configurable options should default to the config values, but respect default values specified by the object
[ "CMS", "configurable", "options", "should", "default", "to", "the", "config", "values", "but", "respect", "default", "values", "specified", "by", "the", "object" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L113-L141
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.getModerationRequired
public function getModerationRequired() { if ($this->owner->getCommentsOption('require_moderation_cms')) { return $this->owner->getField('ModerationRequired'); } if ($this->owner->getCommentsOption('require_moderation')) { return 'Required'; } if ($this->owner->getCommentsOption('require_moderation_nonmembers')) { return 'NonMembersOnly'; } return 'None'; }
php
public function getModerationRequired() { if ($this->owner->getCommentsOption('require_moderation_cms')) { return $this->owner->getField('ModerationRequired'); } if ($this->owner->getCommentsOption('require_moderation')) { return 'Required'; } if ($this->owner->getCommentsOption('require_moderation_nonmembers')) { return 'NonMembersOnly'; } return 'None'; }
[ "public", "function", "getModerationRequired", "(", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'require_moderation_cms'", ")", ")", "{", "return", "$", "this", "->", "owner", "->", "getField", "(", "'ModerationRequired'", ")", ";", "}", "if", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'require_moderation'", ")", ")", "{", "return", "'Required'", ";", "}", "if", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'require_moderation_nonmembers'", ")", ")", "{", "return", "'NonMembersOnly'", ";", "}", "return", "'None'", ";", "}" ]
Get comment moderation rules for this parent None: No moderation required Required: All comments NonMembersOnly: Only anonymous users @return string
[ "Get", "comment", "moderation", "rules", "for", "this", "parent" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L217-L232
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.getCommentsRequireLogin
public function getCommentsRequireLogin() { if ($this->owner->getCommentsOption('require_login_cms')) { return (bool) $this->owner->getField('CommentsRequireLogin'); } return (bool) $this->owner->getCommentsOption('require_login'); }
php
public function getCommentsRequireLogin() { if ($this->owner->getCommentsOption('require_login_cms')) { return (bool) $this->owner->getField('CommentsRequireLogin'); } return (bool) $this->owner->getCommentsOption('require_login'); }
[ "public", "function", "getCommentsRequireLogin", "(", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'require_login_cms'", ")", ")", "{", "return", "(", "bool", ")", "$", "this", "->", "owner", "->", "getField", "(", "'CommentsRequireLogin'", ")", ";", "}", "return", "(", "bool", ")", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'require_login'", ")", ";", "}" ]
Determine if users must be logged in to post comments @return boolean
[ "Determine", "if", "users", "must", "be", "logged", "in", "to", "post", "comments" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L239-L245
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.AllComments
public function AllComments() { $order = $this->owner->getCommentsOption('order_comments_by'); $comments = Comment::get() ->filter('ParentID', $this->owner->ID) ->sort($order); $this->owner->extend('updateAllComments', $comments); return $comments; }
php
public function AllComments() { $order = $this->owner->getCommentsOption('order_comments_by'); $comments = Comment::get() ->filter('ParentID', $this->owner->ID) ->sort($order); $this->owner->extend('updateAllComments', $comments); return $comments; }
[ "public", "function", "AllComments", "(", ")", "{", "$", "order", "=", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'order_comments_by'", ")", ";", "$", "comments", "=", "Comment", "::", "get", "(", ")", "->", "filter", "(", "'ParentID'", ",", "$", "this", "->", "owner", "->", "ID", ")", "->", "sort", "(", "$", "order", ")", ";", "$", "this", "->", "owner", "->", "extend", "(", "'updateAllComments'", ",", "$", "comments", ")", ";", "return", "$", "comments", ";", "}" ]
Returns the RelationList of all comments against this object. Can be used as a data source for a gridfield with write access. @return DataList
[ "Returns", "the", "RelationList", "of", "all", "comments", "against", "this", "object", ".", "Can", "be", "used", "as", "a", "data", "source", "for", "a", "gridfield", "with", "write", "access", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L253-L261
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.AllVisibleComments
public function AllVisibleComments() { $list = $this->AllComments(); // Filter spam comments for non-administrators if configured $showSpam = $this->owner->getCommentsOption('frontend_spam') && $this->owner->canModerateComments(); if (!$showSpam) { $list = $list->filter('IsSpam', 0); } // Filter un-moderated comments for non-administrators if moderation is enabled $showUnmoderated = ($this->owner->ModerationRequired === 'None') || ($this->owner->getCommentsOption('frontend_moderation') && $this->owner->canModerateComments()); if (!$showUnmoderated) { $list = $list->filter('Moderated', 1); } $this->owner->extend('updateAllVisibleComments', $list); return $list; }
php
public function AllVisibleComments() { $list = $this->AllComments(); // Filter spam comments for non-administrators if configured $showSpam = $this->owner->getCommentsOption('frontend_spam') && $this->owner->canModerateComments(); if (!$showSpam) { $list = $list->filter('IsSpam', 0); } // Filter un-moderated comments for non-administrators if moderation is enabled $showUnmoderated = ($this->owner->ModerationRequired === 'None') || ($this->owner->getCommentsOption('frontend_moderation') && $this->owner->canModerateComments()); if (!$showUnmoderated) { $list = $list->filter('Moderated', 1); } $this->owner->extend('updateAllVisibleComments', $list); return $list; }
[ "public", "function", "AllVisibleComments", "(", ")", "{", "$", "list", "=", "$", "this", "->", "AllComments", "(", ")", ";", "// Filter spam comments for non-administrators if configured", "$", "showSpam", "=", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'frontend_spam'", ")", "&&", "$", "this", "->", "owner", "->", "canModerateComments", "(", ")", ";", "if", "(", "!", "$", "showSpam", ")", "{", "$", "list", "=", "$", "list", "->", "filter", "(", "'IsSpam'", ",", "0", ")", ";", "}", "// Filter un-moderated comments for non-administrators if moderation is enabled", "$", "showUnmoderated", "=", "(", "$", "this", "->", "owner", "->", "ModerationRequired", "===", "'None'", ")", "||", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'frontend_moderation'", ")", "&&", "$", "this", "->", "owner", "->", "canModerateComments", "(", ")", ")", ";", "if", "(", "!", "$", "showUnmoderated", ")", "{", "$", "list", "=", "$", "list", "->", "filter", "(", "'Moderated'", ",", "1", ")", ";", "}", "$", "this", "->", "owner", "->", "extend", "(", "'updateAllVisibleComments'", ",", "$", "list", ")", ";", "return", "$", "list", ";", "}" ]
Returns all comments against this object, with with spam and unmoderated items excluded, for use in the frontend @return DataList
[ "Returns", "all", "comments", "against", "this", "object", "with", "with", "spam", "and", "unmoderated", "items", "excluded", "for", "use", "in", "the", "frontend" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L268-L288
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.Comments
public function Comments() { $list = $this->AllVisibleComments(); // If nesting comments, only show root level if ($this->owner->getCommentsOption('nested_comments')) { $list = $list->filter('ParentCommentID', 0); } $this->owner->extend('updateComments', $list); return $list; }
php
public function Comments() { $list = $this->AllVisibleComments(); // If nesting comments, only show root level if ($this->owner->getCommentsOption('nested_comments')) { $list = $list->filter('ParentCommentID', 0); } $this->owner->extend('updateComments', $list); return $list; }
[ "public", "function", "Comments", "(", ")", "{", "$", "list", "=", "$", "this", "->", "AllVisibleComments", "(", ")", ";", "// If nesting comments, only show root level", "if", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'nested_comments'", ")", ")", "{", "$", "list", "=", "$", "list", "->", "filter", "(", "'ParentCommentID'", ",", "0", ")", ";", "}", "$", "this", "->", "owner", "->", "extend", "(", "'updateComments'", ",", "$", "list", ")", ";", "return", "$", "list", ";", "}" ]
Returns the root level comments, with spam and unmoderated items excluded, for use in the frontend @return DataList
[ "Returns", "the", "root", "level", "comments", "with", "spam", "and", "unmoderated", "items", "excluded", "for", "use", "in", "the", "frontend" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L295-L306
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.PagedComments
public function PagedComments() { $list = $this->Comments(); // Add pagination $list = PaginatedList::create($list, Controller::curr()->getRequest()); $list->setPaginationGetVar('commentsstart' . $this->owner->ID); $list->setPageLength($this->owner->getCommentsOption('comments_per_page')); $this->owner->extend('updatePagedComments', $list); return $list; }
php
public function PagedComments() { $list = $this->Comments(); // Add pagination $list = PaginatedList::create($list, Controller::curr()->getRequest()); $list->setPaginationGetVar('commentsstart' . $this->owner->ID); $list->setPageLength($this->owner->getCommentsOption('comments_per_page')); $this->owner->extend('updatePagedComments', $list); return $list; }
[ "public", "function", "PagedComments", "(", ")", "{", "$", "list", "=", "$", "this", "->", "Comments", "(", ")", ";", "// Add pagination", "$", "list", "=", "PaginatedList", "::", "create", "(", "$", "list", ",", "Controller", "::", "curr", "(", ")", "->", "getRequest", "(", ")", ")", ";", "$", "list", "->", "setPaginationGetVar", "(", "'commentsstart'", ".", "$", "this", "->", "owner", "->", "ID", ")", ";", "$", "list", "->", "setPageLength", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'comments_per_page'", ")", ")", ";", "$", "this", "->", "owner", "->", "extend", "(", "'updatePagedComments'", ",", "$", "list", ")", ";", "return", "$", "list", ";", "}" ]
Returns a paged list of the root level comments, with spam and unmoderated items excluded, for use in the frontend @return PaginatedList
[ "Returns", "a", "paged", "list", "of", "the", "root", "level", "comments", "with", "spam", "and", "unmoderated", "items", "excluded", "for", "use", "in", "the", "frontend" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L314-L325
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.getCommentsEnabled
public function getCommentsEnabled() { // Don't display comments form for pseudo-pages (such as the login form) if (!$this->owner->exists()) { return false; } // Determine which flag should be used to determine if this is enabled if ($this->owner->getCommentsOption('enabled_cms')) { return (bool) $this->owner->ProvideComments; } return (bool) $this->owner->getCommentsOption('enabled'); }
php
public function getCommentsEnabled() { // Don't display comments form for pseudo-pages (such as the login form) if (!$this->owner->exists()) { return false; } // Determine which flag should be used to determine if this is enabled if ($this->owner->getCommentsOption('enabled_cms')) { return (bool) $this->owner->ProvideComments; } return (bool) $this->owner->getCommentsOption('enabled'); }
[ "public", "function", "getCommentsEnabled", "(", ")", "{", "// Don't display comments form for pseudo-pages (such as the login form)", "if", "(", "!", "$", "this", "->", "owner", "->", "exists", "(", ")", ")", "{", "return", "false", ";", "}", "// Determine which flag should be used to determine if this is enabled", "if", "(", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'enabled_cms'", ")", ")", "{", "return", "(", "bool", ")", "$", "this", "->", "owner", "->", "ProvideComments", ";", "}", "return", "(", "bool", ")", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'enabled'", ")", ";", "}" ]
Determine if comments are enabled for this instance @return boolean
[ "Determine", "if", "comments", "are", "enabled", "for", "this", "instance" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L332-L345
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.canPostComment
public function canPostComment($member = null) { // Deny if not enabled for this object if (!$this->owner->CommentsEnabled) { return false; } if (!$this->owner->canView($member)) { // deny if current user cannot view the underlying record. return false; } // Check if member is required $requireLogin = $this->owner->CommentsRequireLogin; if (!$requireLogin) { return true; } // Check member is logged in $member = $member ?: Security::getCurrentUser(); if (!$member) { return false; } // If member required check permissions $requiredPermission = $this->owner->PostingRequiredPermission; if ($requiredPermission && !Permission::checkMember($member, $requiredPermission)) { return false; } return true; }
php
public function canPostComment($member = null) { // Deny if not enabled for this object if (!$this->owner->CommentsEnabled) { return false; } if (!$this->owner->canView($member)) { // deny if current user cannot view the underlying record. return false; } // Check if member is required $requireLogin = $this->owner->CommentsRequireLogin; if (!$requireLogin) { return true; } // Check member is logged in $member = $member ?: Security::getCurrentUser(); if (!$member) { return false; } // If member required check permissions $requiredPermission = $this->owner->PostingRequiredPermission; if ($requiredPermission && !Permission::checkMember($member, $requiredPermission)) { return false; } return true; }
[ "public", "function", "canPostComment", "(", "$", "member", "=", "null", ")", "{", "// Deny if not enabled for this object", "if", "(", "!", "$", "this", "->", "owner", "->", "CommentsEnabled", ")", "{", "return", "false", ";", "}", "if", "(", "!", "$", "this", "->", "owner", "->", "canView", "(", "$", "member", ")", ")", "{", "// deny if current user cannot view the underlying record.", "return", "false", ";", "}", "// Check if member is required", "$", "requireLogin", "=", "$", "this", "->", "owner", "->", "CommentsRequireLogin", ";", "if", "(", "!", "$", "requireLogin", ")", "{", "return", "true", ";", "}", "// Check member is logged in", "$", "member", "=", "$", "member", "?", ":", "Security", "::", "getCurrentUser", "(", ")", ";", "if", "(", "!", "$", "member", ")", "{", "return", "false", ";", "}", "// If member required check permissions", "$", "requiredPermission", "=", "$", "this", "->", "owner", "->", "PostingRequiredPermission", ";", "if", "(", "$", "requiredPermission", "&&", "!", "Permission", "::", "checkMember", "(", "$", "member", ",", "$", "requiredPermission", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determine if a user can post comments on this item @param Member $member Member to check @return boolean
[ "Determine", "if", "a", "user", "can", "post", "comments", "on", "this", "item" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L374-L405
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.canModerateComments
public function canModerateComments($member = null) { // Deny if not enabled for this object if (!$this->owner->CommentsEnabled) { return false; } // Fallback to can-edit return $this->owner->canEdit($member); }
php
public function canModerateComments($member = null) { // Deny if not enabled for this object if (!$this->owner->CommentsEnabled) { return false; } // Fallback to can-edit return $this->owner->canEdit($member); }
[ "public", "function", "canModerateComments", "(", "$", "member", "=", "null", ")", "{", "// Deny if not enabled for this object", "if", "(", "!", "$", "this", "->", "owner", "->", "CommentsEnabled", ")", "{", "return", "false", ";", "}", "// Fallback to can-edit", "return", "$", "this", "->", "owner", "->", "canEdit", "(", "$", "member", ")", ";", "}" ]
Determine if this member can moderate comments in the CMS @param Member $member @return boolean
[ "Determine", "if", "this", "member", "can", "moderate", "comments", "in", "the", "CMS" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L414-L423
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.getCommentRSSLinkPage
public function getCommentRSSLinkPage() { return Controller::join_links( $this->getCommentRSSLink(), str_replace('\\', '-', get_class($this->owner)), $this->owner->ID ); }
php
public function getCommentRSSLinkPage() { return Controller::join_links( $this->getCommentRSSLink(), str_replace('\\', '-', get_class($this->owner)), $this->owner->ID ); }
[ "public", "function", "getCommentRSSLinkPage", "(", ")", "{", "return", "Controller", "::", "join_links", "(", "$", "this", "->", "getCommentRSSLink", "(", ")", ",", "str_replace", "(", "'\\\\'", ",", "'-'", ",", "get_class", "(", "$", "this", "->", "owner", ")", ")", ",", "$", "this", "->", "owner", "->", "ID", ")", ";", "}" ]
Get the RSS link to all comments on this page @return string
[ "Get", "the", "RSS", "link", "to", "all", "comments", "on", "this", "page" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L440-L447
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.CommentsForm
public function CommentsForm() { // Check if enabled $enabled = $this->getCommentsEnabled(); if ($enabled && $this->owner->getCommentsOption('include_js')) { Requirements::javascript('//code.jquery.com/jquery-3.3.1.min.js'); Requirements::javascript('silverstripe/comments:thirdparty/jquery-validate/jquery.validate.min.js'); Requirements::javascript('silverstripe/admin:client/dist/js/i18n.js'); Requirements::add_i18n_javascript('silverstripe/comments:javascript/lang'); Requirements::javascript('silverstripe/comments:javascript/CommentsInterface.js'); } $controller = CommentingController::create(); $controller->setOwnerRecord($this->owner); $controller->setParentClass($this->owner->getClassName()); $controller->setOwnerController(Controller::curr()); $session = Controller::curr()->getRequest()->getSession(); $moderatedSubmitted = $session->get('CommentsModerated'); $session->clear('CommentsModerated'); $form = ($enabled) ? $controller->CommentsForm() : false; // a little bit all over the show but to ensure a slightly easier upgrade for users // return back the same variables as previously done in comments return $this ->owner ->customise([ 'AddCommentForm' => $form, 'ModeratedSubmitted' => $moderatedSubmitted, ]) ->renderWith('CommentsInterface'); }
php
public function CommentsForm() { // Check if enabled $enabled = $this->getCommentsEnabled(); if ($enabled && $this->owner->getCommentsOption('include_js')) { Requirements::javascript('//code.jquery.com/jquery-3.3.1.min.js'); Requirements::javascript('silverstripe/comments:thirdparty/jquery-validate/jquery.validate.min.js'); Requirements::javascript('silverstripe/admin:client/dist/js/i18n.js'); Requirements::add_i18n_javascript('silverstripe/comments:javascript/lang'); Requirements::javascript('silverstripe/comments:javascript/CommentsInterface.js'); } $controller = CommentingController::create(); $controller->setOwnerRecord($this->owner); $controller->setParentClass($this->owner->getClassName()); $controller->setOwnerController(Controller::curr()); $session = Controller::curr()->getRequest()->getSession(); $moderatedSubmitted = $session->get('CommentsModerated'); $session->clear('CommentsModerated'); $form = ($enabled) ? $controller->CommentsForm() : false; // a little bit all over the show but to ensure a slightly easier upgrade for users // return back the same variables as previously done in comments return $this ->owner ->customise([ 'AddCommentForm' => $form, 'ModeratedSubmitted' => $moderatedSubmitted, ]) ->renderWith('CommentsInterface'); }
[ "public", "function", "CommentsForm", "(", ")", "{", "// Check if enabled", "$", "enabled", "=", "$", "this", "->", "getCommentsEnabled", "(", ")", ";", "if", "(", "$", "enabled", "&&", "$", "this", "->", "owner", "->", "getCommentsOption", "(", "'include_js'", ")", ")", "{", "Requirements", "::", "javascript", "(", "'//code.jquery.com/jquery-3.3.1.min.js'", ")", ";", "Requirements", "::", "javascript", "(", "'silverstripe/comments:thirdparty/jquery-validate/jquery.validate.min.js'", ")", ";", "Requirements", "::", "javascript", "(", "'silverstripe/admin:client/dist/js/i18n.js'", ")", ";", "Requirements", "::", "add_i18n_javascript", "(", "'silverstripe/comments:javascript/lang'", ")", ";", "Requirements", "::", "javascript", "(", "'silverstripe/comments:javascript/CommentsInterface.js'", ")", ";", "}", "$", "controller", "=", "CommentingController", "::", "create", "(", ")", ";", "$", "controller", "->", "setOwnerRecord", "(", "$", "this", "->", "owner", ")", ";", "$", "controller", "->", "setParentClass", "(", "$", "this", "->", "owner", "->", "getClassName", "(", ")", ")", ";", "$", "controller", "->", "setOwnerController", "(", "Controller", "::", "curr", "(", ")", ")", ";", "$", "session", "=", "Controller", "::", "curr", "(", ")", "->", "getRequest", "(", ")", "->", "getSession", "(", ")", ";", "$", "moderatedSubmitted", "=", "$", "session", "->", "get", "(", "'CommentsModerated'", ")", ";", "$", "session", "->", "clear", "(", "'CommentsModerated'", ")", ";", "$", "form", "=", "(", "$", "enabled", ")", "?", "$", "controller", "->", "CommentsForm", "(", ")", ":", "false", ";", "// a little bit all over the show but to ensure a slightly easier upgrade for users", "// return back the same variables as previously done in comments", "return", "$", "this", "->", "owner", "->", "customise", "(", "[", "'AddCommentForm'", "=>", "$", "form", ",", "'ModeratedSubmitted'", "=>", "$", "moderatedSubmitted", ",", "]", ")", "->", "renderWith", "(", "'CommentsInterface'", ")", ";", "}" ]
Comments interface for the front end. Includes the CommentAddForm and the composition of the comments display. To customize the html see templates/CommentInterface.ss or extend this function with your own extension. @todo Cleanup the passing of all this configuration based functionality @see docs/en/Extending
[ "Comments", "interface", "for", "the", "front", "end", ".", "Includes", "the", "CommentAddForm", "and", "the", "composition", "of", "the", "comments", "display", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L460-L492
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.getCommentsOption
public function getCommentsOption($key) { $settings = $this->getCommentsOptions(); $value = null; if (isset($settings[$key])) { $value = $settings[$key]; } // To allow other extensions to customise this option if ($this->owner) { $this->owner->extend('updateCommentsOption', $key, $value); } return $value; }
php
public function getCommentsOption($key) { $settings = $this->getCommentsOptions(); $value = null; if (isset($settings[$key])) { $value = $settings[$key]; } // To allow other extensions to customise this option if ($this->owner) { $this->owner->extend('updateCommentsOption', $key, $value); } return $value; }
[ "public", "function", "getCommentsOption", "(", "$", "key", ")", "{", "$", "settings", "=", "$", "this", "->", "getCommentsOptions", "(", ")", ";", "$", "value", "=", "null", ";", "if", "(", "isset", "(", "$", "settings", "[", "$", "key", "]", ")", ")", "{", "$", "value", "=", "$", "settings", "[", "$", "key", "]", ";", "}", "// To allow other extensions to customise this option", "if", "(", "$", "this", "->", "owner", ")", "{", "$", "this", "->", "owner", "->", "extend", "(", "'updateCommentsOption'", ",", "$", "key", ",", "$", "value", ")", ";", "}", "return", "$", "value", ";", "}" ]
Get the commenting option for this object. This can be overridden in any instance or extension to customise the option available. @param string $key @return mixed Result if the setting is available, or null otherwise
[ "Get", "the", "commenting", "option", "for", "this", "object", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L516-L531
train
silverstripe/silverstripe-comments
src/Extensions/CommentsExtension.php
CommentsExtension.updateModerationFields
protected function updateModerationFields(FieldList $fields) { Requirements::css('silverstripe/comments:css/cms.css'); $newComments = $this->owner->AllComments()->filter('Moderated', 0); $newGrid = CommentsGridField::create( 'NewComments', _t('CommentsAdmin.NewComments', 'New'), $newComments, CommentsGridFieldConfig::create() ); $approvedComments = $this->owner->AllComments()->filter('Moderated', 1)->filter('IsSpam', 0); $approvedGrid = new CommentsGridField( 'ApprovedComments', _t('CommentsAdmin.Comments', 'Approved'), $approvedComments, CommentsGridFieldConfig::create() ); $spamComments = $this->owner->AllComments()->filter('Moderated', 1)->filter('IsSpam', 1); $spamGrid = CommentsGridField::create( 'SpamComments', _t('CommentsAdmin.SpamComments', 'Spam'), $spamComments, CommentsGridFieldConfig::create() ); $newCount = '(' . count($newComments) . ')'; $approvedCount = '(' . count($approvedComments) . ')'; $spamCount = '(' . count($spamComments) . ')'; if ($fields->hasTabSet()) { $tabs = TabSet::create( 'Comments', Tab::create( 'CommentsNewCommentsTab', _t('SilverStripe\\Comments\\Admin\\CommentAdmin.NewComments', 'New') . ' ' . $newCount, $newGrid ), Tab::create( 'CommentsCommentsTab', _t('SilverStripe\\Comments\\Admin\\CommentAdmin.Comments', 'Approved') . ' ' . $approvedCount, $approvedGrid ), Tab::create( 'CommentsSpamCommentsTab', _t('SilverStripe\\Comments\\Admin\\CommentAdmin.SpamComments', 'Spam') . ' ' . $spamCount, $spamGrid ) ); $tabs->setTitle(_t(__CLASS__ . '.COMMENTSTABSET', 'Comments')); $fields->addFieldToTab('Root', $tabs); } else { $fields->push($newGrid); $fields->push($approvedGrid); $fields->push($spamGrid); } }
php
protected function updateModerationFields(FieldList $fields) { Requirements::css('silverstripe/comments:css/cms.css'); $newComments = $this->owner->AllComments()->filter('Moderated', 0); $newGrid = CommentsGridField::create( 'NewComments', _t('CommentsAdmin.NewComments', 'New'), $newComments, CommentsGridFieldConfig::create() ); $approvedComments = $this->owner->AllComments()->filter('Moderated', 1)->filter('IsSpam', 0); $approvedGrid = new CommentsGridField( 'ApprovedComments', _t('CommentsAdmin.Comments', 'Approved'), $approvedComments, CommentsGridFieldConfig::create() ); $spamComments = $this->owner->AllComments()->filter('Moderated', 1)->filter('IsSpam', 1); $spamGrid = CommentsGridField::create( 'SpamComments', _t('CommentsAdmin.SpamComments', 'Spam'), $spamComments, CommentsGridFieldConfig::create() ); $newCount = '(' . count($newComments) . ')'; $approvedCount = '(' . count($approvedComments) . ')'; $spamCount = '(' . count($spamComments) . ')'; if ($fields->hasTabSet()) { $tabs = TabSet::create( 'Comments', Tab::create( 'CommentsNewCommentsTab', _t('SilverStripe\\Comments\\Admin\\CommentAdmin.NewComments', 'New') . ' ' . $newCount, $newGrid ), Tab::create( 'CommentsCommentsTab', _t('SilverStripe\\Comments\\Admin\\CommentAdmin.Comments', 'Approved') . ' ' . $approvedCount, $approvedGrid ), Tab::create( 'CommentsSpamCommentsTab', _t('SilverStripe\\Comments\\Admin\\CommentAdmin.SpamComments', 'Spam') . ' ' . $spamCount, $spamGrid ) ); $tabs->setTitle(_t(__CLASS__ . '.COMMENTSTABSET', 'Comments')); $fields->addFieldToTab('Root', $tabs); } else { $fields->push($newGrid); $fields->push($approvedGrid); $fields->push($spamGrid); } }
[ "protected", "function", "updateModerationFields", "(", "FieldList", "$", "fields", ")", "{", "Requirements", "::", "css", "(", "'silverstripe/comments:css/cms.css'", ")", ";", "$", "newComments", "=", "$", "this", "->", "owner", "->", "AllComments", "(", ")", "->", "filter", "(", "'Moderated'", ",", "0", ")", ";", "$", "newGrid", "=", "CommentsGridField", "::", "create", "(", "'NewComments'", ",", "_t", "(", "'CommentsAdmin.NewComments'", ",", "'New'", ")", ",", "$", "newComments", ",", "CommentsGridFieldConfig", "::", "create", "(", ")", ")", ";", "$", "approvedComments", "=", "$", "this", "->", "owner", "->", "AllComments", "(", ")", "->", "filter", "(", "'Moderated'", ",", "1", ")", "->", "filter", "(", "'IsSpam'", ",", "0", ")", ";", "$", "approvedGrid", "=", "new", "CommentsGridField", "(", "'ApprovedComments'", ",", "_t", "(", "'CommentsAdmin.Comments'", ",", "'Approved'", ")", ",", "$", "approvedComments", ",", "CommentsGridFieldConfig", "::", "create", "(", ")", ")", ";", "$", "spamComments", "=", "$", "this", "->", "owner", "->", "AllComments", "(", ")", "->", "filter", "(", "'Moderated'", ",", "1", ")", "->", "filter", "(", "'IsSpam'", ",", "1", ")", ";", "$", "spamGrid", "=", "CommentsGridField", "::", "create", "(", "'SpamComments'", ",", "_t", "(", "'CommentsAdmin.SpamComments'", ",", "'Spam'", ")", ",", "$", "spamComments", ",", "CommentsGridFieldConfig", "::", "create", "(", ")", ")", ";", "$", "newCount", "=", "'('", ".", "count", "(", "$", "newComments", ")", ".", "')'", ";", "$", "approvedCount", "=", "'('", ".", "count", "(", "$", "approvedComments", ")", ".", "')'", ";", "$", "spamCount", "=", "'('", ".", "count", "(", "$", "spamComments", ")", ".", "')'", ";", "if", "(", "$", "fields", "->", "hasTabSet", "(", ")", ")", "{", "$", "tabs", "=", "TabSet", "::", "create", "(", "'Comments'", ",", "Tab", "::", "create", "(", "'CommentsNewCommentsTab'", ",", "_t", "(", "'SilverStripe\\\\Comments\\\\Admin\\\\CommentAdmin.NewComments'", ",", "'New'", ")", ".", "' '", ".", "$", "newCount", ",", "$", "newGrid", ")", ",", "Tab", "::", "create", "(", "'CommentsCommentsTab'", ",", "_t", "(", "'SilverStripe\\\\Comments\\\\Admin\\\\CommentAdmin.Comments'", ",", "'Approved'", ")", ".", "' '", ".", "$", "approvedCount", ",", "$", "approvedGrid", ")", ",", "Tab", "::", "create", "(", "'CommentsSpamCommentsTab'", ",", "_t", "(", "'SilverStripe\\\\Comments\\\\Admin\\\\CommentAdmin.SpamComments'", ",", "'Spam'", ")", ".", "' '", ".", "$", "spamCount", ",", "$", "spamGrid", ")", ")", ";", "$", "tabs", "->", "setTitle", "(", "_t", "(", "__CLASS__", ".", "'.COMMENTSTABSET'", ",", "'Comments'", ")", ")", ";", "$", "fields", "->", "addFieldToTab", "(", "'Root'", ",", "$", "tabs", ")", ";", "}", "else", "{", "$", "fields", "->", "push", "(", "$", "newGrid", ")", ";", "$", "fields", "->", "push", "(", "$", "approvedGrid", ")", ";", "$", "fields", "->", "push", "(", "$", "spamGrid", ")", ";", "}", "}" ]
Add moderation functions to the current fieldlist @param FieldList $fields
[ "Add", "moderation", "functions", "to", "the", "current", "fieldlist" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Extensions/CommentsExtension.php#L552-L614
train
silverstripe/silverstripe-comments
src/Admin/CommentsGridFieldApproveAction.php
CommentsGridFieldApproveAction.getApproveAction
public function getApproveAction($gridField, $record, $columnName) { $field = GridField_FormAction::create( $gridField, 'CustomAction' . $record->ID . 'Approve', _t(__CLASS__ . '.APPROVE', 'Approve'), 'approve', ['RecordID' => $record->ID] ) ->addExtraClass(implode(' ', [ 'btn', 'btn-secondary', 'grid-field__icon-action', 'action-menu--handled', 'font-icon-check-mark', ])) ->setAttribute('classNames', 'font-icon-check-mark'); return ($record->IsSpam || !$record->Moderated) ? $field : null; }
php
public function getApproveAction($gridField, $record, $columnName) { $field = GridField_FormAction::create( $gridField, 'CustomAction' . $record->ID . 'Approve', _t(__CLASS__ . '.APPROVE', 'Approve'), 'approve', ['RecordID' => $record->ID] ) ->addExtraClass(implode(' ', [ 'btn', 'btn-secondary', 'grid-field__icon-action', 'action-menu--handled', 'font-icon-check-mark', ])) ->setAttribute('classNames', 'font-icon-check-mark'); return ($record->IsSpam || !$record->Moderated) ? $field : null; }
[ "public", "function", "getApproveAction", "(", "$", "gridField", ",", "$", "record", ",", "$", "columnName", ")", "{", "$", "field", "=", "GridField_FormAction", "::", "create", "(", "$", "gridField", ",", "'CustomAction'", ".", "$", "record", "->", "ID", ".", "'Approve'", ",", "_t", "(", "__CLASS__", ".", "'.APPROVE'", ",", "'Approve'", ")", ",", "'approve'", ",", "[", "'RecordID'", "=>", "$", "record", "->", "ID", "]", ")", "->", "addExtraClass", "(", "implode", "(", "' '", ",", "[", "'btn'", ",", "'btn-secondary'", ",", "'grid-field__icon-action'", ",", "'action-menu--handled'", ",", "'font-icon-check-mark'", ",", "]", ")", ")", "->", "setAttribute", "(", "'classNames'", ",", "'font-icon-check-mark'", ")", ";", "return", "(", "$", "record", "->", "IsSpam", "||", "!", "$", "record", "->", "Moderated", ")", "?", "$", "field", ":", "null", ";", "}" ]
Returns the FormAction object, used by other methods to get properties @return GridField_FormAction|null
[ "Returns", "the", "FormAction", "object", "used", "by", "other", "methods", "to", "get", "properties" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Admin/CommentsGridFieldApproveAction.php#L96-L115
train
silverstripe/silverstripe-comments
src/Model/Comment/SecurityToken.php
SecurityToken.generate
protected function generate($length = null) { $generator = new RandomGenerator(); $result = $generator->randomToken('sha256'); if ($length !== null) { return substr($result, 0, $length); } return $result; }
php
protected function generate($length = null) { $generator = new RandomGenerator(); $result = $generator->randomToken('sha256'); if ($length !== null) { return substr($result, 0, $length); } return $result; }
[ "protected", "function", "generate", "(", "$", "length", "=", "null", ")", "{", "$", "generator", "=", "new", "RandomGenerator", "(", ")", ";", "$", "result", "=", "$", "generator", "->", "randomToken", "(", "'sha256'", ")", ";", "if", "(", "$", "length", "!==", "null", ")", "{", "return", "substr", "(", "$", "result", ",", "0", ",", "$", "length", ")", ";", "}", "return", "$", "result", ";", "}" ]
Generates new random key @param integer $length @return string
[ "Generates", "new", "random", "key" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment/SecurityToken.php#L111-L119
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.Link
public function Link($action = '') { if ($parent = $this->Parent()) { return $parent->Link($action) . '#' . $this->Permalink(); } }
php
public function Link($action = '') { if ($parent = $this->Parent()) { return $parent->Link($action) . '#' . $this->Permalink(); } }
[ "public", "function", "Link", "(", "$", "action", "=", "''", ")", "{", "if", "(", "$", "parent", "=", "$", "this", "->", "Parent", "(", ")", ")", "{", "return", "$", "parent", "->", "Link", "(", "$", "action", ")", ".", "'#'", ".", "$", "this", "->", "Permalink", "(", ")", ";", "}", "}" ]
Return a link to this comment @param string $action @return string link to this comment.
[ "Return", "a", "link", "to", "this", "comment" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L192-L197
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.getOption
public function getOption($key) { // If possible use the current record $record = $this->Parent(); if (!$record && $this->Parent()) { // Otherwise a singleton of that record $record = singleton($this->Parent()->dataClass()); } elseif (!$record) { // Otherwise just use the default options $record = singleton(CommentsExtension::class); } return ($record instanceof CommentsExtension || $record->hasExtension(CommentsExtension::class)) ? $record->getCommentsOption($key) : null; }
php
public function getOption($key) { // If possible use the current record $record = $this->Parent(); if (!$record && $this->Parent()) { // Otherwise a singleton of that record $record = singleton($this->Parent()->dataClass()); } elseif (!$record) { // Otherwise just use the default options $record = singleton(CommentsExtension::class); } return ($record instanceof CommentsExtension || $record->hasExtension(CommentsExtension::class)) ? $record->getCommentsOption($key) : null; }
[ "public", "function", "getOption", "(", "$", "key", ")", "{", "// If possible use the current record", "$", "record", "=", "$", "this", "->", "Parent", "(", ")", ";", "if", "(", "!", "$", "record", "&&", "$", "this", "->", "Parent", "(", ")", ")", "{", "// Otherwise a singleton of that record", "$", "record", "=", "singleton", "(", "$", "this", "->", "Parent", "(", ")", "->", "dataClass", "(", ")", ")", ";", "}", "elseif", "(", "!", "$", "record", ")", "{", "// Otherwise just use the default options", "$", "record", "=", "singleton", "(", "CommentsExtension", "::", "class", ")", ";", "}", "return", "(", "$", "record", "instanceof", "CommentsExtension", "||", "$", "record", "->", "hasExtension", "(", "CommentsExtension", "::", "class", ")", ")", "?", "$", "record", "->", "getCommentsOption", "(", "$", "key", ")", ":", "null", ";", "}" ]
Get the commenting option @param string $key @return mixed Result if the setting is available, or null otherwise
[ "Get", "the", "commenting", "option" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L241-L257
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.getParentTitle
public function getParentTitle() { if ($parent = $this->Parent()) { return $parent->Title ?: ($parent->ClassName . ' #' . $parent->ID); } }
php
public function getParentTitle() { if ($parent = $this->Parent()) { return $parent->Title ?: ($parent->ClassName . ' #' . $parent->ID); } }
[ "public", "function", "getParentTitle", "(", ")", "{", "if", "(", "$", "parent", "=", "$", "this", "->", "Parent", "(", ")", ")", "{", "return", "$", "parent", "->", "Title", "?", ":", "(", "$", "parent", "->", "ClassName", ".", "' #'", ".", "$", "parent", "->", "ID", ")", ";", "}", "}" ]
Returns a string to help identify the parent of the comment @return string
[ "Returns", "a", "string", "to", "help", "identify", "the", "parent", "of", "the", "comment" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L278-L283
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.canEdit
public function canEdit($member = null) { $member = $this->getMember($member); if (!$member) { return false; } $extended = $this->extendedCan('canEdit', $member); if ($extended !== null) { return $extended; } if (Permission::checkMember($member, 'CMS_ACCESS_CommentAdmin')) { return true; } if ($parent = $this->Parent()) { return $parent->canEdit($member); } return false; }
php
public function canEdit($member = null) { $member = $this->getMember($member); if (!$member) { return false; } $extended = $this->extendedCan('canEdit', $member); if ($extended !== null) { return $extended; } if (Permission::checkMember($member, 'CMS_ACCESS_CommentAdmin')) { return true; } if ($parent = $this->Parent()) { return $parent->canEdit($member); } return false; }
[ "public", "function", "canEdit", "(", "$", "member", "=", "null", ")", "{", "$", "member", "=", "$", "this", "->", "getMember", "(", "$", "member", ")", ";", "if", "(", "!", "$", "member", ")", "{", "return", "false", ";", "}", "$", "extended", "=", "$", "this", "->", "extendedCan", "(", "'canEdit'", ",", "$", "member", ")", ";", "if", "(", "$", "extended", "!==", "null", ")", "{", "return", "$", "extended", ";", "}", "if", "(", "Permission", "::", "checkMember", "(", "$", "member", ",", "'CMS_ACCESS_CommentAdmin'", ")", ")", "{", "return", "true", ";", "}", "if", "(", "$", "parent", "=", "$", "this", "->", "Parent", "(", ")", ")", "{", "return", "$", "parent", "->", "canEdit", "(", "$", "member", ")", ";", "}", "return", "false", ";", "}" ]
Checks if the comment can be edited. @param null|int|Member $member @return Boolean
[ "Checks", "if", "the", "comment", "can", "be", "edited", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L374-L396
train