repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.updateBinary
public function updateBinary(StreamInterface $resource, $name, $destinationPath, $id = '') { $metaData = ['path' => $destinationPath]; if (!empty($id)) { if (!static::isIdValid($id)) { throw new Exception('Id is invalid, please use a correctly formatted id'); } return $this->doPut('File.json/crud/' . $id, [], [ 'filename' => $name, 'length' => $resource->getSize(), 'uploadDate' => date('c'), 'metadata' => $metaData, 'content' => base64_encode($resource->getContents()), ]); } $options = [ 'multipart' => [ [ 'name' => 'File', 'filename' => $name, 'contents' => $resource ], [ 'name' => 'metadata', 'contents' => json_encode($metaData), ] ] ]; $response = $this->call('post', ['File.json/binary', $options]); return $this->parseResult($response->getBody(), $response->getStatusCode()); }
php
public function updateBinary(StreamInterface $resource, $name, $destinationPath, $id = '') { $metaData = ['path' => $destinationPath]; if (!empty($id)) { if (!static::isIdValid($id)) { throw new Exception('Id is invalid, please use a correctly formatted id'); } return $this->doPut('File.json/crud/' . $id, [], [ 'filename' => $name, 'length' => $resource->getSize(), 'uploadDate' => date('c'), 'metadata' => $metaData, 'content' => base64_encode($resource->getContents()), ]); } $options = [ 'multipart' => [ [ 'name' => 'File', 'filename' => $name, 'contents' => $resource ], [ 'name' => 'metadata', 'contents' => json_encode($metaData), ] ] ]; $response = $this->call('post', ['File.json/binary', $options]); return $this->parseResult($response->getBody(), $response->getStatusCode()); }
[ "public", "function", "updateBinary", "(", "StreamInterface", "$", "resource", ",", "$", "name", ",", "$", "destinationPath", ",", "$", "id", "=", "''", ")", "{", "$", "metaData", "=", "[", "'path'", "=>", "$", "destinationPath", "]", ";", "if", "(", "!", "empty", "(", "$", "id", ")", ")", "{", "if", "(", "!", "static", "::", "isIdValid", "(", "$", "id", ")", ")", "{", "throw", "new", "Exception", "(", "'Id is invalid, please use a correctly formatted id'", ")", ";", "}", "return", "$", "this", "->", "doPut", "(", "'File.json/crud/'", ".", "$", "id", ",", "[", "]", ",", "[", "'filename'", "=>", "$", "name", ",", "'length'", "=>", "$", "resource", "->", "getSize", "(", ")", ",", "'uploadDate'", "=>", "date", "(", "'c'", ")", ",", "'metadata'", "=>", "$", "metaData", ",", "'content'", "=>", "base64_encode", "(", "$", "resource", "->", "getContents", "(", ")", ")", ",", "]", ")", ";", "}", "$", "options", "=", "[", "'multipart'", "=>", "[", "[", "'name'", "=>", "'File'", ",", "'filename'", "=>", "$", "name", ",", "'contents'", "=>", "$", "resource", "]", ",", "[", "'name'", "=>", "'metadata'", ",", "'contents'", "=>", "json_encode", "(", "$", "metaData", ")", ",", "]", "]", "]", ";", "$", "response", "=", "$", "this", "->", "call", "(", "'post'", ",", "[", "'File.json/binary'", ",", "$", "options", "]", ")", ";", "return", "$", "this", "->", "parseResult", "(", "$", "response", "->", "getBody", "(", ")", ",", "$", "response", "->", "getStatusCode", "(", ")", ")", ";", "}" ]
Uploads the contents of the resource (this could be a file handle) to Communibase @param StreamInterface $resource @param string $name @param string $destinationPath @param string $id @return array|mixed @throws \RuntimeException | Exception
[ "Uploads", "the", "contents", "of", "the", "resource", "(", "this", "could", "be", "a", "file", "handle", ")", "to", "Communibase" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L415-L449
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.doGet
protected function doGet($path, array $params = null, array $data = null) { return $this->getResult('GET', $path, $params, $data); }
php
protected function doGet($path, array $params = null, array $data = null) { return $this->getResult('GET', $path, $params, $data); }
[ "protected", "function", "doGet", "(", "$", "path", ",", "array", "$", "params", "=", "null", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "getResult", "(", "'GET'", ",", "$", "path", ",", "$", "params", ",", "$", "data", ")", ";", "}" ]
Perform the actual GET @param string $path @param array $params @param array $data @return array @throws Exception
[ "Perform", "the", "actual", "GET" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L462-L465
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.doPost
protected function doPost($path, array $params = null, array $data = null) { return $this->getResult('POST', $path, $params, $data); }
php
protected function doPost($path, array $params = null, array $data = null) { return $this->getResult('POST', $path, $params, $data); }
[ "protected", "function", "doPost", "(", "$", "path", ",", "array", "$", "params", "=", "null", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "getResult", "(", "'POST'", ",", "$", "path", ",", "$", "params", ",", "$", "data", ")", ";", "}" ]
Perform the actual POST @param string $path @param array $params @param array $data @return array @throws Exception
[ "Perform", "the", "actual", "POST" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L478-L481
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.doPut
protected function doPut($path, array $params = null, array $data = null) { return $this->getResult('PUT', $path, $params, $data); }
php
protected function doPut($path, array $params = null, array $data = null) { return $this->getResult('PUT', $path, $params, $data); }
[ "protected", "function", "doPut", "(", "$", "path", ",", "array", "$", "params", "=", "null", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "getResult", "(", "'PUT'", ",", "$", "path", ",", "$", "params", ",", "$", "data", ")", ";", "}" ]
Perform the actual PUT @param string $path @param array $params @param array $data @return array @throws Exception
[ "Perform", "the", "actual", "PUT" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L494-L497
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.doDelete
protected function doDelete($path, array $params = null, array $data = null) { return $this->getResult('DELETE', $path, $params, $data); }
php
protected function doDelete($path, array $params = null, array $data = null) { return $this->getResult('DELETE', $path, $params, $data); }
[ "protected", "function", "doDelete", "(", "$", "path", ",", "array", "$", "params", "=", "null", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "getResult", "(", "'DELETE'", ",", "$", "path", ",", "$", "params", ",", "$", "data", ")", ";", "}" ]
Perform the actual DELETE @param string $path @param array $params @param array $data @return array @throws Exception
[ "Perform", "the", "actual", "DELETE" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L510-L513
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getResult
protected function getResult($method, $path, array $params = null, array $data = null) { if ($params === null) { $params = []; } $options = [ 'query' => $this->preParseParams($params), ]; if (is_array($data) && count($data) > 0) { $options['json'] = $data; } $response = $this->call($method, [$path, $options]); $responseData = $this->parseResult($response->getBody(), $response->getStatusCode()); if ($response->getStatusCode() !== 200) { throw new Exception( $responseData['message'], $responseData['code'], null, (($_ =& $responseData['errors']) ?: []) ); } return $responseData; }
php
protected function getResult($method, $path, array $params = null, array $data = null) { if ($params === null) { $params = []; } $options = [ 'query' => $this->preParseParams($params), ]; if (is_array($data) && count($data) > 0) { $options['json'] = $data; } $response = $this->call($method, [$path, $options]); $responseData = $this->parseResult($response->getBody(), $response->getStatusCode()); if ($response->getStatusCode() !== 200) { throw new Exception( $responseData['message'], $responseData['code'], null, (($_ =& $responseData['errors']) ?: []) ); } return $responseData; }
[ "protected", "function", "getResult", "(", "$", "method", ",", "$", "path", ",", "array", "$", "params", "=", "null", ",", "array", "$", "data", "=", "null", ")", "{", "if", "(", "$", "params", "===", "null", ")", "{", "$", "params", "=", "[", "]", ";", "}", "$", "options", "=", "[", "'query'", "=>", "$", "this", "->", "preParseParams", "(", "$", "params", ")", ",", "]", ";", "if", "(", "is_array", "(", "$", "data", ")", "&&", "count", "(", "$", "data", ")", ">", "0", ")", "{", "$", "options", "[", "'json'", "]", "=", "$", "data", ";", "}", "$", "response", "=", "$", "this", "->", "call", "(", "$", "method", ",", "[", "$", "path", ",", "$", "options", "]", ")", ";", "$", "responseData", "=", "$", "this", "->", "parseResult", "(", "$", "response", "->", "getBody", "(", ")", ",", "$", "response", "->", "getStatusCode", "(", ")", ")", ";", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "!==", "200", ")", "{", "throw", "new", "Exception", "(", "$", "responseData", "[", "'message'", "]", ",", "$", "responseData", "[", "'code'", "]", ",", "null", ",", "(", "(", "$", "_", "=", "&", "$", "responseData", "[", "'errors'", "]", ")", "?", ":", "[", "]", ")", ")", ";", "}", "return", "$", "responseData", ";", "}" ]
Process the request @param string $method @param string $path @param array $params @param array $data @return array i.e. [success => true|false, [errors => ['message' => 'this is broken', ..]]] @throws Exception
[ "Process", "the", "request" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L527-L553
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.preParseParams
private function preParseParams(array $params) { if (!array_key_exists('fields', $params) || !is_array($params['fields'])) { return $params; } $fields = []; foreach ($params['fields'] as $index => $field) { if (!is_numeric($index)) { $fields[$index] = $field; continue; } $modifier = 1; /** @noinspection SubStrUsedAsArrayAccessInspection */ $firstChar = substr($field, 0, 1); if ($firstChar === '+' || $firstChar === '-') { $modifier = $firstChar === '+' ? 1 : 0; $field = substr($field, 1); } $fields[$field] = $modifier; } $params['fields'] = $fields; return $params; }
php
private function preParseParams(array $params) { if (!array_key_exists('fields', $params) || !is_array($params['fields'])) { return $params; } $fields = []; foreach ($params['fields'] as $index => $field) { if (!is_numeric($index)) { $fields[$index] = $field; continue; } $modifier = 1; /** @noinspection SubStrUsedAsArrayAccessInspection */ $firstChar = substr($field, 0, 1); if ($firstChar === '+' || $firstChar === '-') { $modifier = $firstChar === '+' ? 1 : 0; $field = substr($field, 1); } $fields[$field] = $modifier; } $params['fields'] = $fields; return $params; }
[ "private", "function", "preParseParams", "(", "array", "$", "params", ")", "{", "if", "(", "!", "array_key_exists", "(", "'fields'", ",", "$", "params", ")", "||", "!", "is_array", "(", "$", "params", "[", "'fields'", "]", ")", ")", "{", "return", "$", "params", ";", "}", "$", "fields", "=", "[", "]", ";", "foreach", "(", "$", "params", "[", "'fields'", "]", "as", "$", "index", "=>", "$", "field", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "index", ")", ")", "{", "$", "fields", "[", "$", "index", "]", "=", "$", "field", ";", "continue", ";", "}", "$", "modifier", "=", "1", ";", "/** @noinspection SubStrUsedAsArrayAccessInspection */", "$", "firstChar", "=", "substr", "(", "$", "field", ",", "0", ",", "1", ")", ";", "if", "(", "$", "firstChar", "===", "'+'", "||", "$", "firstChar", "===", "'-'", ")", "{", "$", "modifier", "=", "$", "firstChar", "===", "'+'", "?", "1", ":", "0", ";", "$", "field", "=", "substr", "(", "$", "field", ",", "1", ")", ";", "}", "$", "fields", "[", "$", "field", "]", "=", "$", "modifier", ";", "}", "$", "params", "[", "'fields'", "]", "=", "$", "fields", ";", "return", "$", "params", ";", "}" ]
@param array $params @return mixed
[ "@param", "array", "$params" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L560-L585
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.parseResult
private function parseResult($response, $httpCode) { $result = json_decode($response, true); if (is_array($result)) { return $result; } throw new Exception('"' . $this->getLastJsonError() . '" in ' . $response, $httpCode); }
php
private function parseResult($response, $httpCode) { $result = json_decode($response, true); if (is_array($result)) { return $result; } throw new Exception('"' . $this->getLastJsonError() . '" in ' . $response, $httpCode); }
[ "private", "function", "parseResult", "(", "$", "response", ",", "$", "httpCode", ")", "{", "$", "result", "=", "json_decode", "(", "$", "response", ",", "true", ")", ";", "if", "(", "is_array", "(", "$", "result", ")", ")", "{", "return", "$", "result", ";", "}", "throw", "new", "Exception", "(", "'\"'", ".", "$", "this", "->", "getLastJsonError", "(", ")", ".", "'\" in '", ".", "$", "response", ",", "$", "httpCode", ")", ";", "}" ]
Parse the Communibase result and if necessary throw an exception @param string $response @param int $httpCode @return array @throws Exception
[ "Parse", "the", "Communibase", "result", "and", "if", "necessary", "throw", "an", "exception" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L597-L606
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getLastJsonError
private function getLastJsonError() { static $messages = [ JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', ]; $jsonLastError = json_last_error(); return array_key_exists($jsonLastError, $messages) ? $messages[$jsonLastError] : 'Empty response received'; }
php
private function getLastJsonError() { static $messages = [ JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', ]; $jsonLastError = json_last_error(); return array_key_exists($jsonLastError, $messages) ? $messages[$jsonLastError] : 'Empty response received'; }
[ "private", "function", "getLastJsonError", "(", ")", "{", "static", "$", "messages", "=", "[", "JSON_ERROR_DEPTH", "=>", "'Maximum stack depth exceeded'", ",", "JSON_ERROR_STATE_MISMATCH", "=>", "'Underflow or the modes mismatch'", ",", "JSON_ERROR_CTRL_CHAR", "=>", "'Unexpected control character found'", ",", "JSON_ERROR_SYNTAX", "=>", "'Syntax error, malformed JSON'", ",", "JSON_ERROR_UTF8", "=>", "'Malformed UTF-8 characters, possibly incorrectly encoded'", ",", "]", ";", "$", "jsonLastError", "=", "json_last_error", "(", ")", ";", "return", "array_key_exists", "(", "$", "jsonLastError", ",", "$", "messages", ")", "?", "$", "messages", "[", "$", "jsonLastError", "]", ":", "'Empty response received'", ";", "}" ]
Error message based on the most recent JSON error. @see http://nl1.php.net/manual/en/function.json-last-error.php @return string
[ "Error", "message", "based", "on", "the", "most", "recent", "JSON", "error", "." ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L615-L627
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.generateId
public static function generateId() { static $inc = 0; $ts = pack('N', time()); $m = substr(md5(gethostname()), 0, 3); $pid = pack('n', 1); $trail = substr(pack('N', $inc++), 1, 3); $bin = sprintf('%s%s%s%s', $ts, $m, $pid, $trail); $id = ''; for ($i = 0; $i < 12; $i++) { $id .= sprintf('%02X', ord($bin[$i])); } return strtolower($id); }
php
public static function generateId() { static $inc = 0; $ts = pack('N', time()); $m = substr(md5(gethostname()), 0, 3); $pid = pack('n', 1); $trail = substr(pack('N', $inc++), 1, 3); $bin = sprintf('%s%s%s%s', $ts, $m, $pid, $trail); $id = ''; for ($i = 0; $i < 12; $i++) { $id .= sprintf('%02X', ord($bin[$i])); } return strtolower($id); }
[ "public", "static", "function", "generateId", "(", ")", "{", "static", "$", "inc", "=", "0", ";", "$", "ts", "=", "pack", "(", "'N'", ",", "time", "(", ")", ")", ";", "$", "m", "=", "substr", "(", "md5", "(", "gethostname", "(", ")", ")", ",", "0", ",", "3", ")", ";", "$", "pid", "=", "pack", "(", "'n'", ",", "1", ")", ";", "$", "trail", "=", "substr", "(", "pack", "(", "'N'", ",", "$", "inc", "++", ")", ",", "1", ",", "3", ")", ";", "$", "bin", "=", "sprintf", "(", "'%s%s%s%s'", ",", "$", "ts", ",", "$", "m", ",", "$", "pid", ",", "$", "trail", ")", ";", "$", "id", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "12", ";", "$", "i", "++", ")", "{", "$", "id", ".=", "sprintf", "(", "'%02X'", ",", "ord", "(", "$", "bin", "[", "$", "i", "]", ")", ")", ";", "}", "return", "strtolower", "(", "$", "id", ")", ";", "}" ]
Generate a Communibase compatible ID, that consists of: a 4-byte timestamp, a 3-byte machine identifier, a 2-byte process id, and a 3-byte counter, starting with a random value. @return string
[ "Generate", "a", "Communibase", "compatible", "ID", "that", "consists", "of", ":" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L659-L675
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.getClient
protected function getClient() { if ($this->client instanceof ClientInterface) { return $this->client; } if (empty($this->apiKey)) { throw new Exception('Use of connector not possible without API key', Exception::INVALID_API_KEY); } $this->client = new Client([ 'connect_timeout' => 10, 'base_uri' => $this->serviceUrl, 'headers' => array_merge($this->extraHeaders, [ 'User-Agent' => 'Connector-PHP/2', 'X-Api-Key' => $this->apiKey, ]) ]); return $this->client; }
php
protected function getClient() { if ($this->client instanceof ClientInterface) { return $this->client; } if (empty($this->apiKey)) { throw new Exception('Use of connector not possible without API key', Exception::INVALID_API_KEY); } $this->client = new Client([ 'connect_timeout' => 10, 'base_uri' => $this->serviceUrl, 'headers' => array_merge($this->extraHeaders, [ 'User-Agent' => 'Connector-PHP/2', 'X-Api-Key' => $this->apiKey, ]) ]); return $this->client; }
[ "protected", "function", "getClient", "(", ")", "{", "if", "(", "$", "this", "->", "client", "instanceof", "ClientInterface", ")", "{", "return", "$", "this", "->", "client", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "apiKey", ")", ")", "{", "throw", "new", "Exception", "(", "'Use of connector not possible without API key'", ",", "Exception", "::", "INVALID_API_KEY", ")", ";", "}", "$", "this", "->", "client", "=", "new", "Client", "(", "[", "'connect_timeout'", "=>", "10", ",", "'base_uri'", "=>", "$", "this", "->", "serviceUrl", ",", "'headers'", "=>", "array_merge", "(", "$", "this", "->", "extraHeaders", ",", "[", "'User-Agent'", "=>", "'Connector-PHP/2'", ",", "'X-Api-Key'", "=>", "$", "this", "->", "apiKey", ",", "]", ")", "]", ")", ";", "return", "$", "this", "->", "client", ";", "}" ]
@todo inroduce overloadability of default GuzzleClient settings @return ClientInterface @throws Exception
[ "@todo", "inroduce", "overloadability", "of", "default", "GuzzleClient", "settings", "@return", "ClientInterface" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L711-L731
kingsquare/communibase-connector-php
src/Communibase/Connector.php
Connector.call
private function call($method, array $arguments) { try { /** * Due to GuzzleHttp not passing a default host header given to the client to _every_ request made by the * client we manually check to see if we need to add a hostheader to requests. * When the issue is resolved the foreach can be removed (as the function might even?) * * @see https://github.com/guzzle/guzzle/issues/1297 */ if (isset($this->extraHeaders['host'])) { $arguments[1]['headers']['Host'] = $this->extraHeaders['host']; } if ($this->logger) { $this->logger->startQuery($method . ' ' . reset($arguments), $arguments); } $response = call_user_func_array([$this->getClient(), $method], $arguments); if ($this->logger) { $this->logger->stopQuery(); } return $response; // try to catch the Guzzle client exception (404's, validation errors etc) and wrap them into a CB exception } catch (ClientException $e) { $response = $e->getResponse(); $response = json_decode($response === null ? '' : $response->getBody(), true); throw new Exception( $response['message'], $response['code'], $e, (($_ =& $response['errors']) ?: []) ); } catch (ConnectException $e) { throw new Exception('Can not connect', 500, $e, []); } }
php
private function call($method, array $arguments) { try { /** * Due to GuzzleHttp not passing a default host header given to the client to _every_ request made by the * client we manually check to see if we need to add a hostheader to requests. * When the issue is resolved the foreach can be removed (as the function might even?) * * @see https://github.com/guzzle/guzzle/issues/1297 */ if (isset($this->extraHeaders['host'])) { $arguments[1]['headers']['Host'] = $this->extraHeaders['host']; } if ($this->logger) { $this->logger->startQuery($method . ' ' . reset($arguments), $arguments); } $response = call_user_func_array([$this->getClient(), $method], $arguments); if ($this->logger) { $this->logger->stopQuery(); } return $response; // try to catch the Guzzle client exception (404's, validation errors etc) and wrap them into a CB exception } catch (ClientException $e) { $response = $e->getResponse(); $response = json_decode($response === null ? '' : $response->getBody(), true); throw new Exception( $response['message'], $response['code'], $e, (($_ =& $response['errors']) ?: []) ); } catch (ConnectException $e) { throw new Exception('Can not connect', 500, $e, []); } }
[ "private", "function", "call", "(", "$", "method", ",", "array", "$", "arguments", ")", "{", "try", "{", "/**\n * Due to GuzzleHttp not passing a default host header given to the client to _every_ request made by the\n * client we manually check to see if we need to add a hostheader to requests.\n * When the issue is resolved the foreach can be removed (as the function might even?)\n *\n * @see https://github.com/guzzle/guzzle/issues/1297\n */", "if", "(", "isset", "(", "$", "this", "->", "extraHeaders", "[", "'host'", "]", ")", ")", "{", "$", "arguments", "[", "1", "]", "[", "'headers'", "]", "[", "'Host'", "]", "=", "$", "this", "->", "extraHeaders", "[", "'host'", "]", ";", "}", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "startQuery", "(", "$", "method", ".", "' '", ".", "reset", "(", "$", "arguments", ")", ",", "$", "arguments", ")", ";", "}", "$", "response", "=", "call_user_func_array", "(", "[", "$", "this", "->", "getClient", "(", ")", ",", "$", "method", "]", ",", "$", "arguments", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "stopQuery", "(", ")", ";", "}", "return", "$", "response", ";", "// try to catch the Guzzle client exception (404's, validation errors etc) and wrap them into a CB exception", "}", "catch", "(", "ClientException", "$", "e", ")", "{", "$", "response", "=", "$", "e", "->", "getResponse", "(", ")", ";", "$", "response", "=", "json_decode", "(", "$", "response", "===", "null", "?", "''", ":", "$", "response", "->", "getBody", "(", ")", ",", "true", ")", ";", "throw", "new", "Exception", "(", "$", "response", "[", "'message'", "]", ",", "$", "response", "[", "'code'", "]", ",", "$", "e", ",", "(", "(", "$", "_", "=", "&", "$", "response", "[", "'errors'", "]", ")", "?", ":", "[", "]", ")", ")", ";", "}", "catch", "(", "ConnectException", "$", "e", ")", "{", "throw", "new", "Exception", "(", "'Can not connect'", ",", "500", ",", "$", "e", ",", "[", "]", ")", ";", "}", "}" ]
Perform the actual call to Communibase @param string $method @param array $arguments @return \Psr\Http\Message\ResponseInterface @throws Exception
[ "Perform", "the", "actual", "call", "to", "Communibase" ]
train
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L743-L788
weavephp/weave
src/Middleware/Dispatch.php
Dispatch.run
protected function run(Request $request) { // If there's nothing to dispatch, continue along the middleware pipeline $handler = $request->getAttribute('dispatch.handler', false); if ($handler === false) { return $this->chain($request); } // Setup any remaining chained parts of the dispatch for future dispatch $request = $request->withAttribute('dispatch.handler', $this->resolver->shift($handler)); // Resolve the handler into something callable $dispatchable = $this->resolver->resolve($handler, $resolutionType); // Dispatch $parameters = [ $dispatchable, $resolutionType, DispatchAdaptorInterface::SOURCE_DISPATCH_MIDDLEWARE, $request ]; $response = $this->getResponseObject(); if ($response !== null) { $parameters[] = $response; } return $this->dispatcher->dispatch(...$parameters) ?: $this->chain($request); }
php
protected function run(Request $request) { // If there's nothing to dispatch, continue along the middleware pipeline $handler = $request->getAttribute('dispatch.handler', false); if ($handler === false) { return $this->chain($request); } // Setup any remaining chained parts of the dispatch for future dispatch $request = $request->withAttribute('dispatch.handler', $this->resolver->shift($handler)); // Resolve the handler into something callable $dispatchable = $this->resolver->resolve($handler, $resolutionType); // Dispatch $parameters = [ $dispatchable, $resolutionType, DispatchAdaptorInterface::SOURCE_DISPATCH_MIDDLEWARE, $request ]; $response = $this->getResponseObject(); if ($response !== null) { $parameters[] = $response; } return $this->dispatcher->dispatch(...$parameters) ?: $this->chain($request); }
[ "protected", "function", "run", "(", "Request", "$", "request", ")", "{", "// If there's nothing to dispatch, continue along the middleware pipeline", "$", "handler", "=", "$", "request", "->", "getAttribute", "(", "'dispatch.handler'", ",", "false", ")", ";", "if", "(", "$", "handler", "===", "false", ")", "{", "return", "$", "this", "->", "chain", "(", "$", "request", ")", ";", "}", "// Setup any remaining chained parts of the dispatch for future dispatch", "$", "request", "=", "$", "request", "->", "withAttribute", "(", "'dispatch.handler'", ",", "$", "this", "->", "resolver", "->", "shift", "(", "$", "handler", ")", ")", ";", "// Resolve the handler into something callable", "$", "dispatchable", "=", "$", "this", "->", "resolver", "->", "resolve", "(", "$", "handler", ",", "$", "resolutionType", ")", ";", "// Dispatch", "$", "parameters", "=", "[", "$", "dispatchable", ",", "$", "resolutionType", ",", "DispatchAdaptorInterface", "::", "SOURCE_DISPATCH_MIDDLEWARE", ",", "$", "request", "]", ";", "$", "response", "=", "$", "this", "->", "getResponseObject", "(", ")", ";", "if", "(", "$", "response", "!==", "null", ")", "{", "$", "parameters", "[", "]", "=", "$", "response", ";", "}", "return", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "...", "$", "parameters", ")", "?", ":", "$", "this", "->", "chain", "(", "$", "request", ")", ";", "}" ]
Handle a dispatch. @param Request $request The request. @return Response
[ "Handle", "a", "dispatch", "." ]
train
https://github.com/weavephp/weave/blob/44183a5bcb9e3ed3754cc76aa9e0724d718caeec/src/Middleware/Dispatch.php#L56-L82
rinvex/obsolete-module
src/ModuleManager.php
ModuleManager.sort
public function sort() { if ($this->modules) { $modules = []; $sorter = new StringSort(); foreach ($this->modules as $slug => $module) { $sorter->add($slug, array_intersect(array_keys($module->getAttribute('require')), array_keys($this->modules))); } foreach ($sorter->sort() as $slug) { $modules[$slug] = $this->modules[$slug]; } // Override modules array $this->modules = $modules; } return $this; }
php
public function sort() { if ($this->modules) { $modules = []; $sorter = new StringSort(); foreach ($this->modules as $slug => $module) { $sorter->add($slug, array_intersect(array_keys($module->getAttribute('require')), array_keys($this->modules))); } foreach ($sorter->sort() as $slug) { $modules[$slug] = $this->modules[$slug]; } // Override modules array $this->modules = $modules; } return $this; }
[ "public", "function", "sort", "(", ")", "{", "if", "(", "$", "this", "->", "modules", ")", "{", "$", "modules", "=", "[", "]", ";", "$", "sorter", "=", "new", "StringSort", "(", ")", ";", "foreach", "(", "$", "this", "->", "modules", "as", "$", "slug", "=>", "$", "module", ")", "{", "$", "sorter", "->", "add", "(", "$", "slug", ",", "array_intersect", "(", "array_keys", "(", "$", "module", "->", "getAttribute", "(", "'require'", ")", ")", ",", "array_keys", "(", "$", "this", "->", "modules", ")", ")", ")", ";", "}", "foreach", "(", "$", "sorter", "->", "sort", "(", ")", "as", "$", "slug", ")", "{", "$", "modules", "[", "$", "slug", "]", "=", "$", "this", "->", "modules", "[", "$", "slug", "]", ";", "}", "// Override modules array", "$", "this", "->", "modules", "=", "$", "modules", ";", "}", "return", "$", "this", ";", "}" ]
Sort modules by their dependencies. @return $this
[ "Sort", "modules", "by", "their", "dependencies", "." ]
train
https://github.com/rinvex/obsolete-module/blob/95e372ae97ecbe7071c3da397b0afd57f327361f/src/ModuleManager.php#L81-L100
rinvex/obsolete-module
src/ModuleManager.php
ModuleManager.register
public function register() { foreach ($this->modules as $module) { if ($aggregator = $module->getAttribute('aggregator')) { $this->container->register($aggregator); } } return $this; }
php
public function register() { foreach ($this->modules as $module) { if ($aggregator = $module->getAttribute('aggregator')) { $this->container->register($aggregator); } } return $this; }
[ "public", "function", "register", "(", ")", "{", "foreach", "(", "$", "this", "->", "modules", "as", "$", "module", ")", "{", "if", "(", "$", "aggregator", "=", "$", "module", "->", "getAttribute", "(", "'aggregator'", ")", ")", "{", "$", "this", "->", "container", "->", "register", "(", "$", "aggregator", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Register modules with service container. @return $this
[ "Register", "modules", "with", "service", "container", "." ]
train
https://github.com/rinvex/obsolete-module/blob/95e372ae97ecbe7071c3da397b0afd57f327361f/src/ModuleManager.php#L107-L116
baleen/cli
src/CommandBus/Repository/ListHandler.php
ListHandler.handle
public function handle(ListMessage $command) { $input = $command->getInput(); $output = $command->getOutput(); $reverse = $input->getOption('newest-first'); $versions = $this->getCollection($command->getRepository(), $command->getComparator()); if (count($versions) > 0) { if ($reverse) { $versions = $versions->getReverse(); } $this->outputVersions($versions, $output); } else { $output->writeln('No available migrations were found. Please check your settings.'); } }
php
public function handle(ListMessage $command) { $input = $command->getInput(); $output = $command->getOutput(); $reverse = $input->getOption('newest-first'); $versions = $this->getCollection($command->getRepository(), $command->getComparator()); if (count($versions) > 0) { if ($reverse) { $versions = $versions->getReverse(); } $this->outputVersions($versions, $output); } else { $output->writeln('No available migrations were found. Please check your settings.'); } }
[ "public", "function", "handle", "(", "ListMessage", "$", "command", ")", "{", "$", "input", "=", "$", "command", "->", "getInput", "(", ")", ";", "$", "output", "=", "$", "command", "->", "getOutput", "(", ")", ";", "$", "reverse", "=", "$", "input", "->", "getOption", "(", "'newest-first'", ")", ";", "$", "versions", "=", "$", "this", "->", "getCollection", "(", "$", "command", "->", "getRepository", "(", ")", ",", "$", "command", "->", "getComparator", "(", ")", ")", ";", "if", "(", "count", "(", "$", "versions", ")", ">", "0", ")", "{", "if", "(", "$", "reverse", ")", "{", "$", "versions", "=", "$", "versions", "->", "getReverse", "(", ")", ";", "}", "$", "this", "->", "outputVersions", "(", "$", "versions", ",", "$", "output", ")", ";", "}", "else", "{", "$", "output", "->", "writeln", "(", "'No available migrations were found. Please check your settings.'", ")", ";", "}", "}" ]
handle. @param ListMessage $command
[ "handle", "." ]
train
https://github.com/baleen/cli/blob/2ecbc7179c5800c9075fd93204ef25da375536ed/src/CommandBus/Repository/ListHandler.php#L38-L54
WellCommerce/OrderBundle
Form/DataTransformer/ShippingCostCollectionToArrayTransformer.php
ShippingCostCollectionToArrayTransformer.transform
public function transform($modelData) { if (null === $modelData || !$modelData instanceof PersistentCollection) { return []; } $items = []; foreach ($modelData as $item) { $items['ranges'][] = $this->getRangeData($item); } return $items; }
php
public function transform($modelData) { if (null === $modelData || !$modelData instanceof PersistentCollection) { return []; } $items = []; foreach ($modelData as $item) { $items['ranges'][] = $this->getRangeData($item); } return $items; }
[ "public", "function", "transform", "(", "$", "modelData", ")", "{", "if", "(", "null", "===", "$", "modelData", "||", "!", "$", "modelData", "instanceof", "PersistentCollection", ")", "{", "return", "[", "]", ";", "}", "$", "items", "=", "[", "]", ";", "foreach", "(", "$", "modelData", "as", "$", "item", ")", "{", "$", "items", "[", "'ranges'", "]", "[", "]", "=", "$", "this", "->", "getRangeData", "(", "$", "item", ")", ";", "}", "return", "$", "items", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/WellCommerce/OrderBundle/blob/d72cfb51eab7a1f66f186900d1e2d533a822c424/Form/DataTransformer/ShippingCostCollectionToArrayTransformer.php#L33-L45
WellCommerce/OrderBundle
Form/DataTransformer/ShippingCostCollectionToArrayTransformer.php
ShippingCostCollectionToArrayTransformer.getRangeData
private function getRangeData(ShippingMethodCost $cost) { return [ 'min' => $cost->getRangeFrom(), 'max' => $cost->getRangeTo(), 'price' => $cost->getCost()->getGrossAmount(), ]; }
php
private function getRangeData(ShippingMethodCost $cost) { return [ 'min' => $cost->getRangeFrom(), 'max' => $cost->getRangeTo(), 'price' => $cost->getCost()->getGrossAmount(), ]; }
[ "private", "function", "getRangeData", "(", "ShippingMethodCost", "$", "cost", ")", "{", "return", "[", "'min'", "=>", "$", "cost", "->", "getRangeFrom", "(", ")", ",", "'max'", "=>", "$", "cost", "->", "getRangeTo", "(", ")", ",", "'price'", "=>", "$", "cost", "->", "getCost", "(", ")", "->", "getGrossAmount", "(", ")", ",", "]", ";", "}" ]
Returns costs data as an array @param ShippingMethodCost $cost @return array
[ "Returns", "costs", "data", "as", "an", "array" ]
train
https://github.com/WellCommerce/OrderBundle/blob/d72cfb51eab7a1f66f186900d1e2d533a822c424/Form/DataTransformer/ShippingCostCollectionToArrayTransformer.php#L54-L61
WellCommerce/OrderBundle
Form/DataTransformer/ShippingCostCollectionToArrayTransformer.php
ShippingCostCollectionToArrayTransformer.reverseTransform
public function reverseTransform($modelData, PropertyPathInterface $propertyPath, $value) { $newCollection = $this->prepareCostsCollection($value, $modelData); $oldCollection = $this->propertyAccessor->getValue($modelData, $propertyPath); foreach ($oldCollection as $oldEntity) { $modelData->getCosts()->removeElement($oldEntity); } $this->propertyAccessor->setValue($modelData, $propertyPath, $newCollection); }
php
public function reverseTransform($modelData, PropertyPathInterface $propertyPath, $value) { $newCollection = $this->prepareCostsCollection($value, $modelData); $oldCollection = $this->propertyAccessor->getValue($modelData, $propertyPath); foreach ($oldCollection as $oldEntity) { $modelData->getCosts()->removeElement($oldEntity); } $this->propertyAccessor->setValue($modelData, $propertyPath, $newCollection); }
[ "public", "function", "reverseTransform", "(", "$", "modelData", ",", "PropertyPathInterface", "$", "propertyPath", ",", "$", "value", ")", "{", "$", "newCollection", "=", "$", "this", "->", "prepareCostsCollection", "(", "$", "value", ",", "$", "modelData", ")", ";", "$", "oldCollection", "=", "$", "this", "->", "propertyAccessor", "->", "getValue", "(", "$", "modelData", ",", "$", "propertyPath", ")", ";", "foreach", "(", "$", "oldCollection", "as", "$", "oldEntity", ")", "{", "$", "modelData", "->", "getCosts", "(", ")", "->", "removeElement", "(", "$", "oldEntity", ")", ";", "}", "$", "this", "->", "propertyAccessor", "->", "setValue", "(", "$", "modelData", ",", "$", "propertyPath", ",", "$", "newCollection", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/WellCommerce/OrderBundle/blob/d72cfb51eab7a1f66f186900d1e2d533a822c424/Form/DataTransformer/ShippingCostCollectionToArrayTransformer.php#L66-L76
huasituo/hstcms
src/Libraries/Hststring.php
Hststring.substr
public static function substr($string, $start, $length, $dot = false, $charset = self::UTF8) { switch (strtolower($charset)) { case self::GBK: $string = self::substrForGbk($string, $start, $length, $dot); break; case self::UTF8: $string = self::substrForUtf8($string, $start, $length, $dot); break; default: $string = substr($string, $start, $length); } return $string; }
php
public static function substr($string, $start, $length, $dot = false, $charset = self::UTF8) { switch (strtolower($charset)) { case self::GBK: $string = self::substrForGbk($string, $start, $length, $dot); break; case self::UTF8: $string = self::substrForUtf8($string, $start, $length, $dot); break; default: $string = substr($string, $start, $length); } return $string; }
[ "public", "static", "function", "substr", "(", "$", "string", ",", "$", "start", ",", "$", "length", ",", "$", "dot", "=", "false", ",", "$", "charset", "=", "self", "::", "UTF8", ")", "{", "switch", "(", "strtolower", "(", "$", "charset", ")", ")", "{", "case", "self", "::", "GBK", ":", "$", "string", "=", "self", "::", "substrForGbk", "(", "$", "string", ",", "$", "start", ",", "$", "length", ",", "$", "dot", ")", ";", "break", ";", "case", "self", "::", "UTF8", ":", "$", "string", "=", "self", "::", "substrForUtf8", "(", "$", "string", ",", "$", "start", ",", "$", "length", ",", "$", "dot", ")", ";", "break", ";", "default", ":", "$", "string", "=", "substr", "(", "$", "string", ",", "$", "start", ",", "$", "length", ")", ";", "}", "return", "$", "string", ";", "}" ]
截取字符串,支持字符编码,默认为utf-8 ** @param string $string 要截取的字符串编码 @param int $start 开始截取 @param int $length 截取的长度 @param boolean $dot 是否显示省略号,默认为false @param string $charset 原妈编码,默认为UTF8 @return string 截取后的字串
[ "截取字符串", "支持字符编码", "默认为utf", "-", "8", "**" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/Hststring.php#L24-L38
huasituo/hstcms
src/Libraries/Hststring.php
Hststring.strlen
public static function strlen($string, $charset = self::UTF8) { switch (strtolower($charset)) { case self::GBK: $count = self::strlenForGbk($string); break; case self::UTF8: $count = self::strlenForUtf8($string); break; default: $count = strlen($string); } return $count; }
php
public static function strlen($string, $charset = self::UTF8) { switch (strtolower($charset)) { case self::GBK: $count = self::strlenForGbk($string); break; case self::UTF8: $count = self::strlenForUtf8($string); break; default: $count = strlen($string); } return $count; }
[ "public", "static", "function", "strlen", "(", "$", "string", ",", "$", "charset", "=", "self", "::", "UTF8", ")", "{", "switch", "(", "strtolower", "(", "$", "charset", ")", ")", "{", "case", "self", "::", "GBK", ":", "$", "count", "=", "self", "::", "strlenForGbk", "(", "$", "string", ")", ";", "break", ";", "case", "self", "::", "UTF8", ":", "$", "count", "=", "self", "::", "strlenForUtf8", "(", "$", "string", ")", ";", "break", ";", "default", ":", "$", "count", "=", "strlen", "(", "$", "string", ")", ";", "}", "return", "$", "count", ";", "}" ]
求取字符串长度 ** @param string $string 要计算的字符串编码 @param string $charset 原始编码,默认为UTF8 @return int
[ "求取字符串长度", "**" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/Hststring.php#L47-L61
huasituo/hstcms
src/Libraries/Hststring.php
Hststring.varToString
public static function varToString($input, $indent = '') { switch (gettype($input)) { case 'string': return "'" . str_replace(array("\\", "'"), array("\\\\", "\\'"), $input) . "'"; case 'array': $output = "array(\r\n"; foreach ($input as $key => $value) { $output .= $indent . "\t" . self::varToString($key, $indent . "\t") . ' => ' . self::varToString( $value, $indent . "\t"); $output .= ",\r\n"; } $output .= $indent . ')'; return $output; case 'boolean': return $input ? 'true' : 'false'; case 'NULL': return 'NULL'; case 'integer': case 'double': case 'float': return "'" . (string) $input . "'"; } return 'NULL'; }
php
public static function varToString($input, $indent = '') { switch (gettype($input)) { case 'string': return "'" . str_replace(array("\\", "'"), array("\\\\", "\\'"), $input) . "'"; case 'array': $output = "array(\r\n"; foreach ($input as $key => $value) { $output .= $indent . "\t" . self::varToString($key, $indent . "\t") . ' => ' . self::varToString( $value, $indent . "\t"); $output .= ",\r\n"; } $output .= $indent . ')'; return $output; case 'boolean': return $input ? 'true' : 'false'; case 'NULL': return 'NULL'; case 'integer': case 'double': case 'float': return "'" . (string) $input . "'"; } return 'NULL'; }
[ "public", "static", "function", "varToString", "(", "$", "input", ",", "$", "indent", "=", "''", ")", "{", "switch", "(", "gettype", "(", "$", "input", ")", ")", "{", "case", "'string'", ":", "return", "\"'\"", ".", "str_replace", "(", "array", "(", "\"\\\\\"", ",", "\"'\"", ")", ",", "array", "(", "\"\\\\\\\\\"", ",", "\"\\\\'\"", ")", ",", "$", "input", ")", ".", "\"'\"", ";", "case", "'array'", ":", "$", "output", "=", "\"array(\\r\\n\"", ";", "foreach", "(", "$", "input", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "output", ".=", "$", "indent", ".", "\"\\t\"", ".", "self", "::", "varToString", "(", "$", "key", ",", "$", "indent", ".", "\"\\t\"", ")", ".", "' => '", ".", "self", "::", "varToString", "(", "$", "value", ",", "$", "indent", ".", "\"\\t\"", ")", ";", "$", "output", ".=", "\",\\r\\n\"", ";", "}", "$", "output", ".=", "$", "indent", ".", "')'", ";", "return", "$", "output", ";", "case", "'boolean'", ":", "return", "$", "input", "?", "'true'", ":", "'false'", ";", "case", "'NULL'", ":", "return", "'NULL'", ";", "case", "'integer'", ":", "case", "'double'", ":", "case", "'float'", ":", "return", "\"'\"", ".", "(", "string", ")", "$", "input", ".", "\"'\"", ";", "}", "return", "'NULL'", ";", "}" ]
将变量的值转换为字符串 ** @param mixed $input 变量 @param string $indent 缩进,默认为'' @return string
[ "将变量的值转换为字符串", "**" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/Hststring.php#L70-L96
huasituo/hstcms
src/Libraries/Hststring.php
Hststring.substrForUtf8
public static function substrForUtf8($string, $start, $length = null, $dot = false) { $l = strlen($string); $p = $s = 0; if (0 !== $start) { while ($start-- && $p < $l) { $c = $string[$p]; if ($c < "\xC0") $p++; elseif ($c < "\xE0") $p += 2; elseif ($c < "\xF0") $p += 3; elseif ($c < "\xF8") $p += 4; elseif ($c < "\xFC") $p += 5; else $p += 6; } $s = $p; } if (empty($length)) { $t = substr($string, $s); } else { $i = $length; while ($i-- && $p < $l) { $c = $string[$p]; if ($c < "\xC0") $p++; elseif ($c < "\xE0") $p += 2; elseif ($c < "\xF0") $p += 3; elseif ($c < "\xF8") $p += 4; elseif ($c < "\xFC") $p += 5; else $p += 6; } $t = substr($string, $s, $p - $s); } $dot && ($p < $l) && $t .= "..."; return $t; }
php
public static function substrForUtf8($string, $start, $length = null, $dot = false) { $l = strlen($string); $p = $s = 0; if (0 !== $start) { while ($start-- && $p < $l) { $c = $string[$p]; if ($c < "\xC0") $p++; elseif ($c < "\xE0") $p += 2; elseif ($c < "\xF0") $p += 3; elseif ($c < "\xF8") $p += 4; elseif ($c < "\xFC") $p += 5; else $p += 6; } $s = $p; } if (empty($length)) { $t = substr($string, $s); } else { $i = $length; while ($i-- && $p < $l) { $c = $string[$p]; if ($c < "\xC0") $p++; elseif ($c < "\xE0") $p += 2; elseif ($c < "\xF0") $p += 3; elseif ($c < "\xF8") $p += 4; elseif ($c < "\xFC") $p += 5; else $p += 6; } $t = substr($string, $s, $p - $s); } $dot && ($p < $l) && $t .= "..."; return $t; }
[ "public", "static", "function", "substrForUtf8", "(", "$", "string", ",", "$", "start", ",", "$", "length", "=", "null", ",", "$", "dot", "=", "false", ")", "{", "$", "l", "=", "strlen", "(", "$", "string", ")", ";", "$", "p", "=", "$", "s", "=", "0", ";", "if", "(", "0", "!==", "$", "start", ")", "{", "while", "(", "$", "start", "--", "&&", "$", "p", "<", "$", "l", ")", "{", "$", "c", "=", "$", "string", "[", "$", "p", "]", ";", "if", "(", "$", "c", "<", "\"\\xC0\"", ")", "$", "p", "++", ";", "elseif", "(", "$", "c", "<", "\"\\xE0\"", ")", "$", "p", "+=", "2", ";", "elseif", "(", "$", "c", "<", "\"\\xF0\"", ")", "$", "p", "+=", "3", ";", "elseif", "(", "$", "c", "<", "\"\\xF8\"", ")", "$", "p", "+=", "4", ";", "elseif", "(", "$", "c", "<", "\"\\xFC\"", ")", "$", "p", "+=", "5", ";", "else", "$", "p", "+=", "6", ";", "}", "$", "s", "=", "$", "p", ";", "}", "if", "(", "empty", "(", "$", "length", ")", ")", "{", "$", "t", "=", "substr", "(", "$", "string", ",", "$", "s", ")", ";", "}", "else", "{", "$", "i", "=", "$", "length", ";", "while", "(", "$", "i", "--", "&&", "$", "p", "<", "$", "l", ")", "{", "$", "c", "=", "$", "string", "[", "$", "p", "]", ";", "if", "(", "$", "c", "<", "\"\\xC0\"", ")", "$", "p", "++", ";", "elseif", "(", "$", "c", "<", "\"\\xE0\"", ")", "$", "p", "+=", "2", ";", "elseif", "(", "$", "c", "<", "\"\\xF0\"", ")", "$", "p", "+=", "3", ";", "elseif", "(", "$", "c", "<", "\"\\xF8\"", ")", "$", "p", "+=", "4", ";", "elseif", "(", "$", "c", "<", "\"\\xFC\"", ")", "$", "p", "+=", "5", ";", "else", "$", "p", "+=", "6", ";", "}", "$", "t", "=", "substr", "(", "$", "string", ",", "$", "s", ",", "$", "p", "-", "$", "s", ")", ";", "}", "$", "dot", "&&", "(", "$", "p", "<", "$", "l", ")", "&&", "$", "t", ".=", "\"...\"", ";", "return", "$", "t", ";", "}" ]
以utf8格式截取的字符串编码 ** @param string $string 要截取的字符串编码 @param int $start 开始截取 @param int $length 截取的长度,默认为null,取字符串的全长 @param boolean $dot 是否显示省略号,默认为false @return string
[ "以utf8格式截取的字符串编码", "**" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/Hststring.php#L107-L160
huasituo/hstcms
src/Libraries/Hststring.php
Hststring.substrForGbk
public static function substrForGbk($string, $start, $length = null, $dot = false) { $l = strlen($string); $p = $s = 0; if (0 !== $start) { while ($start-- && $p < $l) { if ($string[$p] > "\x80") $p += 2; else $p++; } $s = $p; } if (empty($length)) { $t = substr($string, $s); } else { $i = $length; while ($i-- && $p < $l) { if ($string[$p] > "\x80") $p += 2; else $p++; } $t = substr($string, $s, $p - $s); } $dot && ($p < $l) && $t .= "..."; return $t; }
php
public static function substrForGbk($string, $start, $length = null, $dot = false) { $l = strlen($string); $p = $s = 0; if (0 !== $start) { while ($start-- && $p < $l) { if ($string[$p] > "\x80") $p += 2; else $p++; } $s = $p; } if (empty($length)) { $t = substr($string, $s); } else { $i = $length; while ($i-- && $p < $l) { if ($string[$p] > "\x80") $p += 2; else $p++; } $t = substr($string, $s, $p - $s); } $dot && ($p < $l) && $t .= "..."; return $t; }
[ "public", "static", "function", "substrForGbk", "(", "$", "string", ",", "$", "start", ",", "$", "length", "=", "null", ",", "$", "dot", "=", "false", ")", "{", "$", "l", "=", "strlen", "(", "$", "string", ")", ";", "$", "p", "=", "$", "s", "=", "0", ";", "if", "(", "0", "!==", "$", "start", ")", "{", "while", "(", "$", "start", "--", "&&", "$", "p", "<", "$", "l", ")", "{", "if", "(", "$", "string", "[", "$", "p", "]", ">", "\"\\x80\"", ")", "$", "p", "+=", "2", ";", "else", "$", "p", "++", ";", "}", "$", "s", "=", "$", "p", ";", "}", "if", "(", "empty", "(", "$", "length", ")", ")", "{", "$", "t", "=", "substr", "(", "$", "string", ",", "$", "s", ")", ";", "}", "else", "{", "$", "i", "=", "$", "length", ";", "while", "(", "$", "i", "--", "&&", "$", "p", "<", "$", "l", ")", "{", "if", "(", "$", "string", "[", "$", "p", "]", ">", "\"\\x80\"", ")", "$", "p", "+=", "2", ";", "else", "$", "p", "++", ";", "}", "$", "t", "=", "substr", "(", "$", "string", ",", "$", "s", ",", "$", "p", "-", "$", "s", ")", ";", "}", "$", "dot", "&&", "(", "$", "p", "<", "$", "l", ")", "&&", "$", "t", ".=", "\"...\"", ";", "return", "$", "t", ";", "}" ]
以gbk格式截取的字符串编码 ** @param string $string 要截取的字符串编码 @param int $start 开始截取 @param int $length 截取的长度,默认为null,取字符串的全长 @param boolean $dot 是否显示省略号,默认为false @return string
[ "以gbk格式截取的字符串编码", "**" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/Hststring.php#L171-L206
huasituo/hstcms
src/Libraries/Hststring.php
Hststring.strlenForUtf8
public static function strlenForUtf8($string) { $l = strlen($string); $p = $c = 0; while ($p < $l) { $a = $string[$p]; if ($a < "\xC0") $p++; elseif ($a < "\xE0") $p += 2; elseif ($a < "\xF0") $p += 3; elseif ($a < "\xF8") $p += 4; elseif ($a < "\xFC") $p += 5; else $p += 6; $c++; } return $c; }
php
public static function strlenForUtf8($string) { $l = strlen($string); $p = $c = 0; while ($p < $l) { $a = $string[$p]; if ($a < "\xC0") $p++; elseif ($a < "\xE0") $p += 2; elseif ($a < "\xF0") $p += 3; elseif ($a < "\xF8") $p += 4; elseif ($a < "\xFC") $p += 5; else $p += 6; $c++; } return $c; }
[ "public", "static", "function", "strlenForUtf8", "(", "$", "string", ")", "{", "$", "l", "=", "strlen", "(", "$", "string", ")", ";", "$", "p", "=", "$", "c", "=", "0", ";", "while", "(", "$", "p", "<", "$", "l", ")", "{", "$", "a", "=", "$", "string", "[", "$", "p", "]", ";", "if", "(", "$", "a", "<", "\"\\xC0\"", ")", "$", "p", "++", ";", "elseif", "(", "$", "a", "<", "\"\\xE0\"", ")", "$", "p", "+=", "2", ";", "elseif", "(", "$", "a", "<", "\"\\xF0\"", ")", "$", "p", "+=", "3", ";", "elseif", "(", "$", "a", "<", "\"\\xF8\"", ")", "$", "p", "+=", "4", ";", "elseif", "(", "$", "a", "<", "\"\\xFC\"", ")", "$", "p", "+=", "5", ";", "else", "$", "p", "+=", "6", ";", "$", "c", "++", ";", "}", "return", "$", "c", ";", "}" ]
以utf8求取字符串长度 ** @param string $string 要计算的字符串编码 @return int
[ "以utf8求取字符串长度", "**" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/Hststring.php#L214-L236
huasituo/hstcms
src/Libraries/Hststring.php
Hststring.strlenForGbk
public static function strlenForGbk($string) { $l = strlen($string); $p = $c = 0; while ($p < $l) { if ($string[$p] > "\x80") $p += 2; else $p++; $c++; } return $c; }
php
public static function strlenForGbk($string) { $l = strlen($string); $p = $c = 0; while ($p < $l) { if ($string[$p] > "\x80") $p += 2; else $p++; $c++; } return $c; }
[ "public", "static", "function", "strlenForGbk", "(", "$", "string", ")", "{", "$", "l", "=", "strlen", "(", "$", "string", ")", ";", "$", "p", "=", "$", "c", "=", "0", ";", "while", "(", "$", "p", "<", "$", "l", ")", "{", "if", "(", "$", "string", "[", "$", "p", "]", ">", "\"\\x80\"", ")", "$", "p", "+=", "2", ";", "else", "$", "p", "++", ";", "$", "c", "++", ";", "}", "return", "$", "c", ";", "}" ]
以gbk求取字符串长度 ** @param string $string 要计算的字符串编码 @return int
[ "以gbk求取字符串长度", "**" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/Hststring.php#L244-L257
EcomDev/phpspec-magento-di-adapter
src/Extension.php
Extension.load
public function load(ServiceContainer $container, array $params) { $container->define( 'ecomdev.phpspec.magento_di_adapter.vfs', $this->vfsFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.code_generator.io', $this->ioFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes', $this->simplifiedDefinedClassesFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.parameter_validator', $this->parameterValidatorFactory() ); $container->define( 'runner.maintainers.ecomdev_magento_collaborator', $this->collaboratorMaintainerFactory(), ['runner.maintainers'] ); }
php
public function load(ServiceContainer $container, array $params) { $container->define( 'ecomdev.phpspec.magento_di_adapter.vfs', $this->vfsFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.code_generator.io', $this->ioFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes', $this->simplifiedDefinedClassesFactory() ); $container->define( 'ecomdev.phpspec.magento_di_adapter.parameter_validator', $this->parameterValidatorFactory() ); $container->define( 'runner.maintainers.ecomdev_magento_collaborator', $this->collaboratorMaintainerFactory(), ['runner.maintainers'] ); }
[ "public", "function", "load", "(", "ServiceContainer", "$", "container", ",", "array", "$", "params", ")", "{", "$", "container", "->", "define", "(", "'ecomdev.phpspec.magento_di_adapter.vfs'", ",", "$", "this", "->", "vfsFactory", "(", ")", ")", ";", "$", "container", "->", "define", "(", "'ecomdev.phpspec.magento_di_adapter.code_generator.io'", ",", "$", "this", "->", "ioFactory", "(", ")", ")", ";", "$", "container", "->", "define", "(", "'ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes'", ",", "$", "this", "->", "simplifiedDefinedClassesFactory", "(", ")", ")", ";", "$", "container", "->", "define", "(", "'ecomdev.phpspec.magento_di_adapter.parameter_validator'", ",", "$", "this", "->", "parameterValidatorFactory", "(", ")", ")", ";", "$", "container", "->", "define", "(", "'runner.maintainers.ecomdev_magento_collaborator'", ",", "$", "this", "->", "collaboratorMaintainerFactory", "(", ")", ",", "[", "'runner.maintainers'", "]", ")", ";", "}" ]
Load collaborator into PHPSpec ServiceContainer @param ServiceContainer $container
[ "Load", "collaborator", "into", "PHPSpec", "ServiceContainer" ]
train
https://github.com/EcomDev/phpspec-magento-di-adapter/blob/b39f6f0afbb837dbf0eb4c71e6cdb318b8c9de37/src/Extension.php#L33-L60
EcomDev/phpspec-magento-di-adapter
src/Extension.php
Extension.parameterValidatorFactory
public function parameterValidatorFactory() { return function (ServiceContainer $container) { $parameterValidator = new ParameterValidator( $container->get('ecomdev.phpspec.magento_di_adapter.code_generator.io'), $container->get('ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes'), $container->get('loader.transformer.typehintindex') ); $parameterValidator ->addGenerator(Generator\Factory::class, Generator\Factory::ENTITY_TYPE) ->addGenerator(Generator\Repository::class, Generator\Repository::ENTITY_TYPE) ->addGenerator(Generator\Converter::class, Generator\Converter::ENTITY_TYPE) ->addGenerator(Generator\Persistor::class, Generator\Persistor::ENTITY_TYPE) ->addGenerator(MapperGenerator::class, MapperGenerator::ENTITY_TYPE) ->addGenerator(SearchResults::class, SearchResults::ENTITY_TYPE) ; return $parameterValidator; }; }
php
public function parameterValidatorFactory() { return function (ServiceContainer $container) { $parameterValidator = new ParameterValidator( $container->get('ecomdev.phpspec.magento_di_adapter.code_generator.io'), $container->get('ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes'), $container->get('loader.transformer.typehintindex') ); $parameterValidator ->addGenerator(Generator\Factory::class, Generator\Factory::ENTITY_TYPE) ->addGenerator(Generator\Repository::class, Generator\Repository::ENTITY_TYPE) ->addGenerator(Generator\Converter::class, Generator\Converter::ENTITY_TYPE) ->addGenerator(Generator\Persistor::class, Generator\Persistor::ENTITY_TYPE) ->addGenerator(MapperGenerator::class, MapperGenerator::ENTITY_TYPE) ->addGenerator(SearchResults::class, SearchResults::ENTITY_TYPE) ; return $parameterValidator; }; }
[ "public", "function", "parameterValidatorFactory", "(", ")", "{", "return", "function", "(", "ServiceContainer", "$", "container", ")", "{", "$", "parameterValidator", "=", "new", "ParameterValidator", "(", "$", "container", "->", "get", "(", "'ecomdev.phpspec.magento_di_adapter.code_generator.io'", ")", ",", "$", "container", "->", "get", "(", "'ecomdev.phpspec.magento_di_adapter.code_generator.defined_classes'", ")", ",", "$", "container", "->", "get", "(", "'loader.transformer.typehintindex'", ")", ")", ";", "$", "parameterValidator", "->", "addGenerator", "(", "Generator", "\\", "Factory", "::", "class", ",", "Generator", "\\", "Factory", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "Generator", "\\", "Repository", "::", "class", ",", "Generator", "\\", "Repository", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "Generator", "\\", "Converter", "::", "class", ",", "Generator", "\\", "Converter", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "Generator", "\\", "Persistor", "::", "class", ",", "Generator", "\\", "Persistor", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "MapperGenerator", "::", "class", ",", "MapperGenerator", "::", "ENTITY_TYPE", ")", "->", "addGenerator", "(", "SearchResults", "::", "class", ",", "SearchResults", "::", "ENTITY_TYPE", ")", ";", "return", "$", "parameterValidator", ";", "}", ";", "}" ]
Factory for instantiation of parameter validator @return \Closure
[ "Factory", "for", "instantiation", "of", "parameter", "validator" ]
train
https://github.com/EcomDev/phpspec-magento-di-adapter/blob/b39f6f0afbb837dbf0eb4c71e6cdb318b8c9de37/src/Extension.php#L67-L87
huasituo/hstcms
src/Libraries/HstcmsValidator.php
HstcmsValidator.hasIdCard
public static function hasIdCard($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp("/\d{17}[\d|X]|\d{15}/", $string, $matches, $ifAll); }
php
public static function hasIdCard($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp("/\d{17}[\d|X]|\d{15}/", $string, $matches, $ifAll); }
[ "public", "static", "function", "hasIdCard", "(", "$", "string", ",", "&", "$", "matches", "=", "array", "(", ")", ",", "$", "ifAll", "=", "false", ")", "{", "return", "0", "<", "self", "::", "validateByRegExp", "(", "\"/\\d{17}[\\d|X]|\\d{15}/\"", ",", "$", "string", ",", "$", "matches", ",", "$", "ifAll", ")", ";", "}" ]
验证是否有合法的身份证号 @param string $string 被搜索的 字符串 @param array $matches 会被搜索的结果,默认为array() @param boolean $ifAll 是否进行全局正则表达式匹配,默认为false即仅进行一次匹配 @return boolean 如果匹配成功返回true,否则返回false
[ "验证是否有合法的身份证号" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsValidator.php#L95-L97
huasituo/hstcms
src/Libraries/HstcmsValidator.php
HstcmsValidator.hasUrl
public static function hasUrl($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/', $string, $matches, $ifAll); }
php
public static function hasUrl($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/', $string, $matches, $ifAll); }
[ "public", "static", "function", "hasUrl", "(", "$", "string", ",", "&", "$", "matches", "=", "array", "(", ")", ",", "$", "ifAll", "=", "false", ")", "{", "return", "0", "<", "self", "::", "validateByRegExp", "(", "'/http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?/'", ",", "$", "string", ",", "$", "matches", ",", "$", "ifAll", ")", ";", "}" ]
验证是否有合法的URL @param string $string 被搜索的 字符串 @param array $matches 会被搜索的结果,默认为array() @param boolean $ifAll 是否进行全局正则表达式匹配,默认为false即仅进行一次匹配 @return boolean 如果匹配成功返回true,否则返回false
[ "验证是否有合法的URL" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsValidator.php#L117-L119
huasituo/hstcms
src/Libraries/HstcmsValidator.php
HstcmsValidator.hasChinese
public static function hasChinese($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/[\x{4e00}-\x{9fa5}]+/u', $string, $matches, $ifAll); }
php
public static function hasChinese($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/[\x{4e00}-\x{9fa5}]+/u', $string, $matches, $ifAll); }
[ "public", "static", "function", "hasChinese", "(", "$", "string", ",", "&", "$", "matches", "=", "array", "(", ")", ",", "$", "ifAll", "=", "false", ")", "{", "return", "0", "<", "self", "::", "validateByRegExp", "(", "'/[\\x{4e00}-\\x{9fa5}]+/u'", ",", "$", "string", ",", "$", "matches", ",", "$", "ifAll", ")", ";", "}" ]
验证是否有中文 @param string $string 被搜索的 字符串 @param array $matches 会被搜索的结果,默认为array() @param boolean $ifAll 是否进行全局正则表达式匹配,默认为false即仅进行一次匹配 @return boolean 如果匹配成功返回true,否则返回false
[ "验证是否有中文" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsValidator.php#L139-L141
huasituo/hstcms
src/Libraries/HstcmsValidator.php
HstcmsValidator.hasHtml
public static function hasHtml($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/<(.*)>.*|<(.*)\/>/', $string, $matches, $ifAll); }
php
public static function hasHtml($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/<(.*)>.*|<(.*)\/>/', $string, $matches, $ifAll); }
[ "public", "static", "function", "hasHtml", "(", "$", "string", ",", "&", "$", "matches", "=", "array", "(", ")", ",", "$", "ifAll", "=", "false", ")", "{", "return", "0", "<", "self", "::", "validateByRegExp", "(", "'/<(.*)>.*|<(.*)\\/>/'", ",", "$", "string", ",", "$", "matches", ",", "$", "ifAll", ")", ";", "}" ]
验证是否有html标记 @param string $string 被搜索的 字符串 @param array $matches 会被搜索的结果,默认为array() @param boolean $ifAll 是否进行全局正则表达式匹配,默认为false即仅进行一次匹配 @return boolean 如果匹配成功返回true,否则返回false
[ "验证是否有html标记" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsValidator.php#L161-L163
huasituo/hstcms
src/Libraries/HstcmsValidator.php
HstcmsValidator.hasIpv4
public static function hasIpv4($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/((25[0-5]|2[0-4]\d|1\d{2}|0?[1-9]\d|0?0?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|0?[1-9]\d|0?0?\d)/', $string, $matches, $ifAll); }
php
public static function hasIpv4($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/((25[0-5]|2[0-4]\d|1\d{2}|0?[1-9]\d|0?0?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|0?[1-9]\d|0?0?\d)/', $string, $matches, $ifAll); }
[ "public", "static", "function", "hasIpv4", "(", "$", "string", ",", "&", "$", "matches", "=", "array", "(", ")", ",", "$", "ifAll", "=", "false", ")", "{", "return", "0", "<", "self", "::", "validateByRegExp", "(", "'/((25[0-5]|2[0-4]\\d|1\\d{2}|0?[1-9]\\d|0?0?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|0?[1-9]\\d|0?0?\\d)/'", ",", "$", "string", ",", "$", "matches", ",", "$", "ifAll", ")", ";", "}" ]
验证是否有合法的ipv4地址 @param string $string 被搜索的 字符串 @param array $matches 会被搜索的结果,默认为array() @param boolean $ifAll 是否进行全局正则表达式匹配,默认为false即仅进行一次匹配 @return boolean 如果匹配成功返回true,否则返回false
[ "验证是否有合法的ipv4地址" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsValidator.php#L183-L185
huasituo/hstcms
src/Libraries/HstcmsValidator.php
HstcmsValidator.hasIpv6
public static function hasIpv6($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/\A((([a-f0-9]{1,4}:){6}| ::([a-f0-9]{1,4}:){5}| ([a-f0-9]{1,4})?::([a-f0-9]{1,4}:){4}| (([a-f0-9]{1,4}:){0,1}[a-f0-9]{1,4})?::([a-f0-9]{1,4}:){3}| (([a-f0-9]{1,4}:){0,2}[a-f0-9]{1,4})?::([a-f0-9]{1,4}:){2}| (([a-f0-9]{1,4}:){0,3}[a-f0-9]{1,4})?::[a-f0-9]{1,4}:| (([a-f0-9]{1,4}:){0,4}[a-f0-9]{1,4})?:: )([a-f0-9]{1,4}:[a-f0-9]{1,4}| (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3} ([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]) )|((([a-f0-9]{1,4}:){0,5}[a-f0-9]{1,4})?::[a-f0-9]{1,4}| (([a-f0-9]{1,4}:){0,6}[a-f0-9]{1,4})?:: ) )\Z/ix', $string, $matches, $ifAll); }
php
public static function hasIpv6($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/\A((([a-f0-9]{1,4}:){6}| ::([a-f0-9]{1,4}:){5}| ([a-f0-9]{1,4})?::([a-f0-9]{1,4}:){4}| (([a-f0-9]{1,4}:){0,1}[a-f0-9]{1,4})?::([a-f0-9]{1,4}:){3}| (([a-f0-9]{1,4}:){0,2}[a-f0-9]{1,4})?::([a-f0-9]{1,4}:){2}| (([a-f0-9]{1,4}:){0,3}[a-f0-9]{1,4})?::[a-f0-9]{1,4}:| (([a-f0-9]{1,4}:){0,4}[a-f0-9]{1,4})?:: )([a-f0-9]{1,4}:[a-f0-9]{1,4}| (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3} ([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]) )|((([a-f0-9]{1,4}:){0,5}[a-f0-9]{1,4})?::[a-f0-9]{1,4}| (([a-f0-9]{1,4}:){0,6}[a-f0-9]{1,4})?:: ) )\Z/ix', $string, $matches, $ifAll); }
[ "public", "static", "function", "hasIpv6", "(", "$", "string", ",", "&", "$", "matches", "=", "array", "(", ")", ",", "$", "ifAll", "=", "false", ")", "{", "return", "0", "<", "self", "::", "validateByRegExp", "(", "'/\\A((([a-f0-9]{1,4}:){6}|\n\t\t\t\t\t\t\t\t\t\t::([a-f0-9]{1,4}:){5}|\n\t\t\t\t\t\t\t\t\t\t([a-f0-9]{1,4})?::([a-f0-9]{1,4}:){4}|\n\t\t\t\t\t\t\t\t\t\t(([a-f0-9]{1,4}:){0,1}[a-f0-9]{1,4})?::([a-f0-9]{1,4}:){3}|\n\t\t\t\t\t\t\t\t\t\t(([a-f0-9]{1,4}:){0,2}[a-f0-9]{1,4})?::([a-f0-9]{1,4}:){2}|\n\t\t\t\t\t\t\t\t\t\t(([a-f0-9]{1,4}:){0,3}[a-f0-9]{1,4})?::[a-f0-9]{1,4}:|\n\t\t\t\t\t\t\t\t\t\t(([a-f0-9]{1,4}:){0,4}[a-f0-9]{1,4})?::\n\t\t\t\t\t\t\t\t\t)([a-f0-9]{1,4}:[a-f0-9]{1,4}|\n\t\t\t\t\t\t\t\t\t\t(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}\n\t\t\t\t\t\t\t\t\t\t([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\n\t\t\t\t\t\t\t\t\t)|((([a-f0-9]{1,4}:){0,5}[a-f0-9]{1,4})?::[a-f0-9]{1,4}|\n\t\t\t\t\t\t\t\t\t\t(([a-f0-9]{1,4}:){0,6}[a-f0-9]{1,4})?::\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t)\\Z/ix'", ",", "$", "string", ",", "$", "matches", ",", "$", "ifAll", ")", ";", "}" ]
验证是否有合法的ipV6 @param string $string 被搜索的 字符串 @param array $matches 会被搜索的结果,默认为array() @param boolean $ifAll 是否进行全局正则表达式匹配,默认为false即仅进行一次匹配 @return boolean 如果匹配成功返回true,否则返回false
[ "验证是否有合法的ipV6" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsValidator.php#L205-L220
huasituo/hstcms
src/Libraries/HstcmsValidator.php
HstcmsValidator.hasScript
public static function hasScript($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/<script(.*?)>([^\x00]*?)<\/script>/', $string, $matches, $ifAll); }
php
public static function hasScript($string, &$matches = array(), $ifAll = false) { return 0 < self::validateByRegExp('/<script(.*?)>([^\x00]*?)<\/script>/', $string, $matches, $ifAll); }
[ "public", "static", "function", "hasScript", "(", "$", "string", ",", "&", "$", "matches", "=", "array", "(", ")", ",", "$", "ifAll", "=", "false", ")", "{", "return", "0", "<", "self", "::", "validateByRegExp", "(", "'/<script(.*?)>([^\\x00]*?)<\\/script>/'", ",", "$", "string", ",", "$", "matches", ",", "$", "ifAll", ")", ";", "}" ]
验证是否有客户端脚本 @param string $string 被搜索的 字符串 @param array $matches 会被搜索的结果,默认为array() @param boolean $ifAll 是否进行全局正则表达式匹配,默认为false即仅进行一次匹配 @return boolean 如果匹配成功返回true,否则返回false
[ "验证是否有客户端脚本" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsValidator.php#L253-L255
huasituo/hstcms
src/Libraries/HstcmsValidator.php
HstcmsValidator.validateByRegExp
private static function validateByRegExp($regExp, $string, &$matches = array(), $ifAll = false) { return $ifAll ? preg_match_all($regExp, $string, $matches) : preg_match($regExp, $string, $matches); }
php
private static function validateByRegExp($regExp, $string, &$matches = array(), $ifAll = false) { return $ifAll ? preg_match_all($regExp, $string, $matches) : preg_match($regExp, $string, $matches); }
[ "private", "static", "function", "validateByRegExp", "(", "$", "regExp", ",", "$", "string", ",", "&", "$", "matches", "=", "array", "(", ")", ",", "$", "ifAll", "=", "false", ")", "{", "return", "$", "ifAll", "?", "preg_match_all", "(", "$", "regExp", ",", "$", "string", ",", "$", "matches", ")", ":", "preg_match", "(", "$", "regExp", ",", "$", "string", ",", "$", "matches", ")", ";", "}" ]
在 $string 字符串中搜索与 $regExp 给出的正则表达式相匹配的内容。 @param string $regExp 搜索的规则(正则) @param string $string 被搜索的 字符串 @param array $matches 会被搜索的结果,默认为array() @param boolean $ifAll 是否进行全局正则表达式匹配,默认为false不进行完全匹配 @return int 返回匹配的次数
[ "在", "$string", "字符串中搜索与", "$regExp", "给出的正则表达式相匹配的内容。" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsValidator.php#L316-L318
huasituo/hstcms
src/Libraries/HstcmsPinYin.php
HstcmsPinYin.result
static function result($s, $quanpin = true, $daxie = false, $trim = false) { $pyCount = 0; if(is_array($quanpin) && $quanpin[1]) { $pyCount = $quanpin[1]; unset($quanpin[1]); $quanpin = $quanpin[0]; } $s = preg_replace("/\s/is", "_", $s); $s = preg_replace("/(|\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\+|\=|\{|\}|\[|\]|\||\\|\:|\;|\"|\'|\<|\,|\>|\.|\?|\/)/is", "", $s); $i = 0; $py = ''; $_trim = $trim ? ' ' : ''; // 加入这一句,自动识别UTF-8 if (strlen("拼音") > 4) $s = iconv('UTF-8', 'GBK', $s); if ($quanpin) { // 全拼 for ($i = 0; $i < strlen($s); $i++) { if (ord($s[$i]) > 128) { $char = self::asi2py(ord($s[$i]) + ord($s[$i + 1]) * 256); $py.=$char.$_trim; $i++; } else { $py.=$s[$i].$_trim; } } } else { // 首字母 for ($i = 0; $i < strlen($s); $i++) { if (ord($s[$i]) > 128) { $char = self::asi2py(ord($s[$i]) + ord($s[$i + 1]) * 256); $py .=$char[0].$_trim; $i++; } else { $py .=$s[$i].$_trim; } } } $py = $trim ? trim($py, ' ') : $py; if($pyCount){ $py = substr($py, 0, $pyCount); } return ($daxie == true ? $py : strtolower($py));// 判断是否输出小写字符 }
php
static function result($s, $quanpin = true, $daxie = false, $trim = false) { $pyCount = 0; if(is_array($quanpin) && $quanpin[1]) { $pyCount = $quanpin[1]; unset($quanpin[1]); $quanpin = $quanpin[0]; } $s = preg_replace("/\s/is", "_", $s); $s = preg_replace("/(|\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\+|\=|\{|\}|\[|\]|\||\\|\:|\;|\"|\'|\<|\,|\>|\.|\?|\/)/is", "", $s); $i = 0; $py = ''; $_trim = $trim ? ' ' : ''; // 加入这一句,自动识别UTF-8 if (strlen("拼音") > 4) $s = iconv('UTF-8', 'GBK', $s); if ($quanpin) { // 全拼 for ($i = 0; $i < strlen($s); $i++) { if (ord($s[$i]) > 128) { $char = self::asi2py(ord($s[$i]) + ord($s[$i + 1]) * 256); $py.=$char.$_trim; $i++; } else { $py.=$s[$i].$_trim; } } } else { // 首字母 for ($i = 0; $i < strlen($s); $i++) { if (ord($s[$i]) > 128) { $char = self::asi2py(ord($s[$i]) + ord($s[$i + 1]) * 256); $py .=$char[0].$_trim; $i++; } else { $py .=$s[$i].$_trim; } } } $py = $trim ? trim($py, ' ') : $py; if($pyCount){ $py = substr($py, 0, $pyCount); } return ($daxie == true ? $py : strtolower($py));// 判断是否输出小写字符 }
[ "static", "function", "result", "(", "$", "s", ",", "$", "quanpin", "=", "true", ",", "$", "daxie", "=", "false", ",", "$", "trim", "=", "false", ")", "{", "$", "pyCount", "=", "0", ";", "if", "(", "is_array", "(", "$", "quanpin", ")", "&&", "$", "quanpin", "[", "1", "]", ")", "{", "$", "pyCount", "=", "$", "quanpin", "[", "1", "]", ";", "unset", "(", "$", "quanpin", "[", "1", "]", ")", ";", "$", "quanpin", "=", "$", "quanpin", "[", "0", "]", ";", "}", "$", "s", "=", "preg_replace", "(", "\"/\\s/is\"", ",", "\"_\"", ",", "$", "s", ")", ";", "$", "s", "=", "preg_replace", "(", "\"/(|\\~|\\`|\\!|\\@|\\#|\\$|\\%|\\^|\\&|\\*|\\(|\\)|\\-|\\+|\\=|\\{|\\}|\\[|\\]|\\||\\\\|\\:|\\;|\\\"|\\'|\\<|\\,|\\>|\\.|\\?|\\/)/is\"", ",", "\"\"", ",", "$", "s", ")", ";", "$", "i", "=", "0", ";", "$", "py", "=", "''", ";", "$", "_trim", "=", "$", "trim", "?", "' '", ":", "''", ";", "// 加入这一句,自动识别UTF-8", "if", "(", "strlen", "(", "\"拼音\") > ", "4", "", "", "", "$", "s", "=", "iconv", "(", "'UTF-8'", ",", "'GBK'", ",", "$", "s", ")", ";", "if", "(", "$", "quanpin", ")", "{", "// 全拼", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "s", ")", ";", "$", "i", "++", ")", "{", "if", "(", "ord", "(", "$", "s", "[", "$", "i", "]", ")", ">", "128", ")", "{", "$", "char", "=", "self", "::", "asi2py", "(", "ord", "(", "$", "s", "[", "$", "i", "]", ")", "+", "ord", "(", "$", "s", "[", "$", "i", "+", "1", "]", ")", "*", "256", ")", ";", "$", "py", ".=", "$", "char", ".", "$", "_trim", ";", "$", "i", "++", ";", "}", "else", "{", "$", "py", ".=", "$", "s", "[", "$", "i", "]", ".", "$", "_trim", ";", "}", "}", "}", "else", "{", "// 首字母", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "s", ")", ";", "$", "i", "++", ")", "{", "if", "(", "ord", "(", "$", "s", "[", "$", "i", "]", ")", ">", "128", ")", "{", "$", "char", "=", "self", "::", "asi2py", "(", "ord", "(", "$", "s", "[", "$", "i", "]", ")", "+", "ord", "(", "$", "s", "[", "$", "i", "+", "1", "]", ")", "*", "256", ")", ";", "$", "py", ".=", "$", "char", "[", "0", "]", ".", "$", "_trim", ";", "$", "i", "++", ";", "}", "else", "{", "$", "py", ".=", "$", "s", "[", "$", "i", "]", ".", "$", "_trim", ";", "}", "}", "}", "$", "py", "=", "$", "trim", "?", "trim", "(", "$", "py", ",", "' '", ")", ":", "$", "py", ";", "if", "(", "$", "pyCount", ")", "{", "$", "py", "=", "substr", "(", "$", "py", ",", "0", ",", "$", "pyCount", ")", ";", "}", "return", "(", "$", "daxie", "==", "true", "?", "$", "py", ":", "strtolower", "(", "$", "py", ")", ")", ";", "// 判断是否输出小写字符", "}" ]
汉字转拼音函数 @param string $s @param bool $quanpin @param bool $daxie @return string
[ "汉字转拼音函数" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsPinYin.php#L530-L574
datasift/datasift-php
lib/DataSift/HistoricPreview.php
DataSift_HistoricPreview.fromResponse
public function fromResponse(array $data) { $map = array( 'id' => 'setId', 'start' => 'setStart', 'end' => 'setEnd', 'hash' => 'setHash', 'parameters' => 'setParameters', 'created_at' => 'setCreatedAt', //only present in responses 'progress' => 'setProgress', 'status' => 'setStatus', 'feeds' => 'setFeeds', 'sample' => 'setSample', 'data' => 'setData', ); foreach ($map as $key => $setter) { if (isset($data[$key])) { $this->$setter($data[$key]); } } return $this; }
php
public function fromResponse(array $data) { $map = array( 'id' => 'setId', 'start' => 'setStart', 'end' => 'setEnd', 'hash' => 'setHash', 'parameters' => 'setParameters', 'created_at' => 'setCreatedAt', //only present in responses 'progress' => 'setProgress', 'status' => 'setStatus', 'feeds' => 'setFeeds', 'sample' => 'setSample', 'data' => 'setData', ); foreach ($map as $key => $setter) { if (isset($data[$key])) { $this->$setter($data[$key]); } } return $this; }
[ "public", "function", "fromResponse", "(", "array", "$", "data", ")", "{", "$", "map", "=", "array", "(", "'id'", "=>", "'setId'", ",", "'start'", "=>", "'setStart'", ",", "'end'", "=>", "'setEnd'", ",", "'hash'", "=>", "'setHash'", ",", "'parameters'", "=>", "'setParameters'", ",", "'created_at'", "=>", "'setCreatedAt'", ",", "//only present in responses", "'progress'", "=>", "'setProgress'", ",", "'status'", "=>", "'setStatus'", ",", "'feeds'", "=>", "'setFeeds'", ",", "'sample'", "=>", "'setSample'", ",", "'data'", "=>", "'setData'", ",", ")", ";", "foreach", "(", "$", "map", "as", "$", "key", "=>", "$", "setter", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "$", "setter", "(", "$", "data", "[", "$", "key", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Hydrates this preview from an array of API responses @param array $data @return DataSift_HistoricPreview
[ "Hydrates", "this", "preview", "from", "an", "array", "of", "API", "responses" ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/HistoricPreview.php#L265-L289
datasift/datasift-php
lib/DataSift/HistoricPreview.php
DataSift_HistoricPreview.toArray
public function toArray() { $data = array(); $map = array( 'id' => 'getId', 'start' => 'getStart', 'end' => 'getEnd', 'hash' => 'getHash', 'parameters' => 'getParameters', 'created_at' => 'getCreatedAt' ); foreach ($map as $key => $getter) { $data[$key] = $this->$getter(); } return $data; }
php
public function toArray() { $data = array(); $map = array( 'id' => 'getId', 'start' => 'getStart', 'end' => 'getEnd', 'hash' => 'getHash', 'parameters' => 'getParameters', 'created_at' => 'getCreatedAt' ); foreach ($map as $key => $getter) { $data[$key] = $this->$getter(); } return $data; }
[ "public", "function", "toArray", "(", ")", "{", "$", "data", "=", "array", "(", ")", ";", "$", "map", "=", "array", "(", "'id'", "=>", "'getId'", ",", "'start'", "=>", "'getStart'", ",", "'end'", "=>", "'getEnd'", ",", "'hash'", "=>", "'getHash'", ",", "'parameters'", "=>", "'getParameters'", ",", "'created_at'", "=>", "'getCreatedAt'", ")", ";", "foreach", "(", "$", "map", "as", "$", "key", "=>", "$", "getter", ")", "{", "$", "data", "[", "$", "key", "]", "=", "$", "this", "->", "$", "getter", "(", ")", ";", "}", "return", "$", "data", ";", "}" ]
Converts this Source to an array suitable for transmission to the API @return array
[ "Converts", "this", "Source", "to", "an", "array", "suitable", "for", "transmission", "to", "the", "API" ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/HistoricPreview.php#L296-L312
datasift/datasift-php
lib/DataSift/HistoricPreview.php
DataSift_HistoricPreview.create
public function create() { $params = array( 'start' => $this->getStart(), 'hash' => $this->getHash(), 'parameters' => implode(',', $this->getParameters()) ); if (is_int($this->end)) { $params['end'] = $this->getEnd(); } $this->fromResponse($this->getUser()->post('preview/create', $params)); }
php
public function create() { $params = array( 'start' => $this->getStart(), 'hash' => $this->getHash(), 'parameters' => implode(',', $this->getParameters()) ); if (is_int($this->end)) { $params['end'] = $this->getEnd(); } $this->fromResponse($this->getUser()->post('preview/create', $params)); }
[ "public", "function", "create", "(", ")", "{", "$", "params", "=", "array", "(", "'start'", "=>", "$", "this", "->", "getStart", "(", ")", ",", "'hash'", "=>", "$", "this", "->", "getHash", "(", ")", ",", "'parameters'", "=>", "implode", "(", "','", ",", "$", "this", "->", "getParameters", "(", ")", ")", ")", ";", "if", "(", "is_int", "(", "$", "this", "->", "end", ")", ")", "{", "$", "params", "[", "'end'", "]", "=", "$", "this", "->", "getEnd", "(", ")", ";", "}", "$", "this", "->", "fromResponse", "(", "$", "this", "->", "getUser", "(", ")", "->", "post", "(", "'preview/create'", ",", "$", "params", ")", ")", ";", "}" ]
Create the preview represented by the parameters in this object @return DataSift_HistoricPreview @throws DataSift_Exception_APIError @throws DataSift_Exception_AccessDenied
[ "Create", "the", "preview", "represented", "by", "the", "parameters", "in", "this", "object" ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/HistoricPreview.php#L322-L333
movoin/one-swoole
src/Swoole/Components/Task/Scheduler.php
Scheduler.setSwoole
public function setSwoole(Server $swoole) { $enabled = isset($swoole->setting['task_worker_num']) && (int) $swoole->setting['task_worker_num'] > 0; if ($enable) { $this->swoole = $swoole; } $this->setEnable($enabled); unset($enabled); }
php
public function setSwoole(Server $swoole) { $enabled = isset($swoole->setting['task_worker_num']) && (int) $swoole->setting['task_worker_num'] > 0; if ($enable) { $this->swoole = $swoole; } $this->setEnable($enabled); unset($enabled); }
[ "public", "function", "setSwoole", "(", "Server", "$", "swoole", ")", "{", "$", "enabled", "=", "isset", "(", "$", "swoole", "->", "setting", "[", "'task_worker_num'", "]", ")", "&&", "(", "int", ")", "$", "swoole", "->", "setting", "[", "'task_worker_num'", "]", ">", "0", ";", "if", "(", "$", "enable", ")", "{", "$", "this", "->", "swoole", "=", "$", "swoole", ";", "}", "$", "this", "->", "setEnable", "(", "$", "enabled", ")", ";", "unset", "(", "$", "enabled", ")", ";", "}" ]
设置 Swoole Server @param \Swoole\Server $swoole
[ "设置", "Swoole", "Server" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Components/Task/Scheduler.php#L41-L53
movoin/one-swoole
src/Swoole/Components/Task/Scheduler.php
Scheduler.has
public function has(string $name): bool { return isset($this->handlers[$name]) && count($this->handlers[$name]) > 0; }
php
public function has(string $name): bool { return isset($this->handlers[$name]) && count($this->handlers[$name]) > 0; }
[ "public", "function", "has", "(", "string", "$", "name", ")", ":", "bool", "{", "return", "isset", "(", "$", "this", "->", "handlers", "[", "$", "name", "]", ")", "&&", "count", "(", "$", "this", "->", "handlers", "[", "$", "name", "]", ")", ">", "0", ";", "}" ]
判断是否存在指定任务的响应句柄 @param string $name @return bool
[ "判断是否存在指定任务的响应句柄" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Components/Task/Scheduler.php#L72-L75
movoin/one-swoole
src/Swoole/Components/Task/Scheduler.php
Scheduler.push
public function push(string $name, string $handler) { if (! isset($this->handlers[$name])) { $this->handlers[$name] = []; } if (! in_array($handler, $this->handlers[$name])) { $this->handlers[$name][] = $handler; } }
php
public function push(string $name, string $handler) { if (! isset($this->handlers[$name])) { $this->handlers[$name] = []; } if (! in_array($handler, $this->handlers[$name])) { $this->handlers[$name][] = $handler; } }
[ "public", "function", "push", "(", "string", "$", "name", ",", "string", "$", "handler", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "handlers", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "handlers", "[", "$", "name", "]", "=", "[", "]", ";", "}", "if", "(", "!", "in_array", "(", "$", "handler", ",", "$", "this", "->", "handlers", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "handlers", "[", "$", "name", "]", "[", "]", "=", "$", "handler", ";", "}", "}" ]
添加任务响应句柄 @param string $name @param string $handler
[ "添加任务响应句柄" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Components/Task/Scheduler.php#L83-L92
movoin/one-swoole
src/Swoole/Components/Task/Scheduler.php
Scheduler.run
public function run(string $name, $parameters = null) { if ($this->enabled && $this->has($name)) { $this->getSwoole()->task([ 'name' => $name, 'parameters' => $parameters ]); } }
php
public function run(string $name, $parameters = null) { if ($this->enabled && $this->has($name)) { $this->getSwoole()->task([ 'name' => $name, 'parameters' => $parameters ]); } }
[ "public", "function", "run", "(", "string", "$", "name", ",", "$", "parameters", "=", "null", ")", "{", "if", "(", "$", "this", "->", "enabled", "&&", "$", "this", "->", "has", "(", "$", "name", ")", ")", "{", "$", "this", "->", "getSwoole", "(", ")", "->", "task", "(", "[", "'name'", "=>", "$", "name", ",", "'parameters'", "=>", "$", "parameters", "]", ")", ";", "}", "}" ]
运行任务 @param string $name @param mixed $parameters
[ "运行任务" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Components/Task/Scheduler.php#L100-L108
movoin/one-swoole
src/Swoole/Components/Task/Scheduler.php
Scheduler.finish
public function finish(string $name, array $result = null) { if ($this->enabled && $this->has($name)) { $this->getSwoole()->finish([ 'name' => $name, 'result' => $result ]); } }
php
public function finish(string $name, array $result = null) { if ($this->enabled && $this->has($name)) { $this->getSwoole()->finish([ 'name' => $name, 'result' => $result ]); } }
[ "public", "function", "finish", "(", "string", "$", "name", ",", "array", "$", "result", "=", "null", ")", "{", "if", "(", "$", "this", "->", "enabled", "&&", "$", "this", "->", "has", "(", "$", "name", ")", ")", "{", "$", "this", "->", "getSwoole", "(", ")", "->", "finish", "(", "[", "'name'", "=>", "$", "name", ",", "'result'", "=>", "$", "result", "]", ")", ";", "}", "}" ]
结束任务 @param string $name @param array|null $result
[ "结束任务" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Components/Task/Scheduler.php#L116-L124
movoin/one-swoole
src/Swoole/Components/Task/Scheduler.php
Scheduler.onTask
public function onTask(Server $server, int $taskId, int $fromId, array $data): array { $result = [ 'name' => $data['name'], 'result' => [] ]; array_walk($this->handlers[$data['name']], function ($name) use ($result) { $handler = $this->createHandler($name); $result[$name][] = $handler->handle($data['parameters']); unset($handler); }); return $result; }
php
public function onTask(Server $server, int $taskId, int $fromId, array $data): array { $result = [ 'name' => $data['name'], 'result' => [] ]; array_walk($this->handlers[$data['name']], function ($name) use ($result) { $handler = $this->createHandler($name); $result[$name][] = $handler->handle($data['parameters']); unset($handler); }); return $result; }
[ "public", "function", "onTask", "(", "Server", "$", "server", ",", "int", "$", "taskId", ",", "int", "$", "fromId", ",", "array", "$", "data", ")", ":", "array", "{", "$", "result", "=", "[", "'name'", "=>", "$", "data", "[", "'name'", "]", ",", "'result'", "=>", "[", "]", "]", ";", "array_walk", "(", "$", "this", "->", "handlers", "[", "$", "data", "[", "'name'", "]", "]", ",", "function", "(", "$", "name", ")", "use", "(", "$", "result", ")", "{", "$", "handler", "=", "$", "this", "->", "createHandler", "(", "$", "name", ")", ";", "$", "result", "[", "$", "name", "]", "[", "]", "=", "$", "handler", "->", "handle", "(", "$", "data", "[", "'parameters'", "]", ")", ";", "unset", "(", "$", "handler", ")", ";", "}", ")", ";", "return", "$", "result", ";", "}" ]
Swoole 异步任务响应事件 @param \Swoole\Server $server @param int $taskId @param int $fromId @param array $data @return array @throws \RuntimeException
[ "Swoole", "异步任务响应事件" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Components/Task/Scheduler.php#L137-L151
movoin/one-swoole
src/Swoole/Components/Task/Scheduler.php
Scheduler.onFinish
public function onFinish(Server $server, int $taskId, $data) { array_walk($this->handlers[$data['name']], function ($name) { $handler = $this->createHandler($name); $handler->finish($data['result']); unset($handler); }); }
php
public function onFinish(Server $server, int $taskId, $data) { array_walk($this->handlers[$data['name']], function ($name) { $handler = $this->createHandler($name); $handler->finish($data['result']); unset($handler); }); }
[ "public", "function", "onFinish", "(", "Server", "$", "server", ",", "int", "$", "taskId", ",", "$", "data", ")", "{", "array_walk", "(", "$", "this", "->", "handlers", "[", "$", "data", "[", "'name'", "]", "]", ",", "function", "(", "$", "name", ")", "{", "$", "handler", "=", "$", "this", "->", "createHandler", "(", "$", "name", ")", ";", "$", "handler", "->", "finish", "(", "$", "data", "[", "'result'", "]", ")", ";", "unset", "(", "$", "handler", ")", ";", "}", ")", ";", "}" ]
Swoole 异步任务结束事件 @param \Swoole\Server $server @param int $taskId @param mixed $data @throws \RuntimeException
[ "Swoole", "异步任务结束事件" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Components/Task/Scheduler.php#L162-L169
movoin/one-swoole
src/Swoole/Components/Task/Scheduler.php
Scheduler.createHandler
protected function createHandler(string $name): TaskHandler { $handler = Reflection::newInstance(ltrim($name, '\\')); if ($handler instanceof TaskHandler) { return $handler; } throw new RuntimeException('Task ' . $name . ' handler must implements `TaskHandler` interface'); }
php
protected function createHandler(string $name): TaskHandler { $handler = Reflection::newInstance(ltrim($name, '\\')); if ($handler instanceof TaskHandler) { return $handler; } throw new RuntimeException('Task ' . $name . ' handler must implements `TaskHandler` interface'); }
[ "protected", "function", "createHandler", "(", "string", "$", "name", ")", ":", "TaskHandler", "{", "$", "handler", "=", "Reflection", "::", "newInstance", "(", "ltrim", "(", "$", "name", ",", "'\\\\'", ")", ")", ";", "if", "(", "$", "handler", "instanceof", "TaskHandler", ")", "{", "return", "$", "handler", ";", "}", "throw", "new", "RuntimeException", "(", "'Task '", ".", "$", "name", ".", "' handler must implements `TaskHandler` interface'", ")", ";", "}" ]
创建任务响应句柄 @param string $name @return One\Swoole\Components\Task\Contracts\TaskHandler @throws \RuntimeException
[ "创建任务响应句柄" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Components/Task/Scheduler.php#L179-L188
comodojo/dispatcher.framework
src/Comodojo/Dispatcher/Response/Preprocessor/Status405.php
Status405.consolidate
public function consolidate(Response $response) { // @NOTE Allow Header should be provided by DispatcherException $allow = $response->getHeaders()->get('Allow'); if (empty($allow)) { throw new Exception("Missing Allow header"); } parent::consolidate(); }
php
public function consolidate(Response $response) { // @NOTE Allow Header should be provided by DispatcherException $allow = $response->getHeaders()->get('Allow'); if (empty($allow)) { throw new Exception("Missing Allow header"); } parent::consolidate(); }
[ "public", "function", "consolidate", "(", "Response", "$", "response", ")", "{", "// @NOTE Allow Header should be provided by DispatcherException", "$", "allow", "=", "$", "response", "->", "getHeaders", "(", ")", "->", "get", "(", "'Allow'", ")", ";", "if", "(", "empty", "(", "$", "allow", ")", ")", "{", "throw", "new", "Exception", "(", "\"Missing Allow header\"", ")", ";", "}", "parent", "::", "consolidate", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/comodojo/dispatcher.framework/blob/5093297dcb7441a8d8f79cbb2429c93232e16d1c/src/Comodojo/Dispatcher/Response/Preprocessor/Status405.php#L29-L40
ftrrtf/FtrrtfRollbarBundle
Helper/UserHelper.php
UserHelper.buildUserData
public function buildUserData($user) { if (is_string($user)) { return array( 'id' => $user, ); } if (!($user instanceof UserInterface)) { return array(); } $userData['id'] = method_exists($user, 'getId') ? $user->getId() : $user->getUsername(); $userData['username'] = $user->getUsername(); if (method_exists($user, 'getEmail')) { $userData['email'] = $user->getEmail(); } return $userData; }
php
public function buildUserData($user) { if (is_string($user)) { return array( 'id' => $user, ); } if (!($user instanceof UserInterface)) { return array(); } $userData['id'] = method_exists($user, 'getId') ? $user->getId() : $user->getUsername(); $userData['username'] = $user->getUsername(); if (method_exists($user, 'getEmail')) { $userData['email'] = $user->getEmail(); } return $userData; }
[ "public", "function", "buildUserData", "(", "$", "user", ")", "{", "if", "(", "is_string", "(", "$", "user", ")", ")", "{", "return", "array", "(", "'id'", "=>", "$", "user", ",", ")", ";", "}", "if", "(", "!", "(", "$", "user", "instanceof", "UserInterface", ")", ")", "{", "return", "array", "(", ")", ";", "}", "$", "userData", "[", "'id'", "]", "=", "method_exists", "(", "$", "user", ",", "'getId'", ")", "?", "$", "user", "->", "getId", "(", ")", ":", "$", "user", "->", "getUsername", "(", ")", ";", "$", "userData", "[", "'username'", "]", "=", "$", "user", "->", "getUsername", "(", ")", ";", "if", "(", "method_exists", "(", "$", "user", ",", "'getEmail'", ")", ")", "{", "$", "userData", "[", "'email'", "]", "=", "$", "user", "->", "getEmail", "(", ")", ";", "}", "return", "$", "userData", ";", "}" ]
Get current user info. @param string|UserInterface $user @return null|array
[ "Get", "current", "user", "info", "." ]
train
https://github.com/ftrrtf/FtrrtfRollbarBundle/blob/64c75862b80a4a1ed9e98c0d217003e84df40dd7/Helper/UserHelper.php#L16-L39
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.listHistorics
public static function listHistorics($user, $page = 1, $per_page = 20) { try { $res = $user->post( 'historics/get', array( 'page' => $page, 'max' => $page, ) ); $retval = array('count' => $res['count'], 'historics' => array()); foreach ($res['data'] as $historic) { $retval['historics'][] = new self($user, $historic); } return $retval; } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public static function listHistorics($user, $page = 1, $per_page = 20) { try { $res = $user->post( 'historics/get', array( 'page' => $page, 'max' => $page, ) ); $retval = array('count' => $res['count'], 'historics' => array()); foreach ($res['data'] as $historic) { $retval['historics'][] = new self($user, $historic); } return $retval; } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "static", "function", "listHistorics", "(", "$", "user", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "20", ")", "{", "try", "{", "$", "res", "=", "$", "user", "->", "post", "(", "'historics/get'", ",", "array", "(", "'page'", "=>", "$", "page", ",", "'max'", "=>", "$", "page", ",", ")", ")", ";", "$", "retval", "=", "array", "(", "'count'", "=>", "$", "res", "[", "'count'", "]", ",", "'historics'", "=>", "array", "(", ")", ")", ";", "foreach", "(", "$", "res", "[", "'data'", "]", "as", "$", "historic", ")", "{", "$", "retval", "[", "'historics'", "]", "[", "]", "=", "new", "self", "(", "$", "user", ",", "$", "historic", ")", ";", "}", "return", "$", "retval", ";", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
List Historics queries. @param DataSift_User $user The user object. @param int $page The start page. @param int $per_page The start page. @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError
[ "List", "Historics", "queries", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L36-L66
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.reloadData
public function reloadData() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot reload the data for a deleted Historic.'); } if ($this->_playback_id === false) { throw new DataSift_Exception_InvalidData('Cannot reload the data for a Historic with no playback ID.'); } try { $this->initFromArray($this->_user->post('historics/get', array('id' => $this->_playback_id))); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public function reloadData() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot reload the data for a deleted Historic.'); } if ($this->_playback_id === false) { throw new DataSift_Exception_InvalidData('Cannot reload the data for a Historic with no playback ID.'); } try { $this->initFromArray($this->_user->post('historics/get', array('id' => $this->_playback_id))); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "function", "reloadData", "(", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot reload the data for a deleted Historic.'", ")", ";", "}", "if", "(", "$", "this", "->", "_playback_id", "===", "false", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot reload the data for a Historic with no playback ID.'", ")", ";", "}", "try", "{", "$", "this", "->", "initFromArray", "(", "$", "this", "->", "_user", "->", "post", "(", "'historics/get'", ",", "array", "(", "'id'", "=>", "$", "this", "->", "_playback_id", ")", ")", ")", ";", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
Reload the data for this object from the API. @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError @throws DataSift_Exception_AccessDenied
[ "Reload", "the", "data", "for", "this", "object", "from", "the", "API", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L243-L267
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.initFromArray
protected function initFromArray($data) { if (! isset($data['id'])) { throw new DataSift_Exception_APIError('No playback ID in the response'); } if ($data['id'] != $this->_playback_id) { throw new DataSift_Exception_APIError('Incorrect playback ID in the response'); } if (! isset($data['definition_id'])) { throw new DataSift_Exception_APIError('No definition hash in the response'); } $this->_hash = $data['definition_id']; if (! isset($data['name'])) { throw new DataSift_Exception_APIError('No name in the response'); } $this->_name = $data['name']; if (! isset($data['start'])) { throw new DataSift_Exception_APIError('No start timestamp in the response'); } $this->_start = $data['start']; if (! isset($data['end'])) { throw new DataSift_Exception_APIError('No end timestamp in the response'); } $this->_end = $data['end']; if (! isset($data['created_at'])) { throw new DataSift_Exception_APIError('No created at timestamp in the response'); } $this->_created_at = $data['created_at']; if (! isset($data['status'])) { throw new DataSift_Exception_APIError('No status in the response'); } $this->_status = $data['status']; if (! isset($data['progress'])) { throw new DataSift_Exception_APIError('No progress in the response'); } $this->_progress = $data['progress']; if (! isset($data['sources'])) { throw new DataSift_Exception_APIError('No sources in the response'); } $this->_sources = $data['sources']; if (! isset($data['sample'])) { throw new DataSift_Exception_APIError('No smaple in the response'); } $this->_sample = $data['sample']; if (isset($data['estimated_completion'])) { $this->_estimated_completion = $data['estimated_completion']; } if ($this->_status == 'deleted') { $this->_deleted = true; } }
php
protected function initFromArray($data) { if (! isset($data['id'])) { throw new DataSift_Exception_APIError('No playback ID in the response'); } if ($data['id'] != $this->_playback_id) { throw new DataSift_Exception_APIError('Incorrect playback ID in the response'); } if (! isset($data['definition_id'])) { throw new DataSift_Exception_APIError('No definition hash in the response'); } $this->_hash = $data['definition_id']; if (! isset($data['name'])) { throw new DataSift_Exception_APIError('No name in the response'); } $this->_name = $data['name']; if (! isset($data['start'])) { throw new DataSift_Exception_APIError('No start timestamp in the response'); } $this->_start = $data['start']; if (! isset($data['end'])) { throw new DataSift_Exception_APIError('No end timestamp in the response'); } $this->_end = $data['end']; if (! isset($data['created_at'])) { throw new DataSift_Exception_APIError('No created at timestamp in the response'); } $this->_created_at = $data['created_at']; if (! isset($data['status'])) { throw new DataSift_Exception_APIError('No status in the response'); } $this->_status = $data['status']; if (! isset($data['progress'])) { throw new DataSift_Exception_APIError('No progress in the response'); } $this->_progress = $data['progress']; if (! isset($data['sources'])) { throw new DataSift_Exception_APIError('No sources in the response'); } $this->_sources = $data['sources']; if (! isset($data['sample'])) { throw new DataSift_Exception_APIError('No smaple in the response'); } $this->_sample = $data['sample']; if (isset($data['estimated_completion'])) { $this->_estimated_completion = $data['estimated_completion']; } if ($this->_status == 'deleted') { $this->_deleted = true; } }
[ "protected", "function", "initFromArray", "(", "$", "data", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'id'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No playback ID in the response'", ")", ";", "}", "if", "(", "$", "data", "[", "'id'", "]", "!=", "$", "this", "->", "_playback_id", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'Incorrect playback ID in the response'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "data", "[", "'definition_id'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No definition hash in the response'", ")", ";", "}", "$", "this", "->", "_hash", "=", "$", "data", "[", "'definition_id'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'name'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No name in the response'", ")", ";", "}", "$", "this", "->", "_name", "=", "$", "data", "[", "'name'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'start'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No start timestamp in the response'", ")", ";", "}", "$", "this", "->", "_start", "=", "$", "data", "[", "'start'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'end'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No end timestamp in the response'", ")", ";", "}", "$", "this", "->", "_end", "=", "$", "data", "[", "'end'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'created_at'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No created at timestamp in the response'", ")", ";", "}", "$", "this", "->", "_created_at", "=", "$", "data", "[", "'created_at'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'status'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No status in the response'", ")", ";", "}", "$", "this", "->", "_status", "=", "$", "data", "[", "'status'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'progress'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No progress in the response'", ")", ";", "}", "$", "this", "->", "_progress", "=", "$", "data", "[", "'progress'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'sources'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No sources in the response'", ")", ";", "}", "$", "this", "->", "_sources", "=", "$", "data", "[", "'sources'", "]", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'sample'", "]", ")", ")", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No smaple in the response'", ")", ";", "}", "$", "this", "->", "_sample", "=", "$", "data", "[", "'sample'", "]", ";", "if", "(", "isset", "(", "$", "data", "[", "'estimated_completion'", "]", ")", ")", "{", "$", "this", "->", "_estimated_completion", "=", "$", "data", "[", "'estimated_completion'", "]", ";", "}", "if", "(", "$", "this", "->", "_status", "==", "'deleted'", ")", "{", "$", "this", "->", "_deleted", "=", "true", ";", "}", "}" ]
Initialise this object from the data in the given array. @param array $data The array of data. @throws DataSift_Exception_InvalidData
[ "Initialise", "this", "object", "from", "the", "data", "in", "the", "given", "array", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L276-L337
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.setName
public function setName($name) { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot set the name of a deleted Historic.'); } // Update locally if this query hasn't been prepared, otherwise send // it to the API. if ($this->_playback_id === false) { $this->_name = $name; } else { $res = $this->_user->post( 'historics/update', array( 'id' => $this->_playback_id, 'name' => $name, ) ); $this->reloadData(); } }
php
public function setName($name) { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot set the name of a deleted Historic.'); } // Update locally if this query hasn't been prepared, otherwise send // it to the API. if ($this->_playback_id === false) { $this->_name = $name; } else { $res = $this->_user->post( 'historics/update', array( 'id' => $this->_playback_id, 'name' => $name, ) ); $this->reloadData(); } }
[ "public", "function", "setName", "(", "$", "name", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot set the name of a deleted Historic.'", ")", ";", "}", "// Update locally if this query hasn't been prepared, otherwise send", "// it to the API.", "if", "(", "$", "this", "->", "_playback_id", "===", "false", ")", "{", "$", "this", "->", "_name", "=", "$", "name", ";", "}", "else", "{", "$", "res", "=", "$", "this", "->", "_user", "->", "post", "(", "'historics/update'", ",", "array", "(", "'id'", "=>", "$", "this", "->", "_playback_id", ",", "'name'", "=>", "$", "name", ",", ")", ")", ";", "$", "this", "->", "reloadData", "(", ")", ";", "}", "}" ]
Sets the name. @param string $name The new name. @return void
[ "Sets", "the", "name", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L469-L490
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.prepare
public function prepare() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot prepare a deleted Historic.'); } if ($this->_playback_id !== false) { throw new DataSift_Exception_InvalidData('This historic query has already been prepared.'); } try { $res = $this->_user->post( 'historics/prepare', array( 'hash' => $this->_hash, 'start' => $this->_start, 'end' => $this->_end, 'name' => $this->_name, 'sources' => implode(',', $this->_sources), 'sample' => $this->_sample, ) ); if (isset($res['id'])) { $this->_playback_id = $res['id']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no playback ID in the response'); } if (isset($res['dpus'])) { $this->_dpus = $res['dpus']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no DPU cost in the response'); } if (isset($res['availability'])) { $this->_availability = $res['availability']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no availability in the response'); } } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public function prepare() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot prepare a deleted Historic.'); } if ($this->_playback_id !== false) { throw new DataSift_Exception_InvalidData('This historic query has already been prepared.'); } try { $res = $this->_user->post( 'historics/prepare', array( 'hash' => $this->_hash, 'start' => $this->_start, 'end' => $this->_end, 'name' => $this->_name, 'sources' => implode(',', $this->_sources), 'sample' => $this->_sample, ) ); if (isset($res['id'])) { $this->_playback_id = $res['id']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no playback ID in the response'); } if (isset($res['dpus'])) { $this->_dpus = $res['dpus']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no DPU cost in the response'); } if (isset($res['availability'])) { $this->_availability = $res['availability']; } else { throw new DataSift_Exception_APIError('Prepared successfully but no availability in the response'); } } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "function", "prepare", "(", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot prepare a deleted Historic.'", ")", ";", "}", "if", "(", "$", "this", "->", "_playback_id", "!==", "false", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'This historic query has already been prepared.'", ")", ";", "}", "try", "{", "$", "res", "=", "$", "this", "->", "_user", "->", "post", "(", "'historics/prepare'", ",", "array", "(", "'hash'", "=>", "$", "this", "->", "_hash", ",", "'start'", "=>", "$", "this", "->", "_start", ",", "'end'", "=>", "$", "this", "->", "_end", ",", "'name'", "=>", "$", "this", "->", "_name", ",", "'sources'", "=>", "implode", "(", "','", ",", "$", "this", "->", "_sources", ")", ",", "'sample'", "=>", "$", "this", "->", "_sample", ",", ")", ")", ";", "if", "(", "isset", "(", "$", "res", "[", "'id'", "]", ")", ")", "{", "$", "this", "->", "_playback_id", "=", "$", "res", "[", "'id'", "]", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'Prepared successfully but no playback ID in the response'", ")", ";", "}", "if", "(", "isset", "(", "$", "res", "[", "'dpus'", "]", ")", ")", "{", "$", "this", "->", "_dpus", "=", "$", "res", "[", "'dpus'", "]", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'Prepared successfully but no DPU cost in the response'", ")", ";", "}", "if", "(", "isset", "(", "$", "res", "[", "'availability'", "]", ")", ")", "{", "$", "this", "->", "_availability", "=", "$", "res", "[", "'availability'", "]", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'Prepared successfully but no availability in the response'", ")", ";", "}", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
Call the DataSift API to prepare this historic query. @return void @throws DataSift_Exception_APIError @throws DataSift_Exception_InvalidData
[ "Call", "the", "DataSift", "API", "to", "prepare", "this", "historic", "query", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L530-L582
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.stop
public function stop() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot stop a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot stop a historic query that hasn\'t been prepared.'); } try { $res = $this->_user->post( 'historics/stop', array( 'id' => $this->_playback_id, ) ); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); case 404: // Historic query not found throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public function stop() { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot stop a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot stop a historic query that hasn\'t been prepared.'); } try { $res = $this->_user->post( 'historics/stop', array( 'id' => $this->_playback_id, ) ); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); case 404: // Historic query not found throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "function", "stop", "(", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot stop a deleted Historic.'", ")", ";", "}", "if", "(", "$", "this", "->", "_playback_id", "===", "false", "||", "strlen", "(", "$", "this", "->", "_playback_id", ")", "==", "0", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot stop a historic query that hasn\\'t been prepared.'", ")", ";", "}", "try", "{", "$", "res", "=", "$", "this", "->", "_user", "->", "post", "(", "'historics/stop'", ",", "array", "(", "'id'", "=>", "$", "this", "->", "_playback_id", ",", ")", ")", ";", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "case", "404", ":", "// Historic query not found", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
Stop this historic query. @return void @throws DataSift_Exception_APIError @throws DataSift_Exception_InvalidData
[ "Stop", "this", "historic", "query", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L633-L666
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.pause
public function pause($reason = false) { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot pause a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot pause a historic query that hasn\'t been prepared.'); } try { $params = array('id' => $this->_playback_id); if ($reason) { $params['reason'] = $reason; } $res = $this->_user->post('historics/pause', $params); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); case 404: // Historic query not found throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public function pause($reason = false) { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot pause a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData('Cannot pause a historic query that hasn\'t been prepared.'); } try { $params = array('id' => $this->_playback_id); if ($reason) { $params['reason'] = $reason; } $res = $this->_user->post('historics/pause', $params); } catch (DataSift_Exception_APIError $e) { switch ($e->getCode()) { case 400: // Missing or invalid parameters throw new DataSift_Exception_InvalidData($e->getMessage()); case 404: // Historic query not found throw new DataSift_Exception_InvalidData($e->getMessage()); default: throw new DataSift_Exception_APIError( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "function", "pause", "(", "$", "reason", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot pause a deleted Historic.'", ")", ";", "}", "if", "(", "$", "this", "->", "_playback_id", "===", "false", "||", "strlen", "(", "$", "this", "->", "_playback_id", ")", "==", "0", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot pause a historic query that hasn\\'t been prepared.'", ")", ";", "}", "try", "{", "$", "params", "=", "array", "(", "'id'", "=>", "$", "this", "->", "_playback_id", ")", ";", "if", "(", "$", "reason", ")", "{", "$", "params", "[", "'reason'", "]", "=", "$", "reason", ";", "}", "$", "res", "=", "$", "this", "->", "_user", "->", "post", "(", "'historics/pause'", ",", "$", "params", ")", ";", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Missing or invalid parameters", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "case", "404", ":", "// Historic query not found", "throw", "new", "DataSift_Exception_InvalidData", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "default", ":", "throw", "new", "DataSift_Exception_APIError", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
Pause this historic query. @param string $reason Your reason for pausing the Historics query. @return void @throws DataSift_Exception_APIError @throws DataSift_Exception_InvalidData
[ "Pause", "this", "historic", "query", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L677-L707
datasift/datasift-php
lib/DataSift/Historic.php
DataSift_Historic.getPushSubscriptions
public function getPushSubscriptions( $user, $page = 1, $per_page = 20, $order_by = self::ORDERBY_CREATED_AT, $order_dir = self::ORDERDIR_ASC, $include_finished = false ) { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot get the push subscriptions for a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData( 'Cannot get the push subscriptions for a historic query that hasn\'t been prepared.' ); } return DataSift_Push_Subscription::listSubscriptions( $this->_user, $page, $per_page, $order_by, $order_dir, $include_finished, $hash_type = 'playback_id', $this->_playback_id ); }
php
public function getPushSubscriptions( $user, $page = 1, $per_page = 20, $order_by = self::ORDERBY_CREATED_AT, $order_dir = self::ORDERDIR_ASC, $include_finished = false ) { if ($this->_deleted) { throw new DataSift_Exception_InvalidData('Cannot get the push subscriptions for a deleted Historic.'); } if ($this->_playback_id === false || strlen($this->_playback_id) == 0) { throw new DataSift_Exception_InvalidData( 'Cannot get the push subscriptions for a historic query that hasn\'t been prepared.' ); } return DataSift_Push_Subscription::listSubscriptions( $this->_user, $page, $per_page, $order_by, $order_dir, $include_finished, $hash_type = 'playback_id', $this->_playback_id ); }
[ "public", "function", "getPushSubscriptions", "(", "$", "user", ",", "$", "page", "=", "1", ",", "$", "per_page", "=", "20", ",", "$", "order_by", "=", "self", "::", "ORDERBY_CREATED_AT", ",", "$", "order_dir", "=", "self", "::", "ORDERDIR_ASC", ",", "$", "include_finished", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_deleted", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot get the push subscriptions for a deleted Historic.'", ")", ";", "}", "if", "(", "$", "this", "->", "_playback_id", "===", "false", "||", "strlen", "(", "$", "this", "->", "_playback_id", ")", "==", "0", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot get the push subscriptions for a historic query that hasn\\'t been prepared.'", ")", ";", "}", "return", "DataSift_Push_Subscription", "::", "listSubscriptions", "(", "$", "this", "->", "_user", ",", "$", "page", ",", "$", "per_page", ",", "$", "order_by", ",", "$", "order_dir", ",", "$", "include_finished", ",", "$", "hash_type", "=", "'playback_id'", ",", "$", "this", "->", "_playback_id", ")", ";", "}" ]
Get a page of push subscriptions for this historic query, where each page contains up to $per_page items. Results will be returned in the order requested. @param DataSift_User $user The user object. @param int $page The page number to get. @param int $per_page The number of items per page. @param String $order_by Which field to sort by. @param String $order_dir In asc[ending] or desc[ending] order. @param bool $include_finished Set to true when you want to include finished subscription in the results.
[ "Get", "a", "page", "of", "push", "subscriptions", "for", "this", "historic", "query", "where", "each", "page", "contains", "up", "to", "$per_page", "items", ".", "Results", "will", "be", "returned", "in", "the", "order", "requested", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Historic.php#L801-L829
Nayjest/Tree
src/ChildNodeTrait.php
ChildNodeTrait.internalSetParent
final public function internalSetParent(ParentNodeInterface $parent) { $this->emit('parent.change', [$parent, $this]); $this->parentNode = $parent; }
php
final public function internalSetParent(ParentNodeInterface $parent) { $this->emit('parent.change', [$parent, $this]); $this->parentNode = $parent; }
[ "final", "public", "function", "internalSetParent", "(", "ParentNodeInterface", "$", "parent", ")", "{", "$", "this", "->", "emit", "(", "'parent.change'", ",", "[", "$", "parent", ",", "$", "this", "]", ")", ";", "$", "this", "->", "parentNode", "=", "$", "parent", ";", "}" ]
Attaches component to registry. @param ParentNodeInterface $parent @return null
[ "Attaches", "component", "to", "registry", "." ]
train
https://github.com/Nayjest/Tree/blob/e73da75f939e207b1c25065e9466c28300e7113c/src/ChildNodeTrait.php#L37-L41
esperecyan/dictionary-php
src/validator/WordValidator.php
WordValidator.parseMetadata
public function parseMetadata(array $metaFields): array { $metadata = []; foreach ($metaFields as $fieldName => $field) { $validatedField = $this->parseField($fieldName, $field); if (!is_null($validatedField)) { $metadata[$fieldName] = $validatedField; } } return $metadata; }
php
public function parseMetadata(array $metaFields): array { $metadata = []; foreach ($metaFields as $fieldName => $field) { $validatedField = $this->parseField($fieldName, $field); if (!is_null($validatedField)) { $metadata[$fieldName] = $validatedField; } } return $metadata; }
[ "public", "function", "parseMetadata", "(", "array", "$", "metaFields", ")", ":", "array", "{", "$", "metadata", "=", "[", "]", ";", "foreach", "(", "$", "metaFields", "as", "$", "fieldName", "=>", "$", "field", ")", "{", "$", "validatedField", "=", "$", "this", "->", "parseField", "(", "$", "fieldName", ",", "$", "field", ")", ";", "if", "(", "!", "is_null", "(", "$", "validatedField", ")", ")", "{", "$", "metadata", "[", "$", "fieldName", "]", "=", "$", "validatedField", ";", "}", "}", "return", "$", "metadata", ";", "}" ]
キーにフィールド名、値にフィールド値を持つ配列から、辞書のメタフィールドを生成します。 @param string[] $metaFields フィールド名はバリデート済み、かつフィールド値が空文字列であってはなりません。 @return (string|string[])[]
[ "キーにフィールド名、値にフィールド値を持つ配列から、辞書のメタフィールドを生成します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/validator/WordValidator.php#L41-L53
esperecyan/dictionary-php
src/validator/WordValidator.php
WordValidator.parse
public function parse(array $fieldsAsMultiDimensionalArray): array { $word = []; foreach ($fieldsAsMultiDimensionalArray as $fieldName => $fields) { foreach ($fields as $field) { $validatedField = $this->parseField($fieldName, $field); if (!is_null($validatedField)) { $word[$fieldName][] = $validatedField; } } } if (!isset($word['text'][0])) { // textフィールドが存在しない場合 throw new SyntaxException(_('textフィールドは必須です。')); } if (isset($word['type'][0]) && $word['type'][0] === 'selection') { // typeフィールドにselectionが指定されている場合 if (!isset($word['option'][0])) { throw new SyntaxException( _('typeフィールドに「selection」が指定されている場合、optionフィールドは必須です。') ); } if (isset($word['answer'])) { // 選択問題なら foreach ($word['answer'] as $answer) { if (!in_array($answer, $word['option'])) { throw new SyntaxException(sprintf(_('「%s」はoptionフィールドのいずれの値にも一致しません。'), $answer)); } } } } $answerValidator = new AnswerValidator(); if (isset($word['answer'][0]) && $answerValidator->isRegExp($word['answer'][0])) { // 1個目のanswerフィールドが正規表現文字列だった場合 $this->logger->error(_('1個目のanswerフィールドは、正規表現文字列であってはなりません。')); foreach ($word['answer'] as $index => $answer) { if (!$answerValidator->isRegExp($answer)) { $noRegExpIndex = $index; break; } } if (isset($noRegExpIndex)) { array_unshift( $word['answer'], array_splice($word['answer'], $noRegExpIndex)[0] ); } else { unset($word['answer']); } } if (!isset($word['answer'][0]) && ($word['type'][0] ?? null) !== 'selection') { // answerフィールドが存在せず、typeフィールドがselectionでない場合 $text = $this->parseField('answer', $word['text'][0]); if (is_null($text)) { throw new SyntaxException(sprintf( _('「%s」は解答文字列の規則に合致しません。'), $word['text'][0] )); } else { $word['text'][0] = $text; } } return $word; }
php
public function parse(array $fieldsAsMultiDimensionalArray): array { $word = []; foreach ($fieldsAsMultiDimensionalArray as $fieldName => $fields) { foreach ($fields as $field) { $validatedField = $this->parseField($fieldName, $field); if (!is_null($validatedField)) { $word[$fieldName][] = $validatedField; } } } if (!isset($word['text'][0])) { // textフィールドが存在しない場合 throw new SyntaxException(_('textフィールドは必須です。')); } if (isset($word['type'][0]) && $word['type'][0] === 'selection') { // typeフィールドにselectionが指定されている場合 if (!isset($word['option'][0])) { throw new SyntaxException( _('typeフィールドに「selection」が指定されている場合、optionフィールドは必須です。') ); } if (isset($word['answer'])) { // 選択問題なら foreach ($word['answer'] as $answer) { if (!in_array($answer, $word['option'])) { throw new SyntaxException(sprintf(_('「%s」はoptionフィールドのいずれの値にも一致しません。'), $answer)); } } } } $answerValidator = new AnswerValidator(); if (isset($word['answer'][0]) && $answerValidator->isRegExp($word['answer'][0])) { // 1個目のanswerフィールドが正規表現文字列だった場合 $this->logger->error(_('1個目のanswerフィールドは、正規表現文字列であってはなりません。')); foreach ($word['answer'] as $index => $answer) { if (!$answerValidator->isRegExp($answer)) { $noRegExpIndex = $index; break; } } if (isset($noRegExpIndex)) { array_unshift( $word['answer'], array_splice($word['answer'], $noRegExpIndex)[0] ); } else { unset($word['answer']); } } if (!isset($word['answer'][0]) && ($word['type'][0] ?? null) !== 'selection') { // answerフィールドが存在せず、typeフィールドがselectionでない場合 $text = $this->parseField('answer', $word['text'][0]); if (is_null($text)) { throw new SyntaxException(sprintf( _('「%s」は解答文字列の規則に合致しません。'), $word['text'][0] )); } else { $word['text'][0] = $text; } } return $word; }
[ "public", "function", "parse", "(", "array", "$", "fieldsAsMultiDimensionalArray", ")", ":", "array", "{", "$", "word", "=", "[", "]", ";", "foreach", "(", "$", "fieldsAsMultiDimensionalArray", "as", "$", "fieldName", "=>", "$", "fields", ")", "{", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "validatedField", "=", "$", "this", "->", "parseField", "(", "$", "fieldName", ",", "$", "field", ")", ";", "if", "(", "!", "is_null", "(", "$", "validatedField", ")", ")", "{", "$", "word", "[", "$", "fieldName", "]", "[", "]", "=", "$", "validatedField", ";", "}", "}", "}", "if", "(", "!", "isset", "(", "$", "word", "[", "'text'", "]", "[", "0", "]", ")", ")", "{", "// textフィールドが存在しない場合", "throw", "new", "SyntaxException", "(", "_", "(", "'textフィールドは必須です。'));", "", "", "", "}", "if", "(", "isset", "(", "$", "word", "[", "'type'", "]", "[", "0", "]", ")", "&&", "$", "word", "[", "'type'", "]", "[", "0", "]", "===", "'selection'", ")", "{", "// typeフィールドにselectionが指定されている場合", "if", "(", "!", "isset", "(", "$", "word", "[", "'option'", "]", "[", "0", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'typeフィールドに「selection」が指定されている場合、optionフィールドは必須です。')", "", ")", ";", "}", "if", "(", "isset", "(", "$", "word", "[", "'answer'", "]", ")", ")", "{", "// 選択問題なら", "foreach", "(", "$", "word", "[", "'answer'", "]", "as", "$", "answer", ")", "{", "if", "(", "!", "in_array", "(", "$", "answer", ",", "$", "word", "[", "'option'", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'「%s」はoptionフィールドのいずれの値にも一致しません。'), $answer));", "", "", "", "", "", "", "", "}", "}", "}", "}", "$", "answerValidator", "=", "new", "AnswerValidator", "(", ")", ";", "if", "(", "isset", "(", "$", "word", "[", "'answer'", "]", "[", "0", "]", ")", "&&", "$", "answerValidator", "->", "isRegExp", "(", "$", "word", "[", "'answer'", "]", "[", "0", "]", ")", ")", "{", "// 1個目のanswerフィールドが正規表現文字列だった場合", "$", "this", "->", "logger", "->", "error", "(", "_", "(", "'1個目のanswerフィールドは、正規表現文字列であってはなりません。'));", "", "", "", "foreach", "(", "$", "word", "[", "'answer'", "]", "as", "$", "index", "=>", "$", "answer", ")", "{", "if", "(", "!", "$", "answerValidator", "->", "isRegExp", "(", "$", "answer", ")", ")", "{", "$", "noRegExpIndex", "=", "$", "index", ";", "break", ";", "}", "}", "if", "(", "isset", "(", "$", "noRegExpIndex", ")", ")", "{", "array_unshift", "(", "$", "word", "[", "'answer'", "]", ",", "array_splice", "(", "$", "word", "[", "'answer'", "]", ",", "$", "noRegExpIndex", ")", "[", "0", "]", ")", ";", "}", "else", "{", "unset", "(", "$", "word", "[", "'answer'", "]", ")", ";", "}", "}", "if", "(", "!", "isset", "(", "$", "word", "[", "'answer'", "]", "[", "0", "]", ")", "&&", "(", "$", "word", "[", "'type'", "]", "[", "0", "]", "??", "null", ")", "!==", "'selection'", ")", "{", "// answerフィールドが存在せず、typeフィールドがselectionでない場合", "$", "text", "=", "$", "this", "->", "parseField", "(", "'answer'", ",", "$", "word", "[", "'text'", "]", "[", "0", "]", ")", ";", "if", "(", "is_null", "(", "$", "text", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'「%s」は解答文字列の規則に合致しません。'),", "", "", "$", "word", "[", "'text'", "]", "[", "0", "]", ")", ")", ";", "}", "else", "{", "$", "word", "[", "'text'", "]", "[", "0", "]", "=", "$", "text", ";", "}", "}", "return", "$", "word", ";", "}" ]
キーにフィールド名、値に同名フィールド値の配列を持つ配列から、1つのお題を表す配列を生成します。 @param string[][] $fieldsAsMultiDimensionalArray フィールド名はバリデート済み、かつフィールド値が空文字列であってはなりません。 @throws SyntaxException 妥当なtextフィールドが存在しない場合。 typeフィールドにselectionが指定されているとき、answerフィールド、optionフィールドが規則に合致しない場合。 @return (string|string[]|float)[][]
[ "キーにフィールド名、値に同名フィールド値の配列を持つ配列から、1つのお題を表す配列を生成します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/validator/WordValidator.php#L62-L134
esperecyan/dictionary-php
src/validator/WordValidator.php
WordValidator.parseField
protected function parseField(string $fieldName, string $field) { $field = str_replace("\t", ' ', $field); switch ($fieldName) { case 'image': case 'audio': case 'video': $validator = new FileLocationValidator($fieldName, $this->filenames); $validator->setLogger($this->logger); $output = $validator->correct($field); break; case 'image-source': case 'audio-source': case 'video-source': $validator = new LightweightMarkupValidator(true); $validator->setLogger($this->logger); $output = $validator->correct($field); if ($output !== '') { $output = [ 'lml' => $output, 'html' => (new HTMLFilter())->filter((new CommonMarkConverter())->convertToHtml($output)), ]; } break; case 'answer': case 'option': $validator = new AnswerValidator(); $validator->setLogger($this->logger); $output = $validator->correct($field); break; case 'description': case '@summary': $validator = new LightweightMarkupValidator(false, $this->filenames); $validator->setLogger($this->logger); $output = $validator->correct($field); if ($output !== '') { $output = [ 'lml' => $output, 'html' => (new HTMLFilter())->filter((new CommonMarkConverter())->convertToHtml($output)), ]; } break; case 'weight': $validator = new NumberValidator(true); $validator->setLogger($this->logger); $number = $validator->correct($field); if ($number > 0) { $output = $number; } else { $this->logger->error(sprintf(_('「%s」は0より大きい実数として扱えません。'), $field)); $output = ''; } if ($output !== '') { $output = (float)$output; } break; case 'specifics': $validator = new SpecificsValidator(); $validator->setLogger($this->logger); $output = $validator->correct($field); break; case '@regard': if (preg_match('/^\\[.{3,}]$/u', $field) === 1 && (new AnswerValidator())->validateRegexp("/$field/")) { $output = $field; } else { $this->logger->error(sprintf(_('「%s」は妥当な正規表現文字クラスではありません。'), $field)); $output = ''; } break; default: $output = $field; } $correctedField = is_array($output) ? $output['lml'] : $output; $fieldLength = mb_strlen($correctedField, 'UTF-8'); $maxFieldLength = in_array($fieldName, self::MARKUP_FIELD_NAMES) ? self::MAX_MARKUP_FIELD_LENGTH : self::MAX_FIELD_LENGTH; if ($fieldLength > $maxFieldLength) { throw new SyntaxException(sprintf( _('「%1$s」フィールドの値は%2$d文字です。%3$d文字以内にしなければなりません:'), $fieldName, $fieldLength, $maxFieldLength ) . "\n$correctedField"); } return $output === '' ? null : $output; }
php
protected function parseField(string $fieldName, string $field) { $field = str_replace("\t", ' ', $field); switch ($fieldName) { case 'image': case 'audio': case 'video': $validator = new FileLocationValidator($fieldName, $this->filenames); $validator->setLogger($this->logger); $output = $validator->correct($field); break; case 'image-source': case 'audio-source': case 'video-source': $validator = new LightweightMarkupValidator(true); $validator->setLogger($this->logger); $output = $validator->correct($field); if ($output !== '') { $output = [ 'lml' => $output, 'html' => (new HTMLFilter())->filter((new CommonMarkConverter())->convertToHtml($output)), ]; } break; case 'answer': case 'option': $validator = new AnswerValidator(); $validator->setLogger($this->logger); $output = $validator->correct($field); break; case 'description': case '@summary': $validator = new LightweightMarkupValidator(false, $this->filenames); $validator->setLogger($this->logger); $output = $validator->correct($field); if ($output !== '') { $output = [ 'lml' => $output, 'html' => (new HTMLFilter())->filter((new CommonMarkConverter())->convertToHtml($output)), ]; } break; case 'weight': $validator = new NumberValidator(true); $validator->setLogger($this->logger); $number = $validator->correct($field); if ($number > 0) { $output = $number; } else { $this->logger->error(sprintf(_('「%s」は0より大きい実数として扱えません。'), $field)); $output = ''; } if ($output !== '') { $output = (float)$output; } break; case 'specifics': $validator = new SpecificsValidator(); $validator->setLogger($this->logger); $output = $validator->correct($field); break; case '@regard': if (preg_match('/^\\[.{3,}]$/u', $field) === 1 && (new AnswerValidator())->validateRegexp("/$field/")) { $output = $field; } else { $this->logger->error(sprintf(_('「%s」は妥当な正規表現文字クラスではありません。'), $field)); $output = ''; } break; default: $output = $field; } $correctedField = is_array($output) ? $output['lml'] : $output; $fieldLength = mb_strlen($correctedField, 'UTF-8'); $maxFieldLength = in_array($fieldName, self::MARKUP_FIELD_NAMES) ? self::MAX_MARKUP_FIELD_LENGTH : self::MAX_FIELD_LENGTH; if ($fieldLength > $maxFieldLength) { throw new SyntaxException(sprintf( _('「%1$s」フィールドの値は%2$d文字です。%3$d文字以内にしなければなりません:'), $fieldName, $fieldLength, $maxFieldLength ) . "\n$correctedField"); } return $output === '' ? null : $output; }
[ "protected", "function", "parseField", "(", "string", "$", "fieldName", ",", "string", "$", "field", ")", "{", "$", "field", "=", "str_replace", "(", "\"\\t\"", ",", "' '", ",", "$", "field", ")", ";", "switch", "(", "$", "fieldName", ")", "{", "case", "'image'", ":", "case", "'audio'", ":", "case", "'video'", ":", "$", "validator", "=", "new", "FileLocationValidator", "(", "$", "fieldName", ",", "$", "this", "->", "filenames", ")", ";", "$", "validator", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "$", "output", "=", "$", "validator", "->", "correct", "(", "$", "field", ")", ";", "break", ";", "case", "'image-source'", ":", "case", "'audio-source'", ":", "case", "'video-source'", ":", "$", "validator", "=", "new", "LightweightMarkupValidator", "(", "true", ")", ";", "$", "validator", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "$", "output", "=", "$", "validator", "->", "correct", "(", "$", "field", ")", ";", "if", "(", "$", "output", "!==", "''", ")", "{", "$", "output", "=", "[", "'lml'", "=>", "$", "output", ",", "'html'", "=>", "(", "new", "HTMLFilter", "(", ")", ")", "->", "filter", "(", "(", "new", "CommonMarkConverter", "(", ")", ")", "->", "convertToHtml", "(", "$", "output", ")", ")", ",", "]", ";", "}", "break", ";", "case", "'answer'", ":", "case", "'option'", ":", "$", "validator", "=", "new", "AnswerValidator", "(", ")", ";", "$", "validator", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "$", "output", "=", "$", "validator", "->", "correct", "(", "$", "field", ")", ";", "break", ";", "case", "'description'", ":", "case", "'@summary'", ":", "$", "validator", "=", "new", "LightweightMarkupValidator", "(", "false", ",", "$", "this", "->", "filenames", ")", ";", "$", "validator", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "$", "output", "=", "$", "validator", "->", "correct", "(", "$", "field", ")", ";", "if", "(", "$", "output", "!==", "''", ")", "{", "$", "output", "=", "[", "'lml'", "=>", "$", "output", ",", "'html'", "=>", "(", "new", "HTMLFilter", "(", ")", ")", "->", "filter", "(", "(", "new", "CommonMarkConverter", "(", ")", ")", "->", "convertToHtml", "(", "$", "output", ")", ")", ",", "]", ";", "}", "break", ";", "case", "'weight'", ":", "$", "validator", "=", "new", "NumberValidator", "(", "true", ")", ";", "$", "validator", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "$", "number", "=", "$", "validator", "->", "correct", "(", "$", "field", ")", ";", "if", "(", "$", "number", ">", "0", ")", "{", "$", "output", "=", "$", "number", ";", "}", "else", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "_", "(", "'「%s」は0より大きい実数として扱えません。'), $field));", "", "", "", "", "", "", "", "$", "output", "=", "''", ";", "}", "if", "(", "$", "output", "!==", "''", ")", "{", "$", "output", "=", "(", "float", ")", "$", "output", ";", "}", "break", ";", "case", "'specifics'", ":", "$", "validator", "=", "new", "SpecificsValidator", "(", ")", ";", "$", "validator", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "$", "output", "=", "$", "validator", "->", "correct", "(", "$", "field", ")", ";", "break", ";", "case", "'@regard'", ":", "if", "(", "preg_match", "(", "'/^\\\\[.{3,}]$/u'", ",", "$", "field", ")", "===", "1", "&&", "(", "new", "AnswerValidator", "(", ")", ")", "->", "validateRegexp", "(", "\"/$field/\"", ")", ")", "{", "$", "output", "=", "$", "field", ";", "}", "else", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "_", "(", "'「%s」は妥当な正規表現文字クラスではありません。'), $field));", "", "", "", "", "", "", "", "$", "output", "=", "''", ";", "}", "break", ";", "default", ":", "$", "output", "=", "$", "field", ";", "}", "$", "correctedField", "=", "is_array", "(", "$", "output", ")", "?", "$", "output", "[", "'lml'", "]", ":", "$", "output", ";", "$", "fieldLength", "=", "mb_strlen", "(", "$", "correctedField", ",", "'UTF-8'", ")", ";", "$", "maxFieldLength", "=", "in_array", "(", "$", "fieldName", ",", "self", "::", "MARKUP_FIELD_NAMES", ")", "?", "self", "::", "MAX_MARKUP_FIELD_LENGTH", ":", "self", "::", "MAX_FIELD_LENGTH", ";", "if", "(", "$", "fieldLength", ">", "$", "maxFieldLength", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'「%1$s」フィールドの値は%2$d文字です。%3$d文字以内にしなければなりません:'),", "", "", "$", "fieldName", ",", "$", "fieldLength", ",", "$", "maxFieldLength", ")", ".", "\"\\n$correctedField\"", ")", ";", "}", "return", "$", "output", "===", "''", "?", "null", ":", "$", "output", ";", "}" ]
フィールド単体の構文解析を行います。 @param string $fieldName フィールド名。未知のフィールド名が指定された場合はそのまま返します。 @param string $field フィールド値。 @return string|string[]|float|null 矯正したフィールド値を返します。矯正の結果フィールドの削除が生じるときは null を返します。
[ "フィールド単体の構文解析を行います。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/validator/WordValidator.php#L142-L238
pickles2/px2-sitemapexcel
php/lock.php
lock.lock
public function lock(){ $i = 0; clearstatcache(); while( @is_file( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ) ){ $i ++; if( $i > 2 ){ // 他のプロセスがサイトマップキャッシュを作成中。 // 2秒待って解除されなければ、true を返して終了する。 $this->px->error('Sitemap cache generating is now in progress. This page has been incompletely generated.'); return false; break; } sleep(1); // PHPのFileStatusCacheをクリア clearstatcache(); } touch( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ); touch( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt' ); return $this->update(); }
php
public function lock(){ $i = 0; clearstatcache(); while( @is_file( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ) ){ $i ++; if( $i > 2 ){ // 他のプロセスがサイトマップキャッシュを作成中。 // 2秒待って解除されなければ、true を返して終了する。 $this->px->error('Sitemap cache generating is now in progress. This page has been incompletely generated.'); return false; break; } sleep(1); // PHPのFileStatusCacheをクリア clearstatcache(); } touch( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ); touch( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt' ); return $this->update(); }
[ "public", "function", "lock", "(", ")", "{", "$", "i", "=", "0", ";", "clearstatcache", "(", ")", ";", "while", "(", "@", "is_file", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemap_cache.lock.txt'", ")", ")", "{", "$", "i", "++", ";", "if", "(", "$", "i", ">", "2", ")", "{", "// 他のプロセスがサイトマップキャッシュを作成中。", "// 2秒待って解除されなければ、true を返して終了する。", "$", "this", "->", "px", "->", "error", "(", "'Sitemap cache generating is now in progress. This page has been incompletely generated.'", ")", ";", "return", "false", ";", "break", ";", "}", "sleep", "(", "1", ")", ";", "// PHPのFileStatusCacheをクリア", "clearstatcache", "(", ")", ";", "}", "touch", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemap_cache.lock.txt'", ")", ";", "touch", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemapexcel.lock.txt'", ")", ";", "return", "$", "this", "->", "update", "(", ")", ";", "}" ]
lock
[ "lock" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/lock.php#L35-L57
pickles2/px2-sitemapexcel
php/lock.php
lock.update
public function update(){ if( !is_file( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ) || !is_file( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt' ) ){ // ロックされていない場合、更新できない。 return false; } $lockfile_src = ''; $lockfile_src .= 'ProcessID='.getmypid()."\r\n"; $lockfile_src .= @date( 'Y-m-d H:i:s' , time() )."\r\n"; $lockfile_src .= '* pickles2/px2-sitemapexcel'."\r\n"; $res1 = $this->px->fs()->save_file( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt', $lockfile_src ); $res2 = $this->px->fs()->save_file( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt', $lockfile_src ); clearstatcache(); if( !$res1 || !$res2 ){ return false; } return true; }
php
public function update(){ if( !is_file( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ) || !is_file( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt' ) ){ // ロックされていない場合、更新できない。 return false; } $lockfile_src = ''; $lockfile_src .= 'ProcessID='.getmypid()."\r\n"; $lockfile_src .= @date( 'Y-m-d H:i:s' , time() )."\r\n"; $lockfile_src .= '* pickles2/px2-sitemapexcel'."\r\n"; $res1 = $this->px->fs()->save_file( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt', $lockfile_src ); $res2 = $this->px->fs()->save_file( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt', $lockfile_src ); clearstatcache(); if( !$res1 || !$res2 ){ return false; } return true; }
[ "public", "function", "update", "(", ")", "{", "if", "(", "!", "is_file", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemap_cache.lock.txt'", ")", "||", "!", "is_file", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemapexcel.lock.txt'", ")", ")", "{", "// ロックされていない場合、更新できない。", "return", "false", ";", "}", "$", "lockfile_src", "=", "''", ";", "$", "lockfile_src", ".=", "'ProcessID='", ".", "getmypid", "(", ")", ".", "\"\\r\\n\"", ";", "$", "lockfile_src", ".=", "@", "date", "(", "'Y-m-d H:i:s'", ",", "time", "(", ")", ")", ".", "\"\\r\\n\"", ";", "$", "lockfile_src", ".=", "'* pickles2/px2-sitemapexcel'", ".", "\"\\r\\n\"", ";", "$", "res1", "=", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "save_file", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemap_cache.lock.txt'", ",", "$", "lockfile_src", ")", ";", "$", "res2", "=", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "save_file", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemapexcel.lock.txt'", ",", "$", "lockfile_src", ")", ";", "clearstatcache", "(", ")", ";", "if", "(", "!", "$", "res1", "||", "!", "$", "res2", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Update Lockfile
[ "Update", "Lockfile" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/lock.php#L62-L81
pickles2/px2-sitemapexcel
php/lock.php
lock.is_locked
public function is_locked(){ clearstatcache(); $res1 = $this->px->fs()->is_file( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ); $res2 = $this->px->fs()->is_file( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt' ); if( $res1 || $res2 ){ return true; } return false; }
php
public function is_locked(){ clearstatcache(); $res1 = $this->px->fs()->is_file( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ); $res2 = $this->px->fs()->is_file( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt' ); if( $res1 || $res2 ){ return true; } return false; }
[ "public", "function", "is_locked", "(", ")", "{", "clearstatcache", "(", ")", ";", "$", "res1", "=", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "is_file", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemap_cache.lock.txt'", ")", ";", "$", "res2", "=", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "is_file", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemapexcel.lock.txt'", ")", ";", "if", "(", "$", "res1", "||", "$", "res2", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
is_locked
[ "is_locked" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/lock.php#L86-L94
pickles2/px2-sitemapexcel
php/lock.php
lock.unlock
public function unlock(){ clearstatcache(); $res1 = $this->px->fs()->rm( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ); $res2 = $this->px->fs()->rm( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt' ); if( !$res1 || !$res2 ){ return false; } return true; }
php
public function unlock(){ clearstatcache(); $res1 = $this->px->fs()->rm( $this->path_sitemap_cache_dir.'making_sitemap_cache.lock.txt' ); $res2 = $this->px->fs()->rm( $this->path_sitemap_cache_dir.'making_sitemapexcel.lock.txt' ); if( !$res1 || !$res2 ){ return false; } return true; }
[ "public", "function", "unlock", "(", ")", "{", "clearstatcache", "(", ")", ";", "$", "res1", "=", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "rm", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemap_cache.lock.txt'", ")", ";", "$", "res2", "=", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "rm", "(", "$", "this", "->", "path_sitemap_cache_dir", ".", "'making_sitemapexcel.lock.txt'", ")", ";", "if", "(", "!", "$", "res1", "||", "!", "$", "res2", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
unlock
[ "unlock" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/lock.php#L99-L107
huasituo/hstcms
src/Libraries/HstcmsMd5Sign.php
HstcmsMd5Sign.createSign
public function createSign($data) { $data = $data . self::getSecretKey() . self::getPrivateKey(); return md5($data); }
php
public function createSign($data) { $data = $data . self::getSecretKey() . self::getPrivateKey(); return md5($data); }
[ "public", "function", "createSign", "(", "$", "data", ")", "{", "$", "data", "=", "$", "data", ".", "self", "::", "getSecretKey", "(", ")", ".", "self", "::", "getPrivateKey", "(", ")", ";", "return", "md5", "(", "$", "data", ")", ";", "}" ]
签名字符串 @param $data 需要签名的字符串数据 @param $key 私钥 return 签名结果
[ "签名字符串" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsMd5Sign.php#L50-L54
huasituo/hstcms
src/Libraries/HstcmsMd5Sign.php
HstcmsMd5Sign.verifySign
public function verifySign($data, $sign) { $data = $data . self::getSecretKey() . self::getPrivateKey(); $vsgin = md5($data); if($vsgin == $sign) { return true; } else { return false; } }
php
public function verifySign($data, $sign) { $data = $data . self::getSecretKey() . self::getPrivateKey(); $vsgin = md5($data); if($vsgin == $sign) { return true; } else { return false; } }
[ "public", "function", "verifySign", "(", "$", "data", ",", "$", "sign", ")", "{", "$", "data", "=", "$", "data", ".", "self", "::", "getSecretKey", "(", ")", ".", "self", "::", "getPrivateKey", "(", ")", ";", "$", "vsgin", "=", "md5", "(", "$", "data", ")", ";", "if", "(", "$", "vsgin", "==", "$", "sign", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
验证签名 @param $prestr 需要签名的字符串数据 @param $sign 签名结果 @param $key 私钥 return 签名结果
[ "验证签名" ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsMd5Sign.php#L63-L72
discophp/framework
core/classes/PDO.class.php
PDO.rollback
public function rollback() { if($this->transactionCounter > 0) { $this->transactionCounter = 0; return parent::rollback(); }//if $this->transactionCounter = 0; return false; }
php
public function rollback() { if($this->transactionCounter > 0) { $this->transactionCounter = 0; return parent::rollback(); }//if $this->transactionCounter = 0; return false; }
[ "public", "function", "rollback", "(", ")", "{", "if", "(", "$", "this", "->", "transactionCounter", ">", "0", ")", "{", "$", "this", "->", "transactionCounter", "=", "0", ";", "return", "parent", "::", "rollback", "(", ")", ";", "}", "//if", "$", "this", "->", "transactionCounter", "=", "0", ";", "return", "false", ";", "}" ]
Roll back a transaction. @return boolean
[ "Roll", "back", "a", "transaction", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L154-L164
discophp/framework
core/classes/PDO.class.php
PDO.query
public function query($query, $data = null){ try { if(!$data){ return parent::query($query); }//if $stmt = parent::prepare($query); if(!is_array($data)){ $data = Array($data); }//if $stmt->execute($data); return $stmt; } catch(\PDOException $e){ TRIGGER_ERROR("DB:: Query Error | {$query}\n".$e->getMessage() . "\n" . $e->getTraceAsString(),E_USER_WARNING); throw new \Disco\exceptions\DBQuery($e->getMessage(), (int)$e->getCode()); }//catch }
php
public function query($query, $data = null){ try { if(!$data){ return parent::query($query); }//if $stmt = parent::prepare($query); if(!is_array($data)){ $data = Array($data); }//if $stmt->execute($data); return $stmt; } catch(\PDOException $e){ TRIGGER_ERROR("DB:: Query Error | {$query}\n".$e->getMessage() . "\n" . $e->getTraceAsString(),E_USER_WARNING); throw new \Disco\exceptions\DBQuery($e->getMessage(), (int)$e->getCode()); }//catch }
[ "public", "function", "query", "(", "$", "query", ",", "$", "data", "=", "null", ")", "{", "try", "{", "if", "(", "!", "$", "data", ")", "{", "return", "parent", "::", "query", "(", "$", "query", ")", ";", "}", "//if", "$", "stmt", "=", "parent", "::", "prepare", "(", "$", "query", ")", ";", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", "{", "$", "data", "=", "Array", "(", "$", "data", ")", ";", "}", "//if", "$", "stmt", "->", "execute", "(", "$", "data", ")", ";", "return", "$", "stmt", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "TRIGGER_ERROR", "(", "\"DB:: Query Error | {$query}\\n\"", ".", "$", "e", "->", "getMessage", "(", ")", ".", "\"\\n\"", ".", "$", "e", "->", "getTraceAsString", "(", ")", ",", "E_USER_WARNING", ")", ";", "throw", "new", "\\", "Disco", "\\", "exceptions", "\\", "DBQuery", "(", "$", "e", "->", "getMessage", "(", ")", ",", "(", "int", ")", "$", "e", "->", "getCode", "(", ")", ")", ";", "}", "//catch", "}" ]
Execute a query binding in any passed `$data` and returning the result. @param string $query The query to execute. @param null|string|array The data to bind into the query. @return mixed @throws \Disco\exceptions\DBQuery
[ "Execute", "a", "query", "binding", "in", "any", "passed", "$data", "and", "returning", "the", "result", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L179-L202
discophp/framework
core/classes/PDO.class.php
PDO.insert
public function insert($query, $data = null){ if($this->query($query, $data)){ return $this->lastId(); }//if return null; }
php
public function insert($query, $data = null){ if($this->query($query, $data)){ return $this->lastId(); }//if return null; }
[ "public", "function", "insert", "(", "$", "query", ",", "$", "data", "=", "null", ")", "{", "if", "(", "$", "this", "->", "query", "(", "$", "query", ",", "$", "data", ")", ")", "{", "return", "$", "this", "->", "lastId", "(", ")", ";", "}", "//if", "return", "null", ";", "}" ]
Perform an insert statement working just like `$this->query()` but returning the newly generated Auto Increment ID. @param string $query The query to execute. @param null|string|array The data to bind into the query. @return null|int @throws \Disco\exceptions\DBQuery
[ "Perform", "an", "insert", "statement", "working", "just", "like", "$this", "-", ">", "query", "()", "but", "returning", "the", "newly", "generated", "Auto", "Increment", "ID", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L218-L226
discophp/framework
core/classes/PDO.class.php
PDO.create
public function create($table, $data){ $keys = array_keys($data); $values = ':' . implode(',:', $keys); $keys = implode(',', $keys); return $this->query($this->set("INSERT INTO {$table} ({$keys}) VALUES({$values})", $data)); }
php
public function create($table, $data){ $keys = array_keys($data); $values = ':' . implode(',:', $keys); $keys = implode(',', $keys); return $this->query($this->set("INSERT INTO {$table} ({$keys}) VALUES({$values})", $data)); }
[ "public", "function", "create", "(", "$", "table", ",", "$", "data", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "data", ")", ";", "$", "values", "=", "':'", ".", "implode", "(", "',:'", ",", "$", "keys", ")", ";", "$", "keys", "=", "implode", "(", "','", ",", "$", "keys", ")", ";", "return", "$", "this", "->", "query", "(", "$", "this", "->", "set", "(", "\"INSERT INTO {$table} ({$keys}) VALUES({$values})\"", ",", "$", "data", ")", ")", ";", "}" ]
Perform an INSERT statement. @param string $table The name of the table to insert into. @param array $data The data to insert into the table, must be an associative array. @return mixed @throws \Disco\exceptions\DBQuery
[ "Perform", "an", "INSERT", "statement", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L239-L244
discophp/framework
core/classes/PDO.class.php
PDO.delete
public function delete($table, $data, $conjunction = 'AND'){ $keys = array_keys($data); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=:{$key}"; }//foreach $pairs = implode(" {$conjunction} ", $pairs); return $this->query($this->set("DELETE FROM {$table} WHERE {$pairs}",$data)); }
php
public function delete($table, $data, $conjunction = 'AND'){ $keys = array_keys($data); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=:{$key}"; }//foreach $pairs = implode(" {$conjunction} ", $pairs); return $this->query($this->set("DELETE FROM {$table} WHERE {$pairs}",$data)); }
[ "public", "function", "delete", "(", "$", "table", ",", "$", "data", ",", "$", "conjunction", "=", "'AND'", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "data", ")", ";", "$", "pairs", "=", "Array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "pairs", "[", "]", "=", "\"{$key}=:{$key}\"", ";", "}", "//foreach", "$", "pairs", "=", "implode", "(", "\" {$conjunction} \"", ",", "$", "pairs", ")", ";", "return", "$", "this", "->", "query", "(", "$", "this", "->", "set", "(", "\"DELETE FROM {$table} WHERE {$pairs}\"", ",", "$", "data", ")", ")", ";", "}" ]
Perform a DELETE statement. @param string $table The name of the table to delete from. @param array $data The conditions specifying what rows to delete from the table, must be an associative array. @param string $conjunction The conjunction used to form the where condition of the delete statement. Default is `AND`. @return mixed @throws \Disco\exceptions\DBQuery
[ "Perform", "a", "DELETE", "statement", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L259-L267
discophp/framework
core/classes/PDO.class.php
PDO.update
public function update($table, $data, $where, $conjunction = 'AND'){ $values = array_merge(array_values($data),array_values($where)); $keys = array_keys($data); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=?"; }//foreach $pairs = implode(',',$pairs); $keys = array_keys($where); $condition = Array(); foreach($keys as $key){ $condition[] = "{$key}=?"; }//foreach $condition = implode(" {$conjunction} ",$condition); return $this->query($this->set("UPDATE {$table} SET {$pairs} WHERE {$condition}",$values)); }
php
public function update($table, $data, $where, $conjunction = 'AND'){ $values = array_merge(array_values($data),array_values($where)); $keys = array_keys($data); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=?"; }//foreach $pairs = implode(',',$pairs); $keys = array_keys($where); $condition = Array(); foreach($keys as $key){ $condition[] = "{$key}=?"; }//foreach $condition = implode(" {$conjunction} ",$condition); return $this->query($this->set("UPDATE {$table} SET {$pairs} WHERE {$condition}",$values)); }
[ "public", "function", "update", "(", "$", "table", ",", "$", "data", ",", "$", "where", ",", "$", "conjunction", "=", "'AND'", ")", "{", "$", "values", "=", "array_merge", "(", "array_values", "(", "$", "data", ")", ",", "array_values", "(", "$", "where", ")", ")", ";", "$", "keys", "=", "array_keys", "(", "$", "data", ")", ";", "$", "pairs", "=", "Array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "pairs", "[", "]", "=", "\"{$key}=?\"", ";", "}", "//foreach", "$", "pairs", "=", "implode", "(", "','", ",", "$", "pairs", ")", ";", "$", "keys", "=", "array_keys", "(", "$", "where", ")", ";", "$", "condition", "=", "Array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "condition", "[", "]", "=", "\"{$key}=?\"", ";", "}", "//foreach", "$", "condition", "=", "implode", "(", "\" {$conjunction} \"", ",", "$", "condition", ")", ";", "return", "$", "this", "->", "query", "(", "$", "this", "->", "set", "(", "\"UPDATE {$table} SET {$pairs} WHERE {$condition}\"", ",", "$", "values", ")", ")", ";", "}" ]
Perform an UPDATE statement . @param string $table The name of the table to update. @param array $data The data to update the table with, must be an associative array. @param array $where The conditions specifying what rows should be updated in the table, must be an associative array. @param string $conjunction The conjunction used to form the where condition of the update statement. Default is `AND`. @return mixed @throws \Disco\exceptions\DBQuery
[ "Perform", "an", "UPDATE", "statement", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L283-L301
discophp/framework
core/classes/PDO.class.php
PDO.select
public function select($table, $select, $where, $conjunction = 'AND'){ $keys = array_keys($where); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=:{$key}"; }//foreach $pairs = implode(" {$conjunction} ",$pairs); if(is_array($select)){ $select = implode(',',$select); }//if return $this->query($this->set("SELECT {$select} FROM {$table} WHERE {$pairs}",$where)); }
php
public function select($table, $select, $where, $conjunction = 'AND'){ $keys = array_keys($where); $pairs = Array(); foreach($keys as $key){ $pairs[] = "{$key}=:{$key}"; }//foreach $pairs = implode(" {$conjunction} ",$pairs); if(is_array($select)){ $select = implode(',',$select); }//if return $this->query($this->set("SELECT {$select} FROM {$table} WHERE {$pairs}",$where)); }
[ "public", "function", "select", "(", "$", "table", ",", "$", "select", ",", "$", "where", ",", "$", "conjunction", "=", "'AND'", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "where", ")", ";", "$", "pairs", "=", "Array", "(", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "pairs", "[", "]", "=", "\"{$key}=:{$key}\"", ";", "}", "//foreach", "$", "pairs", "=", "implode", "(", "\" {$conjunction} \"", ",", "$", "pairs", ")", ";", "if", "(", "is_array", "(", "$", "select", ")", ")", "{", "$", "select", "=", "implode", "(", "','", ",", "$", "select", ")", ";", "}", "//if", "return", "$", "this", "->", "query", "(", "$", "this", "->", "set", "(", "\"SELECT {$select} FROM {$table} WHERE {$pairs}\"", ",", "$", "where", ")", ")", ";", "}" ]
Perform a SELECT statement . @param string $table The name of the table to select from. @param string|array $select The fields to select from the table, can be a string of field or an array of fields. @param array $where The conditions specifying what rows should be selected from the table, must be an associative array. @param string $conjunction The conjunction used to form the where condition of the select statement. Default is `AND`. @return mixed @throws \Disco\exceptions\DBQuery
[ "Perform", "a", "SELECT", "statement", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L318-L333
discophp/framework
core/classes/PDO.class.php
PDO.set
public function set($q, $args){ if(is_array($args) && isset($args['raw'])){ $q = implode($args['raw'],explode('?',$q,2));; }//if else if(is_array($args)){ $first = array_keys($args); $first = array_shift($first); if(!is_numeric($first)){ return $this->setAssociativeArrayPlaceHolders($q,$args); }//if return $this->setQuestionMarkPlaceHolders($q,$args); }//if else { $q = implode($this->prepareType($args), explode('?', $q, 2)); }//el return $q; }
php
public function set($q, $args){ if(is_array($args) && isset($args['raw'])){ $q = implode($args['raw'],explode('?',$q,2));; }//if else if(is_array($args)){ $first = array_keys($args); $first = array_shift($first); if(!is_numeric($first)){ return $this->setAssociativeArrayPlaceHolders($q,$args); }//if return $this->setQuestionMarkPlaceHolders($q,$args); }//if else { $q = implode($this->prepareType($args), explode('?', $q, 2)); }//el return $q; }
[ "public", "function", "set", "(", "$", "q", ",", "$", "args", ")", "{", "if", "(", "is_array", "(", "$", "args", ")", "&&", "isset", "(", "$", "args", "[", "'raw'", "]", ")", ")", "{", "$", "q", "=", "implode", "(", "$", "args", "[", "'raw'", "]", ",", "explode", "(", "'?'", ",", "$", "q", ",", "2", ")", ")", ";", ";", "}", "//if", "else", "if", "(", "is_array", "(", "$", "args", ")", ")", "{", "$", "first", "=", "array_keys", "(", "$", "args", ")", ";", "$", "first", "=", "array_shift", "(", "$", "first", ")", ";", "if", "(", "!", "is_numeric", "(", "$", "first", ")", ")", "{", "return", "$", "this", "->", "setAssociativeArrayPlaceHolders", "(", "$", "q", ",", "$", "args", ")", ";", "}", "//if", "return", "$", "this", "->", "setQuestionMarkPlaceHolders", "(", "$", "q", ",", "$", "args", ")", ";", "}", "//if", "else", "{", "$", "q", "=", "implode", "(", "$", "this", "->", "prepareType", "(", "$", "args", ")", ",", "explode", "(", "'?'", ",", "$", "q", ",", "2", ")", ")", ";", "}", "//el", "return", "$", "q", ";", "}" ]
Bind passed variables into a query string and do proper type checking and escaping before binding. @param string $q The query string. @param string|array $args The variables to bind to the $q. @return string The $q with $args bound into it. @throws \Disco\exceptions\DBQuery When the number of arguements doesn't match the numebr of `?` placeholders.
[ "Bind", "passed", "variables", "into", "a", "query", "string", "and", "do", "proper", "type", "checking", "and", "escaping", "before", "binding", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L362-L385
discophp/framework
core/classes/PDO.class.php
PDO.setAssociativeArrayPlaceHolders
private function setAssociativeArrayPlaceHolders($q, $args){ foreach($args as $key => $value){ if(is_array($value) && isset($value['raw'])){ $value = $value['raw']; }//if else { $value = $this->prepareType($value); }//el $positions = Array(); $p = -1; $offset = 1; $keyPlaceHolder = ":{$key}"; $keyLength = strlen($keyPlaceHolder); while(($p = strpos($q,$keyPlaceHolder, $p + $offset)) !== false){ $positions[] = $p; $offset = $keyLength; }//while //reverse the positions so we dont have to keep track in the changes in str length affected by replacing //the placeholders $positions = array_reverse($positions); foreach($positions as $p){ $q = substr_replace($q, $value, $p, $keyLength); }//foreach }//foreach return $q; }
php
private function setAssociativeArrayPlaceHolders($q, $args){ foreach($args as $key => $value){ if(is_array($value) && isset($value['raw'])){ $value = $value['raw']; }//if else { $value = $this->prepareType($value); }//el $positions = Array(); $p = -1; $offset = 1; $keyPlaceHolder = ":{$key}"; $keyLength = strlen($keyPlaceHolder); while(($p = strpos($q,$keyPlaceHolder, $p + $offset)) !== false){ $positions[] = $p; $offset = $keyLength; }//while //reverse the positions so we dont have to keep track in the changes in str length affected by replacing //the placeholders $positions = array_reverse($positions); foreach($positions as $p){ $q = substr_replace($q, $value, $p, $keyLength); }//foreach }//foreach return $q; }
[ "private", "function", "setAssociativeArrayPlaceHolders", "(", "$", "q", ",", "$", "args", ")", "{", "foreach", "(", "$", "args", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "isset", "(", "$", "value", "[", "'raw'", "]", ")", ")", "{", "$", "value", "=", "$", "value", "[", "'raw'", "]", ";", "}", "//if", "else", "{", "$", "value", "=", "$", "this", "->", "prepareType", "(", "$", "value", ")", ";", "}", "//el", "$", "positions", "=", "Array", "(", ")", ";", "$", "p", "=", "-", "1", ";", "$", "offset", "=", "1", ";", "$", "keyPlaceHolder", "=", "\":{$key}\"", ";", "$", "keyLength", "=", "strlen", "(", "$", "keyPlaceHolder", ")", ";", "while", "(", "(", "$", "p", "=", "strpos", "(", "$", "q", ",", "$", "keyPlaceHolder", ",", "$", "p", "+", "$", "offset", ")", ")", "!==", "false", ")", "{", "$", "positions", "[", "]", "=", "$", "p", ";", "$", "offset", "=", "$", "keyLength", ";", "}", "//while", "//reverse the positions so we dont have to keep track in the changes in str length affected by replacing ", "//the placeholders", "$", "positions", "=", "array_reverse", "(", "$", "positions", ")", ";", "foreach", "(", "$", "positions", "as", "$", "p", ")", "{", "$", "q", "=", "substr_replace", "(", "$", "q", ",", "$", "value", ",", "$", "p", ",", "$", "keyLength", ")", ";", "}", "//foreach", "}", "//foreach", "return", "$", "q", ";", "}" ]
Set assocative array place holders in the query like `:id` with the corresponding value in the args. @param string $q The query string. @param string|array $args The variables to bind to the $q. @return string The $q with $args bound into it.
[ "Set", "assocative", "array", "place", "holders", "in", "the", "query", "like", ":", "id", "with", "the", "corresponding", "value", "in", "the", "args", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L398-L432
discophp/framework
core/classes/PDO.class.php
PDO.setQuestionMarkPlaceHolders
private function setQuestionMarkPlaceHolders($q, $args){ foreach($args as $k=>$a){ if(is_array($a) && isset($a['raw'])){ $args[$k] = $a['raw']; }//if else { $args[$k] = $this->prepareType($a); }//el }//foreach $positions = Array(); $p = -1; while(($p = strpos($q, '?', $p + 1)) !== false){ $positions[] = $p; }//while if(count($args) != count($positions)){ throw new \Disco\exceptions\DBQuery('Number of passed arguements does not match the number of `?` placeholders'); }//if //reverse em so when we do replacements we dont have //to keep track of the change in length to positions $args = array_reverse($args); $positions = array_reverse($positions); foreach($positions as $k=>$pos){ $q = substr_replace($q,$args[$k],$pos,1); }//foreach return $q; }
php
private function setQuestionMarkPlaceHolders($q, $args){ foreach($args as $k=>$a){ if(is_array($a) && isset($a['raw'])){ $args[$k] = $a['raw']; }//if else { $args[$k] = $this->prepareType($a); }//el }//foreach $positions = Array(); $p = -1; while(($p = strpos($q, '?', $p + 1)) !== false){ $positions[] = $p; }//while if(count($args) != count($positions)){ throw new \Disco\exceptions\DBQuery('Number of passed arguements does not match the number of `?` placeholders'); }//if //reverse em so when we do replacements we dont have //to keep track of the change in length to positions $args = array_reverse($args); $positions = array_reverse($positions); foreach($positions as $k=>$pos){ $q = substr_replace($q,$args[$k],$pos,1); }//foreach return $q; }
[ "private", "function", "setQuestionMarkPlaceHolders", "(", "$", "q", ",", "$", "args", ")", "{", "foreach", "(", "$", "args", "as", "$", "k", "=>", "$", "a", ")", "{", "if", "(", "is_array", "(", "$", "a", ")", "&&", "isset", "(", "$", "a", "[", "'raw'", "]", ")", ")", "{", "$", "args", "[", "$", "k", "]", "=", "$", "a", "[", "'raw'", "]", ";", "}", "//if", "else", "{", "$", "args", "[", "$", "k", "]", "=", "$", "this", "->", "prepareType", "(", "$", "a", ")", ";", "}", "//el", "}", "//foreach", "$", "positions", "=", "Array", "(", ")", ";", "$", "p", "=", "-", "1", ";", "while", "(", "(", "$", "p", "=", "strpos", "(", "$", "q", ",", "'?'", ",", "$", "p", "+", "1", ")", ")", "!==", "false", ")", "{", "$", "positions", "[", "]", "=", "$", "p", ";", "}", "//while", "if", "(", "count", "(", "$", "args", ")", "!=", "count", "(", "$", "positions", ")", ")", "{", "throw", "new", "\\", "Disco", "\\", "exceptions", "\\", "DBQuery", "(", "'Number of passed arguements does not match the number of `?` placeholders'", ")", ";", "}", "//if", "//reverse em so when we do replacements we dont have ", "//to keep track of the change in length to positions", "$", "args", "=", "array_reverse", "(", "$", "args", ")", ";", "$", "positions", "=", "array_reverse", "(", "$", "positions", ")", ";", "foreach", "(", "$", "positions", "as", "$", "k", "=>", "$", "pos", ")", "{", "$", "q", "=", "substr_replace", "(", "$", "q", ",", "$", "args", "[", "$", "k", "]", ",", "$", "pos", ",", "1", ")", ";", "}", "//foreach", "return", "$", "q", ";", "}" ]
Set `?` mark value placeholders with the values passed in args in the order they are set in the query and the args. @param string $q The query string. @param string|array $args The variables to bind to the $q. @return string The $q with $args bound into it. @throws \Disco\exceptions\DBQuery When the number of arguements doesn't match the numebr of `?` placeholders.
[ "Set", "?", "mark", "value", "placeholders", "with", "the", "values", "passed", "in", "args", "in", "the", "order", "they", "are", "set", "in", "the", "query", "and", "the", "args", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L448-L482
discophp/framework
core/classes/PDO.class.php
PDO.prepareType
private function prepareType($arg){ if(($arg===null || $arg=='null') && $arg !== 0){ return 'NULL'; }//if if(!is_numeric($arg)){ return $this->quote($arg); }//if return $arg; }
php
private function prepareType($arg){ if(($arg===null || $arg=='null') && $arg !== 0){ return 'NULL'; }//if if(!is_numeric($arg)){ return $this->quote($arg); }//if return $arg; }
[ "private", "function", "prepareType", "(", "$", "arg", ")", "{", "if", "(", "(", "$", "arg", "===", "null", "||", "$", "arg", "==", "'null'", ")", "&&", "$", "arg", "!==", "0", ")", "{", "return", "'NULL'", ";", "}", "//if", "if", "(", "!", "is_numeric", "(", "$", "arg", ")", ")", "{", "return", "$", "this", "->", "quote", "(", "$", "arg", ")", ";", "}", "//if", "return", "$", "arg", ";", "}" ]
Determine the type of variable being bound into the query, either a String or Numeric. @param string|int|float $arg The variable to prepare. @return string|int|float The $arg prepared.
[ "Determine", "the", "type", "of", "variable", "being", "bound", "into", "the", "query", "either", "a", "String", "or", "Numeric", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/classes/PDO.class.php#L493-L501
pipelinersales/pipeliner-php-sdk
src/PipelinerSales/ApiClient/PipelinerClient.php
PipelinerClient.create
public static function create($url, $pipelineId, $apiToken, $password) { $baseUrl = $url . '/rest_services/v1/' . $pipelineId; $httpClient = new CurlHttpClient(); $httpClient->setUserCredentials($apiToken, $password); $dateTimeFormat = Defaults::DATE_FORMAT; $repoFactory = new RestRepositoryFactory($baseUrl, $httpClient, $dateTimeFormat); $infoMethods = new RestInfoMethods($baseUrl, $httpClient); $entityTypes = array_flip($infoMethods->fetchEntityPublic()); $client = new PipelinerClient($entityTypes, $repoFactory, $infoMethods); return $client; }
php
public static function create($url, $pipelineId, $apiToken, $password) { $baseUrl = $url . '/rest_services/v1/' . $pipelineId; $httpClient = new CurlHttpClient(); $httpClient->setUserCredentials($apiToken, $password); $dateTimeFormat = Defaults::DATE_FORMAT; $repoFactory = new RestRepositoryFactory($baseUrl, $httpClient, $dateTimeFormat); $infoMethods = new RestInfoMethods($baseUrl, $httpClient); $entityTypes = array_flip($infoMethods->fetchEntityPublic()); $client = new PipelinerClient($entityTypes, $repoFactory, $infoMethods); return $client; }
[ "public", "static", "function", "create", "(", "$", "url", ",", "$", "pipelineId", ",", "$", "apiToken", ",", "$", "password", ")", "{", "$", "baseUrl", "=", "$", "url", ".", "'/rest_services/v1/'", ".", "$", "pipelineId", ";", "$", "httpClient", "=", "new", "CurlHttpClient", "(", ")", ";", "$", "httpClient", "->", "setUserCredentials", "(", "$", "apiToken", ",", "$", "password", ")", ";", "$", "dateTimeFormat", "=", "Defaults", "::", "DATE_FORMAT", ";", "$", "repoFactory", "=", "new", "RestRepositoryFactory", "(", "$", "baseUrl", ",", "$", "httpClient", ",", "$", "dateTimeFormat", ")", ";", "$", "infoMethods", "=", "new", "RestInfoMethods", "(", "$", "baseUrl", ",", "$", "httpClient", ")", ";", "$", "entityTypes", "=", "array_flip", "(", "$", "infoMethods", "->", "fetchEntityPublic", "(", ")", ")", ";", "$", "client", "=", "new", "PipelinerClient", "(", "$", "entityTypes", ",", "$", "repoFactory", ",", "$", "infoMethods", ")", ";", "return", "$", "client", ";", "}" ]
Creates a PipelinerClient object with sensible default configuration. Will perform a HTTP request to fetch the existing entity types for the pipeline. @param string $url base url of the REST server, without the trailing slash @param string $pipelineId the unique team pipeline id @param string $apiToken API token @param string $password API password @return PipelinerClient @throws PipelinerClientException when trying to use an unsupported pipeline version @throws PipelinerHttpException if fetching the pipeline version fails
[ "Creates", "a", "PipelinerClient", "object", "with", "sensible", "default", "configuration", ".", "Will", "perform", "a", "HTTP", "request", "to", "fetch", "the", "existing", "entity", "types", "for", "the", "pipeline", "." ]
train
https://github.com/pipelinersales/pipeliner-php-sdk/blob/a020149ffde815be17634542010814cf854c3d5f/src/PipelinerSales/ApiClient/PipelinerClient.php#L97-L112
pipelinersales/pipeliner-php-sdk
src/PipelinerSales/ApiClient/PipelinerClient.php
PipelinerClient.getRepository
public function getRepository($entityName) { if ($entityName instanceof Entity) { $entityName = $entityName->getType(); } if (!isset($this->repositories[$entityName])) { $plural = $this->getCollectionName($entityName); $this->repositories[$entityName] = $this->repositoryFactory->createRepository( $entityName, $plural ); } return $this->repositories[$entityName]; }
php
public function getRepository($entityName) { if ($entityName instanceof Entity) { $entityName = $entityName->getType(); } if (!isset($this->repositories[$entityName])) { $plural = $this->getCollectionName($entityName); $this->repositories[$entityName] = $this->repositoryFactory->createRepository( $entityName, $plural ); } return $this->repositories[$entityName]; }
[ "public", "function", "getRepository", "(", "$", "entityName", ")", "{", "if", "(", "$", "entityName", "instanceof", "Entity", ")", "{", "$", "entityName", "=", "$", "entityName", "->", "getType", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "repositories", "[", "$", "entityName", "]", ")", ")", "{", "$", "plural", "=", "$", "this", "->", "getCollectionName", "(", "$", "entityName", ")", ";", "$", "this", "->", "repositories", "[", "$", "entityName", "]", "=", "$", "this", "->", "repositoryFactory", "->", "createRepository", "(", "$", "entityName", ",", "$", "plural", ")", ";", "}", "return", "$", "this", "->", "repositories", "[", "$", "entityName", "]", ";", "}" ]
Returns a repository for the specified entity. @param mixed $entityName an {@see Entity} object or entity name, can be both singular (Account) and plural (Accounts) @return RepositoryInterface
[ "Returns", "a", "repository", "for", "the", "specified", "entity", "." ]
train
https://github.com/pipelinersales/pipeliner-php-sdk/blob/a020149ffde815be17634542010814cf854c3d5f/src/PipelinerSales/ApiClient/PipelinerClient.php#L152-L167
model3/model3
src/Model3/Request/Request.php
Request.getEnv
public function getEnv($key = null, $default = null) { if (null === $key) { return $_ENV; } return (isset($_ENV[$key])) ? $_ENV[$key] : $default; }
php
public function getEnv($key = null, $default = null) { if (null === $key) { return $_ENV; } return (isset($_ENV[$key])) ? $_ENV[$key] : $default; }
[ "public", "function", "getEnv", "(", "$", "key", "=", "null", ",", "$", "default", "=", "null", ")", "{", "if", "(", "null", "===", "$", "key", ")", "{", "return", "$", "_ENV", ";", "}", "return", "(", "isset", "(", "$", "_ENV", "[", "$", "key", "]", ")", ")", "?", "$", "_ENV", "[", "$", "key", "]", ":", "$", "default", ";", "}" ]
Retrieve a member of the $_ENV superglobal If no $key is passed, returns the entire $_ENV array. @param string $key @param mixed $default Default value to use if key not found @return mixed Returns null if key does not exist
[ "Retrieve", "a", "member", "of", "the", "$_ENV", "superglobal" ]
train
https://github.com/model3/model3/blob/c62858013fce9bac597d47a2475c69aebe7d6209/src/Model3/Request/Request.php#L280-L288
discophp/framework
core/twig/tag/PageTokenParser.php
PageTokenParser.parse
public function parse(\Twig_Token $token) { $lineno = $token->getLine(); $nodes['criteria'] = $this->parser->getExpressionParser()->parseExpression(); $this->parser->getStream()->expect('as'); $targets = $this->parser->getExpressionParser()->parseAssignmentExpression(); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $nodes['body'] = $this->parser->subparse(array($this, 'endOfTag'), true); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $elementsTarget = $targets->getNode(0); $nodes['elementsTarget'] = new \Twig_Node_Expression_AssignName($elementsTarget->getAttribute('name'), $elementsTarget->getLine()); return new PageNode($nodes, array(), $lineno, $this->getTag()); }
php
public function parse(\Twig_Token $token) { $lineno = $token->getLine(); $nodes['criteria'] = $this->parser->getExpressionParser()->parseExpression(); $this->parser->getStream()->expect('as'); $targets = $this->parser->getExpressionParser()->parseAssignmentExpression(); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $nodes['body'] = $this->parser->subparse(array($this, 'endOfTag'), true); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $elementsTarget = $targets->getNode(0); $nodes['elementsTarget'] = new \Twig_Node_Expression_AssignName($elementsTarget->getAttribute('name'), $elementsTarget->getLine()); return new PageNode($nodes, array(), $lineno, $this->getTag()); }
[ "public", "function", "parse", "(", "\\", "Twig_Token", "$", "token", ")", "{", "$", "lineno", "=", "$", "token", "->", "getLine", "(", ")", ";", "$", "nodes", "[", "'criteria'", "]", "=", "$", "this", "->", "parser", "->", "getExpressionParser", "(", ")", "->", "parseExpression", "(", ")", ";", "$", "this", "->", "parser", "->", "getStream", "(", ")", "->", "expect", "(", "'as'", ")", ";", "$", "targets", "=", "$", "this", "->", "parser", "->", "getExpressionParser", "(", ")", "->", "parseAssignmentExpression", "(", ")", ";", "$", "this", "->", "parser", "->", "getStream", "(", ")", "->", "expect", "(", "\\", "Twig_Token", "::", "BLOCK_END_TYPE", ")", ";", "$", "nodes", "[", "'body'", "]", "=", "$", "this", "->", "parser", "->", "subparse", "(", "array", "(", "$", "this", ",", "'endOfTag'", ")", ",", "true", ")", ";", "$", "this", "->", "parser", "->", "getStream", "(", ")", "->", "expect", "(", "\\", "Twig_Token", "::", "BLOCK_END_TYPE", ")", ";", "$", "elementsTarget", "=", "$", "targets", "->", "getNode", "(", "0", ")", ";", "$", "nodes", "[", "'elementsTarget'", "]", "=", "new", "\\", "Twig_Node_Expression_AssignName", "(", "$", "elementsTarget", "->", "getAttribute", "(", "'name'", ")", ",", "$", "elementsTarget", "->", "getLine", "(", ")", ")", ";", "return", "new", "PageNode", "(", "$", "nodes", ",", "array", "(", ")", ",", "$", "lineno", ",", "$", "this", "->", "getTag", "(", ")", ")", ";", "}" ]
Define how our page tag should be parsed. @param \Twig_Token $token An instance of a \Twig_Token. @return \Disco\twig\PageNode
[ "Define", "how", "our", "page", "tag", "should", "be", "parsed", "." ]
train
https://github.com/discophp/framework/blob/40ff3ea5225810534195494dc6c21083da4d1356/core/twig/tag/PageTokenParser.php#L20-L37
datasift/datasift-php
lib/DataSift/ApiClient.php
DataSift_ApiClient.call
public static function call( DataSift_User $user, $endPoint, $method, $params = array(), $headers = array(), $userAgent = DataSift_User::USER_AGENT, $qs = array(), $ingest = false ) { $decodeCode = array( self::HTTP_OK, self::HTTP_NO_CONTENT ); // Curl is required if (! function_exists('curl_init')) { throw new DataSift_Exception_NotYetImplemented('Curl is required for DataSift_ApiClient'); } if (empty($headers)) { $headers = array( 'Auth: ' . $user->getUsername() . ':' . $user->getAPIKey(), 'Expect:', 'Content-Type: application/json' ); } $ssl = $user->useSSL(); // Build the full endpoint URL if ($ingest) { $url = 'http' . ($ssl ? 's' : '') . '://' . $user->getIngestUrl() . $endPoint; } else { $url = 'http' . ($ssl ? 's' : '') . '://' . $user->getApiUrl() . $user->getApiVersion() . '/' . $endPoint; } $ch = self::initialize($method, $ssl, $url, $headers, $params, $userAgent, $qs, $ingest); $res = curl_exec($ch); $info = curl_getinfo($ch); curl_close($ch); $res = self::parseHTTPResponse($res); if ($user->getDebug()) { $log['headers'] = $res['headers']; $log['status'] = $info['http_code']; $log['body'] = self::decodeBody($res); $user->setLastResponse($log); } $retval = array( 'response_code' => $info['http_code'], 'data' => (strlen($res['body']) == 0 ? array() : self::decodeBody($res)), 'rate_limit' => (isset($res['headers']['x-ratelimit-limit']) ? $res['headers']['x-ratelimit-limit'] : -1), 'rate_limit_remaining' => (isset($res['headers']['x-ratelimit-remaining']) ? $res['headers']['x-ratelimit-remaining'] : -1), ); return $retval; }
php
public static function call( DataSift_User $user, $endPoint, $method, $params = array(), $headers = array(), $userAgent = DataSift_User::USER_AGENT, $qs = array(), $ingest = false ) { $decodeCode = array( self::HTTP_OK, self::HTTP_NO_CONTENT ); // Curl is required if (! function_exists('curl_init')) { throw new DataSift_Exception_NotYetImplemented('Curl is required for DataSift_ApiClient'); } if (empty($headers)) { $headers = array( 'Auth: ' . $user->getUsername() . ':' . $user->getAPIKey(), 'Expect:', 'Content-Type: application/json' ); } $ssl = $user->useSSL(); // Build the full endpoint URL if ($ingest) { $url = 'http' . ($ssl ? 's' : '') . '://' . $user->getIngestUrl() . $endPoint; } else { $url = 'http' . ($ssl ? 's' : '') . '://' . $user->getApiUrl() . $user->getApiVersion() . '/' . $endPoint; } $ch = self::initialize($method, $ssl, $url, $headers, $params, $userAgent, $qs, $ingest); $res = curl_exec($ch); $info = curl_getinfo($ch); curl_close($ch); $res = self::parseHTTPResponse($res); if ($user->getDebug()) { $log['headers'] = $res['headers']; $log['status'] = $info['http_code']; $log['body'] = self::decodeBody($res); $user->setLastResponse($log); } $retval = array( 'response_code' => $info['http_code'], 'data' => (strlen($res['body']) == 0 ? array() : self::decodeBody($res)), 'rate_limit' => (isset($res['headers']['x-ratelimit-limit']) ? $res['headers']['x-ratelimit-limit'] : -1), 'rate_limit_remaining' => (isset($res['headers']['x-ratelimit-remaining']) ? $res['headers']['x-ratelimit-remaining'] : -1), ); return $retval; }
[ "public", "static", "function", "call", "(", "DataSift_User", "$", "user", ",", "$", "endPoint", ",", "$", "method", ",", "$", "params", "=", "array", "(", ")", ",", "$", "headers", "=", "array", "(", ")", ",", "$", "userAgent", "=", "DataSift_User", "::", "USER_AGENT", ",", "$", "qs", "=", "array", "(", ")", ",", "$", "ingest", "=", "false", ")", "{", "$", "decodeCode", "=", "array", "(", "self", "::", "HTTP_OK", ",", "self", "::", "HTTP_NO_CONTENT", ")", ";", "// Curl is required", "if", "(", "!", "function_exists", "(", "'curl_init'", ")", ")", "{", "throw", "new", "DataSift_Exception_NotYetImplemented", "(", "'Curl is required for DataSift_ApiClient'", ")", ";", "}", "if", "(", "empty", "(", "$", "headers", ")", ")", "{", "$", "headers", "=", "array", "(", "'Auth: '", ".", "$", "user", "->", "getUsername", "(", ")", ".", "':'", ".", "$", "user", "->", "getAPIKey", "(", ")", ",", "'Expect:'", ",", "'Content-Type: application/json'", ")", ";", "}", "$", "ssl", "=", "$", "user", "->", "useSSL", "(", ")", ";", "// Build the full endpoint URL", "if", "(", "$", "ingest", ")", "{", "$", "url", "=", "'http'", ".", "(", "$", "ssl", "?", "'s'", ":", "''", ")", ".", "'://'", ".", "$", "user", "->", "getIngestUrl", "(", ")", ".", "$", "endPoint", ";", "}", "else", "{", "$", "url", "=", "'http'", ".", "(", "$", "ssl", "?", "'s'", ":", "''", ")", ".", "'://'", ".", "$", "user", "->", "getApiUrl", "(", ")", ".", "$", "user", "->", "getApiVersion", "(", ")", ".", "'/'", ".", "$", "endPoint", ";", "}", "$", "ch", "=", "self", "::", "initialize", "(", "$", "method", ",", "$", "ssl", ",", "$", "url", ",", "$", "headers", ",", "$", "params", ",", "$", "userAgent", ",", "$", "qs", ",", "$", "ingest", ")", ";", "$", "res", "=", "curl_exec", "(", "$", "ch", ")", ";", "$", "info", "=", "curl_getinfo", "(", "$", "ch", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "$", "res", "=", "self", "::", "parseHTTPResponse", "(", "$", "res", ")", ";", "if", "(", "$", "user", "->", "getDebug", "(", ")", ")", "{", "$", "log", "[", "'headers'", "]", "=", "$", "res", "[", "'headers'", "]", ";", "$", "log", "[", "'status'", "]", "=", "$", "info", "[", "'http_code'", "]", ";", "$", "log", "[", "'body'", "]", "=", "self", "::", "decodeBody", "(", "$", "res", ")", ";", "$", "user", "->", "setLastResponse", "(", "$", "log", ")", ";", "}", "$", "retval", "=", "array", "(", "'response_code'", "=>", "$", "info", "[", "'http_code'", "]", ",", "'data'", "=>", "(", "strlen", "(", "$", "res", "[", "'body'", "]", ")", "==", "0", "?", "array", "(", ")", ":", "self", "::", "decodeBody", "(", "$", "res", ")", ")", ",", "'rate_limit'", "=>", "(", "isset", "(", "$", "res", "[", "'headers'", "]", "[", "'x-ratelimit-limit'", "]", ")", "?", "$", "res", "[", "'headers'", "]", "[", "'x-ratelimit-limit'", "]", ":", "-", "1", ")", ",", "'rate_limit_remaining'", "=>", "(", "isset", "(", "$", "res", "[", "'headers'", "]", "[", "'x-ratelimit-remaining'", "]", ")", "?", "$", "res", "[", "'headers'", "]", "[", "'x-ratelimit-remaining'", "]", ":", "-", "1", ")", ",", ")", ";", "return", "$", "retval", ";", "}" ]
Make a call to a DataSift API endpoint. @param DataSift_User $user The user's username. @param string $endPoint The endpoint of the API call. @param array $headers The headers to be sent. @param array $successCode The codes defined as a success for the call. @param array $params The parameters to be passed along with the request. @param string $userAgent The HTTP User-Agent header. @return array The response from the server. @throws DataSift_Exception_APIError @throws DataSift_Exception_RateLimitExceeded @throws DataSift_Exception_NotYetImplemented
[ "Make", "a", "call", "to", "a", "DataSift", "API", "endpoint", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/ApiClient.php#L42-L102
datasift/datasift-php
lib/DataSift/ApiClient.php
DataSift_ApiClient.initialize
private static function initialize($method, $ssl, $url, $headers, $params, $userAgent, $qs, $raw = false) { $ch = curl_init(); switch (strtolower($method)) { case 'post': curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, ($raw ? $params : json_encode($params))); break; case 'get': curl_setopt($ch, CURLOPT_HTTPGET, true); break; case 'put': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); break; case 'delete': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; default: throw new DataSift_Exception_NotYetImplemented('Method not of valid type'); } $url = self::appendQueryString($url, $qs); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); if ($ssl) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2'); } return $ch; }
php
private static function initialize($method, $ssl, $url, $headers, $params, $userAgent, $qs, $raw = false) { $ch = curl_init(); switch (strtolower($method)) { case 'post': curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, ($raw ? $params : json_encode($params))); break; case 'get': curl_setopt($ch, CURLOPT_HTTPGET, true); break; case 'put': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); break; case 'delete': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; default: throw new DataSift_Exception_NotYetImplemented('Method not of valid type'); } $url = self::appendQueryString($url, $qs); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); if ($ssl) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2'); } return $ch; }
[ "private", "static", "function", "initialize", "(", "$", "method", ",", "$", "ssl", ",", "$", "url", ",", "$", "headers", ",", "$", "params", ",", "$", "userAgent", ",", "$", "qs", ",", "$", "raw", "=", "false", ")", "{", "$", "ch", "=", "curl_init", "(", ")", ";", "switch", "(", "strtolower", "(", "$", "method", ")", ")", "{", "case", "'post'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "(", "$", "raw", "?", "$", "params", ":", "json_encode", "(", "$", "params", ")", ")", ")", ";", "break", ";", "case", "'get'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPGET", ",", "true", ")", ";", "break", ";", "case", "'put'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "'PUT'", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "json_encode", "(", "$", "params", ")", ")", ";", "break", ";", "case", "'delete'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "'DELETE'", ")", ";", "break", ";", "default", ":", "throw", "new", "DataSift_Exception_NotYetImplemented", "(", "'Method not of valid type'", ")", ";", "}", "$", "url", "=", "self", "::", "appendQueryString", "(", "$", "url", ",", "$", "qs", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "$", "headers", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "$", "userAgent", ")", ";", "if", "(", "$", "ssl", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYHOST", ",", "2", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSLVERSION", ",", "'CURL_SSLVERSION_TLSv1_2'", ")", ";", "}", "return", "$", "ch", ";", "}" ]
Initalize the cURL connection. @param string $method The HTTP method to use. @param boolean $ssl Is SSL Enabled. @param string $url The URL of the call. @param array $headers The headers to be sent. @param array $params The parameters to be passed along with the request. @param string $userAgent The HTTP User-Agent header. @return resource The cURL resource @throws DataSift_Exception_NotYetImplemented
[ "Initalize", "the", "cURL", "connection", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/ApiClient.php#L117-L155
datasift/datasift-php
lib/DataSift/ApiClient.php
DataSift_ApiClient.decodeBody
protected static function decodeBody(array $res) { $format = isset($res['headers']['x-datasift-format']) ? $res['headers']['x-datasift-format'] : $res['headers']['content-type']; $retval = array(); if (strtolower($format) == 'json_new_line') { foreach (explode("\n", $res['body']) as $json_string) { $retval[] = json_decode($json_string, true); } } else { $retval = json_decode($res['body'], true); } return $retval; }
php
protected static function decodeBody(array $res) { $format = isset($res['headers']['x-datasift-format']) ? $res['headers']['x-datasift-format'] : $res['headers']['content-type']; $retval = array(); if (strtolower($format) == 'json_new_line') { foreach (explode("\n", $res['body']) as $json_string) { $retval[] = json_decode($json_string, true); } } else { $retval = json_decode($res['body'], true); } return $retval; }
[ "protected", "static", "function", "decodeBody", "(", "array", "$", "res", ")", "{", "$", "format", "=", "isset", "(", "$", "res", "[", "'headers'", "]", "[", "'x-datasift-format'", "]", ")", "?", "$", "res", "[", "'headers'", "]", "[", "'x-datasift-format'", "]", ":", "$", "res", "[", "'headers'", "]", "[", "'content-type'", "]", ";", "$", "retval", "=", "array", "(", ")", ";", "if", "(", "strtolower", "(", "$", "format", ")", "==", "'json_new_line'", ")", "{", "foreach", "(", "explode", "(", "\"\\n\"", ",", "$", "res", "[", "'body'", "]", ")", "as", "$", "json_string", ")", "{", "$", "retval", "[", "]", "=", "json_decode", "(", "$", "json_string", ",", "true", ")", ";", "}", "}", "else", "{", "$", "retval", "=", "json_decode", "(", "$", "res", "[", "'body'", "]", ",", "true", ")", ";", "}", "return", "$", "retval", ";", "}" ]
Decode the JSON response depending on the format. @param array $res The parsed HTTP response. @return array An array of the decoded JSON response
[ "Decode", "the", "JSON", "response", "depending", "on", "the", "format", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/ApiClient.php#L173-L189
datasift/datasift-php
lib/DataSift/ApiClient.php
DataSift_ApiClient.parseHTTPResponse
private static function parseHTTPResponse($str) { $retval = array( 'headers' => array(), 'body' => '', ); $lastfield = false; $fields = explode("\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $str)); foreach ($fields as $field) { if (strlen(trim($field)) == 0) { $lastfield = ':body'; } elseif ($lastfield == ':body') { $retval['body'] .= $field . "\n"; } else { if (($field[0] == ' ' or $field[0] == "\t") and $lastfield !== false) { $retval['headers'][$lastfield] .= ' ' . $field; } elseif (preg_match('/([^:]+): (.+)/m', $field, $match)) { $match[1] = strtolower($match[1]); if (isset($retval['headers'][$match[1]])) { if (is_array($retval['headers'][$match[1]])) { $retval['headers'][$match[1]][] = $match[2]; } else { $retval['headers'][$match[1]] = array($retval['headers'][$match[1]], $match[2]); } } else { $retval['headers'][$match[1]] = trim($match[2]); } } } } return $retval; }
php
private static function parseHTTPResponse($str) { $retval = array( 'headers' => array(), 'body' => '', ); $lastfield = false; $fields = explode("\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $str)); foreach ($fields as $field) { if (strlen(trim($field)) == 0) { $lastfield = ':body'; } elseif ($lastfield == ':body') { $retval['body'] .= $field . "\n"; } else { if (($field[0] == ' ' or $field[0] == "\t") and $lastfield !== false) { $retval['headers'][$lastfield] .= ' ' . $field; } elseif (preg_match('/([^:]+): (.+)/m', $field, $match)) { $match[1] = strtolower($match[1]); if (isset($retval['headers'][$match[1]])) { if (is_array($retval['headers'][$match[1]])) { $retval['headers'][$match[1]][] = $match[2]; } else { $retval['headers'][$match[1]] = array($retval['headers'][$match[1]], $match[2]); } } else { $retval['headers'][$match[1]] = trim($match[2]); } } } } return $retval; }
[ "private", "static", "function", "parseHTTPResponse", "(", "$", "str", ")", "{", "$", "retval", "=", "array", "(", "'headers'", "=>", "array", "(", ")", ",", "'body'", "=>", "''", ",", ")", ";", "$", "lastfield", "=", "false", ";", "$", "fields", "=", "explode", "(", "\"\\n\"", ",", "preg_replace", "(", "'/\\x0D\\x0A[\\x09\\x20]+/'", ",", "' '", ",", "$", "str", ")", ")", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "if", "(", "strlen", "(", "trim", "(", "$", "field", ")", ")", "==", "0", ")", "{", "$", "lastfield", "=", "':body'", ";", "}", "elseif", "(", "$", "lastfield", "==", "':body'", ")", "{", "$", "retval", "[", "'body'", "]", ".=", "$", "field", ".", "\"\\n\"", ";", "}", "else", "{", "if", "(", "(", "$", "field", "[", "0", "]", "==", "' '", "or", "$", "field", "[", "0", "]", "==", "\"\\t\"", ")", "and", "$", "lastfield", "!==", "false", ")", "{", "$", "retval", "[", "'headers'", "]", "[", "$", "lastfield", "]", ".=", "' '", ".", "$", "field", ";", "}", "elseif", "(", "preg_match", "(", "'/([^:]+): (.+)/m'", ",", "$", "field", ",", "$", "match", ")", ")", "{", "$", "match", "[", "1", "]", "=", "strtolower", "(", "$", "match", "[", "1", "]", ")", ";", "if", "(", "isset", "(", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", ")", ")", "{", "if", "(", "is_array", "(", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", ")", ")", "{", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", "[", "]", "=", "$", "match", "[", "2", "]", ";", "}", "else", "{", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", "=", "array", "(", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", ",", "$", "match", "[", "2", "]", ")", ";", "}", "}", "else", "{", "$", "retval", "[", "'headers'", "]", "[", "$", "match", "[", "1", "]", "]", "=", "trim", "(", "$", "match", "[", "2", "]", ")", ";", "}", "}", "}", "}", "return", "$", "retval", ";", "}" ]
Parse an HTTP response. Separates the headers from the body and puts the headers into an associative array. @param string $str The HTTP response to be parsed. @return array An array containing headers => array(header => value), and body.
[ "Parse", "an", "HTTP", "response", ".", "Separates", "the", "headers", "from", "the", "body", "and", "puts", "the", "headers", "into", "an", "associative", "array", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/ApiClient.php#L199-L231
flownative/flow-doubleoptin
Classes/TypeConverter/TokenConverter.php
TokenConverter.convertFrom
public function convertFrom($source, $targetType, array $convertedChildProperties = [], PropertyMappingConfigurationInterface $configuration = null) { $doubleOptInHelper = new Helper(); return $doubleOptInHelper->validateTokenHash($source); }
php
public function convertFrom($source, $targetType, array $convertedChildProperties = [], PropertyMappingConfigurationInterface $configuration = null) { $doubleOptInHelper = new Helper(); return $doubleOptInHelper->validateTokenHash($source); }
[ "public", "function", "convertFrom", "(", "$", "source", ",", "$", "targetType", ",", "array", "$", "convertedChildProperties", "=", "[", "]", ",", "PropertyMappingConfigurationInterface", "$", "configuration", "=", "null", ")", "{", "$", "doubleOptInHelper", "=", "new", "Helper", "(", ")", ";", "return", "$", "doubleOptInHelper", "->", "validateTokenHash", "(", "$", "source", ")", ";", "}" ]
Actually convert from $source to $targetType, taking into account the fully built $convertedChildProperties and $configuration. @param mixed $source @param string $targetType @param array $convertedChildProperties @param PropertyMappingConfigurationInterface $configuration @return Token|null the target type, or NULL if it was not a valid token @throws \Flownative\DoubleOptIn\UnknownPresetException
[ "Actually", "convert", "from", "$source", "to", "$targetType", "taking", "into", "account", "the", "fully", "built", "$convertedChildProperties", "and", "$configuration", "." ]
train
https://github.com/flownative/flow-doubleoptin/blob/18ae7e9b326118d5592816896b46ad840c67491c/Classes/TypeConverter/TokenConverter.php#L45-L50
groupby/api-php
src/API/Util/DeepCopy.php
DeepCopy.copyObject
private function copyObject($object) { $objectHash = spl_object_hash($object); if (isset($this->hashMap[$objectHash])) { return $this->hashMap[$objectHash]; } $reflectedObject = new \ReflectionObject($object); if (false === $isCloneable = $reflectedObject->isCloneable() and $this->skipUncloneable) { $this->hashMap[$objectHash] = $object; return $object; } if (false === $isCloneable) { throw new \UnexpectedValueException(sprintf( 'Class "%s" is not cloneable.', $object->getName() )); } $newObject = clone $object; $this->hashMap[$objectHash] = $newObject; foreach ($reflectedObject->getProperties() as $property) { $this->copyObjectProperty($newObject, $property); } return $newObject; }
php
private function copyObject($object) { $objectHash = spl_object_hash($object); if (isset($this->hashMap[$objectHash])) { return $this->hashMap[$objectHash]; } $reflectedObject = new \ReflectionObject($object); if (false === $isCloneable = $reflectedObject->isCloneable() and $this->skipUncloneable) { $this->hashMap[$objectHash] = $object; return $object; } if (false === $isCloneable) { throw new \UnexpectedValueException(sprintf( 'Class "%s" is not cloneable.', $object->getName() )); } $newObject = clone $object; $this->hashMap[$objectHash] = $newObject; foreach ($reflectedObject->getProperties() as $property) { $this->copyObjectProperty($newObject, $property); } return $newObject; }
[ "private", "function", "copyObject", "(", "$", "object", ")", "{", "$", "objectHash", "=", "spl_object_hash", "(", "$", "object", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "hashMap", "[", "$", "objectHash", "]", ")", ")", "{", "return", "$", "this", "->", "hashMap", "[", "$", "objectHash", "]", ";", "}", "$", "reflectedObject", "=", "new", "\\", "ReflectionObject", "(", "$", "object", ")", ";", "if", "(", "false", "===", "$", "isCloneable", "=", "$", "reflectedObject", "->", "isCloneable", "(", ")", "and", "$", "this", "->", "skipUncloneable", ")", "{", "$", "this", "->", "hashMap", "[", "$", "objectHash", "]", "=", "$", "object", ";", "return", "$", "object", ";", "}", "if", "(", "false", "===", "$", "isCloneable", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "sprintf", "(", "'Class \"%s\" is not cloneable.'", ",", "$", "object", "->", "getName", "(", ")", ")", ")", ";", "}", "$", "newObject", "=", "clone", "$", "object", ";", "$", "this", "->", "hashMap", "[", "$", "objectHash", "]", "=", "$", "newObject", ";", "foreach", "(", "$", "reflectedObject", "->", "getProperties", "(", ")", "as", "$", "property", ")", "{", "$", "this", "->", "copyObjectProperty", "(", "$", "newObject", ",", "$", "property", ")", ";", "}", "return", "$", "newObject", ";", "}" ]
Copy an object @param object $object @return object
[ "Copy", "an", "object" ]
train
https://github.com/groupby/api-php/blob/43c31ed1f729981dd9532ce5c3efbeaaa016c147/src/API/Util/DeepCopy.php#L93-L123
ftrrtf/FtrrtfRollbarBundle
EventListener/RollbarListener.php
RollbarListener.onKernelRequest
public function onKernelRequest(GetResponseEvent $event) { $this->errorHandler->registerErrorHandler($this->notifier); $this->errorHandler->registerShutdownHandler($this->notifier); }
php
public function onKernelRequest(GetResponseEvent $event) { $this->errorHandler->registerErrorHandler($this->notifier); $this->errorHandler->registerShutdownHandler($this->notifier); }
[ "public", "function", "onKernelRequest", "(", "GetResponseEvent", "$", "event", ")", "{", "$", "this", "->", "errorHandler", "->", "registerErrorHandler", "(", "$", "this", "->", "notifier", ")", ";", "$", "this", "->", "errorHandler", "->", "registerShutdownHandler", "(", "$", "this", "->", "notifier", ")", ";", "}" ]
Register error handler. @param GetResponseEvent $event
[ "Register", "error", "handler", "." ]
train
https://github.com/ftrrtf/FtrrtfRollbarBundle/blob/64c75862b80a4a1ed9e98c0d217003e84df40dd7/EventListener/RollbarListener.php#L88-L92
ftrrtf/FtrrtfRollbarBundle
EventListener/RollbarListener.php
RollbarListener.onKernelException
public function onKernelException(GetResponseForExceptionEvent $event) { // Skip HTTP exception if ($event->getException() instanceof HttpException) { return; } $this->setException($event->getException()); }
php
public function onKernelException(GetResponseForExceptionEvent $event) { // Skip HTTP exception if ($event->getException() instanceof HttpException) { return; } $this->setException($event->getException()); }
[ "public", "function", "onKernelException", "(", "GetResponseForExceptionEvent", "$", "event", ")", "{", "// Skip HTTP exception", "if", "(", "$", "event", "->", "getException", "(", ")", "instanceof", "HttpException", ")", "{", "return", ";", "}", "$", "this", "->", "setException", "(", "$", "event", "->", "getException", "(", ")", ")", ";", "}" ]
Save exception. @param GetResponseForExceptionEvent $event
[ "Save", "exception", "." ]
train
https://github.com/ftrrtf/FtrrtfRollbarBundle/blob/64c75862b80a4a1ed9e98c0d217003e84df40dd7/EventListener/RollbarListener.php#L99-L107
ftrrtf/FtrrtfRollbarBundle
EventListener/RollbarListener.php
RollbarListener.onKernelResponse
public function onKernelResponse(FilterResponseEvent $event) { if ($this->getException()) { $this->notifier->reportException($this->getException()); $this->setException(null); } }
php
public function onKernelResponse(FilterResponseEvent $event) { if ($this->getException()) { $this->notifier->reportException($this->getException()); $this->setException(null); } }
[ "public", "function", "onKernelResponse", "(", "FilterResponseEvent", "$", "event", ")", "{", "if", "(", "$", "this", "->", "getException", "(", ")", ")", "{", "$", "this", "->", "notifier", "->", "reportException", "(", "$", "this", "->", "getException", "(", ")", ")", ";", "$", "this", "->", "setException", "(", "null", ")", ";", "}", "}" ]
Wrap exception with additional info. @param FilterResponseEvent $event
[ "Wrap", "exception", "with", "additional", "info", "." ]
train
https://github.com/ftrrtf/FtrrtfRollbarBundle/blob/64c75862b80a4a1ed9e98c0d217003e84df40dd7/EventListener/RollbarListener.php#L130-L136
ftrrtf/FtrrtfRollbarBundle
EventListener/RollbarListener.php
RollbarListener.getUserData
public function getUserData() { if (!$this->tokenStorage->getToken() || !$this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED') ) { return null; } $user = $this->tokenStorage->getToken()->getUser(); if (!$user) { return null; } return $this->userHelper->buildUserData($user); }
php
public function getUserData() { if (!$this->tokenStorage->getToken() || !$this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED') ) { return null; } $user = $this->tokenStorage->getToken()->getUser(); if (!$user) { return null; } return $this->userHelper->buildUserData($user); }
[ "public", "function", "getUserData", "(", ")", "{", "if", "(", "!", "$", "this", "->", "tokenStorage", "->", "getToken", "(", ")", "||", "!", "$", "this", "->", "authorizationChecker", "->", "isGranted", "(", "'IS_AUTHENTICATED_REMEMBERED'", ")", ")", "{", "return", "null", ";", "}", "$", "user", "=", "$", "this", "->", "tokenStorage", "->", "getToken", "(", ")", "->", "getUser", "(", ")", ";", "if", "(", "!", "$", "user", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "userHelper", "->", "buildUserData", "(", "$", "user", ")", ";", "}" ]
Get current user info. @return null|array
[ "Get", "current", "user", "info", "." ]
train
https://github.com/ftrrtf/FtrrtfRollbarBundle/blob/64c75862b80a4a1ed9e98c0d217003e84df40dd7/EventListener/RollbarListener.php#L143-L158
gdbots/pbjx-bundle-php
src/Command/ExportEventsCommand.php
ExportEventsCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $errOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output; $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); $errOutput->setVerbosity(OutputInterface::VERBOSITY_NORMAL); $batchSize = NumberUtils::bound($input->getOption('batch-size'), 1, 1000); $batchDelay = NumberUtils::bound($input->getOption('batch-delay'), 100, 600000); $since = $input->getOption('since'); $until = $input->getOption('until'); $context = json_decode($input->getOption('context') ?: '{}', true); $context['tenant_id'] = (string)$input->getOption('tenant-id'); $streamId = $input->getArgument('stream-id') ? StreamId::fromString($input->getArgument('stream-id')) : null; if (!empty($since)) { $since = Microtime::fromString(str_pad($since, 16, '0')); } if (!empty($until)) { $until = Microtime::fromString(str_pad($until, 16, '0')); } $i = 0; $receiver = function (Event $event, StreamId $streamId) use ($errOutput, $batchSize, $batchDelay, &$i) { ++$i; try { echo json_encode($event) . PHP_EOL; } catch (\Throwable $e) { $errOutput->writeln($e->getMessage()); } if (0 === $i % $batchSize) { if ($batchDelay > 0) { usleep($batchDelay * 1000); } } }; if ($streamId) { $this->getPbjx()->getEventStore()->pipeEvents($streamId, $receiver, $since, $until, $context); } else { $this->getPbjx()->getEventStore()->pipeAllEvents($receiver, $since, $until, $context); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $errOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output; $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); $errOutput->setVerbosity(OutputInterface::VERBOSITY_NORMAL); $batchSize = NumberUtils::bound($input->getOption('batch-size'), 1, 1000); $batchDelay = NumberUtils::bound($input->getOption('batch-delay'), 100, 600000); $since = $input->getOption('since'); $until = $input->getOption('until'); $context = json_decode($input->getOption('context') ?: '{}', true); $context['tenant_id'] = (string)$input->getOption('tenant-id'); $streamId = $input->getArgument('stream-id') ? StreamId::fromString($input->getArgument('stream-id')) : null; if (!empty($since)) { $since = Microtime::fromString(str_pad($since, 16, '0')); } if (!empty($until)) { $until = Microtime::fromString(str_pad($until, 16, '0')); } $i = 0; $receiver = function (Event $event, StreamId $streamId) use ($errOutput, $batchSize, $batchDelay, &$i) { ++$i; try { echo json_encode($event) . PHP_EOL; } catch (\Throwable $e) { $errOutput->writeln($e->getMessage()); } if (0 === $i % $batchSize) { if ($batchDelay > 0) { usleep($batchDelay * 1000); } } }; if ($streamId) { $this->getPbjx()->getEventStore()->pipeEvents($streamId, $receiver, $since, $until, $context); } else { $this->getPbjx()->getEventStore()->pipeAllEvents($receiver, $since, $until, $context); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "errOutput", "=", "$", "output", "instanceof", "ConsoleOutputInterface", "?", "$", "output", "->", "getErrorOutput", "(", ")", ":", "$", "output", ";", "$", "output", "->", "setVerbosity", "(", "OutputInterface", "::", "VERBOSITY_QUIET", ")", ";", "$", "errOutput", "->", "setVerbosity", "(", "OutputInterface", "::", "VERBOSITY_NORMAL", ")", ";", "$", "batchSize", "=", "NumberUtils", "::", "bound", "(", "$", "input", "->", "getOption", "(", "'batch-size'", ")", ",", "1", ",", "1000", ")", ";", "$", "batchDelay", "=", "NumberUtils", "::", "bound", "(", "$", "input", "->", "getOption", "(", "'batch-delay'", ")", ",", "100", ",", "600000", ")", ";", "$", "since", "=", "$", "input", "->", "getOption", "(", "'since'", ")", ";", "$", "until", "=", "$", "input", "->", "getOption", "(", "'until'", ")", ";", "$", "context", "=", "json_decode", "(", "$", "input", "->", "getOption", "(", "'context'", ")", "?", ":", "'{}'", ",", "true", ")", ";", "$", "context", "[", "'tenant_id'", "]", "=", "(", "string", ")", "$", "input", "->", "getOption", "(", "'tenant-id'", ")", ";", "$", "streamId", "=", "$", "input", "->", "getArgument", "(", "'stream-id'", ")", "?", "StreamId", "::", "fromString", "(", "$", "input", "->", "getArgument", "(", "'stream-id'", ")", ")", ":", "null", ";", "if", "(", "!", "empty", "(", "$", "since", ")", ")", "{", "$", "since", "=", "Microtime", "::", "fromString", "(", "str_pad", "(", "$", "since", ",", "16", ",", "'0'", ")", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "until", ")", ")", "{", "$", "until", "=", "Microtime", "::", "fromString", "(", "str_pad", "(", "$", "until", ",", "16", ",", "'0'", ")", ")", ";", "}", "$", "i", "=", "0", ";", "$", "receiver", "=", "function", "(", "Event", "$", "event", ",", "StreamId", "$", "streamId", ")", "use", "(", "$", "errOutput", ",", "$", "batchSize", ",", "$", "batchDelay", ",", "&", "$", "i", ")", "{", "++", "$", "i", ";", "try", "{", "echo", "json_encode", "(", "$", "event", ")", ".", "PHP_EOL", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "$", "errOutput", "->", "writeln", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "if", "(", "0", "===", "$", "i", "%", "$", "batchSize", ")", "{", "if", "(", "$", "batchDelay", ">", "0", ")", "{", "usleep", "(", "$", "batchDelay", "*", "1000", ")", ";", "}", "}", "}", ";", "if", "(", "$", "streamId", ")", "{", "$", "this", "->", "getPbjx", "(", ")", "->", "getEventStore", "(", ")", "->", "pipeEvents", "(", "$", "streamId", ",", "$", "receiver", ",", "$", "since", ",", "$", "until", ",", "$", "context", ")", ";", "}", "else", "{", "$", "this", "->", "getPbjx", "(", ")", "->", "getEventStore", "(", ")", "->", "pipeAllEvents", "(", "$", "receiver", ",", "$", "since", ",", "$", "until", ",", "$", "context", ")", ";", "}", "}" ]
@param InputInterface $input @param OutputInterface $output @return null
[ "@param", "InputInterface", "$input", "@param", "OutputInterface", "$output" ]
train
https://github.com/gdbots/pbjx-bundle-php/blob/f3c0088583879fc92f13247a0752634bd8696eac/src/Command/ExportEventsCommand.php#L101-L145
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.setTheme
public function setTheme(DataSourceViewInterface $dataSource, $theme, array $vars = []) { $this->themes[$dataSource->getName()] = ($theme instanceof Twig_Template) ? $theme : $this->environment->loadTemplate($theme); $this->themesVars[$dataSource->getName()] = $vars; }
php
public function setTheme(DataSourceViewInterface $dataSource, $theme, array $vars = []) { $this->themes[$dataSource->getName()] = ($theme instanceof Twig_Template) ? $theme : $this->environment->loadTemplate($theme); $this->themesVars[$dataSource->getName()] = $vars; }
[ "public", "function", "setTheme", "(", "DataSourceViewInterface", "$", "dataSource", ",", "$", "theme", ",", "array", "$", "vars", "=", "[", "]", ")", "{", "$", "this", "->", "themes", "[", "$", "dataSource", "->", "getName", "(", ")", "]", "=", "(", "$", "theme", "instanceof", "Twig_Template", ")", "?", "$", "theme", ":", "$", "this", "->", "environment", "->", "loadTemplate", "(", "$", "theme", ")", ";", "$", "this", "->", "themesVars", "[", "$", "dataSource", "->", "getName", "(", ")", "]", "=", "$", "vars", ";", "}" ]
Set theme for specific DataSource. Theme is nothing more than twig template that contains some or all of blocks required to render DataSource. @param DataSourceViewInterface $dataSource @param $theme @param array $vars
[ "Set", "theme", "for", "specific", "DataSource", ".", "Theme", "is", "nothing", "more", "than", "twig", "template", "that", "contains", "some", "or", "all", "of", "blocks", "required", "to", "render", "DataSource", "." ]
train
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L118-L124
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.setRoute
public function setRoute(DataSourceViewInterface $dataSource, $route, array $additional_parameters = []) { $this->routes[$dataSource->getName()] = $route; $this->additional_parameters[$dataSource->getName()] = $additional_parameters; }
php
public function setRoute(DataSourceViewInterface $dataSource, $route, array $additional_parameters = []) { $this->routes[$dataSource->getName()] = $route; $this->additional_parameters[$dataSource->getName()] = $additional_parameters; }
[ "public", "function", "setRoute", "(", "DataSourceViewInterface", "$", "dataSource", ",", "$", "route", ",", "array", "$", "additional_parameters", "=", "[", "]", ")", "{", "$", "this", "->", "routes", "[", "$", "dataSource", "->", "getName", "(", ")", "]", "=", "$", "route", ";", "$", "this", "->", "additional_parameters", "[", "$", "dataSource", "->", "getName", "(", ")", "]", "=", "$", "additional_parameters", ";", "}" ]
Set route and optionally additional parameters for specific DataSource. @param DataSourceViewInterface $dataSource @param $route @param array $additional_parameters
[ "Set", "route", "and", "optionally", "additional", "parameters", "for", "specific", "DataSource", "." ]
train
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L133-L137
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.resolveMaxResultsOptions
private function resolveMaxResultsOptions(array $options, DataSourceViewInterface $dataSource) { $optionsResolver = new OptionsResolver(); $optionsResolver ->setDefaults([ 'route' => $this->getCurrentRoute($dataSource), 'active_class' => 'active', 'additional_parameters' => [], 'results' => [5, 10, 20, 50, 100] ]) ->setAllowedTypes('route', 'string') ->setAllowedTypes('active_class', 'string') ->setAllowedTypes('additional_parameters', 'array') ->setAllowedTypes('results', 'array'); return $optionsResolver->resolve($options); }
php
private function resolveMaxResultsOptions(array $options, DataSourceViewInterface $dataSource) { $optionsResolver = new OptionsResolver(); $optionsResolver ->setDefaults([ 'route' => $this->getCurrentRoute($dataSource), 'active_class' => 'active', 'additional_parameters' => [], 'results' => [5, 10, 20, 50, 100] ]) ->setAllowedTypes('route', 'string') ->setAllowedTypes('active_class', 'string') ->setAllowedTypes('additional_parameters', 'array') ->setAllowedTypes('results', 'array'); return $optionsResolver->resolve($options); }
[ "private", "function", "resolveMaxResultsOptions", "(", "array", "$", "options", ",", "DataSourceViewInterface", "$", "dataSource", ")", "{", "$", "optionsResolver", "=", "new", "OptionsResolver", "(", ")", ";", "$", "optionsResolver", "->", "setDefaults", "(", "[", "'route'", "=>", "$", "this", "->", "getCurrentRoute", "(", "$", "dataSource", ")", ",", "'active_class'", "=>", "'active'", ",", "'additional_parameters'", "=>", "[", "]", ",", "'results'", "=>", "[", "5", ",", "10", ",", "20", ",", "50", ",", "100", "]", "]", ")", "->", "setAllowedTypes", "(", "'route'", ",", "'string'", ")", "->", "setAllowedTypes", "(", "'active_class'", ",", "'string'", ")", "->", "setAllowedTypes", "(", "'additional_parameters'", ",", "'array'", ")", "->", "setAllowedTypes", "(", "'results'", ",", "'array'", ")", ";", "return", "$", "optionsResolver", "->", "resolve", "(", "$", "options", ")", ";", "}" ]
Validate and resolve options passed in Twig to datasource_results_per_page_widget @param array $options @return array
[ "Validate", "and", "resolve", "options", "passed", "in", "Twig", "to", "datasource_results_per_page_widget" ]
train
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L333-L349
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.getTemplates
private function getTemplates(DataSourceViewInterface $dataSource) { $templates = []; if (isset($this->themes[$dataSource->getName()])) { $templates[] = $this->themes[$dataSource->getName()]; } $templates[] = $this->themes[self::DEFAULT_THEME]; return $templates; }
php
private function getTemplates(DataSourceViewInterface $dataSource) { $templates = []; if (isset($this->themes[$dataSource->getName()])) { $templates[] = $this->themes[$dataSource->getName()]; } $templates[] = $this->themes[self::DEFAULT_THEME]; return $templates; }
[ "private", "function", "getTemplates", "(", "DataSourceViewInterface", "$", "dataSource", ")", "{", "$", "templates", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "themes", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ")", ")", "{", "$", "templates", "[", "]", "=", "$", "this", "->", "themes", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ";", "}", "$", "templates", "[", "]", "=", "$", "this", "->", "themes", "[", "self", "::", "DEFAULT_THEME", "]", ";", "return", "$", "templates", ";", "}" ]
Return list of templates that might be useful to render DataSourceView. Always the last template will be default one. @param DataSourceViewInterface $dataSource @return array
[ "Return", "list", "of", "templates", "that", "might", "be", "useful", "to", "render", "DataSourceView", ".", "Always", "the", "last", "template", "will", "be", "default", "one", "." ]
train
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L409-L420
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.getVars
private function getVars(DataSourceViewInterface $dataSource) { return isset($this->themesVars[$dataSource->getName()]) ? $this->themesVars[$dataSource->getName()] : [] ; }
php
private function getVars(DataSourceViewInterface $dataSource) { return isset($this->themesVars[$dataSource->getName()]) ? $this->themesVars[$dataSource->getName()] : [] ; }
[ "private", "function", "getVars", "(", "DataSourceViewInterface", "$", "dataSource", ")", "{", "return", "isset", "(", "$", "this", "->", "themesVars", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ")", "?", "$", "this", "->", "themesVars", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ":", "[", "]", ";", "}" ]
Return vars passed to theme. Those vars will be added to block context. @param DataSourceViewInterface $dataSource @return array
[ "Return", "vars", "passed", "to", "theme", ".", "Those", "vars", "will", "be", "added", "to", "block", "context", "." ]
train
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L428-L434
fsi-open/datasource-bundle
Twig/Extension/DataSourceExtension.php
DataSourceExtension.getUrl
private function getUrl(DataSourceViewInterface $dataSource, array $options = [], array $parameters = []) { $router = $this->container->get('router'); return $router->generate( $options['route'], array_merge( isset($this->additional_parameters[$dataSource->getName()]) ? $this->additional_parameters[$dataSource->getName()] : [], isset($options['additional_parameters']) ? $options['additional_parameters'] : [], $parameters ) ); }
php
private function getUrl(DataSourceViewInterface $dataSource, array $options = [], array $parameters = []) { $router = $this->container->get('router'); return $router->generate( $options['route'], array_merge( isset($this->additional_parameters[$dataSource->getName()]) ? $this->additional_parameters[$dataSource->getName()] : [], isset($options['additional_parameters']) ? $options['additional_parameters'] : [], $parameters ) ); }
[ "private", "function", "getUrl", "(", "DataSourceViewInterface", "$", "dataSource", ",", "array", "$", "options", "=", "[", "]", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "$", "router", "=", "$", "this", "->", "container", "->", "get", "(", "'router'", ")", ";", "return", "$", "router", "->", "generate", "(", "$", "options", "[", "'route'", "]", ",", "array_merge", "(", "isset", "(", "$", "this", "->", "additional_parameters", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ")", "?", "$", "this", "->", "additional_parameters", "[", "$", "dataSource", "->", "getName", "(", ")", "]", ":", "[", "]", ",", "isset", "(", "$", "options", "[", "'additional_parameters'", "]", ")", "?", "$", "options", "[", "'additional_parameters'", "]", ":", "[", "]", ",", "$", "parameters", ")", ")", ";", "}" ]
Return additional parameters that should be passed to the URL generation for specified datasource. @param DataSourceViewInterface $dataSource @return array
[ "Return", "additional", "parameters", "that", "should", "be", "passed", "to", "the", "URL", "generation", "for", "specified", "datasource", "." ]
train
https://github.com/fsi-open/datasource-bundle/blob/06964672c838af9f4125065e3a90b2df4e8aa077/Twig/Extension/DataSourceExtension.php#L442-L458