id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
223,900
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.addCommonHeader
private function addCommonHeader($isOption = false) { $headers = $this->getResponse()->getHeaders(); $headers->addHeaderLine('Tus-Resumable', self::TUS_VERSION); $headers->addHeaderLine('Access-Control-Allow-Origin', '*'); $headers->addHeaderLine('Access-Control-Expose-Headers', 'Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata'); if ($isOption) { $allowedMethods = 'OPTIONS,HEAD,POST,PATCH'; if ($this->getAllowGetMethod()) { $allowedMethods .= ',GET'; } $headers->addHeaders([ 'Tus-Version' => self::TUS_VERSION, 'Tus-Extension' => 'creation', 'Tus-Max-Size' => $this->allowMaxSize, 'Allow' => $allowedMethods, 'Access-Control-Allow-Methods' => $allowedMethods, 'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Final-Length, Upload-Offset, Upload-Length, Tus-Resumable, Upload-Metadata', ]); } return $this->response->setHeaders($headers); }
php
private function addCommonHeader($isOption = false) { $headers = $this->getResponse()->getHeaders(); $headers->addHeaderLine('Tus-Resumable', self::TUS_VERSION); $headers->addHeaderLine('Access-Control-Allow-Origin', '*'); $headers->addHeaderLine('Access-Control-Expose-Headers', 'Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata'); if ($isOption) { $allowedMethods = 'OPTIONS,HEAD,POST,PATCH'; if ($this->getAllowGetMethod()) { $allowedMethods .= ',GET'; } $headers->addHeaders([ 'Tus-Version' => self::TUS_VERSION, 'Tus-Extension' => 'creation', 'Tus-Max-Size' => $this->allowMaxSize, 'Allow' => $allowedMethods, 'Access-Control-Allow-Methods' => $allowedMethods, 'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Final-Length, Upload-Offset, Upload-Length, Tus-Resumable, Upload-Metadata', ]); } return $this->response->setHeaders($headers); }
[ "private", "function", "addCommonHeader", "(", "$", "isOption", "=", "false", ")", "{", "$", "headers", "=", "$", "this", "->", "getResponse", "(", ")", "->", "getHeaders", "(", ")", ";", "$", "headers", "->", "addHeaderLine", "(", "'Tus-Resumable'", ",", "self", "::", "TUS_VERSION", ")", ";", "$", "headers", "->", "addHeaderLine", "(", "'Access-Control-Allow-Origin'", ",", "'*'", ")", ";", "$", "headers", "->", "addHeaderLine", "(", "'Access-Control-Expose-Headers'", ",", "'Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata'", ")", ";", "if", "(", "$", "isOption", ")", "{", "$", "allowedMethods", "=", "'OPTIONS,HEAD,POST,PATCH'", ";", "if", "(", "$", "this", "->", "getAllowGetMethod", "(", ")", ")", "{", "$", "allowedMethods", ".=", "',GET'", ";", "}", "$", "headers", "->", "addHeaders", "(", "[", "'Tus-Version'", "=>", "self", "::", "TUS_VERSION", ",", "'Tus-Extension'", "=>", "'creation'", ",", "'Tus-Max-Size'", "=>", "$", "this", "->", "allowMaxSize", ",", "'Allow'", "=>", "$", "allowedMethods", ",", "'Access-Control-Allow-Methods'", "=>", "$", "allowedMethods", ",", "'Access-Control-Allow-Headers'", "=>", "'Origin, X-Requested-With, Content-Type, Accept, Final-Length, Upload-Offset, Upload-Length, Tus-Resumable, Upload-Metadata'", ",", "]", ")", ";", "}", "return", "$", "this", "->", "response", "->", "setHeaders", "(", "$", "headers", ")", ";", "}" ]
Add the commons headers to the HTTP response @param bool $isOption Is OPTION request @access private
[ "Add", "the", "commons", "headers", "to", "the", "HTTP", "response" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L510-L532
223,901
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.extractHeaders
private function extractHeaders($headers) { if (is_array($headers) === false) { throw new \InvalidArgumentException('Headers must be an array'); } $headers_values = array(); foreach ($headers as $headerName) { $headerObj = $this->getRequest()->getHeader($headerName); if ($headerObj instanceof \Zend\Http\Header\HeaderInterface) { $value = $headerObj->getFieldValue(); // \Zend\Http\Header\ContentLength has a bug in initialization // if header value is 0 then it sets value as null if (is_null($value) && $headerObj instanceof \Zend\Http\Header\ContentLength) { $value = 0; } if (trim($value) === '') { throw new Exception\BadHeader($headerName . ' can\'t be empty'); } $headers_values[$headerName] = $value; } } return $headers_values; }
php
private function extractHeaders($headers) { if (is_array($headers) === false) { throw new \InvalidArgumentException('Headers must be an array'); } $headers_values = array(); foreach ($headers as $headerName) { $headerObj = $this->getRequest()->getHeader($headerName); if ($headerObj instanceof \Zend\Http\Header\HeaderInterface) { $value = $headerObj->getFieldValue(); // \Zend\Http\Header\ContentLength has a bug in initialization // if header value is 0 then it sets value as null if (is_null($value) && $headerObj instanceof \Zend\Http\Header\ContentLength) { $value = 0; } if (trim($value) === '') { throw new Exception\BadHeader($headerName . ' can\'t be empty'); } $headers_values[$headerName] = $value; } } return $headers_values; }
[ "private", "function", "extractHeaders", "(", "$", "headers", ")", "{", "if", "(", "is_array", "(", "$", "headers", ")", "===", "false", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Headers must be an array'", ")", ";", "}", "$", "headers_values", "=", "array", "(", ")", ";", "foreach", "(", "$", "headers", "as", "$", "headerName", ")", "{", "$", "headerObj", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getHeader", "(", "$", "headerName", ")", ";", "if", "(", "$", "headerObj", "instanceof", "\\", "Zend", "\\", "Http", "\\", "Header", "\\", "HeaderInterface", ")", "{", "$", "value", "=", "$", "headerObj", "->", "getFieldValue", "(", ")", ";", "// \\Zend\\Http\\Header\\ContentLength has a bug in initialization", "// if header value is 0 then it sets value as null", "if", "(", "is_null", "(", "$", "value", ")", "&&", "$", "headerObj", "instanceof", "\\", "Zend", "\\", "Http", "\\", "Header", "\\", "ContentLength", ")", "{", "$", "value", "=", "0", ";", "}", "if", "(", "trim", "(", "$", "value", ")", "===", "''", ")", "{", "throw", "new", "Exception", "\\", "BadHeader", "(", "$", "headerName", ".", "' can\\'t be empty'", ")", ";", "}", "$", "headers_values", "[", "$", "headerName", "]", "=", "$", "value", ";", "}", "}", "return", "$", "headers_values", ";", "}" ]
Extract a list of headers in the HTTP headers @param array $headers A list of header name to extract @return array A list if header ([header name => header value]) @throws \InvalidArgumentException If headers isn't array @throws \\Exception\BadHeader If a header sought doesn't exist or are empty @access private
[ "Extract", "a", "list", "of", "headers", "in", "the", "HTTP", "headers" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L543-L569
223,902
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.setDirectory
private function setDirectory($directory) { if (is_string($directory) === false) { throw new \InvalidArgumentException('Directory must be a string'); } if (is_dir($directory) === false || is_writable($directory) === false) { throw new Exception\File($directory . ' doesn\'t exist or isn\'t writable'); } $this->directory = $directory . (substr($directory, -1) !== DIRECTORY_SEPARATOR ? DIRECTORY_SEPARATOR : ''); return $this; }
php
private function setDirectory($directory) { if (is_string($directory) === false) { throw new \InvalidArgumentException('Directory must be a string'); } if (is_dir($directory) === false || is_writable($directory) === false) { throw new Exception\File($directory . ' doesn\'t exist or isn\'t writable'); } $this->directory = $directory . (substr($directory, -1) !== DIRECTORY_SEPARATOR ? DIRECTORY_SEPARATOR : ''); return $this; }
[ "private", "function", "setDirectory", "(", "$", "directory", ")", "{", "if", "(", "is_string", "(", "$", "directory", ")", "===", "false", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Directory must be a string'", ")", ";", "}", "if", "(", "is_dir", "(", "$", "directory", ")", "===", "false", "||", "is_writable", "(", "$", "directory", ")", "===", "false", ")", "{", "throw", "new", "Exception", "\\", "File", "(", "$", "directory", ".", "' doesn\\'t exist or isn\\'t writable'", ")", ";", "}", "$", "this", "->", "directory", "=", "$", "directory", ".", "(", "substr", "(", "$", "directory", ",", "-", "1", ")", "!==", "DIRECTORY_SEPARATOR", "?", "DIRECTORY_SEPARATOR", ":", "''", ")", ";", "return", "$", "this", ";", "}" ]
Set the directory where the file will be store @param string $directory The directory where the file are stored @return \\Server The current Server instance @throws \InvalidArgumentException If directory isn't string @throws \\Exception\File If directory isn't writable @access private
[ "Set", "the", "directory", "where", "the", "file", "will", "be", "store" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L580-L592
223,903
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.getMetaData
private function getMetaData() { if ($this->metaData === null) { $this->metaData = $this->readMetaData($this->getUserUuid()); } return $this->metaData; }
php
private function getMetaData() { if ($this->metaData === null) { $this->metaData = $this->readMetaData($this->getUserUuid()); } return $this->metaData; }
[ "private", "function", "getMetaData", "(", ")", "{", "if", "(", "$", "this", "->", "metaData", "===", "null", ")", "{", "$", "this", "->", "metaData", "=", "$", "this", "->", "readMetaData", "(", "$", "this", "->", "getUserUuid", "(", ")", ")", ";", "}", "return", "$", "this", "->", "metaData", ";", "}" ]
Get the session info @return \Zend\Session\Container @access private
[ "Get", "the", "session", "info" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L600-L607
223,904
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.setMetaDataValue
private function setMetaDataValue($id, $key, $value) { $data = $this->getMetaData($id); if (isset($data[$key])) { $data[$key] = $value; } else { throw new \Exception($key . ' is not defined in medatada'); } }
php
private function setMetaDataValue($id, $key, $value) { $data = $this->getMetaData($id); if (isset($data[$key])) { $data[$key] = $value; } else { throw new \Exception($key . ' is not defined in medatada'); } }
[ "private", "function", "setMetaDataValue", "(", "$", "id", ",", "$", "key", ",", "$", "value", ")", "{", "$", "data", "=", "$", "this", "->", "getMetaData", "(", "$", "id", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "$", "key", "]", ")", ")", "{", "$", "data", "[", "$", "key", "]", "=", "$", "value", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "$", "key", ".", "' is not defined in medatada'", ")", ";", "}", "}" ]
Set a value in the session @param string $id The id to use to set the value (an id can have multiple key) @param string $key The key for wich you want set the value @param mixed $value The value for the id-key to save @return void @access private
[ "Set", "a", "value", "in", "the", "session" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L618-L626
223,905
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.getMetaDataValue
private function getMetaDataValue($id, $key) { $data = $this->getMetaData($id); if (isset($data[$key])) { return $data[$key]; } throw new \Exception($key . ' is not defined in medatada'); }
php
private function getMetaDataValue($id, $key) { $data = $this->getMetaData($id); if (isset($data[$key])) { return $data[$key]; } throw new \Exception($key . ' is not defined in medatada'); }
[ "private", "function", "getMetaDataValue", "(", "$", "id", ",", "$", "key", ")", "{", "$", "data", "=", "$", "this", "->", "getMetaData", "(", "$", "id", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "$", "key", "]", ")", ")", "{", "return", "$", "data", "[", "$", "key", "]", ";", "}", "throw", "new", "\\", "Exception", "(", "$", "key", ".", "' is not defined in medatada'", ")", ";", "}" ]
Get a value from session @param string $id The id to use to get the value (an id can have multiple key) @param string $key The key for wich you want value @return mixed The value for the id-key @throws \Exception key is not defined in medatada @access private
[ "Get", "a", "value", "from", "session" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L637-L643
223,906
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.saveMetaData
private function saveMetaData($size, $offset = 0, $isFinal = false, $isPartial = false) { $this->setMetaDataValue($this->getUserUuid(), 'ID', $this->getUserUuid()); $this->metaData['ID'] = $this->getUserUuid(); $this->metaData['Offset'] = $offset; $this->metaData['IsPartial'] = (bool) $isPartial; $this->metaData['IsFinal'] = (bool) $isFinal; if ($this->metaData['Size'] === 0) { $this->metaData['Size'] = $size; } if (empty($this->metaData['FileName'])) { $this->metaData['FileName'] = $this->getRealFileName(); $info = new \SplFileInfo($this->getRealFileName()); $ext = $info->getExtension(); $this->metaData['Extension'] = $ext; } if ($isFinal) { $this->metaData['MimeType'] = FileToolsService::detectMimeType( $this->directory . $this->getUserUuid(), $this->getRealFileName() ); } $json = Json::encode($this->metaData); file_put_contents($this->directory . $this->getUserUuid() . '.info', $json); }
php
private function saveMetaData($size, $offset = 0, $isFinal = false, $isPartial = false) { $this->setMetaDataValue($this->getUserUuid(), 'ID', $this->getUserUuid()); $this->metaData['ID'] = $this->getUserUuid(); $this->metaData['Offset'] = $offset; $this->metaData['IsPartial'] = (bool) $isPartial; $this->metaData['IsFinal'] = (bool) $isFinal; if ($this->metaData['Size'] === 0) { $this->metaData['Size'] = $size; } if (empty($this->metaData['FileName'])) { $this->metaData['FileName'] = $this->getRealFileName(); $info = new \SplFileInfo($this->getRealFileName()); $ext = $info->getExtension(); $this->metaData['Extension'] = $ext; } if ($isFinal) { $this->metaData['MimeType'] = FileToolsService::detectMimeType( $this->directory . $this->getUserUuid(), $this->getRealFileName() ); } $json = Json::encode($this->metaData); file_put_contents($this->directory . $this->getUserUuid() . '.info', $json); }
[ "private", "function", "saveMetaData", "(", "$", "size", ",", "$", "offset", "=", "0", ",", "$", "isFinal", "=", "false", ",", "$", "isPartial", "=", "false", ")", "{", "$", "this", "->", "setMetaDataValue", "(", "$", "this", "->", "getUserUuid", "(", ")", ",", "'ID'", ",", "$", "this", "->", "getUserUuid", "(", ")", ")", ";", "$", "this", "->", "metaData", "[", "'ID'", "]", "=", "$", "this", "->", "getUserUuid", "(", ")", ";", "$", "this", "->", "metaData", "[", "'Offset'", "]", "=", "$", "offset", ";", "$", "this", "->", "metaData", "[", "'IsPartial'", "]", "=", "(", "bool", ")", "$", "isPartial", ";", "$", "this", "->", "metaData", "[", "'IsFinal'", "]", "=", "(", "bool", ")", "$", "isFinal", ";", "if", "(", "$", "this", "->", "metaData", "[", "'Size'", "]", "===", "0", ")", "{", "$", "this", "->", "metaData", "[", "'Size'", "]", "=", "$", "size", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "metaData", "[", "'FileName'", "]", ")", ")", "{", "$", "this", "->", "metaData", "[", "'FileName'", "]", "=", "$", "this", "->", "getRealFileName", "(", ")", ";", "$", "info", "=", "new", "\\", "SplFileInfo", "(", "$", "this", "->", "getRealFileName", "(", ")", ")", ";", "$", "ext", "=", "$", "info", "->", "getExtension", "(", ")", ";", "$", "this", "->", "metaData", "[", "'Extension'", "]", "=", "$", "ext", ";", "}", "if", "(", "$", "isFinal", ")", "{", "$", "this", "->", "metaData", "[", "'MimeType'", "]", "=", "FileToolsService", "::", "detectMimeType", "(", "$", "this", "->", "directory", ".", "$", "this", "->", "getUserUuid", "(", ")", ",", "$", "this", "->", "getRealFileName", "(", ")", ")", ";", "}", "$", "json", "=", "Json", "::", "encode", "(", "$", "this", "->", "metaData", ")", ";", "file_put_contents", "(", "$", "this", "->", "directory", ".", "$", "this", "->", "getUserUuid", "(", ")", ".", "'.info'", ",", "$", "json", ")", ";", "}" ]
Saves metadata about uploaded file. Metadata are saved into a file with name mask 'uuid'.info @param int $size @param int $offset @param bool $isFinal @param bool $isPartial
[ "Saves", "metadata", "about", "uploaded", "file", ".", "Metadata", "are", "saved", "into", "a", "file", "with", "name", "mask", "uuid", ".", "info" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L683-L709
223,907
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.readMetaData
private function readMetaData($name) { $refData = [ 'ID' => '', 'Size' => 0, 'Offset' => 0, 'Extension' => '', 'FileName' => '', 'MimeType' => '', 'IsPartial' => true, 'IsFinal' => false, 'PartialUploads' => null, // unused ]; $storageFileName = $this->directory . $name . '.info'; if (file_exists($storageFileName)) { $json = file_get_contents($storageFileName); $data = Json::decode($json, Json::TYPE_ARRAY); if (is_array($data)) { return array_merge($refData, $data); } } return $refData; }
php
private function readMetaData($name) { $refData = [ 'ID' => '', 'Size' => 0, 'Offset' => 0, 'Extension' => '', 'FileName' => '', 'MimeType' => '', 'IsPartial' => true, 'IsFinal' => false, 'PartialUploads' => null, // unused ]; $storageFileName = $this->directory . $name . '.info'; if (file_exists($storageFileName)) { $json = file_get_contents($storageFileName); $data = Json::decode($json, Json::TYPE_ARRAY); if (is_array($data)) { return array_merge($refData, $data); } } return $refData; }
[ "private", "function", "readMetaData", "(", "$", "name", ")", "{", "$", "refData", "=", "[", "'ID'", "=>", "''", ",", "'Size'", "=>", "0", ",", "'Offset'", "=>", "0", ",", "'Extension'", "=>", "''", ",", "'FileName'", "=>", "''", ",", "'MimeType'", "=>", "''", ",", "'IsPartial'", "=>", "true", ",", "'IsFinal'", "=>", "false", ",", "'PartialUploads'", "=>", "null", ",", "// unused", "]", ";", "$", "storageFileName", "=", "$", "this", "->", "directory", ".", "$", "name", ".", "'.info'", ";", "if", "(", "file_exists", "(", "$", "storageFileName", ")", ")", "{", "$", "json", "=", "file_get_contents", "(", "$", "storageFileName", ")", ";", "$", "data", "=", "Json", "::", "decode", "(", "$", "json", ",", "Json", "::", "TYPE_ARRAY", ")", ";", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "return", "array_merge", "(", "$", "refData", ",", "$", "data", ")", ";", "}", "}", "return", "$", "refData", ";", "}" ]
Reads or initialize metadata about file. @param string $name @return array
[ "Reads", "or", "initialize", "metadata", "about", "file", "." ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L717-L739
223,908
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.setRealFileName
private function setRealFileName($value) { $base64FileNamePos = strpos($value, 'filename '); if (is_int($base64FileNamePos) && $base64FileNamePos >= 0) { $value = substr($value, $base64FileNamePos + 9); // 9 - length of 'filename ' $this->realFileName = base64_decode($value); } else { $this->realFileName = $value; } return $this; }
php
private function setRealFileName($value) { $base64FileNamePos = strpos($value, 'filename '); if (is_int($base64FileNamePos) && $base64FileNamePos >= 0) { $value = substr($value, $base64FileNamePos + 9); // 9 - length of 'filename ' $this->realFileName = base64_decode($value); } else { $this->realFileName = $value; } return $this; }
[ "private", "function", "setRealFileName", "(", "$", "value", ")", "{", "$", "base64FileNamePos", "=", "strpos", "(", "$", "value", ",", "'filename '", ")", ";", "if", "(", "is_int", "(", "$", "base64FileNamePos", ")", "&&", "$", "base64FileNamePos", ">=", "0", ")", "{", "$", "value", "=", "substr", "(", "$", "value", ",", "$", "base64FileNamePos", "+", "9", ")", ";", "// 9 - length of 'filename '", "$", "this", "->", "realFileName", "=", "base64_decode", "(", "$", "value", ")", ";", "}", "else", "{", "$", "this", "->", "realFileName", "=", "$", "value", ";", "}", "return", "$", "this", ";", "}" ]
Sets real file name @param string $value plain or base64 encoded file name @return \ZfTusServer\Server object @access private
[ "Sets", "real", "file", "name" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L797-L806
223,909
Orajo/zf2-tus-server
src/ZfTusServer/Server.php
Server.setAllowMaxSize
public function setAllowMaxSize($value) { $value = intval($value); if ($value > 0) { $this->allowMaxSize = $value; } else { throw new \BadMethodCallException('given $value must be integer, greater them 0'); } return $this; }
php
public function setAllowMaxSize($value) { $value = intval($value); if ($value > 0) { $this->allowMaxSize = $value; } else { throw new \BadMethodCallException('given $value must be integer, greater them 0'); } return $this; }
[ "public", "function", "setAllowMaxSize", "(", "$", "value", ")", "{", "$", "value", "=", "intval", "(", "$", "value", ")", ";", "if", "(", "$", "value", ">", "0", ")", "{", "$", "this", "->", "allowMaxSize", "=", "$", "value", ";", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "'given $value must be integer, greater them 0'", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets upload size limit @param int $value @return \ZfTusServer\Server @throws \BadMethodCallException
[ "Sets", "upload", "size", "limit" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/Server.php#L832-L840
223,910
koala-framework/composer-extra-assets
Kwf/ComposerExtraAssets/Plugin.php
Plugin._mergeDependencyVersions
private function _mergeDependencyVersions(array $array1, array $array2) { foreach ($array2 as $package => $version) { if (!isset($array1[$package])) { $array1[$package] = $version; } else { if ($array1[$package] != $version) { $array1[$package] .= " ".$version; } } } return $array1; }
php
private function _mergeDependencyVersions(array $array1, array $array2) { foreach ($array2 as $package => $version) { if (!isset($array1[$package])) { $array1[$package] = $version; } else { if ($array1[$package] != $version) { $array1[$package] .= " ".$version; } } } return $array1; }
[ "private", "function", "_mergeDependencyVersions", "(", "array", "$", "array1", ",", "array", "$", "array2", ")", "{", "foreach", "(", "$", "array2", "as", "$", "package", "=>", "$", "version", ")", "{", "if", "(", "!", "isset", "(", "$", "array1", "[", "$", "package", "]", ")", ")", "{", "$", "array1", "[", "$", "package", "]", "=", "$", "version", ";", "}", "else", "{", "if", "(", "$", "array1", "[", "$", "package", "]", "!=", "$", "version", ")", "{", "$", "array1", "[", "$", "package", "]", ".=", "\" \"", ".", "$", "version", ";", "}", "}", "}", "return", "$", "array1", ";", "}" ]
Merges 2 version of arrays. @param array $array1 @param array $array2 @return array
[ "Merges", "2", "version", "of", "arrays", "." ]
8421543ac20ee59f5171e7b36a8830b7070a57cb
https://github.com/koala-framework/composer-extra-assets/blob/8421543ac20ee59f5171e7b36a8830b7070a57cb/Kwf/ComposerExtraAssets/Plugin.php#L284-L295
223,911
himiklab/yii2-jqgrid-widget
actions/JqGridActionTrait.php
JqGridActionTrait.getRequestData
protected function getRequestData() { if (Yii::$app->request->method === 'POST') { return $this->getRealPOSTData(); } if (Yii::$app->request->method === 'GET') { $requestData = Yii::$app->request->get(); unset($requestData['action']); // delete service GET param return $requestData; } throw new BadRequestHttpException('Unsupported request method.'); }
php
protected function getRequestData() { if (Yii::$app->request->method === 'POST') { return $this->getRealPOSTData(); } if (Yii::$app->request->method === 'GET') { $requestData = Yii::$app->request->get(); unset($requestData['action']); // delete service GET param return $requestData; } throw new BadRequestHttpException('Unsupported request method.'); }
[ "protected", "function", "getRequestData", "(", ")", "{", "if", "(", "Yii", "::", "$", "app", "->", "request", "->", "method", "===", "'POST'", ")", "{", "return", "$", "this", "->", "getRealPOSTData", "(", ")", ";", "}", "if", "(", "Yii", "::", "$", "app", "->", "request", "->", "method", "===", "'GET'", ")", "{", "$", "requestData", "=", "Yii", "::", "$", "app", "->", "request", "->", "get", "(", ")", ";", "unset", "(", "$", "requestData", "[", "'action'", "]", ")", ";", "// delete service GET param", "return", "$", "requestData", ";", "}", "throw", "new", "BadRequestHttpException", "(", "'Unsupported request method.'", ")", ";", "}" ]
Returns an array of all request parameters. @return array @throws BadRequestHttpException
[ "Returns", "an", "array", "of", "all", "request", "parameters", "." ]
da647d3cf4de5a5231608477890eba646b474373
https://github.com/himiklab/yii2-jqgrid-widget/blob/da647d3cf4de5a5231608477890eba646b474373/actions/JqGridActionTrait.php#L26-L38
223,912
phonetworks/pho-microkernel
src/Pho/Kernel/Graphsystem.php
Graphsystem.node
public function node(string $node_id): Graph\NodeInterface { if(isset($this->node_cache[$node_id])) { return $this->node_cache[$node_id]; } $query = (string) $node_id; // sprintf("node:%s", (string) $node_id); $node = $this->database->get($query); if(is_null($node)) { throw new Exceptions\NodeDoesNotExistException($node_id); } $node = unserialize($node); if(!$node instanceof Framework\ParticleInterface && !$node instanceof Foundation\World) { throw new Exceptions\NotANodeException($node_id); } $node->registerHandler( "set", \Pho\Kernel\Foundation\Handlers\Set::class ); if($node instanceof Foundation\AbstractActor) { $node->registerHandler( "form", \Pho\Kernel\Foundation\Handlers\Form::class ); } $node->init(); $this->node_cache[$node_id] = $node; return $node; }
php
public function node(string $node_id): Graph\NodeInterface { if(isset($this->node_cache[$node_id])) { return $this->node_cache[$node_id]; } $query = (string) $node_id; // sprintf("node:%s", (string) $node_id); $node = $this->database->get($query); if(is_null($node)) { throw new Exceptions\NodeDoesNotExistException($node_id); } $node = unserialize($node); if(!$node instanceof Framework\ParticleInterface && !$node instanceof Foundation\World) { throw new Exceptions\NotANodeException($node_id); } $node->registerHandler( "set", \Pho\Kernel\Foundation\Handlers\Set::class ); if($node instanceof Foundation\AbstractActor) { $node->registerHandler( "form", \Pho\Kernel\Foundation\Handlers\Form::class ); } $node->init(); $this->node_cache[$node_id] = $node; return $node; }
[ "public", "function", "node", "(", "string", "$", "node_id", ")", ":", "Graph", "\\", "NodeInterface", "{", "if", "(", "isset", "(", "$", "this", "->", "node_cache", "[", "$", "node_id", "]", ")", ")", "{", "return", "$", "this", "->", "node_cache", "[", "$", "node_id", "]", ";", "}", "$", "query", "=", "(", "string", ")", "$", "node_id", ";", "// sprintf(\"node:%s\", (string) $node_id);", "$", "node", "=", "$", "this", "->", "database", "->", "get", "(", "$", "query", ")", ";", "if", "(", "is_null", "(", "$", "node", ")", ")", "{", "throw", "new", "Exceptions", "\\", "NodeDoesNotExistException", "(", "$", "node_id", ")", ";", "}", "$", "node", "=", "unserialize", "(", "$", "node", ")", ";", "if", "(", "!", "$", "node", "instanceof", "Framework", "\\", "ParticleInterface", "&&", "!", "$", "node", "instanceof", "Foundation", "\\", "World", ")", "{", "throw", "new", "Exceptions", "\\", "NotANodeException", "(", "$", "node_id", ")", ";", "}", "$", "node", "->", "registerHandler", "(", "\"set\"", ",", "\\", "Pho", "\\", "Kernel", "\\", "Foundation", "\\", "Handlers", "\\", "Set", "::", "class", ")", ";", "if", "(", "$", "node", "instanceof", "Foundation", "\\", "AbstractActor", ")", "{", "$", "node", "->", "registerHandler", "(", "\"form\"", ",", "\\", "Pho", "\\", "Kernel", "\\", "Foundation", "\\", "Handlers", "\\", "Form", "::", "class", ")", ";", "}", "$", "node", "->", "init", "(", ")", ";", "$", "this", "->", "node_cache", "[", "$", "node_id", "]", "=", "$", "node", ";", "return", "$", "node", ";", "}" ]
Retrieves a node @param string $node_id @return Pho\Lib\Graph\NodeInterface The node object. @throws Pho\Kernel\Exceptions\NodeDoesNotExistException When there is no entity with the given id. @throws Pho\Kernel\Exceptions\NotANodeException When the given id does not belong to a node.
[ "Retrieves", "a", "node" ]
3983764e4e7cf980bc11d0385f1c6ea57ae723b1
https://github.com/phonetworks/pho-microkernel/blob/3983764e4e7cf980bc11d0385f1c6ea57ae723b1/src/Pho/Kernel/Graphsystem.php#L100-L128
223,913
phonetworks/pho-microkernel
src/Pho/Kernel/Graphsystem.php
Graphsystem.edge
public function edge(string $edge_id): Graph\EdgeInterface { if(isset($this->edge_cache[$edge_id])) return $this->edge_cache[$edge_id]; $query = (string) $edge_id; // sprintf("edge:%s", (string) $edge_id); $edge = $this->database->get($query); if(is_null($edge)) { throw new Exceptions\EdgeDoesNotExistException($edge_id); } $edge = unserialize($edge); if(!$edge instanceof Graph\EdgeInterface) { throw new Exceptions\NotAnEdgeException($edge_id); } $edge->setup(); $edge->init(); $this->edge_cache[$edge_id] = $edge; return $edge; }
php
public function edge(string $edge_id): Graph\EdgeInterface { if(isset($this->edge_cache[$edge_id])) return $this->edge_cache[$edge_id]; $query = (string) $edge_id; // sprintf("edge:%s", (string) $edge_id); $edge = $this->database->get($query); if(is_null($edge)) { throw new Exceptions\EdgeDoesNotExistException($edge_id); } $edge = unserialize($edge); if(!$edge instanceof Graph\EdgeInterface) { throw new Exceptions\NotAnEdgeException($edge_id); } $edge->setup(); $edge->init(); $this->edge_cache[$edge_id] = $edge; return $edge; }
[ "public", "function", "edge", "(", "string", "$", "edge_id", ")", ":", "Graph", "\\", "EdgeInterface", "{", "if", "(", "isset", "(", "$", "this", "->", "edge_cache", "[", "$", "edge_id", "]", ")", ")", "return", "$", "this", "->", "edge_cache", "[", "$", "edge_id", "]", ";", "$", "query", "=", "(", "string", ")", "$", "edge_id", ";", "// sprintf(\"edge:%s\", (string) $edge_id);", "$", "edge", "=", "$", "this", "->", "database", "->", "get", "(", "$", "query", ")", ";", "if", "(", "is_null", "(", "$", "edge", ")", ")", "{", "throw", "new", "Exceptions", "\\", "EdgeDoesNotExistException", "(", "$", "edge_id", ")", ";", "}", "$", "edge", "=", "unserialize", "(", "$", "edge", ")", ";", "if", "(", "!", "$", "edge", "instanceof", "Graph", "\\", "EdgeInterface", ")", "{", "throw", "new", "Exceptions", "\\", "NotAnEdgeException", "(", "$", "edge_id", ")", ";", "}", "$", "edge", "->", "setup", "(", ")", ";", "$", "edge", "->", "init", "(", ")", ";", "$", "this", "->", "edge_cache", "[", "$", "edge_id", "]", "=", "$", "edge", ";", "return", "$", "edge", ";", "}" ]
Retrieves an edge Reconstructs a single edge object based on its ID. @param string $node_id @return Pho\Lib\Graph\EdgeInterface The edge in its object form. @throws Pho\Kernel\Exceptions\EdgeDoesNotExistException when the given id does not exist in the database. @throws Pho\Kernel\Exceptions\NotAnEdgeException when the given id does not belong to an edge.
[ "Retrieves", "an", "edge" ]
3983764e4e7cf980bc11d0385f1c6ea57ae723b1
https://github.com/phonetworks/pho-microkernel/blob/3983764e4e7cf980bc11d0385f1c6ea57ae723b1/src/Pho/Kernel/Graphsystem.php#L142-L159
223,914
phonetworks/pho-microkernel
src/Pho/Kernel/Graphsystem.php
Graphsystem.touch
public function touch(EntityInterface $entity): void { $this->logger->info("Touching %s", $entity->id()->toString()); $this->database->set( (string) $entity->id(), serialize($entity) ); $this->logger->info("Indexing %s", $entity->id()->toString()); $arr = $entity->toArray(); $this->events->emit("graphsystem.touched", [$arr]); //$this->index->index($entity); }
php
public function touch(EntityInterface $entity): void { $this->logger->info("Touching %s", $entity->id()->toString()); $this->database->set( (string) $entity->id(), serialize($entity) ); $this->logger->info("Indexing %s", $entity->id()->toString()); $arr = $entity->toArray(); $this->events->emit("graphsystem.touched", [$arr]); //$this->index->index($entity); }
[ "public", "function", "touch", "(", "EntityInterface", "$", "entity", ")", ":", "void", "{", "$", "this", "->", "logger", "->", "info", "(", "\"Touching %s\"", ",", "$", "entity", "->", "id", "(", ")", "->", "toString", "(", ")", ")", ";", "$", "this", "->", "database", "->", "set", "(", "(", "string", ")", "$", "entity", "->", "id", "(", ")", ",", "serialize", "(", "$", "entity", ")", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "\"Indexing %s\"", ",", "$", "entity", "->", "id", "(", ")", "->", "toString", "(", ")", ")", ";", "$", "arr", "=", "$", "entity", "->", "toArray", "(", ")", ";", "$", "this", "->", "events", "->", "emit", "(", "\"graphsystem.touched\"", ",", "[", "$", "arr", "]", ")", ";", "//$this->index->index($entity);", "}" ]
Creates the entity in the graphsystem @param Graph\EntityInterface $entity @return void
[ "Creates", "the", "entity", "in", "the", "graphsystem" ]
3983764e4e7cf980bc11d0385f1c6ea57ae723b1
https://github.com/phonetworks/pho-microkernel/blob/3983764e4e7cf980bc11d0385f1c6ea57ae723b1/src/Pho/Kernel/Graphsystem.php#L188-L198
223,915
Orajo/zf2-tus-server
src/ZfTusServer/FileToolsService.php
FileToolsService.downloadFile
public static function downloadFile($filePath, $fileName, $mime = '', $size = -1, $openMode = self::OPEN_MODE_ATTACHMENT) { if (!file_exists($filePath)) { throw new Exception\FileNotFoundException(null, 0, null, $filePath); } if (!is_readable($filePath)) { throw new Exception\FileNotFoundException(sprintf('File %s is not readable', $filePath), 0, null, $filePath); } // Fetching File $mtime = ($mtime = filemtime($filePath)) ? $mtime : gmtime(); if ($mime === '') { header("Content-Type: application/force-download"); header('Content-Type: application/octet-stream'); } else { if(is_null($mime)) { $mime = self::detectMimeType($filePath, $fileName); } header('Content-Type: ' . $mime); } if (strstr(filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_STRING), "MSIE") != false) { header("Content-Disposition: ".$openMode."; filename=" . urlencode($fileName) . '; modification-date="' . date('r', $mtime) . '";'); } else { header("Content-Disposition: ".$openMode."; filename=\"" . $fileName . '"; modification-date="' . date('r', $mtime) . '";'); } if (function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules())) { // Sending file via mod_xsendfile header("X-Sendfile: " . $filePath); } else { // Sending file directly via script // according memory_limit byt not higher than 1GB $memory_limit = ini_get('memory_limit'); // get file size if ($size === -1) { $size = filesize($filePath); } if (intval($size + 1) > self::toBytes($memory_limit) && intval($size * 1.5) <= 1073741824) { // Setting memory limit ini_set('memory_limit', intval($size * 1.5)); } @ini_set('zlib.output_compression', 0); header("Content-Length: " . $size); // Set the time limit based on an average D/L speed of 50kb/sec set_time_limit(min(7200, // No more than 120 minutes (this is really bad, but...) ($size > 0) ? intval($size / 51200) + 60 // 1 minute more than what it should take to D/L at 50kb/sec : 1 // Minimum of 1 second in case size is found to be 0 )); $chunksize = 1 * (1024 * 1024); // how many megabytes to read at a time if ($size > $chunksize) { // Chunking file for download $handle = fopen($filePath, 'rb'); if ($handle === false) { return false; } $buffer = ''; while (!feof($handle)) { $buffer = fread($handle, $chunksize); echo $buffer; // if somewhare before was ob_start() if (ob_get_level() > 0) ob_flush(); flush(); } fclose($handle); } else { // Streaming whole file for download readfile($filePath); } } return true; }
php
public static function downloadFile($filePath, $fileName, $mime = '', $size = -1, $openMode = self::OPEN_MODE_ATTACHMENT) { if (!file_exists($filePath)) { throw new Exception\FileNotFoundException(null, 0, null, $filePath); } if (!is_readable($filePath)) { throw new Exception\FileNotFoundException(sprintf('File %s is not readable', $filePath), 0, null, $filePath); } // Fetching File $mtime = ($mtime = filemtime($filePath)) ? $mtime : gmtime(); if ($mime === '') { header("Content-Type: application/force-download"); header('Content-Type: application/octet-stream'); } else { if(is_null($mime)) { $mime = self::detectMimeType($filePath, $fileName); } header('Content-Type: ' . $mime); } if (strstr(filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_STRING), "MSIE") != false) { header("Content-Disposition: ".$openMode."; filename=" . urlencode($fileName) . '; modification-date="' . date('r', $mtime) . '";'); } else { header("Content-Disposition: ".$openMode."; filename=\"" . $fileName . '"; modification-date="' . date('r', $mtime) . '";'); } if (function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules())) { // Sending file via mod_xsendfile header("X-Sendfile: " . $filePath); } else { // Sending file directly via script // according memory_limit byt not higher than 1GB $memory_limit = ini_get('memory_limit'); // get file size if ($size === -1) { $size = filesize($filePath); } if (intval($size + 1) > self::toBytes($memory_limit) && intval($size * 1.5) <= 1073741824) { // Setting memory limit ini_set('memory_limit', intval($size * 1.5)); } @ini_set('zlib.output_compression', 0); header("Content-Length: " . $size); // Set the time limit based on an average D/L speed of 50kb/sec set_time_limit(min(7200, // No more than 120 minutes (this is really bad, but...) ($size > 0) ? intval($size / 51200) + 60 // 1 minute more than what it should take to D/L at 50kb/sec : 1 // Minimum of 1 second in case size is found to be 0 )); $chunksize = 1 * (1024 * 1024); // how many megabytes to read at a time if ($size > $chunksize) { // Chunking file for download $handle = fopen($filePath, 'rb'); if ($handle === false) { return false; } $buffer = ''; while (!feof($handle)) { $buffer = fread($handle, $chunksize); echo $buffer; // if somewhare before was ob_start() if (ob_get_level() > 0) ob_flush(); flush(); } fclose($handle); } else { // Streaming whole file for download readfile($filePath); } } return true; }
[ "public", "static", "function", "downloadFile", "(", "$", "filePath", ",", "$", "fileName", ",", "$", "mime", "=", "''", ",", "$", "size", "=", "-", "1", ",", "$", "openMode", "=", "self", "::", "OPEN_MODE_ATTACHMENT", ")", "{", "if", "(", "!", "file_exists", "(", "$", "filePath", ")", ")", "{", "throw", "new", "Exception", "\\", "FileNotFoundException", "(", "null", ",", "0", ",", "null", ",", "$", "filePath", ")", ";", "}", "if", "(", "!", "is_readable", "(", "$", "filePath", ")", ")", "{", "throw", "new", "Exception", "\\", "FileNotFoundException", "(", "sprintf", "(", "'File %s is not readable'", ",", "$", "filePath", ")", ",", "0", ",", "null", ",", "$", "filePath", ")", ";", "}", "// Fetching File", "$", "mtime", "=", "(", "$", "mtime", "=", "filemtime", "(", "$", "filePath", ")", ")", "?", "$", "mtime", ":", "gmtime", "(", ")", ";", "if", "(", "$", "mime", "===", "''", ")", "{", "header", "(", "\"Content-Type: application/force-download\"", ")", ";", "header", "(", "'Content-Type: application/octet-stream'", ")", ";", "}", "else", "{", "if", "(", "is_null", "(", "$", "mime", ")", ")", "{", "$", "mime", "=", "self", "::", "detectMimeType", "(", "$", "filePath", ",", "$", "fileName", ")", ";", "}", "header", "(", "'Content-Type: '", ".", "$", "mime", ")", ";", "}", "if", "(", "strstr", "(", "filter_input", "(", "INPUT_SERVER", ",", "'HTTP_USER_AGENT'", ",", "FILTER_SANITIZE_STRING", ")", ",", "\"MSIE\"", ")", "!=", "false", ")", "{", "header", "(", "\"Content-Disposition: \"", ".", "$", "openMode", ".", "\"; filename=\"", ".", "urlencode", "(", "$", "fileName", ")", ".", "'; modification-date=\"'", ".", "date", "(", "'r'", ",", "$", "mtime", ")", ".", "'\";'", ")", ";", "}", "else", "{", "header", "(", "\"Content-Disposition: \"", ".", "$", "openMode", ".", "\"; filename=\\\"\"", ".", "$", "fileName", ".", "'\"; modification-date=\"'", ".", "date", "(", "'r'", ",", "$", "mtime", ")", ".", "'\";'", ")", ";", "}", "if", "(", "function_exists", "(", "'apache_get_modules'", ")", "&&", "in_array", "(", "'mod_xsendfile'", ",", "apache_get_modules", "(", ")", ")", ")", "{", "// Sending file via mod_xsendfile", "header", "(", "\"X-Sendfile: \"", ".", "$", "filePath", ")", ";", "}", "else", "{", "// Sending file directly via script", "// according memory_limit byt not higher than 1GB", "$", "memory_limit", "=", "ini_get", "(", "'memory_limit'", ")", ";", "// get file size", "if", "(", "$", "size", "===", "-", "1", ")", "{", "$", "size", "=", "filesize", "(", "$", "filePath", ")", ";", "}", "if", "(", "intval", "(", "$", "size", "+", "1", ")", ">", "self", "::", "toBytes", "(", "$", "memory_limit", ")", "&&", "intval", "(", "$", "size", "*", "1.5", ")", "<=", "1073741824", ")", "{", "// Setting memory limit", "ini_set", "(", "'memory_limit'", ",", "intval", "(", "$", "size", "*", "1.5", ")", ")", ";", "}", "@", "ini_set", "(", "'zlib.output_compression'", ",", "0", ")", ";", "header", "(", "\"Content-Length: \"", ".", "$", "size", ")", ";", "// Set the time limit based on an average D/L speed of 50kb/sec", "set_time_limit", "(", "min", "(", "7200", ",", "// No more than 120 minutes (this is really bad, but...)", "(", "$", "size", ">", "0", ")", "?", "intval", "(", "$", "size", "/", "51200", ")", "+", "60", "// 1 minute more than what it should take to D/L at 50kb/sec", ":", "1", "// Minimum of 1 second in case size is found to be 0", ")", ")", ";", "$", "chunksize", "=", "1", "*", "(", "1024", "*", "1024", ")", ";", "// how many megabytes to read at a time", "if", "(", "$", "size", ">", "$", "chunksize", ")", "{", "// Chunking file for download", "$", "handle", "=", "fopen", "(", "$", "filePath", ",", "'rb'", ")", ";", "if", "(", "$", "handle", "===", "false", ")", "{", "return", "false", ";", "}", "$", "buffer", "=", "''", ";", "while", "(", "!", "feof", "(", "$", "handle", ")", ")", "{", "$", "buffer", "=", "fread", "(", "$", "handle", ",", "$", "chunksize", ")", ";", "echo", "$", "buffer", ";", "// if somewhare before was ob_start()", "if", "(", "ob_get_level", "(", ")", ">", "0", ")", "ob_flush", "(", ")", ";", "flush", "(", ")", ";", "}", "fclose", "(", "$", "handle", ")", ";", "}", "else", "{", "// Streaming whole file for download", "readfile", "(", "$", "filePath", ")", ";", "}", "}", "return", "true", ";", "}" ]
Handles file download to browser @link https://gist.github.com/854168 this method is based on this code @access public @api @param string $filePath full local path to downloaded file (typically contains hashed file name) @param string $fileName original file name @param string|null $mime MIME type; if null tries to guess using @see FileToolsService::downloadFile() @param int $size file size in bytes @return boolean @throws \Symfony\Component\Filesystem\Exception\FileNotFoundException
[ "Handles", "file", "download", "to", "browser" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/FileToolsService.php#L38-L117
223,916
Orajo/zf2-tus-server
src/ZfTusServer/FileToolsService.php
FileToolsService.detectMimeType
public static function detectMimeType($fileName, $userFileName = '') { if (!file_exists($fileName)) { return ''; } $mime = ''; if (class_exists('finfo', false)) { $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME; if (empty($mime)) { $mime = @finfo_open($const); } if (!empty($mime)) { $result = finfo_file($mime, $fileName); } unset($mime); } if (empty($result) && (function_exists('mime_content_type') && ini_get('mime_magic.magicfile'))) { $result = mime_content_type($fileName); } // dodatkowe sprawdzenie i korekta dla docx, xlsx, pptx if (empty($result) || $result == 'application/zip') { if (empty($userFileName)) { $userFileName = $fileName; } $pathParts = pathinfo($userFileName); if (isset($pathParts['extension'])) { switch ($pathParts['extension']) { case '7z': $result = 'application/x-7z-compressed'; break; case 'xlsx': case 'xltx': case 'xlsm': case 'xltm': case 'xlam': case 'xlsb': $result = 'application/msexcel'; break; case 'docx': case 'dotx': case 'docm': case 'dotm': $result = 'application/msword'; break; case 'pptx': case 'pptx': case 'potx': case 'ppsx': case 'ppam': case 'pptm': case 'potm': case 'ppsm': $result = 'application/mspowerpoint'; break; case 'vsd': case 'vsdx': $result = 'application/x-visio'; break; } } } if (empty($result)) { $result = 'application/octet-stream'; } return $result; }
php
public static function detectMimeType($fileName, $userFileName = '') { if (!file_exists($fileName)) { return ''; } $mime = ''; if (class_exists('finfo', false)) { $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME; if (empty($mime)) { $mime = @finfo_open($const); } if (!empty($mime)) { $result = finfo_file($mime, $fileName); } unset($mime); } if (empty($result) && (function_exists('mime_content_type') && ini_get('mime_magic.magicfile'))) { $result = mime_content_type($fileName); } // dodatkowe sprawdzenie i korekta dla docx, xlsx, pptx if (empty($result) || $result == 'application/zip') { if (empty($userFileName)) { $userFileName = $fileName; } $pathParts = pathinfo($userFileName); if (isset($pathParts['extension'])) { switch ($pathParts['extension']) { case '7z': $result = 'application/x-7z-compressed'; break; case 'xlsx': case 'xltx': case 'xlsm': case 'xltm': case 'xlam': case 'xlsb': $result = 'application/msexcel'; break; case 'docx': case 'dotx': case 'docm': case 'dotm': $result = 'application/msword'; break; case 'pptx': case 'pptx': case 'potx': case 'ppsx': case 'ppam': case 'pptm': case 'potm': case 'ppsm': $result = 'application/mspowerpoint'; break; case 'vsd': case 'vsdx': $result = 'application/x-visio'; break; } } } if (empty($result)) { $result = 'application/octet-stream'; } return $result; }
[ "public", "static", "function", "detectMimeType", "(", "$", "fileName", ",", "$", "userFileName", "=", "''", ")", "{", "if", "(", "!", "file_exists", "(", "$", "fileName", ")", ")", "{", "return", "''", ";", "}", "$", "mime", "=", "''", ";", "if", "(", "class_exists", "(", "'finfo'", ",", "false", ")", ")", "{", "$", "const", "=", "defined", "(", "'FILEINFO_MIME_TYPE'", ")", "?", "FILEINFO_MIME_TYPE", ":", "FILEINFO_MIME", ";", "if", "(", "empty", "(", "$", "mime", ")", ")", "{", "$", "mime", "=", "@", "finfo_open", "(", "$", "const", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "mime", ")", ")", "{", "$", "result", "=", "finfo_file", "(", "$", "mime", ",", "$", "fileName", ")", ";", "}", "unset", "(", "$", "mime", ")", ";", "}", "if", "(", "empty", "(", "$", "result", ")", "&&", "(", "function_exists", "(", "'mime_content_type'", ")", "&&", "ini_get", "(", "'mime_magic.magicfile'", ")", ")", ")", "{", "$", "result", "=", "mime_content_type", "(", "$", "fileName", ")", ";", "}", "// dodatkowe sprawdzenie i korekta dla docx, xlsx, pptx", "if", "(", "empty", "(", "$", "result", ")", "||", "$", "result", "==", "'application/zip'", ")", "{", "if", "(", "empty", "(", "$", "userFileName", ")", ")", "{", "$", "userFileName", "=", "$", "fileName", ";", "}", "$", "pathParts", "=", "pathinfo", "(", "$", "userFileName", ")", ";", "if", "(", "isset", "(", "$", "pathParts", "[", "'extension'", "]", ")", ")", "{", "switch", "(", "$", "pathParts", "[", "'extension'", "]", ")", "{", "case", "'7z'", ":", "$", "result", "=", "'application/x-7z-compressed'", ";", "break", ";", "case", "'xlsx'", ":", "case", "'xltx'", ":", "case", "'xlsm'", ":", "case", "'xltm'", ":", "case", "'xlam'", ":", "case", "'xlsb'", ":", "$", "result", "=", "'application/msexcel'", ";", "break", ";", "case", "'docx'", ":", "case", "'dotx'", ":", "case", "'docm'", ":", "case", "'dotm'", ":", "$", "result", "=", "'application/msword'", ";", "break", ";", "case", "'pptx'", ":", "case", "'pptx'", ":", "case", "'potx'", ":", "case", "'ppsx'", ":", "case", "'ppam'", ":", "case", "'pptm'", ":", "case", "'potm'", ":", "case", "'ppsm'", ":", "$", "result", "=", "'application/mspowerpoint'", ";", "break", ";", "case", "'vsd'", ":", "case", "'vsdx'", ":", "$", "result", "=", "'application/x-visio'", ";", "break", ";", "}", "}", "}", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "$", "result", "=", "'application/octet-stream'", ";", "}", "return", "$", "result", ";", "}" ]
Internal method to detect the mime type of a file @param string $fileName File name on storage; could be a hash or anything @param string $userFileName Real name of file, understandable for users. If ommited $fileName will be used. @return string Mimetype of given file
[ "Internal", "method", "to", "detect", "the", "mime", "type", "of", "a", "file" ]
38deebf73e6144217498bfafc3999a0b7e783736
https://github.com/Orajo/zf2-tus-server/blob/38deebf73e6144217498bfafc3999a0b7e783736/src/ZfTusServer/FileToolsService.php#L126-L199
223,917
phonetworks/pho-microkernel
src/Pho/Kernel/Kernel.php
Kernel.boot
public function boot(? Foundation\AbstractActor $founder = null): void { if($this->is_running) { throw new Exceptions\KernelAlreadyRunningException(); } $GLOBALS["kernel"] = &$this; // one more time, yes. $this->is_running = true; $this->setupServices(); $this->gs()->init(); // now that the services are ready, it may start $this["logger"]->info("Services set up. Root seed begins."); $this->seedRoot($founder); $this["logger"]->info("Root seeded"); $this->registerListeners($this["graph"]); $this->initPlugins(); $this->events()->emit("kernel.booted_up"); $this["logger"]->info("Boot complete."); }
php
public function boot(? Foundation\AbstractActor $founder = null): void { if($this->is_running) { throw new Exceptions\KernelAlreadyRunningException(); } $GLOBALS["kernel"] = &$this; // one more time, yes. $this->is_running = true; $this->setupServices(); $this->gs()->init(); // now that the services are ready, it may start $this["logger"]->info("Services set up. Root seed begins."); $this->seedRoot($founder); $this["logger"]->info("Root seeded"); $this->registerListeners($this["graph"]); $this->initPlugins(); $this->events()->emit("kernel.booted_up"); $this["logger"]->info("Boot complete."); }
[ "public", "function", "boot", "(", "?", "Foundation", "\\", "AbstractActor", "$", "founder", "=", "null", ")", ":", "void", "{", "if", "(", "$", "this", "->", "is_running", ")", "{", "throw", "new", "Exceptions", "\\", "KernelAlreadyRunningException", "(", ")", ";", "}", "$", "GLOBALS", "[", "\"kernel\"", "]", "=", "&", "$", "this", ";", "// one more time, yes.", "$", "this", "->", "is_running", "=", "true", ";", "$", "this", "->", "setupServices", "(", ")", ";", "$", "this", "->", "gs", "(", ")", "->", "init", "(", ")", ";", "// now that the services are ready, it may start", "$", "this", "[", "\"logger\"", "]", "->", "info", "(", "\"Services set up. Root seed begins.\"", ")", ";", "$", "this", "->", "seedRoot", "(", "$", "founder", ")", ";", "$", "this", "[", "\"logger\"", "]", "->", "info", "(", "\"Root seeded\"", ")", ";", "$", "this", "->", "registerListeners", "(", "$", "this", "[", "\"graph\"", "]", ")", ";", "$", "this", "->", "initPlugins", "(", ")", ";", "$", "this", "->", "events", "(", ")", "->", "emit", "(", "\"kernel.booted_up\"", ")", ";", "$", "this", "[", "\"logger\"", "]", "->", "info", "(", "\"Boot complete.\"", ")", ";", "}" ]
Initializes the kernel. Once the configuration is set, run "boot" to start the kernel. Please note, you will not be able to reconfigure the kernel or register new nodes after this point, or you will encounter the {@link Pho\Kernel\Exceptions\KernelIsAlreadyRunningException} exception. @param ?Foundation\AbstractActor The founder object or null (to set it up with default values or retrieve from the database) @return void @throws KernelIsAlreadyRunningException When run after the kernel has booted up.
[ "Initializes", "the", "kernel", "." ]
3983764e4e7cf980bc11d0385f1c6ea57ae723b1
https://github.com/phonetworks/pho-microkernel/blob/3983764e4e7cf980bc11d0385f1c6ea57ae723b1/src/Pho/Kernel/Kernel.php#L124-L145
223,918
sjelfull/craft3-autologin
src/services/AutologinService.php
AutologinService._matchIp
private function _matchIp ($currentIp) { $settings = $this->_getSettings(); foreach ($settings->ipWhitelist as $craftUsername => $ips) { $filteredIps = array_filter($ips, function ($ip) { return filter_var($ip, FILTER_VALIDATE_IP); }); if ( in_array($currentIp, $filteredIps) ) { return $craftUsername; } } }
php
private function _matchIp ($currentIp) { $settings = $this->_getSettings(); foreach ($settings->ipWhitelist as $craftUsername => $ips) { $filteredIps = array_filter($ips, function ($ip) { return filter_var($ip, FILTER_VALIDATE_IP); }); if ( in_array($currentIp, $filteredIps) ) { return $craftUsername; } } }
[ "private", "function", "_matchIp", "(", "$", "currentIp", ")", "{", "$", "settings", "=", "$", "this", "->", "_getSettings", "(", ")", ";", "foreach", "(", "$", "settings", "->", "ipWhitelist", "as", "$", "craftUsername", "=>", "$", "ips", ")", "{", "$", "filteredIps", "=", "array_filter", "(", "$", "ips", ",", "function", "(", "$", "ip", ")", "{", "return", "filter_var", "(", "$", "ip", ",", "FILTER_VALIDATE_IP", ")", ";", "}", ")", ";", "if", "(", "in_array", "(", "$", "currentIp", ",", "$", "filteredIps", ")", ")", "{", "return", "$", "craftUsername", ";", "}", "}", "}" ]
Match IP against whitelist @param $currentIp @return int|string
[ "Match", "IP", "against", "whitelist" ]
9d826714f0208bdd4439bdb744783eb046461f3b
https://github.com/sjelfull/craft3-autologin/blob/9d826714f0208bdd4439bdb744783eb046461f3b/src/services/AutologinService.php#L86-L97
223,919
sjelfull/craft3-autologin
src/services/AutologinService.php
AutologinService._loginByUsername
private function _loginByUsername ($username, $redirectMode = self::REDIRECT_MODE_SITE) { $craftUser = Craft::$app->users->getUserByUsernameOrEmail($username); if ( $craftUser ) { $success = Craft::$app->user->loginByUserId($craftUser->id); if ( $success ) { return $this->_afterLogin($redirectMode); } } }
php
private function _loginByUsername ($username, $redirectMode = self::REDIRECT_MODE_SITE) { $craftUser = Craft::$app->users->getUserByUsernameOrEmail($username); if ( $craftUser ) { $success = Craft::$app->user->loginByUserId($craftUser->id); if ( $success ) { return $this->_afterLogin($redirectMode); } } }
[ "private", "function", "_loginByUsername", "(", "$", "username", ",", "$", "redirectMode", "=", "self", "::", "REDIRECT_MODE_SITE", ")", "{", "$", "craftUser", "=", "Craft", "::", "$", "app", "->", "users", "->", "getUserByUsernameOrEmail", "(", "$", "username", ")", ";", "if", "(", "$", "craftUser", ")", "{", "$", "success", "=", "Craft", "::", "$", "app", "->", "user", "->", "loginByUserId", "(", "$", "craftUser", "->", "id", ")", ";", "if", "(", "$", "success", ")", "{", "return", "$", "this", "->", "_afterLogin", "(", "$", "redirectMode", ")", ";", "}", "}", "}" ]
Login by username or email @param string $username @param string $redirectMode
[ "Login", "by", "username", "or", "email" ]
9d826714f0208bdd4439bdb744783eb046461f3b
https://github.com/sjelfull/craft3-autologin/blob/9d826714f0208bdd4439bdb744783eb046461f3b/src/services/AutologinService.php#L105-L116
223,920
tivie/php-git-log-parser
src/Parser.php
Parser.setGitDir
public function setGitDir($dir, $check = true) { if (!is_string($dir)) { throw new InvalidArgumentException('string', 0); } if ($check && !realpath($dir)) { throw new Exception("Directory $dir does not exist"); } $this->gitDir = $dir; $this->command->chdir($dir); return $this; }
php
public function setGitDir($dir, $check = true) { if (!is_string($dir)) { throw new InvalidArgumentException('string', 0); } if ($check && !realpath($dir)) { throw new Exception("Directory $dir does not exist"); } $this->gitDir = $dir; $this->command->chdir($dir); return $this; }
[ "public", "function", "setGitDir", "(", "$", "dir", ",", "$", "check", "=", "true", ")", "{", "if", "(", "!", "is_string", "(", "$", "dir", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'string'", ",", "0", ")", ";", "}", "if", "(", "$", "check", "&&", "!", "realpath", "(", "$", "dir", ")", ")", "{", "throw", "new", "Exception", "(", "\"Directory $dir does not exist\"", ")", ";", "}", "$", "this", "->", "gitDir", "=", "$", "dir", ";", "$", "this", "->", "command", "->", "chdir", "(", "$", "dir", ")", ";", "return", "$", "this", ";", "}" ]
Set the directory where git log should be run on @param string $dir @param boolean $check Check if the directory exists @return $this @throws Exception @throws InvalidArgumentException
[ "Set", "the", "directory", "where", "git", "log", "should", "be", "run", "on" ]
bb6742cbbd4dd293f92b0d50b63c458b9b3986c2
https://github.com/tivie/php-git-log-parser/blob/bb6742cbbd4dd293f92b0d50b63c458b9b3986c2/src/Parser.php#L138-L150
223,921
tivie/php-git-log-parser
src/Parser.php
Parser.setBranch
public function setBranch($branch) { if (!is_string($branch)) { throw new InvalidArgumentException('string', 0); } $oldBranch = $this->branch; $oldArg = $this->command->searchArgument($oldBranch); if (!$oldArg) { throw new Exception("Couldn't change the command to new branch. Was the Command object modified?"); } $newArg = new Argument($branch); $this->command->replaceArgument($oldArg, $newArg); $this->branch = $branch; return $this; }
php
public function setBranch($branch) { if (!is_string($branch)) { throw new InvalidArgumentException('string', 0); } $oldBranch = $this->branch; $oldArg = $this->command->searchArgument($oldBranch); if (!$oldArg) { throw new Exception("Couldn't change the command to new branch. Was the Command object modified?"); } $newArg = new Argument($branch); $this->command->replaceArgument($oldArg, $newArg); $this->branch = $branch; return $this; }
[ "public", "function", "setBranch", "(", "$", "branch", ")", "{", "if", "(", "!", "is_string", "(", "$", "branch", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'string'", ",", "0", ")", ";", "}", "$", "oldBranch", "=", "$", "this", "->", "branch", ";", "$", "oldArg", "=", "$", "this", "->", "command", "->", "searchArgument", "(", "$", "oldBranch", ")", ";", "if", "(", "!", "$", "oldArg", ")", "{", "throw", "new", "Exception", "(", "\"Couldn't change the command to new branch. Was the Command object modified?\"", ")", ";", "}", "$", "newArg", "=", "new", "Argument", "(", "$", "branch", ")", ";", "$", "this", "->", "command", "->", "replaceArgument", "(", "$", "oldArg", ",", "$", "newArg", ")", ";", "$", "this", "->", "branch", "=", "$", "branch", ";", "return", "$", "this", ";", "}" ]
Set the branch that should be logged @param string $branch @return $this @throws Exception @throws InvalidArgumentException @throws \Tivie\Command\Exception\DomainException
[ "Set", "the", "branch", "that", "should", "be", "logged" ]
bb6742cbbd4dd293f92b0d50b63c458b9b3986c2
https://github.com/tivie/php-git-log-parser/blob/bb6742cbbd4dd293f92b0d50b63c458b9b3986c2/src/Parser.php#L161-L177
223,922
tivie/php-git-log-parser
src/Parser.php
Parser.parse
public function parse() { $result = $this->command->run(); $log = $result->getStdOut(); $buffer = array(); $commits = explode($this->format->getCommitDelimiter(), $log); foreach ($commits as $commit) { $fields = explode($this->format->getFieldDelimiter(), $commit); $entry = array(); foreach ($fields as $field) { if (!preg_match('/^\[(\S*?)\](.*)/', $field, $matches)) { continue; } $entry[trim($matches[1])] = trim($matches[2]); } if (!empty($entry)) { $buffer[] = $entry; } } return $buffer; }
php
public function parse() { $result = $this->command->run(); $log = $result->getStdOut(); $buffer = array(); $commits = explode($this->format->getCommitDelimiter(), $log); foreach ($commits as $commit) { $fields = explode($this->format->getFieldDelimiter(), $commit); $entry = array(); foreach ($fields as $field) { if (!preg_match('/^\[(\S*?)\](.*)/', $field, $matches)) { continue; } $entry[trim($matches[1])] = trim($matches[2]); } if (!empty($entry)) { $buffer[] = $entry; } } return $buffer; }
[ "public", "function", "parse", "(", ")", "{", "$", "result", "=", "$", "this", "->", "command", "->", "run", "(", ")", ";", "$", "log", "=", "$", "result", "->", "getStdOut", "(", ")", ";", "$", "buffer", "=", "array", "(", ")", ";", "$", "commits", "=", "explode", "(", "$", "this", "->", "format", "->", "getCommitDelimiter", "(", ")", ",", "$", "log", ")", ";", "foreach", "(", "$", "commits", "as", "$", "commit", ")", "{", "$", "fields", "=", "explode", "(", "$", "this", "->", "format", "->", "getFieldDelimiter", "(", ")", ",", "$", "commit", ")", ";", "$", "entry", "=", "array", "(", ")", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "if", "(", "!", "preg_match", "(", "'/^\\[(\\S*?)\\](.*)/'", ",", "$", "field", ",", "$", "matches", ")", ")", "{", "continue", ";", "}", "$", "entry", "[", "trim", "(", "$", "matches", "[", "1", "]", ")", "]", "=", "trim", "(", "$", "matches", "[", "2", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "entry", ")", ")", "{", "$", "buffer", "[", "]", "=", "$", "entry", ";", "}", "}", "return", "$", "buffer", ";", "}" ]
Parse the git log @return array
[ "Parse", "the", "git", "log" ]
bb6742cbbd4dd293f92b0d50b63c458b9b3986c2
https://github.com/tivie/php-git-log-parser/blob/bb6742cbbd4dd293f92b0d50b63c458b9b3986c2/src/Parser.php#L184-L208
223,923
voku/phonetic-algorithms
src/voku/helper/Phonetic.php
Phonetic.phonetic_sentence
public function phonetic_sentence($input, $useStopWords = true, $skipShortWords = 2, $key = null) { // init $words = array(); static $STOP_WORDS_CACHE = array(); if ($skipShortWords === false) { $skipShortWords = null; } if (\is_array($input) === true) { foreach ($input as $inputKey => $inputString) { $words[$inputKey] = UTF8::str_to_words($inputString, '', true, $skipShortWords); } } else { $words = UTF8::str_to_words($input, '', true, $skipShortWords); } if ( $useStopWords === true && !isset($STOP_WORDS_CACHE[$this->language]) ) { try { $STOP_WORDS_CACHE[$this->language] = $this->stopWords->getStopWordsFromLanguage($this->language); } catch (StopWordsLanguageNotExists $e) { $STOP_WORDS_CACHE[$this->language] = array(); } } $return = array(); foreach ($words as $wordKey => $word) { if (\is_array($word) === true) { foreach ($word as $wordInner) { $return = \array_replace_recursive( $return, $this->phonetic_sentence($wordInner, $useStopWords, $skipShortWords, $key !== null ? $key : $wordKey) ); } continue; } if ( $useStopWords === true && \in_array($word, $STOP_WORDS_CACHE[$this->language], true) ) { continue; } $code = $this->phonetic->phonetic_word($word); if ($code !== '') { if ($key !== null) { $return[$key][$word] = $code; } else { $return[$word] = $code; } } } return $return; }
php
public function phonetic_sentence($input, $useStopWords = true, $skipShortWords = 2, $key = null) { // init $words = array(); static $STOP_WORDS_CACHE = array(); if ($skipShortWords === false) { $skipShortWords = null; } if (\is_array($input) === true) { foreach ($input as $inputKey => $inputString) { $words[$inputKey] = UTF8::str_to_words($inputString, '', true, $skipShortWords); } } else { $words = UTF8::str_to_words($input, '', true, $skipShortWords); } if ( $useStopWords === true && !isset($STOP_WORDS_CACHE[$this->language]) ) { try { $STOP_WORDS_CACHE[$this->language] = $this->stopWords->getStopWordsFromLanguage($this->language); } catch (StopWordsLanguageNotExists $e) { $STOP_WORDS_CACHE[$this->language] = array(); } } $return = array(); foreach ($words as $wordKey => $word) { if (\is_array($word) === true) { foreach ($word as $wordInner) { $return = \array_replace_recursive( $return, $this->phonetic_sentence($wordInner, $useStopWords, $skipShortWords, $key !== null ? $key : $wordKey) ); } continue; } if ( $useStopWords === true && \in_array($word, $STOP_WORDS_CACHE[$this->language], true) ) { continue; } $code = $this->phonetic->phonetic_word($word); if ($code !== '') { if ($key !== null) { $return[$key][$word] = $code; } else { $return[$word] = $code; } } } return $return; }
[ "public", "function", "phonetic_sentence", "(", "$", "input", ",", "$", "useStopWords", "=", "true", ",", "$", "skipShortWords", "=", "2", ",", "$", "key", "=", "null", ")", "{", "// init", "$", "words", "=", "array", "(", ")", ";", "static", "$", "STOP_WORDS_CACHE", "=", "array", "(", ")", ";", "if", "(", "$", "skipShortWords", "===", "false", ")", "{", "$", "skipShortWords", "=", "null", ";", "}", "if", "(", "\\", "is_array", "(", "$", "input", ")", "===", "true", ")", "{", "foreach", "(", "$", "input", "as", "$", "inputKey", "=>", "$", "inputString", ")", "{", "$", "words", "[", "$", "inputKey", "]", "=", "UTF8", "::", "str_to_words", "(", "$", "inputString", ",", "''", ",", "true", ",", "$", "skipShortWords", ")", ";", "}", "}", "else", "{", "$", "words", "=", "UTF8", "::", "str_to_words", "(", "$", "input", ",", "''", ",", "true", ",", "$", "skipShortWords", ")", ";", "}", "if", "(", "$", "useStopWords", "===", "true", "&&", "!", "isset", "(", "$", "STOP_WORDS_CACHE", "[", "$", "this", "->", "language", "]", ")", ")", "{", "try", "{", "$", "STOP_WORDS_CACHE", "[", "$", "this", "->", "language", "]", "=", "$", "this", "->", "stopWords", "->", "getStopWordsFromLanguage", "(", "$", "this", "->", "language", ")", ";", "}", "catch", "(", "StopWordsLanguageNotExists", "$", "e", ")", "{", "$", "STOP_WORDS_CACHE", "[", "$", "this", "->", "language", "]", "=", "array", "(", ")", ";", "}", "}", "$", "return", "=", "array", "(", ")", ";", "foreach", "(", "$", "words", "as", "$", "wordKey", "=>", "$", "word", ")", "{", "if", "(", "\\", "is_array", "(", "$", "word", ")", "===", "true", ")", "{", "foreach", "(", "$", "word", "as", "$", "wordInner", ")", "{", "$", "return", "=", "\\", "array_replace_recursive", "(", "$", "return", ",", "$", "this", "->", "phonetic_sentence", "(", "$", "wordInner", ",", "$", "useStopWords", ",", "$", "skipShortWords", ",", "$", "key", "!==", "null", "?", "$", "key", ":", "$", "wordKey", ")", ")", ";", "}", "continue", ";", "}", "if", "(", "$", "useStopWords", "===", "true", "&&", "\\", "in_array", "(", "$", "word", ",", "$", "STOP_WORDS_CACHE", "[", "$", "this", "->", "language", "]", ",", "true", ")", ")", "{", "continue", ";", "}", "$", "code", "=", "$", "this", "->", "phonetic", "->", "phonetic_word", "(", "$", "word", ")", ";", "if", "(", "$", "code", "!==", "''", ")", "{", "if", "(", "$", "key", "!==", "null", ")", "{", "$", "return", "[", "$", "key", "]", "[", "$", "word", "]", "=", "$", "code", ";", "}", "else", "{", "$", "return", "[", "$", "word", "]", "=", "$", "code", ";", "}", "}", "}", "return", "$", "return", ";", "}" ]
Phonetic for more then one word. @param string|string[] $input @param bool $useStopWords @param false|int $skipShortWords @param int $key @return array <p>key === orig word<br />value === code word</p>
[ "Phonetic", "for", "more", "then", "one", "word", "." ]
e22b1078f318271153fff4b84ea59c007d643691
https://github.com/voku/phonetic-algorithms/blob/e22b1078f318271153fff4b84ea59c007d643691/src/voku/helper/Phonetic.php#L141-L204
223,924
phonetworks/pho-microkernel
src/Pho/Kernel/Hooks.php
Hooks.setup
public static function setup(/* mixed */ $obj): void { if($obj instanceof Graph\GraphInterface) { Hooks\Graph::setup($obj); } // . (on purpose) if($obj instanceof Graph\EdgeInterface) { Hooks\Edge::setup($obj); } elseif($obj instanceof Graph\NodeInterface) { Hooks\Node::setup($obj); } elseif($obj instanceof AbstractNotification) { Hooks\Notification::setup($obj); } }
php
public static function setup(/* mixed */ $obj): void { if($obj instanceof Graph\GraphInterface) { Hooks\Graph::setup($obj); } // . (on purpose) if($obj instanceof Graph\EdgeInterface) { Hooks\Edge::setup($obj); } elseif($obj instanceof Graph\NodeInterface) { Hooks\Node::setup($obj); } elseif($obj instanceof AbstractNotification) { Hooks\Notification::setup($obj); } }
[ "public", "static", "function", "setup", "(", "/* mixed */", "$", "obj", ")", ":", "void", "{", "if", "(", "$", "obj", "instanceof", "Graph", "\\", "GraphInterface", ")", "{", "Hooks", "\\", "Graph", "::", "setup", "(", "$", "obj", ")", ";", "}", "// . (on purpose)", "if", "(", "$", "obj", "instanceof", "Graph", "\\", "EdgeInterface", ")", "{", "Hooks", "\\", "Edge", "::", "setup", "(", "$", "obj", ")", ";", "}", "elseif", "(", "$", "obj", "instanceof", "Graph", "\\", "NodeInterface", ")", "{", "Hooks", "\\", "Node", "::", "setup", "(", "$", "obj", ")", ";", "}", "elseif", "(", "$", "obj", "instanceof", "AbstractNotification", ")", "{", "Hooks", "\\", "Notification", "::", "setup", "(", "$", "obj", ")", ";", "}", "}" ]
Detects the object type and calls the right Hooks class. @param mixed $obj The object. @return void
[ "Detects", "the", "object", "type", "and", "calls", "the", "right", "Hooks", "class", "." ]
3983764e4e7cf980bc11d0385f1c6ea57ae723b1
https://github.com/phonetworks/pho-microkernel/blob/3983764e4e7cf980bc11d0385f1c6ea57ae723b1/src/Pho/Kernel/Hooks.php#L29-L44
223,925
ribafs/auto-crud-pt
paginacao.php
Paginacao.paginate
function paginate() { //Check for valid mysql connection //Find total number of rows $all_rs = $this->conn->prepare( $this->sql ); $all_rs->execute(); if (! $all_rs) { if ($this->debug) echo "SQL query failed. Check your query.<br /><br />Error Returned: " . mysql_error(); return false; } $this->total_rows = $all_rs->rowCount(); //Return FALSE if no rows found if ($this->total_rows == 0) { if ($this->debug) echo "Query returned zero rows."; return FALSE; } //Max number of pages $this->max_pages = ceil($this->total_rows / $this->rows_per_page ); if ($this->links_per_page > $this->max_pages) { $this->links_per_page = $this->max_pages; } //Check the page value just in case someone is trying to input an aribitrary value if ($this->page > $this->max_pages || $this->page <= 0) { $this->page = 1; } //Calculate Offset $this->offset = $this->rows_per_page * ($this->page - 1); //Fetch the required result set $query = $this->sql . " LIMIT {$this->rows_per_page} OFFSET {$this->offset}"; $rs = $this->conn->prepare( $query ); $rs->execute(); if (! $rs) { if ($this->debug) echo "Pagination query failed. Check your query.<br /><br />Error Returned: " . mysql_error(); return false; } return $rs; }
php
function paginate() { //Check for valid mysql connection //Find total number of rows $all_rs = $this->conn->prepare( $this->sql ); $all_rs->execute(); if (! $all_rs) { if ($this->debug) echo "SQL query failed. Check your query.<br /><br />Error Returned: " . mysql_error(); return false; } $this->total_rows = $all_rs->rowCount(); //Return FALSE if no rows found if ($this->total_rows == 0) { if ($this->debug) echo "Query returned zero rows."; return FALSE; } //Max number of pages $this->max_pages = ceil($this->total_rows / $this->rows_per_page ); if ($this->links_per_page > $this->max_pages) { $this->links_per_page = $this->max_pages; } //Check the page value just in case someone is trying to input an aribitrary value if ($this->page > $this->max_pages || $this->page <= 0) { $this->page = 1; } //Calculate Offset $this->offset = $this->rows_per_page * ($this->page - 1); //Fetch the required result set $query = $this->sql . " LIMIT {$this->rows_per_page} OFFSET {$this->offset}"; $rs = $this->conn->prepare( $query ); $rs->execute(); if (! $rs) { if ($this->debug) echo "Pagination query failed. Check your query.<br /><br />Error Returned: " . mysql_error(); return false; } return $rs; }
[ "function", "paginate", "(", ")", "{", "//Check for valid mysql connection", "//Find total number of rows", "$", "all_rs", "=", "$", "this", "->", "conn", "->", "prepare", "(", "$", "this", "->", "sql", ")", ";", "$", "all_rs", "->", "execute", "(", ")", ";", "if", "(", "!", "$", "all_rs", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "echo", "\"SQL query failed. Check your query.<br /><br />Error Returned: \"", ".", "mysql_error", "(", ")", ";", "return", "false", ";", "}", "$", "this", "->", "total_rows", "=", "$", "all_rs", "->", "rowCount", "(", ")", ";", "//Return FALSE if no rows found", "if", "(", "$", "this", "->", "total_rows", "==", "0", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "echo", "\"Query returned zero rows.\"", ";", "return", "FALSE", ";", "}", "//Max number of pages", "$", "this", "->", "max_pages", "=", "ceil", "(", "$", "this", "->", "total_rows", "/", "$", "this", "->", "rows_per_page", ")", ";", "if", "(", "$", "this", "->", "links_per_page", ">", "$", "this", "->", "max_pages", ")", "{", "$", "this", "->", "links_per_page", "=", "$", "this", "->", "max_pages", ";", "}", "//Check the page value just in case someone is trying to input an aribitrary value", "if", "(", "$", "this", "->", "page", ">", "$", "this", "->", "max_pages", "||", "$", "this", "->", "page", "<=", "0", ")", "{", "$", "this", "->", "page", "=", "1", ";", "}", "//Calculate Offset", "$", "this", "->", "offset", "=", "$", "this", "->", "rows_per_page", "*", "(", "$", "this", "->", "page", "-", "1", ")", ";", "//Fetch the required result set", "$", "query", "=", "$", "this", "->", "sql", ".", "\" LIMIT {$this->rows_per_page} OFFSET {$this->offset}\"", ";", "$", "rs", "=", "$", "this", "->", "conn", "->", "prepare", "(", "$", "query", ")", ";", "$", "rs", "->", "execute", "(", ")", ";", "if", "(", "!", "$", "rs", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "echo", "\"Pagination query failed. Check your query.<br /><br />Error Returned: \"", ".", "mysql_error", "(", ")", ";", "return", "false", ";", "}", "return", "$", "rs", ";", "}" ]
Executes the SQL query and initializes internal variables @access public @return resource
[ "Executes", "the", "SQL", "query", "and", "initializes", "internal", "variables" ]
dbfc892c03944ad417b7b8c129be063314a674fe
https://github.com/ribafs/auto-crud-pt/blob/dbfc892c03944ad417b7b8c129be063314a674fe/paginacao.php#L62-L111
223,926
ribafs/auto-crud-pt
paginacao.php
Paginacao.renderPrev
function renderPrev($tag = '&lt;&lt;') { if ($this->total_rows == 0) return FALSE; if ($this->page > 1) { //return ' <a href="' . $this->php_self . '?page=' . ($this->page - 1) . '&' . $this->append . '">' . $tag . '</a>'; $pageno = $this->page - 1; return " <a href='javascript:void(0);' OnClick='getdata( $pageno )' title='Anterior'>$tag</a> "; } else { return " $tag "; } }
php
function renderPrev($tag = '&lt;&lt;') { if ($this->total_rows == 0) return FALSE; if ($this->page > 1) { //return ' <a href="' . $this->php_self . '?page=' . ($this->page - 1) . '&' . $this->append . '">' . $tag . '</a>'; $pageno = $this->page - 1; return " <a href='javascript:void(0);' OnClick='getdata( $pageno )' title='Anterior'>$tag</a> "; } else { return " $tag "; } }
[ "function", "renderPrev", "(", "$", "tag", "=", "'&lt;&lt;'", ")", "{", "if", "(", "$", "this", "->", "total_rows", "==", "0", ")", "return", "FALSE", ";", "if", "(", "$", "this", "->", "page", ">", "1", ")", "{", "//return ' <a href=\"' . $this->php_self . '?page=' . ($this->page - 1) . '&' . $this->append . '\">' . $tag . '</a>';", "$", "pageno", "=", "$", "this", "->", "page", "-", "1", ";", "return", "\" <a href='javascript:void(0);' OnClick='getdata( $pageno )' title='Anterior'>$tag</a> \"", ";", "}", "else", "{", "return", "\" $tag \"", ";", "}", "}" ]
Display the previous link @access public @param string $tag Text string to be displayed as the link. Defaults to '<<' @return string
[ "Display", "the", "previous", "link" ]
dbfc892c03944ad417b7b8c129be063314a674fe
https://github.com/ribafs/auto-crud-pt/blob/dbfc892c03944ad417b7b8c129be063314a674fe/paginacao.php#L180-L191
223,927
ribafs/auto-crud-pt
paginacao.php
Paginacao.renderFullNav
function renderFullNav() { //echo $this->renderFirst() . " " . $this->renderPrev(); return $this->renderFirst() . '&nbsp;' . $this->renderPrev() . '&nbsp;' . $this->renderNav() . '&nbsp;' . $this->renderNext() . '&nbsp;' . $this->renderLast(); }
php
function renderFullNav() { //echo $this->renderFirst() . " " . $this->renderPrev(); return $this->renderFirst() . '&nbsp;' . $this->renderPrev() . '&nbsp;' . $this->renderNav() . '&nbsp;' . $this->renderNext() . '&nbsp;' . $this->renderLast(); }
[ "function", "renderFullNav", "(", ")", "{", "//echo $this->renderFirst() . \" \" . $this->renderPrev();", "return", "$", "this", "->", "renderFirst", "(", ")", ".", "'&nbsp;'", ".", "$", "this", "->", "renderPrev", "(", ")", ".", "'&nbsp;'", ".", "$", "this", "->", "renderNav", "(", ")", ".", "'&nbsp;'", ".", "$", "this", "->", "renderNext", "(", ")", ".", "'&nbsp;'", ".", "$", "this", "->", "renderLast", "(", ")", ";", "}" ]
Display full pagination navigation @access public @return string
[ "Display", "full", "pagination", "navigation" ]
dbfc892c03944ad417b7b8c129be063314a674fe
https://github.com/ribafs/auto-crud-pt/blob/dbfc892c03944ad417b7b8c129be063314a674fe/paginacao.php#L232-L236
223,928
rbnvrw/markdown-forms
MarkdownForms.php
MarkdownForms.sanitize_key
function sanitize_key( $key ) { $raw_key = $key; $key = strtolower( $key ); $key = preg_replace( '/[^a-z0-9_\-]/', '', $key ); return $key; }
php
function sanitize_key( $key ) { $raw_key = $key; $key = strtolower( $key ); $key = preg_replace( '/[^a-z0-9_\-]/', '', $key ); return $key; }
[ "function", "sanitize_key", "(", "$", "key", ")", "{", "$", "raw_key", "=", "$", "key", ";", "$", "key", "=", "strtolower", "(", "$", "key", ")", ";", "$", "key", "=", "preg_replace", "(", "'/[^a-z0-9_\\-]/'", ",", "''", ",", "$", "key", ")", ";", "return", "$", "key", ";", "}" ]
Sanitizes a string key. Lowercase alphanumeric characters, dashes and underscores are allowed. @param string $key String key @return string Sanitized key
[ "Sanitizes", "a", "string", "key", "." ]
f4e78f57808010f9a6b0b6d8177fcab17189e656
https://github.com/rbnvrw/markdown-forms/blob/f4e78f57808010f9a6b0b6d8177fcab17189e656/MarkdownForms.php#L193-L199
223,929
LupeCode/phpTraderInterface
source/Trader.php
Trader.chaikinAccumulationDistributionLine
public static function chaikinAccumulationDistributionLine(array $high, array $low, array $close, array $volume): array { return static::ad($high, $low, $close, $volume); }
php
public static function chaikinAccumulationDistributionLine(array $high, array $low, array $close, array $volume): array { return static::ad($high, $low, $close, $volume); }
[ "public", "static", "function", "chaikinAccumulationDistributionLine", "(", "array", "$", "high", ",", "array", "$", "low", ",", "array", "$", "close", ",", "array", "$", "volume", ")", ":", "array", "{", "return", "static", "::", "ad", "(", "$", "high", ",", "$", "low", ",", "$", "close", ",", "$", "volume", ")", ";", "}" ]
Chaikin Accumulation Distribution Line This indicator is a volume based indicator developed by Marc Chaikin which measures the cumulative flow of money into and out of an instrument. The A/D line is calculated by multiplying the specific period’s volume with a multiplier that is based on the relationship of the closing price to the high-low range. The A/D Line is formed by the running total of the Money Flow Volume. This indicator can be used to assert an underlying trend or to predict reversals. The combination of a high positive multiplier value and high volume indicates buying pressure. So even with a downtrend in prices when there is an uptrend in the Accumulation Distribution Line there is indication for buying pressure (accumulation) that may result to a bullish reversal. Conversely a low negative multiplier value combined with, again, high volumes indicates selling pressure (distribution). @param array $high High price, array of real values. @param array $low Low price, array of real values. @param array $close Closing price, array of real values. @param array $volume Volume traded, array of real values. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Chaikin", "Accumulation", "Distribution", "Line" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/Trader.php#L54-L57
223,930
LupeCode/phpTraderInterface
source/Trader.php
Trader.chaikinAccumulationDistributionOscillator
public static function chaikinAccumulationDistributionOscillator(array $high, array $low, array $close, array $volume, int $fastPeriod = null, int $slowPeriod = null): array { return static::adosc($high, $low, $close, $volume, $fastPeriod, $slowPeriod); }
php
public static function chaikinAccumulationDistributionOscillator(array $high, array $low, array $close, array $volume, int $fastPeriod = null, int $slowPeriod = null): array { return static::adosc($high, $low, $close, $volume, $fastPeriod, $slowPeriod); }
[ "public", "static", "function", "chaikinAccumulationDistributionOscillator", "(", "array", "$", "high", ",", "array", "$", "low", ",", "array", "$", "close", ",", "array", "$", "volume", ",", "int", "$", "fastPeriod", "=", "null", ",", "int", "$", "slowPeriod", "=", "null", ")", ":", "array", "{", "return", "static", "::", "adosc", "(", "$", "high", ",", "$", "low", ",", "$", "close", ",", "$", "volume", ",", "$", "fastPeriod", ",", "$", "slowPeriod", ")", ";", "}" ]
Chaikin Accumulation Distribution Oscillator Chaikin Oscillator is positive when the 3-day EMA moves higher than the 10-day EMA and vice versa. The Chaikin Oscillator is the continuation of the Chaikin A/D Line and is used to observe changes in the A/D Line. The oscillator is based on the difference between the 3-day Exponential Moving Average (EMA) of the A/D Line and the 10-day EMA of the A/D Line and hence adds momentum to the A/D Line. It is helpful for investors to use the Oscillator in order to determine the appropriate timing of trend reversals. When the Chaikin Oscillator turns positive there is indication that the A/D Line will increase and hence a Bullish (buy) signal will be generated. On the other hand a move into negative territory indicates a Bearish (sell) signal. @param array $high High price, array of real values. @param array $low Low price, array of real values. @param array $close Closing price, array of real values. @param array $volume Volume traded, array of real values. @param int|null $fastPeriod Number of period for the fast MA. Valid range from 2 to 100000. @param int|null $slowPeriod Number of period for the slow MA. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Chaikin", "Accumulation", "Distribution", "Oscillator" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/Trader.php#L95-L98
223,931
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.cmo
public static function cmo(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_cmo($real, $timePeriod); static::checkForError(); return $return; }
php
public static function cmo(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_cmo($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "cmo", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "14", ";", "$", "return", "=", "trader_cmo", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Chande Momentum Oscillator @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 14] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Chande", "Momentum", "Oscillator" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L1636-L1643
223,932
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.dema
public static function dema(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_dema($real, $timePeriod); static::checkForError(); return $return; }
php
public static function dema(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_dema($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "dema", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_dema", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Double Exponential Moving Average @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 3.] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Double", "Exponential", "Moving", "Average" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L1707-L1714
223,933
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.ema
public static function ema(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_ema($real, $timePeriod); static::checkForError(); return $return; }
php
public static function ema(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_ema($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "ema", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_ema", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Exponential Moving Average @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Exponential", "Moving", "Average" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L1763-L1770
223,934
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.kama
public static function kama(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_kama($real, $timePeriod); static::checkForError(); return $return; }
php
public static function kama(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_kama($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "kama", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_kama", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Kaufman Adaptive Moving Average @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Kaufman", "Adaptive", "Moving", "Average" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L1958-L1965
223,935
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.linearreg_slope
public static function linearreg_slope(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_linearreg_slope($real, $timePeriod); static::checkForError(); return $return; }
php
public static function linearreg_slope(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_linearreg_slope($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "linearreg_slope", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "14", ";", "$", "return", "=", "trader_linearreg_slope", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Linear Regression Slope @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 14] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Linear", "Regression", "Slope" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2012-L2019
223,936
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.max
public static function max(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_max($real, $timePeriod); static::checkForError(); return $return; }
php
public static function max(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_max($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "max", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_max", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Highest value over a specified period @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Highest", "value", "over", "a", "specified", "period" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2211-L2218
223,937
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.maxindex
public static function maxindex(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_maxindex($real, $timePeriod); static::checkForError(); return $return; }
php
public static function maxindex(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_maxindex($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "maxindex", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_maxindex", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Index of highest value over a specified period @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Index", "of", "highest", "value", "over", "a", "specified", "period" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2229-L2236
223,938
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.midpoint
public static function midpoint(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_midpoint($real, $timePeriod); static::checkForError(); return $return; }
php
public static function midpoint(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_midpoint($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "midpoint", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "14", ";", "$", "return", "=", "trader_midpoint", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
MidPoint over period @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 14] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "MidPoint", "over", "period" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2285-L2292
223,939
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.min
public static function min(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_min($real, $timePeriod); static::checkForError(); return $return; }
php
public static function min(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_min($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "min", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_min", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Lowest value over a specified period @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Lowest", "value", "over", "a", "specified", "period" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2322-L2329
223,940
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.minindex
public static function minindex(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_minindex($real, $timePeriod); static::checkForError(); return $return; }
php
public static function minindex(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_minindex($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "minindex", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_minindex", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Index of lowest value over a specified period @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Index", "of", "lowest", "value", "over", "a", "specified", "period" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2340-L2347
223,941
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.minmax
public static function minmax(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_minmax($real, $timePeriod); static::checkForError(); return $return; }
php
public static function minmax(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_minmax($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "minmax", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_minmax", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Lowest and highest values over a specified period @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Lowest", "and", "highest", "values", "over", "a", "specified", "period" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2358-L2365
223,942
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.minmaxindex
public static function minmaxindex(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_minmaxindex($real, $timePeriod); static::checkForError(); return $return; }
php
public static function minmaxindex(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_minmaxindex($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "minmaxindex", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_minmaxindex", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Indexes of lowest and highest values over a specified period @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Indexes", "of", "lowest", "and", "highest", "values", "over", "a", "specified", "period" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2376-L2383
223,943
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.rsi
public static function rsi(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_rsi($real, $timePeriod); static::checkForError(); return $return; }
php
public static function rsi(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_rsi($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "rsi", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "14", ";", "$", "return", "=", "trader_rsi", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Relative Strength Index @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 14] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Relative", "Strength", "Index" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2639-L2646
223,944
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.sma
public static function sma(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_sma($real, $timePeriod); static::checkForError(); return $return; }
php
public static function sma(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_sma($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "sma", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_sma", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Simple Moving Average @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Simple", "Moving", "Average" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2774-L2781
223,945
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.tema
public static function tema(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_tema($real, $timePeriod); static::checkForError(); return $return; }
php
public static function tema(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_tema($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "tema", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_tema", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Triple Exponential Moving Average @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Triple", "Exponential", "Moving", "Average" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L2995-L3002
223,946
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.trima
public static function trima(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_trima($real, $timePeriod); static::checkForError(); return $return; }
php
public static function trima(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_trima($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "trima", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_trima", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Triangular Moving Average @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Triangular", "Moving", "Average" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L3031-L3038
223,947
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.tsf
public static function tsf(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_tsf($real, $timePeriod); static::checkForError(); return $return; }
php
public static function tsf(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 14; $return = trader_tsf($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "tsf", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "14", ";", "$", "return", "=", "trader_tsf", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Time Series Forecast @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 14] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Time", "Series", "Forecast" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L3067-L3074
223,948
LupeCode/phpTraderInterface
source/TraderTrait.php
TraderTrait.wma
public static function wma(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_wma($real, $timePeriod); static::checkForError(); return $return; }
php
public static function wma(array $real, int $timePeriod = null): array { $timePeriod = $timePeriod ?? 30; $return = trader_wma($real, $timePeriod); static::checkForError(); return $return; }
[ "public", "static", "function", "wma", "(", "array", "$", "real", ",", "int", "$", "timePeriod", "=", "null", ")", ":", "array", "{", "$", "timePeriod", "=", "$", "timePeriod", "??", "30", ";", "$", "return", "=", "trader_wma", "(", "$", "real", ",", "$", "timePeriod", ")", ";", "static", "::", "checkForError", "(", ")", ";", "return", "$", "return", ";", "}" ]
Weighted Moving Average @param array $real Array of real values. @param int $timePeriod [OPTIONAL] [DEFAULT 30] Number of period. Valid range from 2 to 100000. @return array Returns an array with calculated data or false on failure. @throws \Exception
[ "Weighted", "Moving", "Average" ]
91976b8665199f441e4f43842461104f82f3ef66
https://github.com/LupeCode/phpTraderInterface/blob/91976b8665199f441e4f43842461104f82f3ef66/source/TraderTrait.php#L3185-L3192
223,949
phonetworks/pho-microkernel
src/Pho/Kernel/Foundation/AttributeBag.php
AttributeBag.hydrate
private function hydrate(): void { /*($this->owner->kernel()->logger()->info( "Hydration of AttributeBag with data:", print_r($this->bag, true) );*/ foreach($this->bag as $key=>$value) { if(!is_string($value)) continue; $s = S::create($value); if( $s->startsWith(Kernel::PARTICLE_IN_ATTRIBUTEBAG_TPL[0]) && $s->endsWith(Kernel::PARTICLE_IN_ATTRIBUTEBAG_TPL[1]) ) { $id = (string) $s ->removeLeft(Kernel::PARTICLE_IN_ATTRIBUTEBAG_TPL[0]) ->removeRight(Kernel::PARTICLE_IN_ATTRIBUTEBAG_TPL[1]); $this->bag[$key] = $this->owner->kernel()->gs()->node($id); } } }
php
private function hydrate(): void { /*($this->owner->kernel()->logger()->info( "Hydration of AttributeBag with data:", print_r($this->bag, true) );*/ foreach($this->bag as $key=>$value) { if(!is_string($value)) continue; $s = S::create($value); if( $s->startsWith(Kernel::PARTICLE_IN_ATTRIBUTEBAG_TPL[0]) && $s->endsWith(Kernel::PARTICLE_IN_ATTRIBUTEBAG_TPL[1]) ) { $id = (string) $s ->removeLeft(Kernel::PARTICLE_IN_ATTRIBUTEBAG_TPL[0]) ->removeRight(Kernel::PARTICLE_IN_ATTRIBUTEBAG_TPL[1]); $this->bag[$key] = $this->owner->kernel()->gs()->node($id); } } }
[ "private", "function", "hydrate", "(", ")", ":", "void", "{", "/*($this->owner->kernel()->logger()->info(\n \"Hydration of AttributeBag with data:\",\n print_r($this->bag, true)\n );*/", "foreach", "(", "$", "this", "->", "bag", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", ")", "continue", ";", "$", "s", "=", "S", "::", "create", "(", "$", "value", ")", ";", "if", "(", "$", "s", "->", "startsWith", "(", "Kernel", "::", "PARTICLE_IN_ATTRIBUTEBAG_TPL", "", "[", "0", "]", ")", "&&", "$", "s", "->", "endsWith", "(", "Kernel", "::", "PARTICLE_IN_ATTRIBUTEBAG_TPL", "", "[", "1", "]", ")", ")", "{", "$", "id", "=", "(", "string", ")", "$", "s", "->", "removeLeft", "(", "Kernel", "::", "PARTICLE_IN_ATTRIBUTEBAG_TPL", "", "[", "0", "]", ")", "-", ">", "removeRight", "(", "Kernel", "::", "PARTICLE_IN_ATTRIBUTEBAG_TPL", "", "[", "1", "]", ")", ";", "$", "this", "->", "bag", "[", "$", "key", "]", "=", "$", "this", "->", "owner", "->", "kernel", "(", ")", "->", "gs", "(", ")", "->", "node", "(", "$", "id", ")", ";", "}", "}", "}" ]
Hydrates the imported values. !! unusued !! it was creating when in __construct @return void
[ "Hydrates", "the", "imported", "values", "." ]
3983764e4e7cf980bc11d0385f1c6ea57ae723b1
https://github.com/phonetworks/pho-microkernel/blob/3983764e4e7cf980bc11d0385f1c6ea57ae723b1/src/Pho/Kernel/Foundation/AttributeBag.php#L51-L72
223,950
phonetworks/pho-microkernel
src/Pho/Kernel/Services/ServiceFactory.php
ServiceFactory.create
public function create(string $category, string $type, string $uri): ServiceInterface { if(!self::serviceExists($category, $type)) { throw new AdapterNonExistentException(); } $service = $this->convertTypeToServiceClassName($category, $type); return new $service($this->kernel, $uri); }
php
public function create(string $category, string $type, string $uri): ServiceInterface { if(!self::serviceExists($category, $type)) { throw new AdapterNonExistentException(); } $service = $this->convertTypeToServiceClassName($category, $type); return new $service($this->kernel, $uri); }
[ "public", "function", "create", "(", "string", "$", "category", ",", "string", "$", "type", ",", "string", "$", "uri", ")", ":", "ServiceInterface", "{", "if", "(", "!", "self", "::", "serviceExists", "(", "$", "category", ",", "$", "type", ")", ")", "{", "throw", "new", "AdapterNonExistentException", "(", ")", ";", "}", "$", "service", "=", "$", "this", "->", "convertTypeToServiceClassName", "(", "$", "category", ",", "$", "type", ")", ";", "return", "new", "$", "service", "(", "$", "this", "->", "kernel", ",", "$", "uri", ")", ";", "}" ]
This function creates an instance of the valid service using the indicated adapter and returns the final object. @param string $category Service category @param string $type Service type @param mixed $options Service options @return ServiceInterface @throws AdapterNonExistentException
[ "This", "function", "creates", "an", "instance", "of", "the", "valid", "service", "using", "the", "indicated", "adapter", "and", "returns", "the", "final", "object", "." ]
3983764e4e7cf980bc11d0385f1c6ea57ae723b1
https://github.com/phonetworks/pho-microkernel/blob/3983764e4e7cf980bc11d0385f1c6ea57ae723b1/src/Pho/Kernel/Services/ServiceFactory.php#L46-L54
223,951
phonetworks/pho-microkernel
src/Pho/Kernel/Services/ServiceFactory.php
ServiceFactory.convertTypeToServiceClassName
private function convertTypeToServiceClassName(string $category, string $type): ?string { if( class_exists($type)) { // custom service return $type; } else { $type = $this->kernel->config()->namespaces->services . ucfirst(strtolower($category))."\\Adapters\\".ucfirst(strtolower($type)); if(class_exists($type)) { // standard service return $type; } } return null; }
php
private function convertTypeToServiceClassName(string $category, string $type): ?string { if( class_exists($type)) { // custom service return $type; } else { $type = $this->kernel->config()->namespaces->services . ucfirst(strtolower($category))."\\Adapters\\".ucfirst(strtolower($type)); if(class_exists($type)) { // standard service return $type; } } return null; }
[ "private", "function", "convertTypeToServiceClassName", "(", "string", "$", "category", ",", "string", "$", "type", ")", ":", "?", "string", "{", "if", "(", "class_exists", "(", "$", "type", ")", ")", "{", "// custom service", "return", "$", "type", ";", "}", "else", "{", "$", "type", "=", "$", "this", "->", "kernel", "->", "config", "(", ")", "->", "namespaces", "->", "services", ".", "ucfirst", "(", "strtolower", "(", "$", "category", ")", ")", ".", "\"\\\\Adapters\\\\\"", ".", "ucfirst", "(", "strtolower", "(", "$", "type", ")", ")", ";", "if", "(", "class_exists", "(", "$", "type", ")", ")", "{", "// standard service", "return", "$", "type", ";", "}", "}", "return", "null", ";", "}" ]
This function converts a type name's such that it matches the standard service class name format. Please note this function doesn't necessarily check if this class name conforms the requirements to be a valid kernel service. @see serviceExists @param string $category Service category @param string $type Service type @return string|null
[ "This", "function", "converts", "a", "type", "name", "s", "such", "that", "it", "matches", "the", "standard", "service", "class", "name", "format", ".", "Please", "note", "this", "function", "doesn", "t", "necessarily", "check", "if", "this", "class", "name", "conforms", "the", "requirements", "to", "be", "a", "valid", "kernel", "service", "." ]
3983764e4e7cf980bc11d0385f1c6ea57ae723b1
https://github.com/phonetworks/pho-microkernel/blob/3983764e4e7cf980bc11d0385f1c6ea57ae723b1/src/Pho/Kernel/Services/ServiceFactory.php#L70-L82
223,952
phonetworks/pho-microkernel
src/Pho/Kernel/Services/ServiceFactory.php
ServiceFactory.serviceExists
private function serviceExists(string $category, string $type): bool { $service_class = $this->convertTypeToServiceClassName($category, $type); if(is_null($service_class)) return false; $interfaces = class_implements($service_class); if($interfaces===false || !is_array($interfaces)) return false; $category = ucfirst(strtolower($category)); $sought_adapter_interface = $this->kernel->config()->namespaces->services . $category. "\\" . $category . "Interface"; return (in_array(self::SOUGHT_SERVICE_INTERFACE, $interfaces) && in_array($sought_adapter_interface, $interfaces)); }
php
private function serviceExists(string $category, string $type): bool { $service_class = $this->convertTypeToServiceClassName($category, $type); if(is_null($service_class)) return false; $interfaces = class_implements($service_class); if($interfaces===false || !is_array($interfaces)) return false; $category = ucfirst(strtolower($category)); $sought_adapter_interface = $this->kernel->config()->namespaces->services . $category. "\\" . $category . "Interface"; return (in_array(self::SOUGHT_SERVICE_INTERFACE, $interfaces) && in_array($sought_adapter_interface, $interfaces)); }
[ "private", "function", "serviceExists", "(", "string", "$", "category", ",", "string", "$", "type", ")", ":", "bool", "{", "$", "service_class", "=", "$", "this", "->", "convertTypeToServiceClassName", "(", "$", "category", ",", "$", "type", ")", ";", "if", "(", "is_null", "(", "$", "service_class", ")", ")", "return", "false", ";", "$", "interfaces", "=", "class_implements", "(", "$", "service_class", ")", ";", "if", "(", "$", "interfaces", "===", "false", "||", "!", "is_array", "(", "$", "interfaces", ")", ")", "return", "false", ";", "$", "category", "=", "ucfirst", "(", "strtolower", "(", "$", "category", ")", ")", ";", "$", "sought_adapter_interface", "=", "$", "this", "->", "kernel", "->", "config", "(", ")", "->", "namespaces", "->", "services", ".", "$", "category", ".", "\"\\\\\"", ".", "$", "category", ".", "\"Interface\"", ";", "return", "(", "in_array", "(", "self", "::", "SOUGHT_SERVICE_INTERFACE", ",", "$", "interfaces", ")", "&&", "in_array", "(", "$", "sought_adapter_interface", ",", "$", "interfaces", ")", ")", ";", "}" ]
Checks if the given type matches any valid service that implements appropriate service interfaces. @param string $category Service category @param string $type Service type @return bool
[ "Checks", "if", "the", "given", "type", "matches", "any", "valid", "service", "that", "implements", "appropriate", "service", "interfaces", "." ]
3983764e4e7cf980bc11d0385f1c6ea57ae723b1
https://github.com/phonetworks/pho-microkernel/blob/3983764e4e7cf980bc11d0385f1c6ea57ae723b1/src/Pho/Kernel/Services/ServiceFactory.php#L93-L108
223,953
adrianmejias/laravel-states
src/AdrianMejias/States/States.php
States.getStates
protected function getStates() { //Get the states from the JSON file if (sizeof($this->states) == 0) { $this->states = json_decode(file_get_contents(__DIR__ . '/Models/states.json'), true); } //Return the states return $this->states; }
php
protected function getStates() { //Get the states from the JSON file if (sizeof($this->states) == 0) { $this->states = json_decode(file_get_contents(__DIR__ . '/Models/states.json'), true); } //Return the states return $this->states; }
[ "protected", "function", "getStates", "(", ")", "{", "//Get the states from the JSON file", "if", "(", "sizeof", "(", "$", "this", "->", "states", ")", "==", "0", ")", "{", "$", "this", "->", "states", "=", "json_decode", "(", "file_get_contents", "(", "__DIR__", ".", "'/Models/states.json'", ")", ",", "true", ")", ";", "}", "//Return the states", "return", "$", "this", "->", "states", ";", "}" ]
Get the states from the JSON file, if it hasn't already been loaded. @return array
[ "Get", "the", "states", "from", "the", "JSON", "file", "if", "it", "hasn", "t", "already", "been", "loaded", "." ]
e9ed83f8e4e2eb8a02cc96166d82a4c7171f6055
https://github.com/adrianmejias/laravel-states/blob/e9ed83f8e4e2eb8a02cc96166d82a4c7171f6055/src/AdrianMejias/States/States.php#L41-L50
223,954
adrianmejias/laravel-states
src/AdrianMejias/States/States.php
States.getList
public function getList($sort = null) { //Get the states list $states = $this->getStates(); //Sorting $validSorts = [ 'iso_3166_2', 'name', 'country_code', ]; if (! is_null($sort) && in_array($sort, $validSorts)) { uasort($states, function ($a, $b) use ($sort) { if (!isset($a[$sort]) && !isset($b[$sort])) { return 0; } elseif (!isset($a[$sort])) { return -1; } elseif (!isset($b[$sort])) { return 1; } else { return strcasecmp($a[$sort], $b[$sort]); } }); } //Return the states return $states; }
php
public function getList($sort = null) { //Get the states list $states = $this->getStates(); //Sorting $validSorts = [ 'iso_3166_2', 'name', 'country_code', ]; if (! is_null($sort) && in_array($sort, $validSorts)) { uasort($states, function ($a, $b) use ($sort) { if (!isset($a[$sort]) && !isset($b[$sort])) { return 0; } elseif (!isset($a[$sort])) { return -1; } elseif (!isset($b[$sort])) { return 1; } else { return strcasecmp($a[$sort], $b[$sort]); } }); } //Return the states return $states; }
[ "public", "function", "getList", "(", "$", "sort", "=", "null", ")", "{", "//Get the states list", "$", "states", "=", "$", "this", "->", "getStates", "(", ")", ";", "//Sorting", "$", "validSorts", "=", "[", "'iso_3166_2'", ",", "'name'", ",", "'country_code'", ",", "]", ";", "if", "(", "!", "is_null", "(", "$", "sort", ")", "&&", "in_array", "(", "$", "sort", ",", "$", "validSorts", ")", ")", "{", "uasort", "(", "$", "states", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "sort", ")", "{", "if", "(", "!", "isset", "(", "$", "a", "[", "$", "sort", "]", ")", "&&", "!", "isset", "(", "$", "b", "[", "$", "sort", "]", ")", ")", "{", "return", "0", ";", "}", "elseif", "(", "!", "isset", "(", "$", "a", "[", "$", "sort", "]", ")", ")", "{", "return", "-", "1", ";", "}", "elseif", "(", "!", "isset", "(", "$", "b", "[", "$", "sort", "]", ")", ")", "{", "return", "1", ";", "}", "else", "{", "return", "strcasecmp", "(", "$", "a", "[", "$", "sort", "]", ",", "$", "b", "[", "$", "sort", "]", ")", ";", "}", "}", ")", ";", "}", "//Return the states", "return", "$", "states", ";", "}" ]
Returns a list of states @param string sort @return array
[ "Returns", "a", "list", "of", "states" ]
e9ed83f8e4e2eb8a02cc96166d82a4c7171f6055
https://github.com/adrianmejias/laravel-states/blob/e9ed83f8e4e2eb8a02cc96166d82a4c7171f6055/src/AdrianMejias/States/States.php#L72-L100
223,955
dannyweeks/laravel-base-repository
src/Traits/CacheResults.php
CacheResults.processCacheRequest
protected function processCacheRequest($callback, $method, $args) { $key = $this->createCacheKey($method, $args); return $this->getCache()->remember($key, $this->getCacheTtl(), $callback); }
php
protected function processCacheRequest($callback, $method, $args) { $key = $this->createCacheKey($method, $args); return $this->getCache()->remember($key, $this->getCacheTtl(), $callback); }
[ "protected", "function", "processCacheRequest", "(", "$", "callback", ",", "$", "method", ",", "$", "args", ")", "{", "$", "key", "=", "$", "this", "->", "createCacheKey", "(", "$", "method", ",", "$", "args", ")", ";", "return", "$", "this", "->", "getCache", "(", ")", "->", "remember", "(", "$", "key", ",", "$", "this", "->", "getCacheTtl", "(", ")", ",", "$", "callback", ")", ";", "}" ]
Perform the query and cache if required. @param $callback @param $method @param $args @return mixed
[ "Perform", "the", "query", "and", "cache", "if", "required", "." ]
69f294898b98a10cb84b9a6f664e789a5ff24122
https://github.com/dannyweeks/laravel-base-repository/blob/69f294898b98a10cb84b9a6f664e789a5ff24122/src/Traits/CacheResults.php#L64-L69
223,956
Eluinhost/minecraft-auth
src/AuthServer/BaseClient.php
BaseClient.onData
public function onData($data) { //if we're in encryption stage decrypt it first if($this->secret !== null) { mcrypt_generic_init($this->encryptor, $this->secret, $this->secret); $data = mdecrypt_generic($this->encryptor, $data); mcrypt_generic_deinit($this->encryptor); } //attempt to parse the data as a packet try { //add the data to the current buffer $this->packetBuffer .= $data; //for as long as we have data left in the buffer do { //read the packet length from the stream $packetLengthVarInt = VarInt::readUnsignedVarInt($this->packetBuffer); //not enough data to read the packet length, wait for more data if($packetLengthVarInt === false) { return; } //total length of the packet is the length of the varint + it's value $totalLength = $packetLengthVarInt->getDataLength() + $packetLengthVarInt->getValue(); //if we don't have enough data to read the entire packet wait for more data to enter $bufferLength = strlen($this->packetBuffer); if ($bufferLength < $totalLength) { return; } //remove the packet length varint from the buffer $this->packetBuffer = substr($this->packetBuffer, $packetLengthVarInt->getDataLength()); //read the packet ID from the buffer $packetDataWithPacketID = substr($this->packetBuffer, 0, $packetLengthVarInt->getValue()); //remove the rest of the packet from the buffer $this->packetBuffer = substr($this->packetBuffer, $packetLengthVarInt->getValue()); //read the packet ID $packetID = VarInt::readUnsignedVarInt($packetDataWithPacketID); //get the raw packet data $packetData = substr($packetDataWithPacketID, $packetID->getDataLength()); $this->lastPacket = $this->currentTime(); //trigger packet processing $this->processPacket($packetID->getValue(), $packetData); //if we have buffer left run again } while (strlen($this->packetBuffer) > 0); //if any exceptions are thrown (error parsing the packets e.t.c.) send a disconnect packet } catch (Exception $ex) { echo "EXCEPTION IN PACKET PARSING {$ex->getMessage()}\n"; echo $ex->getTraceAsString(); $dis = new DisconnectPacket(); $dis->setReason('Internal Server Error: '.$ex->getMessage()); $this->end($dis->encodePacket()); } }
php
public function onData($data) { //if we're in encryption stage decrypt it first if($this->secret !== null) { mcrypt_generic_init($this->encryptor, $this->secret, $this->secret); $data = mdecrypt_generic($this->encryptor, $data); mcrypt_generic_deinit($this->encryptor); } //attempt to parse the data as a packet try { //add the data to the current buffer $this->packetBuffer .= $data; //for as long as we have data left in the buffer do { //read the packet length from the stream $packetLengthVarInt = VarInt::readUnsignedVarInt($this->packetBuffer); //not enough data to read the packet length, wait for more data if($packetLengthVarInt === false) { return; } //total length of the packet is the length of the varint + it's value $totalLength = $packetLengthVarInt->getDataLength() + $packetLengthVarInt->getValue(); //if we don't have enough data to read the entire packet wait for more data to enter $bufferLength = strlen($this->packetBuffer); if ($bufferLength < $totalLength) { return; } //remove the packet length varint from the buffer $this->packetBuffer = substr($this->packetBuffer, $packetLengthVarInt->getDataLength()); //read the packet ID from the buffer $packetDataWithPacketID = substr($this->packetBuffer, 0, $packetLengthVarInt->getValue()); //remove the rest of the packet from the buffer $this->packetBuffer = substr($this->packetBuffer, $packetLengthVarInt->getValue()); //read the packet ID $packetID = VarInt::readUnsignedVarInt($packetDataWithPacketID); //get the raw packet data $packetData = substr($packetDataWithPacketID, $packetID->getDataLength()); $this->lastPacket = $this->currentTime(); //trigger packet processing $this->processPacket($packetID->getValue(), $packetData); //if we have buffer left run again } while (strlen($this->packetBuffer) > 0); //if any exceptions are thrown (error parsing the packets e.t.c.) send a disconnect packet } catch (Exception $ex) { echo "EXCEPTION IN PACKET PARSING {$ex->getMessage()}\n"; echo $ex->getTraceAsString(); $dis = new DisconnectPacket(); $dis->setReason('Internal Server Error: '.$ex->getMessage()); $this->end($dis->encodePacket()); } }
[ "public", "function", "onData", "(", "$", "data", ")", "{", "//if we're in encryption stage decrypt it first", "if", "(", "$", "this", "->", "secret", "!==", "null", ")", "{", "mcrypt_generic_init", "(", "$", "this", "->", "encryptor", ",", "$", "this", "->", "secret", ",", "$", "this", "->", "secret", ")", ";", "$", "data", "=", "mdecrypt_generic", "(", "$", "this", "->", "encryptor", ",", "$", "data", ")", ";", "mcrypt_generic_deinit", "(", "$", "this", "->", "encryptor", ")", ";", "}", "//attempt to parse the data as a packet", "try", "{", "//add the data to the current buffer", "$", "this", "->", "packetBuffer", ".=", "$", "data", ";", "//for as long as we have data left in the buffer", "do", "{", "//read the packet length from the stream", "$", "packetLengthVarInt", "=", "VarInt", "::", "readUnsignedVarInt", "(", "$", "this", "->", "packetBuffer", ")", ";", "//not enough data to read the packet length, wait for more data", "if", "(", "$", "packetLengthVarInt", "===", "false", ")", "{", "return", ";", "}", "//total length of the packet is the length of the varint + it's value", "$", "totalLength", "=", "$", "packetLengthVarInt", "->", "getDataLength", "(", ")", "+", "$", "packetLengthVarInt", "->", "getValue", "(", ")", ";", "//if we don't have enough data to read the entire packet wait for more data to enter", "$", "bufferLength", "=", "strlen", "(", "$", "this", "->", "packetBuffer", ")", ";", "if", "(", "$", "bufferLength", "<", "$", "totalLength", ")", "{", "return", ";", "}", "//remove the packet length varint from the buffer", "$", "this", "->", "packetBuffer", "=", "substr", "(", "$", "this", "->", "packetBuffer", ",", "$", "packetLengthVarInt", "->", "getDataLength", "(", ")", ")", ";", "//read the packet ID from the buffer", "$", "packetDataWithPacketID", "=", "substr", "(", "$", "this", "->", "packetBuffer", ",", "0", ",", "$", "packetLengthVarInt", "->", "getValue", "(", ")", ")", ";", "//remove the rest of the packet from the buffer", "$", "this", "->", "packetBuffer", "=", "substr", "(", "$", "this", "->", "packetBuffer", ",", "$", "packetLengthVarInt", "->", "getValue", "(", ")", ")", ";", "//read the packet ID", "$", "packetID", "=", "VarInt", "::", "readUnsignedVarInt", "(", "$", "packetDataWithPacketID", ")", ";", "//get the raw packet data", "$", "packetData", "=", "substr", "(", "$", "packetDataWithPacketID", ",", "$", "packetID", "->", "getDataLength", "(", ")", ")", ";", "$", "this", "->", "lastPacket", "=", "$", "this", "->", "currentTime", "(", ")", ";", "//trigger packet processing", "$", "this", "->", "processPacket", "(", "$", "packetID", "->", "getValue", "(", ")", ",", "$", "packetData", ")", ";", "//if we have buffer left run again", "}", "while", "(", "strlen", "(", "$", "this", "->", "packetBuffer", ")", ">", "0", ")", ";", "//if any exceptions are thrown (error parsing the packets e.t.c.) send a disconnect packet", "}", "catch", "(", "Exception", "$", "ex", ")", "{", "echo", "\"EXCEPTION IN PACKET PARSING {$ex->getMessage()}\\n\"", ";", "echo", "$", "ex", "->", "getTraceAsString", "(", ")", ";", "$", "dis", "=", "new", "DisconnectPacket", "(", ")", ";", "$", "dis", "->", "setReason", "(", "'Internal Server Error: '", ".", "$", "ex", "->", "getMessage", "(", ")", ")", ";", "$", "this", "->", "end", "(", "$", "dis", "->", "encodePacket", "(", ")", ")", ";", "}", "}" ]
Called whenever there is data available on the stream @param $data String the raw data
[ "Called", "whenever", "there", "is", "data", "available", "on", "the", "stream" ]
ebe9a09d1de45dbc765545137514c8cf7c8e075f
https://github.com/Eluinhost/minecraft-auth/blob/ebe9a09d1de45dbc765545137514c8cf7c8e075f/src/AuthServer/BaseClient.php#L100-L166
223,957
Eluinhost/minecraft-auth
src/AuthServer/BaseClient.php
BaseClient.write
public function write($data) { //encrypt the data if needed if($this->secret !== null) { mcrypt_generic_init($this->encryptor, $this->secret, $this->secret); $data = mcrypt_generic($this->encryptor, $data); mcrypt_generic_deinit($this->encryptor); } return parent::write($data); }
php
public function write($data) { //encrypt the data if needed if($this->secret !== null) { mcrypt_generic_init($this->encryptor, $this->secret, $this->secret); $data = mcrypt_generic($this->encryptor, $data); mcrypt_generic_deinit($this->encryptor); } return parent::write($data); }
[ "public", "function", "write", "(", "$", "data", ")", "{", "//encrypt the data if needed", "if", "(", "$", "this", "->", "secret", "!==", "null", ")", "{", "mcrypt_generic_init", "(", "$", "this", "->", "encryptor", ",", "$", "this", "->", "secret", ",", "$", "this", "->", "secret", ")", ";", "$", "data", "=", "mcrypt_generic", "(", "$", "this", "->", "encryptor", ",", "$", "data", ")", ";", "mcrypt_generic_deinit", "(", "$", "this", "->", "encryptor", ")", ";", "}", "return", "parent", "::", "write", "(", "$", "data", ")", ";", "}" ]
Override the base write to add encryption if we're in an encypted stage @param $data String the data to write @return bool @Override
[ "Override", "the", "base", "write", "to", "add", "encryption", "if", "we", "re", "in", "an", "encypted", "stage" ]
ebe9a09d1de45dbc765545137514c8cf7c8e075f
https://github.com/Eluinhost/minecraft-auth/blob/ebe9a09d1de45dbc765545137514c8cf7c8e075f/src/AuthServer/BaseClient.php#L228-L237
223,958
Eluinhost/minecraft-auth
src/AuthServer/BaseClient.php
BaseClient.enableAES
public function enableAES($secret) { $this->secret = $secret; $this->encryptor = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CFB, ''); }
php
public function enableAES($secret) { $this->secret = $secret; $this->encryptor = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CFB, ''); }
[ "public", "function", "enableAES", "(", "$", "secret", ")", "{", "$", "this", "->", "secret", "=", "$", "secret", ";", "$", "this", "->", "encryptor", "=", "mcrypt_module_open", "(", "MCRYPT_RIJNDAEL_128", ",", "''", ",", "MCRYPT_MODE_CFB", ",", "''", ")", ";", "}" ]
Enables encryption of the stream @param $secret String the secret generated by the client, used to encrypt the stream
[ "Enables", "encryption", "of", "the", "stream" ]
ebe9a09d1de45dbc765545137514c8cf7c8e075f
https://github.com/Eluinhost/minecraft-auth/blob/ebe9a09d1de45dbc765545137514c8cf7c8e075f/src/AuthServer/BaseClient.php#L261-L265
223,959
pattern-lab/plugin-php-reload
src/PatternLab/Reload/AutoReloadApplication.php
AutoReloadApplication.onUpdate
public function onUpdate() { if (file_exists($this->savedTimestampPath)) { $readTimestamp = file_get_contents($this->savedTimestampPath); if ($readTimestamp != $this->savedTimestamp) { foreach ($this->clients as $sendto) { $sendto->send($readTimestamp); } $this->savedTimestamp = $readTimestamp; } } }
php
public function onUpdate() { if (file_exists($this->savedTimestampPath)) { $readTimestamp = file_get_contents($this->savedTimestampPath); if ($readTimestamp != $this->savedTimestamp) { foreach ($this->clients as $sendto) { $sendto->send($readTimestamp); } $this->savedTimestamp = $readTimestamp; } } }
[ "public", "function", "onUpdate", "(", ")", "{", "if", "(", "file_exists", "(", "$", "this", "->", "savedTimestampPath", ")", ")", "{", "$", "readTimestamp", "=", "file_get_contents", "(", "$", "this", "->", "savedTimestampPath", ")", ";", "if", "(", "$", "readTimestamp", "!=", "$", "this", "->", "savedTimestamp", ")", "{", "foreach", "(", "$", "this", "->", "clients", "as", "$", "sendto", ")", "{", "$", "sendto", "->", "send", "(", "$", "readTimestamp", ")", ";", "}", "$", "this", "->", "savedTimestamp", "=", "$", "readTimestamp", ";", "}", "}", "}" ]
Sends out a message once a second to all connected clients containing the contents of latest-change.txt
[ "Sends", "out", "a", "message", "once", "a", "second", "to", "all", "connected", "clients", "containing", "the", "contents", "of", "latest", "-", "change", ".", "txt" ]
d7e19f0cdfd0d15e8e16a3858140da64e8ade84b
https://github.com/pattern-lab/plugin-php-reload/blob/d7e19f0cdfd0d15e8e16a3858140da64e8ade84b/src/PatternLab/Reload/AutoReloadApplication.php#L64-L76
223,960
yii2mod/yii2-image
ImageComponent.php
ImageComponent.getUrl
public function getUrl($file, $type): string { if (!$this->checkPermission($type)) { $file = $this->noImage; } $filePath = $this->getCachePath($file, $type); if (file_exists($filePath['system']) && (time() - filemtime($filePath['system']) < $this->cacheTime)) { return $filePath['public']; } return Url::toRoute([$this->imageAction, 'path' => urlencode($file), 'type' => $type]); }
php
public function getUrl($file, $type): string { if (!$this->checkPermission($type)) { $file = $this->noImage; } $filePath = $this->getCachePath($file, $type); if (file_exists($filePath['system']) && (time() - filemtime($filePath['system']) < $this->cacheTime)) { return $filePath['public']; } return Url::toRoute([$this->imageAction, 'path' => urlencode($file), 'type' => $type]); }
[ "public", "function", "getUrl", "(", "$", "file", ",", "$", "type", ")", ":", "string", "{", "if", "(", "!", "$", "this", "->", "checkPermission", "(", "$", "type", ")", ")", "{", "$", "file", "=", "$", "this", "->", "noImage", ";", "}", "$", "filePath", "=", "$", "this", "->", "getCachePath", "(", "$", "file", ",", "$", "type", ")", ";", "if", "(", "file_exists", "(", "$", "filePath", "[", "'system'", "]", ")", "&&", "(", "time", "(", ")", "-", "filemtime", "(", "$", "filePath", "[", "'system'", "]", ")", "<", "$", "this", "->", "cacheTime", ")", ")", "{", "return", "$", "filePath", "[", "'public'", "]", ";", "}", "return", "Url", "::", "toRoute", "(", "[", "$", "this", "->", "imageAction", ",", "'path'", "=>", "urlencode", "(", "$", "file", ")", ",", "'type'", "=>", "$", "type", "]", ")", ";", "}" ]
Get image url @param $file @param $type @return string
[ "Get", "image", "url" ]
4ca69a5ebbe9c9a658adc3a383b1a75b53968486
https://github.com/yii2mod/yii2-image/blob/4ca69a5ebbe9c9a658adc3a383b1a75b53968486/ImageComponent.php#L138-L151
223,961
yii2mod/yii2-image
ImageComponent.php
ImageComponent.getCachePath
protected function getCachePath($file, $type): array { $hash = md5($file . $type); if (isset($this->config[$type])) { $isTransparent = ArrayHelper::getValue($this->config[$type], 'transparent', false); } else { $isTransparent = false; } $cacheFileExt = $isTransparent ? self::TRANSPARENT_EXTENSION : strtolower(pathinfo($file, PATHINFO_EXTENSION)); $cachePath = $this->cachePath . $hash[0] . DIRECTORY_SEPARATOR; $cachePublicPath = $this->cachePublicPath . $hash[0] . DIRECTORY_SEPARATOR; $cacheFile = "{$hash}.{$cacheFileExt}"; $systemPath = Yii::getAlias('@app') . $cachePath; FileHelper::createDirectory($systemPath); return [ 'system' => $systemPath . $cacheFile, 'web' => $cachePath . $cacheFile, 'public' => $cachePublicPath . $cacheFile, 'extension' => $cacheFileExt, ]; }
php
protected function getCachePath($file, $type): array { $hash = md5($file . $type); if (isset($this->config[$type])) { $isTransparent = ArrayHelper::getValue($this->config[$type], 'transparent', false); } else { $isTransparent = false; } $cacheFileExt = $isTransparent ? self::TRANSPARENT_EXTENSION : strtolower(pathinfo($file, PATHINFO_EXTENSION)); $cachePath = $this->cachePath . $hash[0] . DIRECTORY_SEPARATOR; $cachePublicPath = $this->cachePublicPath . $hash[0] . DIRECTORY_SEPARATOR; $cacheFile = "{$hash}.{$cacheFileExt}"; $systemPath = Yii::getAlias('@app') . $cachePath; FileHelper::createDirectory($systemPath); return [ 'system' => $systemPath . $cacheFile, 'web' => $cachePath . $cacheFile, 'public' => $cachePublicPath . $cacheFile, 'extension' => $cacheFileExt, ]; }
[ "protected", "function", "getCachePath", "(", "$", "file", ",", "$", "type", ")", ":", "array", "{", "$", "hash", "=", "md5", "(", "$", "file", ".", "$", "type", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "config", "[", "$", "type", "]", ")", ")", "{", "$", "isTransparent", "=", "ArrayHelper", "::", "getValue", "(", "$", "this", "->", "config", "[", "$", "type", "]", ",", "'transparent'", ",", "false", ")", ";", "}", "else", "{", "$", "isTransparent", "=", "false", ";", "}", "$", "cacheFileExt", "=", "$", "isTransparent", "?", "self", "::", "TRANSPARENT_EXTENSION", ":", "strtolower", "(", "pathinfo", "(", "$", "file", ",", "PATHINFO_EXTENSION", ")", ")", ";", "$", "cachePath", "=", "$", "this", "->", "cachePath", ".", "$", "hash", "[", "0", "]", ".", "DIRECTORY_SEPARATOR", ";", "$", "cachePublicPath", "=", "$", "this", "->", "cachePublicPath", ".", "$", "hash", "[", "0", "]", ".", "DIRECTORY_SEPARATOR", ";", "$", "cacheFile", "=", "\"{$hash}.{$cacheFileExt}\"", ";", "$", "systemPath", "=", "Yii", "::", "getAlias", "(", "'@app'", ")", ".", "$", "cachePath", ";", "FileHelper", "::", "createDirectory", "(", "$", "systemPath", ")", ";", "return", "[", "'system'", "=>", "$", "systemPath", ".", "$", "cacheFile", ",", "'web'", "=>", "$", "cachePath", ".", "$", "cacheFile", ",", "'public'", "=>", "$", "cachePublicPath", ".", "$", "cacheFile", ",", "'extension'", "=>", "$", "cacheFileExt", ",", "]", ";", "}" ]
Get image cache path @param $file @param $type @return array
[ "Get", "image", "cache", "path" ]
4ca69a5ebbe9c9a658adc3a383b1a75b53968486
https://github.com/yii2mod/yii2-image/blob/4ca69a5ebbe9c9a658adc3a383b1a75b53968486/ImageComponent.php#L161-L184
223,962
yii2mod/yii2-image
ImageComponent.php
ImageComponent.checkPermission
protected function checkPermission($type) { if (isset($this->config[$type]['visible'])) { $role = $this->config[$type]['visible']; unset($this->config[$type]['visible']); if (!Yii::$app->getUser()->can($role)) { return false; } } return true; }
php
protected function checkPermission($type) { if (isset($this->config[$type]['visible'])) { $role = $this->config[$type]['visible']; unset($this->config[$type]['visible']); if (!Yii::$app->getUser()->can($role)) { return false; } } return true; }
[ "protected", "function", "checkPermission", "(", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "config", "[", "$", "type", "]", "[", "'visible'", "]", ")", ")", "{", "$", "role", "=", "$", "this", "->", "config", "[", "$", "type", "]", "[", "'visible'", "]", ";", "unset", "(", "$", "this", "->", "config", "[", "$", "type", "]", "[", "'visible'", "]", ")", ";", "if", "(", "!", "Yii", "::", "$", "app", "->", "getUser", "(", ")", "->", "can", "(", "$", "role", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check permission for current user @param $type @return bool
[ "Check", "permission", "for", "current", "user" ]
4ca69a5ebbe9c9a658adc3a383b1a75b53968486
https://github.com/yii2mod/yii2-image/blob/4ca69a5ebbe9c9a658adc3a383b1a75b53968486/ImageComponent.php#L355-L366
223,963
jurchiks/numbers2words
src/Speller.php
Speller.spellNumber
public static function spellNumber($number, $language) { if (!is_numeric($number)) { throw new InvalidArgumentException('Invalid number specified.'); } return self::get($language) ->parseInt(intval($number), false); }
php
public static function spellNumber($number, $language) { if (!is_numeric($number)) { throw new InvalidArgumentException('Invalid number specified.'); } return self::get($language) ->parseInt(intval($number), false); }
[ "public", "static", "function", "spellNumber", "(", "$", "number", ",", "$", "language", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "number", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid number specified.'", ")", ";", "}", "return", "self", "::", "get", "(", "$", "language", ")", "->", "parseInt", "(", "intval", "(", "$", "number", ")", ",", "false", ")", ";", "}" ]
Convert a number into its linguistic representation. @param int $number : the number to spell in the specified language @param string $language : a two-letter, ISO 639-1 code of the language to spell the number in @return string : the number as written in words in the specified language @throws InvalidArgumentException if any parameter is invalid
[ "Convert", "a", "number", "into", "its", "linguistic", "representation", "." ]
2997c3ffb784497126c2c64fb4d2bbd508475bfa
https://github.com/jurchiks/numbers2words/blob/2997c3ffb784497126c2c64fb4d2bbd508475bfa/src/Speller.php#L99-L108
223,964
jurchiks/numbers2words
src/Speller.php
Speller.spellCurrency
public static function spellCurrency($amount, $language, $currency, $requireDecimal = true, $spellDecimal = false) { if (!is_numeric($amount)) { throw new InvalidArgumentException('Invalid number specified.'); } if (!is_string($currency)) { throw new InvalidArgumentException('Invalid currency code specified.'); } $currency = strtoupper(trim($currency)); if (!in_array($currency, self::$currencies)) { throw new InvalidArgumentException('That currency is not implemented yet.'); } $amount = number_format($amount, 2, '.', ''); // ensure decimal is always 2 digits $parts = explode('.', $amount); $speller = self::get($language); $wholeAmount = intval($parts[0]); $decimalAmount = intval($parts[1]); $text = trim($speller->parseInt($wholeAmount, false, $currency)) . ' ' . $speller->getCurrencyName('whole', $wholeAmount, $currency); if ($requireDecimal || ($decimalAmount > 0)) { $text .= $speller->decimalSeparator . ($spellDecimal ? trim($speller->parseInt($decimalAmount, true, $currency)) : $decimalAmount) . ' ' . $speller->getCurrencyName('decimal', $decimalAmount, $currency); } return $text; }
php
public static function spellCurrency($amount, $language, $currency, $requireDecimal = true, $spellDecimal = false) { if (!is_numeric($amount)) { throw new InvalidArgumentException('Invalid number specified.'); } if (!is_string($currency)) { throw new InvalidArgumentException('Invalid currency code specified.'); } $currency = strtoupper(trim($currency)); if (!in_array($currency, self::$currencies)) { throw new InvalidArgumentException('That currency is not implemented yet.'); } $amount = number_format($amount, 2, '.', ''); // ensure decimal is always 2 digits $parts = explode('.', $amount); $speller = self::get($language); $wholeAmount = intval($parts[0]); $decimalAmount = intval($parts[1]); $text = trim($speller->parseInt($wholeAmount, false, $currency)) . ' ' . $speller->getCurrencyName('whole', $wholeAmount, $currency); if ($requireDecimal || ($decimalAmount > 0)) { $text .= $speller->decimalSeparator . ($spellDecimal ? trim($speller->parseInt($decimalAmount, true, $currency)) : $decimalAmount) . ' ' . $speller->getCurrencyName('decimal', $decimalAmount, $currency); } return $text; }
[ "public", "static", "function", "spellCurrency", "(", "$", "amount", ",", "$", "language", ",", "$", "currency", ",", "$", "requireDecimal", "=", "true", ",", "$", "spellDecimal", "=", "false", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "amount", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid number specified.'", ")", ";", "}", "if", "(", "!", "is_string", "(", "$", "currency", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid currency code specified.'", ")", ";", "}", "$", "currency", "=", "strtoupper", "(", "trim", "(", "$", "currency", ")", ")", ";", "if", "(", "!", "in_array", "(", "$", "currency", ",", "self", "::", "$", "currencies", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'That currency is not implemented yet.'", ")", ";", "}", "$", "amount", "=", "number_format", "(", "$", "amount", ",", "2", ",", "'.'", ",", "''", ")", ";", "// ensure decimal is always 2 digits", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "amount", ")", ";", "$", "speller", "=", "self", "::", "get", "(", "$", "language", ")", ";", "$", "wholeAmount", "=", "intval", "(", "$", "parts", "[", "0", "]", ")", ";", "$", "decimalAmount", "=", "intval", "(", "$", "parts", "[", "1", "]", ")", ";", "$", "text", "=", "trim", "(", "$", "speller", "->", "parseInt", "(", "$", "wholeAmount", ",", "false", ",", "$", "currency", ")", ")", ".", "' '", ".", "$", "speller", "->", "getCurrencyName", "(", "'whole'", ",", "$", "wholeAmount", ",", "$", "currency", ")", ";", "if", "(", "$", "requireDecimal", "||", "(", "$", "decimalAmount", ">", "0", ")", ")", "{", "$", "text", ".=", "$", "speller", "->", "decimalSeparator", ".", "(", "$", "spellDecimal", "?", "trim", "(", "$", "speller", "->", "parseInt", "(", "$", "decimalAmount", ",", "true", ",", "$", "currency", ")", ")", ":", "$", "decimalAmount", ")", ".", "' '", ".", "$", "speller", "->", "getCurrencyName", "(", "'decimal'", ",", "$", "decimalAmount", ",", "$", "currency", ")", ";", "}", "return", "$", "text", ";", "}" ]
Convert currency to its linguistic representation. @param int|float $amount : the amount to spell in the specified language @param string $language : a two-letter, ISO 639-1 code of the language to spell the amount in @param string $currency : a three-letter, ISO 4217 currency code @param bool $requireDecimal : if true, output decimals even if the value is 0 @param bool $spellDecimal : if true, spell decimals out same as whole numbers; otherwise, output decimals as numbers @return string : the currency as written in words in the specified language @throws InvalidArgumentException if any parameter is invalid
[ "Convert", "currency", "to", "its", "linguistic", "representation", "." ]
2997c3ffb784497126c2c64fb4d2bbd508475bfa
https://github.com/jurchiks/numbers2words/blob/2997c3ffb784497126c2c64fb4d2bbd508475bfa/src/Speller.php#L122-L162
223,965
blar/openssl
lib/Blar/OpenSSL/Chain.php
Chain.verify
public function verify(int $purpose = X509_PURPOSE_ANY): bool { $chainFile = new TempFile(); $chainFile->setContent($this); $certificate = $this[0]; return $certificate->checkPurpose($purpose, [], $chainFile); }
php
public function verify(int $purpose = X509_PURPOSE_ANY): bool { $chainFile = new TempFile(); $chainFile->setContent($this); $certificate = $this[0]; return $certificate->checkPurpose($purpose, [], $chainFile); }
[ "public", "function", "verify", "(", "int", "$", "purpose", "=", "X509_PURPOSE_ANY", ")", ":", "bool", "{", "$", "chainFile", "=", "new", "TempFile", "(", ")", ";", "$", "chainFile", "->", "setContent", "(", "$", "this", ")", ";", "$", "certificate", "=", "$", "this", "[", "0", "]", ";", "return", "$", "certificate", "->", "checkPurpose", "(", "$", "purpose", ",", "[", "]", ",", "$", "chainFile", ")", ";", "}" ]
Verify the chain file. @param int $purpose X509_PURPOSE_* @return bool
[ "Verify", "the", "chain", "file", "." ]
9a7faf31492cefe8c8b166ef775a6e2eba04c3ec
https://github.com/blar/openssl/blob/9a7faf31492cefe8c8b166ef775a6e2eba04c3ec/lib/Blar/OpenSSL/Chain.php#L33-L39
223,966
Eluinhost/minecraft-auth
src/AuthServer/AuthClient.php
AuthClient.onEncryptionResponsePacket
public function onEncryptionResponsePacket(EncryptionResponsePacket $packet) { //if we don't have a verifiyToken sent yet then the packet has been sent without us sending a request, disconnect client if(null === $this->verifyToken) { $this->disconnectClient((new DisconnectPacket())->setReason('Packet received out of order')); return; } //get the verify token from the packet it and decrypt it using our key $verifyToken = $this->certificate->getPrivateKey()->decrypt($packet->getToken()); //if it isn't the same as our token then encryption failed, disconnect the client if($verifyToken != $this->verifyToken) { $this->disconnectClient((new DisconnectPacket())->setReason('Invalid validation token')); return; } //decrypt the shared secret from the packet and decrypt it using our key $secret = $this->certificate->getPrivateKey()->decrypt($packet->getSecret()); //enable encryption using the client generated secret $this->enableAES($secret); //generate a login hash the same as the client for the session server request $publicKey = $this->certificate->getPublicKey()->getPublicKey(); $publicKey = base64_decode(substr($publicKey, 28, -26)); //cut out the start and end lines of the key $loginHash = $this->serverID . $secret . $publicKey; $loginHash = self::sha1($loginHash); //create a new Yggdrasil for checking against Mojang $yggdrasil = new DefaultYggdrasil(); try { //ask Mojang if the user has sent a join request, throws exception on failure $response = $yggdrasil->hasJoined($this->username, $loginHash); //get and set the clients UUID from the response $this->uuid = $response->getUuid(); //trigger the login success with the disconnect packet $disconnect = new DisconnectPacket(); $this->emit('login_success', [$this, $disconnect]); //if no reason was set after the event then set a default if($disconnect->getReasonJSON() === null) { $disconnect->setReason("No kick reason supplied"); } //disconnect the client $this->disconnectClient($disconnect); } catch (Exception $ex) { echo "{$this->username} failed authentication with Mojang session servers\n"; //exception occured checking against Mojang $this->disconnectClient((new DisconnectPacket())->setReason("Error Authenticating with Mojang servers")); } }
php
public function onEncryptionResponsePacket(EncryptionResponsePacket $packet) { //if we don't have a verifiyToken sent yet then the packet has been sent without us sending a request, disconnect client if(null === $this->verifyToken) { $this->disconnectClient((new DisconnectPacket())->setReason('Packet received out of order')); return; } //get the verify token from the packet it and decrypt it using our key $verifyToken = $this->certificate->getPrivateKey()->decrypt($packet->getToken()); //if it isn't the same as our token then encryption failed, disconnect the client if($verifyToken != $this->verifyToken) { $this->disconnectClient((new DisconnectPacket())->setReason('Invalid validation token')); return; } //decrypt the shared secret from the packet and decrypt it using our key $secret = $this->certificate->getPrivateKey()->decrypt($packet->getSecret()); //enable encryption using the client generated secret $this->enableAES($secret); //generate a login hash the same as the client for the session server request $publicKey = $this->certificate->getPublicKey()->getPublicKey(); $publicKey = base64_decode(substr($publicKey, 28, -26)); //cut out the start and end lines of the key $loginHash = $this->serverID . $secret . $publicKey; $loginHash = self::sha1($loginHash); //create a new Yggdrasil for checking against Mojang $yggdrasil = new DefaultYggdrasil(); try { //ask Mojang if the user has sent a join request, throws exception on failure $response = $yggdrasil->hasJoined($this->username, $loginHash); //get and set the clients UUID from the response $this->uuid = $response->getUuid(); //trigger the login success with the disconnect packet $disconnect = new DisconnectPacket(); $this->emit('login_success', [$this, $disconnect]); //if no reason was set after the event then set a default if($disconnect->getReasonJSON() === null) { $disconnect->setReason("No kick reason supplied"); } //disconnect the client $this->disconnectClient($disconnect); } catch (Exception $ex) { echo "{$this->username} failed authentication with Mojang session servers\n"; //exception occured checking against Mojang $this->disconnectClient((new DisconnectPacket())->setReason("Error Authenticating with Mojang servers")); } }
[ "public", "function", "onEncryptionResponsePacket", "(", "EncryptionResponsePacket", "$", "packet", ")", "{", "//if we don't have a verifiyToken sent yet then the packet has been sent without us sending a request, disconnect client", "if", "(", "null", "===", "$", "this", "->", "verifyToken", ")", "{", "$", "this", "->", "disconnectClient", "(", "(", "new", "DisconnectPacket", "(", ")", ")", "->", "setReason", "(", "'Packet received out of order'", ")", ")", ";", "return", ";", "}", "//get the verify token from the packet it and decrypt it using our key", "$", "verifyToken", "=", "$", "this", "->", "certificate", "->", "getPrivateKey", "(", ")", "->", "decrypt", "(", "$", "packet", "->", "getToken", "(", ")", ")", ";", "//if it isn't the same as our token then encryption failed, disconnect the client", "if", "(", "$", "verifyToken", "!=", "$", "this", "->", "verifyToken", ")", "{", "$", "this", "->", "disconnectClient", "(", "(", "new", "DisconnectPacket", "(", ")", ")", "->", "setReason", "(", "'Invalid validation token'", ")", ")", ";", "return", ";", "}", "//decrypt the shared secret from the packet and decrypt it using our key", "$", "secret", "=", "$", "this", "->", "certificate", "->", "getPrivateKey", "(", ")", "->", "decrypt", "(", "$", "packet", "->", "getSecret", "(", ")", ")", ";", "//enable encryption using the client generated secret", "$", "this", "->", "enableAES", "(", "$", "secret", ")", ";", "//generate a login hash the same as the client for the session server request", "$", "publicKey", "=", "$", "this", "->", "certificate", "->", "getPublicKey", "(", ")", "->", "getPublicKey", "(", ")", ";", "$", "publicKey", "=", "base64_decode", "(", "substr", "(", "$", "publicKey", ",", "28", ",", "-", "26", ")", ")", ";", "//cut out the start and end lines of the key", "$", "loginHash", "=", "$", "this", "->", "serverID", ".", "$", "secret", ".", "$", "publicKey", ";", "$", "loginHash", "=", "self", "::", "sha1", "(", "$", "loginHash", ")", ";", "//create a new Yggdrasil for checking against Mojang", "$", "yggdrasil", "=", "new", "DefaultYggdrasil", "(", ")", ";", "try", "{", "//ask Mojang if the user has sent a join request, throws exception on failure", "$", "response", "=", "$", "yggdrasil", "->", "hasJoined", "(", "$", "this", "->", "username", ",", "$", "loginHash", ")", ";", "//get and set the clients UUID from the response", "$", "this", "->", "uuid", "=", "$", "response", "->", "getUuid", "(", ")", ";", "//trigger the login success with the disconnect packet", "$", "disconnect", "=", "new", "DisconnectPacket", "(", ")", ";", "$", "this", "->", "emit", "(", "'login_success'", ",", "[", "$", "this", ",", "$", "disconnect", "]", ")", ";", "//if no reason was set after the event then set a default", "if", "(", "$", "disconnect", "->", "getReasonJSON", "(", ")", "===", "null", ")", "{", "$", "disconnect", "->", "setReason", "(", "\"No kick reason supplied\"", ")", ";", "}", "//disconnect the client", "$", "this", "->", "disconnectClient", "(", "$", "disconnect", ")", ";", "}", "catch", "(", "Exception", "$", "ex", ")", "{", "echo", "\"{$this->username} failed authentication with Mojang session servers\\n\"", ";", "//exception occured checking against Mojang", "$", "this", "->", "disconnectClient", "(", "(", "new", "DisconnectPacket", "(", ")", ")", "->", "setReason", "(", "\"Error Authenticating with Mojang servers\"", ")", ")", ";", "}", "}" ]
Called on event LOGIN.EncryptionResponsePacket @param EncryptionResponsePacket $packet
[ "Called", "on", "event", "LOGIN", ".", "EncryptionResponsePacket" ]
ebe9a09d1de45dbc765545137514c8cf7c8e075f
https://github.com/Eluinhost/minecraft-auth/blob/ebe9a09d1de45dbc765545137514c8cf7c8e075f/src/AuthServer/AuthClient.php#L64-L119
223,967
Eluinhost/minecraft-auth
src/AuthServer/AuthClient.php
AuthClient.onLoginStartPacket
public function onLoginStartPacket(LoginStartPacket $packet) { //set the users name as supplied in the packet $this->username = $packet->getUsername(); //create a new encryption request $request = new EncryptionRequestPacket(); //set our randomly generated server ID and verifyToken for this connection $this->serverID = $request->getRandomServerID(); $this->verifyToken = $request->getRandomServerID(); //the public key needs to not have the start and end lines on it $publicKey = $this->certificate->getPublicKey()->getPublicKey(); $publicKey = substr($publicKey, 28, -26); //set the request data $request->setPublicKey($publicKey) ->setServerID($this->serverID) ->setToken($this->verifyToken); //send the packet to the client $this->sendPacket($request); }
php
public function onLoginStartPacket(LoginStartPacket $packet) { //set the users name as supplied in the packet $this->username = $packet->getUsername(); //create a new encryption request $request = new EncryptionRequestPacket(); //set our randomly generated server ID and verifyToken for this connection $this->serverID = $request->getRandomServerID(); $this->verifyToken = $request->getRandomServerID(); //the public key needs to not have the start and end lines on it $publicKey = $this->certificate->getPublicKey()->getPublicKey(); $publicKey = substr($publicKey, 28, -26); //set the request data $request->setPublicKey($publicKey) ->setServerID($this->serverID) ->setToken($this->verifyToken); //send the packet to the client $this->sendPacket($request); }
[ "public", "function", "onLoginStartPacket", "(", "LoginStartPacket", "$", "packet", ")", "{", "//set the users name as supplied in the packet", "$", "this", "->", "username", "=", "$", "packet", "->", "getUsername", "(", ")", ";", "//create a new encryption request", "$", "request", "=", "new", "EncryptionRequestPacket", "(", ")", ";", "//set our randomly generated server ID and verifyToken for this connection", "$", "this", "->", "serverID", "=", "$", "request", "->", "getRandomServerID", "(", ")", ";", "$", "this", "->", "verifyToken", "=", "$", "request", "->", "getRandomServerID", "(", ")", ";", "//the public key needs to not have the start and end lines on it", "$", "publicKey", "=", "$", "this", "->", "certificate", "->", "getPublicKey", "(", ")", "->", "getPublicKey", "(", ")", ";", "$", "publicKey", "=", "substr", "(", "$", "publicKey", ",", "28", ",", "-", "26", ")", ";", "//set the request data", "$", "request", "->", "setPublicKey", "(", "$", "publicKey", ")", "->", "setServerID", "(", "$", "this", "->", "serverID", ")", "->", "setToken", "(", "$", "this", "->", "verifyToken", ")", ";", "//send the packet to the client", "$", "this", "->", "sendPacket", "(", "$", "request", ")", ";", "}" ]
Called on event LOGIN.LoginStartPacket @param LoginStartPacket $packet
[ "Called", "on", "event", "LOGIN", ".", "LoginStartPacket" ]
ebe9a09d1de45dbc765545137514c8cf7c8e075f
https://github.com/Eluinhost/minecraft-auth/blob/ebe9a09d1de45dbc765545137514c8cf7c8e075f/src/AuthServer/AuthClient.php#L125-L148
223,968
Eluinhost/minecraft-auth
src/AuthServer/AuthClient.php
AuthClient.onPingRequestPacket
public function onPingRequestPacket(PingRequestPacket $packet) { //a ping data contains a long, but because the client just expects the same data back no point in parsing/reencoding it $ping = new PingResponsePacket(); $ping->setPingData($packet->getPingData()); //disconnect the client with the ping response $this->disconnectClient($ping); }
php
public function onPingRequestPacket(PingRequestPacket $packet) { //a ping data contains a long, but because the client just expects the same data back no point in parsing/reencoding it $ping = new PingResponsePacket(); $ping->setPingData($packet->getPingData()); //disconnect the client with the ping response $this->disconnectClient($ping); }
[ "public", "function", "onPingRequestPacket", "(", "PingRequestPacket", "$", "packet", ")", "{", "//a ping data contains a long, but because the client just expects the same data back no point in parsing/reencoding it", "$", "ping", "=", "new", "PingResponsePacket", "(", ")", ";", "$", "ping", "->", "setPingData", "(", "$", "packet", "->", "getPingData", "(", ")", ")", ";", "//disconnect the client with the ping response", "$", "this", "->", "disconnectClient", "(", "$", "ping", ")", ";", "}" ]
Called on event STATUS.PingRequestPacket @param PingRequestPacket $packet
[ "Called", "on", "event", "STATUS", ".", "PingRequestPacket" ]
ebe9a09d1de45dbc765545137514c8cf7c8e075f
https://github.com/Eluinhost/minecraft-auth/blob/ebe9a09d1de45dbc765545137514c8cf7c8e075f/src/AuthServer/AuthClient.php#L154-L162
223,969
Eluinhost/minecraft-auth
src/AuthServer/AuthClient.php
AuthClient.onStatusRequestPacket
public function onStatusRequestPacket(StatusRequestPacket $packet) { //status request packet has no data, just expects a StatusResponse in return $response = new StatusResponsePacket(); //call the status_request event for packet modification $this->emit('status_request', [$response]); //send the packet to the client $this->sendPacket($response); }
php
public function onStatusRequestPacket(StatusRequestPacket $packet) { //status request packet has no data, just expects a StatusResponse in return $response = new StatusResponsePacket(); //call the status_request event for packet modification $this->emit('status_request', [$response]); //send the packet to the client $this->sendPacket($response); }
[ "public", "function", "onStatusRequestPacket", "(", "StatusRequestPacket", "$", "packet", ")", "{", "//status request packet has no data, just expects a StatusResponse in return", "$", "response", "=", "new", "StatusResponsePacket", "(", ")", ";", "//call the status_request event for packet modification", "$", "this", "->", "emit", "(", "'status_request'", ",", "[", "$", "response", "]", ")", ";", "//send the packet to the client", "$", "this", "->", "sendPacket", "(", "$", "response", ")", ";", "}" ]
Called on STATUS.StatusRequestPacket @param StatusRequestPacket $packet
[ "Called", "on", "STATUS", ".", "StatusRequestPacket" ]
ebe9a09d1de45dbc765545137514c8cf7c8e075f
https://github.com/Eluinhost/minecraft-auth/blob/ebe9a09d1de45dbc765545137514c8cf7c8e075f/src/AuthServer/AuthClient.php#L168-L178
223,970
Eluinhost/minecraft-auth
src/AuthServer/AuthClient.php
AuthClient.onHandshakePacket
public function onHandshakePacket(HandshakePacket $packet) { //only allow protocol 47 to connect (1.8+) TODO can probably allow greater range, needs testing if($packet->getProtocolVersion() != 47) { $this->disconnectClient((new DisconnectPacket())->setReason('Invalid Minecraft Version, use 1.8+')); } //move to the next stage as defined in the packet (STATUS or LOGIN) $this->setStage($packet->getNextStage()); }
php
public function onHandshakePacket(HandshakePacket $packet) { //only allow protocol 47 to connect (1.8+) TODO can probably allow greater range, needs testing if($packet->getProtocolVersion() != 47) { $this->disconnectClient((new DisconnectPacket())->setReason('Invalid Minecraft Version, use 1.8+')); } //move to the next stage as defined in the packet (STATUS or LOGIN) $this->setStage($packet->getNextStage()); }
[ "public", "function", "onHandshakePacket", "(", "HandshakePacket", "$", "packet", ")", "{", "//only allow protocol 47 to connect (1.8+) TODO can probably allow greater range, needs testing", "if", "(", "$", "packet", "->", "getProtocolVersion", "(", ")", "!=", "47", ")", "{", "$", "this", "->", "disconnectClient", "(", "(", "new", "DisconnectPacket", "(", ")", ")", "->", "setReason", "(", "'Invalid Minecraft Version, use 1.8+'", ")", ")", ";", "}", "//move to the next stage as defined in the packet (STATUS or LOGIN)", "$", "this", "->", "setStage", "(", "$", "packet", "->", "getNextStage", "(", ")", ")", ";", "}" ]
Called on HANDSHAKE.HandshakePacket @param HandshakePacket $packet
[ "Called", "on", "HANDSHAKE", ".", "HandshakePacket" ]
ebe9a09d1de45dbc765545137514c8cf7c8e075f
https://github.com/Eluinhost/minecraft-auth/blob/ebe9a09d1de45dbc765545137514c8cf7c8e075f/src/AuthServer/AuthClient.php#L184-L193
223,971
everypay/everypay-php
src/Everypay.php
Everypay.checkRequirements
public static function checkRequirements() { $extensions = array('curl', 'json'); foreach ($extensions as $extension) { if (!extension_loaded($extension)) { throw new Exception\RuntimeException( 'You need the PHP ' . $extension . ' extension in order to use EveryPay PHP Library' ); } } }
php
public static function checkRequirements() { $extensions = array('curl', 'json'); foreach ($extensions as $extension) { if (!extension_loaded($extension)) { throw new Exception\RuntimeException( 'You need the PHP ' . $extension . ' extension in order to use EveryPay PHP Library' ); } } }
[ "public", "static", "function", "checkRequirements", "(", ")", "{", "$", "extensions", "=", "array", "(", "'curl'", ",", "'json'", ")", ";", "foreach", "(", "$", "extensions", "as", "$", "extension", ")", "{", "if", "(", "!", "extension_loaded", "(", "$", "extension", ")", ")", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "'You need the PHP '", ".", "$", "extension", ".", "' extension in order to use EveryPay PHP Library'", ")", ";", "}", "}", "}" ]
Check for needed requirements. @throws Everypay\Exception\RuntimeException
[ "Check", "for", "needed", "requirements", "." ]
7f5cdac41535521454ea1481ed935e7b8a1197c6
https://github.com/everypay/everypay-php/blob/7f5cdac41535521454ea1481ed935e7b8a1197c6/src/Everypay.php#L43-L55
223,972
everypay/everypay-php
src/Everypay.php
Everypay.setApiUrl
public static function setApiUrl($url) { $apiUrl = filter_var($url, FILTER_VALIDATE_URL); if (!$apiUrl) { throw new Exception\InvalidArgumentException( 'API URL should be a valid url' ); } self::$apiUrl = rtrim($url, '\\/'); }
php
public static function setApiUrl($url) { $apiUrl = filter_var($url, FILTER_VALIDATE_URL); if (!$apiUrl) { throw new Exception\InvalidArgumentException( 'API URL should be a valid url' ); } self::$apiUrl = rtrim($url, '\\/'); }
[ "public", "static", "function", "setApiUrl", "(", "$", "url", ")", "{", "$", "apiUrl", "=", "filter_var", "(", "$", "url", ",", "FILTER_VALIDATE_URL", ")", ";", "if", "(", "!", "$", "apiUrl", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "'API URL should be a valid url'", ")", ";", "}", "self", "::", "$", "apiUrl", "=", "rtrim", "(", "$", "url", ",", "'\\\\/'", ")", ";", "}" ]
Set the API url for the request. @param string $url @throws Everypay\Exception\InvalidArgumentException
[ "Set", "the", "API", "url", "for", "the", "request", "." ]
7f5cdac41535521454ea1481ed935e7b8a1197c6
https://github.com/everypay/everypay-php/blob/7f5cdac41535521454ea1481ed935e7b8a1197c6/src/Everypay.php#L90-L101
223,973
everypay/everypay-php
src/Everypay.php
Everypay.reset
public static function reset() { self::$apiKey = null; self::$isTest = false; self::$throwExceptions = false; }
php
public static function reset() { self::$apiKey = null; self::$isTest = false; self::$throwExceptions = false; }
[ "public", "static", "function", "reset", "(", ")", "{", "self", "::", "$", "apiKey", "=", "null", ";", "self", "::", "$", "isTest", "=", "false", ";", "self", "::", "$", "throwExceptions", "=", "false", ";", "}" ]
Reset Everypay class to its default values @return void
[ "Reset", "Everypay", "class", "to", "its", "default", "values" ]
7f5cdac41535521454ea1481ed935e7b8a1197c6
https://github.com/everypay/everypay-php/blob/7f5cdac41535521454ea1481ed935e7b8a1197c6/src/Everypay.php#L125-L130
223,974
blar/openssl
lib/Blar/OpenSSL/PrivateKey.php
PrivateKey.export
public function export(string $password = NULL): string { $status = openssl_pkey_export( $this->getHandle(), $output, $password ); if(!$status) { throw new RuntimeException(OpenSSL::getLastError()); } return $output; }
php
public function export(string $password = NULL): string { $status = openssl_pkey_export( $this->getHandle(), $output, $password ); if(!$status) { throw new RuntimeException(OpenSSL::getLastError()); } return $output; }
[ "public", "function", "export", "(", "string", "$", "password", "=", "NULL", ")", ":", "string", "{", "$", "status", "=", "openssl_pkey_export", "(", "$", "this", "->", "getHandle", "(", ")", ",", "$", "output", ",", "$", "password", ")", ";", "if", "(", "!", "$", "status", ")", "{", "throw", "new", "RuntimeException", "(", "OpenSSL", "::", "getLastError", "(", ")", ")", ";", "}", "return", "$", "output", ";", "}" ]
Export the key to a string as PEM. @param string $password @return string
[ "Export", "the", "key", "to", "a", "string", "as", "PEM", "." ]
9a7faf31492cefe8c8b166ef775a6e2eba04c3ec
https://github.com/blar/openssl/blob/9a7faf31492cefe8c8b166ef775a6e2eba04c3ec/lib/Blar/OpenSSL/PrivateKey.php#L65-L75
223,975
blar/openssl
lib/Blar/OpenSSL/PrivateKey.php
PrivateKey.exportToFile
public function exportToFile(string $filename, string $password = NULL) { $status = openssl_pkey_export_to_file( $this->getHandle(), $filename, $password ); if(!$status) { throw new RuntimeException(OpenSSL::getLastError()); } }
php
public function exportToFile(string $filename, string $password = NULL) { $status = openssl_pkey_export_to_file( $this->getHandle(), $filename, $password ); if(!$status) { throw new RuntimeException(OpenSSL::getLastError()); } }
[ "public", "function", "exportToFile", "(", "string", "$", "filename", ",", "string", "$", "password", "=", "NULL", ")", "{", "$", "status", "=", "openssl_pkey_export_to_file", "(", "$", "this", "->", "getHandle", "(", ")", ",", "$", "filename", ",", "$", "password", ")", ";", "if", "(", "!", "$", "status", ")", "{", "throw", "new", "RuntimeException", "(", "OpenSSL", "::", "getLastError", "(", ")", ")", ";", "}", "}" ]
Export the key to a file as PEM. @param string $filename @param string $password
[ "Export", "the", "key", "to", "a", "file", "as", "PEM", "." ]
9a7faf31492cefe8c8b166ef775a6e2eba04c3ec
https://github.com/blar/openssl/blob/9a7faf31492cefe8c8b166ef775a6e2eba04c3ec/lib/Blar/OpenSSL/PrivateKey.php#L83-L92
223,976
blar/openssl
lib/Blar/OpenSSL/Certificate.php
Certificate.getFingerprint
public function getFingerprint(string $algorithm = 'SHA1'): Hash { $value = openssl_x509_fingerprint( $this->getHandle(), $algorithm, TRUE ); if(!$value) { throw new RuntimeException(OpenSSL::getLastError()); } $hash = new Hash($algorithm); $hash->setValue($value); return $hash; }
php
public function getFingerprint(string $algorithm = 'SHA1'): Hash { $value = openssl_x509_fingerprint( $this->getHandle(), $algorithm, TRUE ); if(!$value) { throw new RuntimeException(OpenSSL::getLastError()); } $hash = new Hash($algorithm); $hash->setValue($value); return $hash; }
[ "public", "function", "getFingerprint", "(", "string", "$", "algorithm", "=", "'SHA1'", ")", ":", "Hash", "{", "$", "value", "=", "openssl_x509_fingerprint", "(", "$", "this", "->", "getHandle", "(", ")", ",", "$", "algorithm", ",", "TRUE", ")", ";", "if", "(", "!", "$", "value", ")", "{", "throw", "new", "RuntimeException", "(", "OpenSSL", "::", "getLastError", "(", ")", ")", ";", "}", "$", "hash", "=", "new", "Hash", "(", "$", "algorithm", ")", ";", "$", "hash", "->", "setValue", "(", "$", "value", ")", ";", "return", "$", "hash", ";", "}" ]
Get the fingerprint from certificate. @param string $algorithm @return Hash
[ "Get", "the", "fingerprint", "from", "certificate", "." ]
9a7faf31492cefe8c8b166ef775a6e2eba04c3ec
https://github.com/blar/openssl/blob/9a7faf31492cefe8c8b166ef775a6e2eba04c3ec/lib/Blar/OpenSSL/Certificate.php#L236-L248
223,977
kalfheim/sanitizer
src/Laravel/SanitizesRequests.php
SanitizesRequests.sanitize
public function sanitize(Request $request, array $ruleset) { $factory = app(Sanitizer::class)->rules($ruleset); return $factory->sanitize($request->all()); }
php
public function sanitize(Request $request, array $ruleset) { $factory = app(Sanitizer::class)->rules($ruleset); return $factory->sanitize($request->all()); }
[ "public", "function", "sanitize", "(", "Request", "$", "request", ",", "array", "$", "ruleset", ")", "{", "$", "factory", "=", "app", "(", "Sanitizer", "::", "class", ")", "->", "rules", "(", "$", "ruleset", ")", ";", "return", "$", "factory", "->", "sanitize", "(", "$", "request", "->", "all", "(", ")", ")", ";", "}" ]
Run a sanitizer on a request object and return the sanitized data. @param \Illuminate\Http\Request $request @param array $ruleset @return array
[ "Run", "a", "sanitizer", "on", "a", "request", "object", "and", "return", "the", "sanitized", "data", "." ]
67aa0df0d1fcdc292d1904ce4e7618232bea964e
https://github.com/kalfheim/sanitizer/blob/67aa0df0d1fcdc292d1904ce4e7618232bea964e/src/Laravel/SanitizesRequests.php#L40-L45
223,978
pattern-lab/plugin-php-reload
src/PatternLab/Reload/PatternLabListener.php
PatternLabListener.addProcess
public function addProcess(ProcessSpawnerEvent $event) { if ((bool)Config::getOption("plugins.reload.enabled")) { // only run this command if watch is going to be used if (Console::findCommand("w|watch") || Console::findCommandOption("with-watch")) { // set-up the command $pathPHP = Console::getPathPHP(); $pathReload = __DIR__."/AutoReloadServer.php"; $command = "exec ".$pathPHP." ".$pathReload; // send the processes on their way $processes = array(); $processes[] = array("command" => $command, "timeout" => null, "idle" => 600, "output" => false); $event->addPluginProcesses($processes); } } }
php
public function addProcess(ProcessSpawnerEvent $event) { if ((bool)Config::getOption("plugins.reload.enabled")) { // only run this command if watch is going to be used if (Console::findCommand("w|watch") || Console::findCommandOption("with-watch")) { // set-up the command $pathPHP = Console::getPathPHP(); $pathReload = __DIR__."/AutoReloadServer.php"; $command = "exec ".$pathPHP." ".$pathReload; // send the processes on their way $processes = array(); $processes[] = array("command" => $command, "timeout" => null, "idle" => 600, "output" => false); $event->addPluginProcesses($processes); } } }
[ "public", "function", "addProcess", "(", "ProcessSpawnerEvent", "$", "event", ")", "{", "if", "(", "(", "bool", ")", "Config", "::", "getOption", "(", "\"plugins.reload.enabled\"", ")", ")", "{", "// only run this command if watch is going to be used", "if", "(", "Console", "::", "findCommand", "(", "\"w|watch\"", ")", "||", "Console", "::", "findCommandOption", "(", "\"with-watch\"", ")", ")", "{", "// set-up the command", "$", "pathPHP", "=", "Console", "::", "getPathPHP", "(", ")", ";", "$", "pathReload", "=", "__DIR__", ".", "\"/AutoReloadServer.php\"", ";", "$", "command", "=", "\"exec \"", ".", "$", "pathPHP", ".", "\" \"", ".", "$", "pathReload", ";", "// send the processes on their way", "$", "processes", "=", "array", "(", ")", ";", "$", "processes", "[", "]", "=", "array", "(", "\"command\"", "=>", "$", "command", ",", "\"timeout\"", "=>", "null", ",", "\"idle\"", "=>", "600", ",", "\"output\"", "=>", "false", ")", ";", "$", "event", "->", "addPluginProcesses", "(", "$", "processes", ")", ";", "}", "}", "}" ]
Add command to initialize the websocket server
[ "Add", "command", "to", "initialize", "the", "websocket", "server" ]
d7e19f0cdfd0d15e8e16a3858140da64e8ade84b
https://github.com/pattern-lab/plugin-php-reload/blob/d7e19f0cdfd0d15e8e16a3858140da64e8ade84b/src/PatternLab/Reload/PatternLabListener.php#L35-L56
223,979
dcarbone/xml-writer-plus
src/XMLWriterPlus.php
XMLWriterPlus.text
public function text($text) { if (is_string($text) || settype($text, 'string') !== false) { return parent::text($this->encodeString($text)); } throw new \InvalidArgumentException(get_class($this) . ':text - Cannot cast passed value to string (did you forget to define a __toString on your object?)'); }
php
public function text($text) { if (is_string($text) || settype($text, 'string') !== false) { return parent::text($this->encodeString($text)); } throw new \InvalidArgumentException(get_class($this) . ':text - Cannot cast passed value to string (did you forget to define a __toString on your object?)'); }
[ "public", "function", "text", "(", "$", "text", ")", "{", "if", "(", "is_string", "(", "$", "text", ")", "||", "settype", "(", "$", "text", ",", "'string'", ")", "!==", "false", ")", "{", "return", "parent", "::", "text", "(", "$", "this", "->", "encodeString", "(", "$", "text", ")", ")", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "get_class", "(", "$", "this", ")", ".", "':text - Cannot cast passed value to string (did you forget to define a __toString on your object?)'", ")", ";", "}" ]
Write Text into Attribute or Element @link http://www.php.net/manual/en/function.xmlwriter-text.php @param string $text Value to write @throws \InvalidArgumentException @return bool
[ "Write", "Text", "into", "Attribute", "or", "Element" ]
2e8bbc30f9f292acae899608bf51a6541144a437
https://github.com/dcarbone/xml-writer-plus/blob/2e8bbc30f9f292acae899608bf51a6541144a437/src/XMLWriterPlus.php#L234-L240
223,980
dcarbone/xml-writer-plus
src/XMLWriterPlus.php
XMLWriterPlus.appendList
public function appendList(array $data, $elementName, $nsPrefix = null, $nsUri = null) { if (null === $nsPrefix) { foreach ($data as $value) { $this->writeElement($elementName, $value); } } else { foreach ($data as $value) { $this->writeElementNS($nsPrefix, $elementName, $nsUri, $value); } } return true; }
php
public function appendList(array $data, $elementName, $nsPrefix = null, $nsUri = null) { if (null === $nsPrefix) { foreach ($data as $value) { $this->writeElement($elementName, $value); } } else { foreach ($data as $value) { $this->writeElementNS($nsPrefix, $elementName, $nsUri, $value); } } return true; }
[ "public", "function", "appendList", "(", "array", "$", "data", ",", "$", "elementName", ",", "$", "nsPrefix", "=", "null", ",", "$", "nsUri", "=", "null", ")", "{", "if", "(", "null", "===", "$", "nsPrefix", ")", "{", "foreach", "(", "$", "data", "as", "$", "value", ")", "{", "$", "this", "->", "writeElement", "(", "$", "elementName", ",", "$", "value", ")", ";", "}", "}", "else", "{", "foreach", "(", "$", "data", "as", "$", "value", ")", "{", "$", "this", "->", "writeElementNS", "(", "$", "nsPrefix", ",", "$", "elementName", ",", "$", "nsUri", ",", "$", "value", ")", ";", "}", "}", "return", "true", ";", "}" ]
Append an integer index array of values to this XML document @param array $data @param string $elementName @param string|null $nsPrefix @param string|null $nsUri @return bool
[ "Append", "an", "integer", "index", "array", "of", "values", "to", "this", "XML", "document" ]
2e8bbc30f9f292acae899608bf51a6541144a437
https://github.com/dcarbone/xml-writer-plus/blob/2e8bbc30f9f292acae899608bf51a6541144a437/src/XMLWriterPlus.php#L334-L347
223,981
dcarbone/xml-writer-plus
src/XMLWriterPlus.php
XMLWriterPlus.appendHash
public function appendHash($data, $_previousKey = null) { foreach ($data as $key => $value) { $this->appendHashData($key, $value, $_previousKey); } return false; }
php
public function appendHash($data, $_previousKey = null) { foreach ($data as $key => $value) { $this->appendHashData($key, $value, $_previousKey); } return false; }
[ "public", "function", "appendHash", "(", "$", "data", ",", "$", "_previousKey", "=", "null", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "appendHashData", "(", "$", "key", ",", "$", "value", ",", "$", "_previousKey", ")", ";", "}", "return", "false", ";", "}" ]
Append an associative array or object to this XML document @param array|object $data @param string|null $_previousKey @return bool
[ "Append", "an", "associative", "array", "or", "object", "to", "this", "XML", "document" ]
2e8bbc30f9f292acae899608bf51a6541144a437
https://github.com/dcarbone/xml-writer-plus/blob/2e8bbc30f9f292acae899608bf51a6541144a437/src/XMLWriterPlus.php#L356-L363
223,982
dcarbone/xml-writer-plus
src/XMLWriterPlus.php
XMLWriterPlus.encodeString
protected function encodeString($string) { // If no encoding value was passed in... if ($this->encoding === null) { return $string; } $detect = mb_detect_encoding($string); // If the current encoding is already the requested encoding if (is_string($detect) && $detect === $this->encoding) { return $string; } // Failed to determine encoding if (is_bool($detect)) { return $string; } // Convert it! return mb_convert_encoding($string, $this->encoding, $detect); }
php
protected function encodeString($string) { // If no encoding value was passed in... if ($this->encoding === null) { return $string; } $detect = mb_detect_encoding($string); // If the current encoding is already the requested encoding if (is_string($detect) && $detect === $this->encoding) { return $string; } // Failed to determine encoding if (is_bool($detect)) { return $string; } // Convert it! return mb_convert_encoding($string, $this->encoding, $detect); }
[ "protected", "function", "encodeString", "(", "$", "string", ")", "{", "// If no encoding value was passed in...", "if", "(", "$", "this", "->", "encoding", "===", "null", ")", "{", "return", "$", "string", ";", "}", "$", "detect", "=", "mb_detect_encoding", "(", "$", "string", ")", ";", "// If the current encoding is already the requested encoding", "if", "(", "is_string", "(", "$", "detect", ")", "&&", "$", "detect", "===", "$", "this", "->", "encoding", ")", "{", "return", "$", "string", ";", "}", "// Failed to determine encoding", "if", "(", "is_bool", "(", "$", "detect", ")", ")", "{", "return", "$", "string", ";", "}", "// Convert it!", "return", "mb_convert_encoding", "(", "$", "string", ",", "$", "this", "->", "encoding", ",", "$", "detect", ")", ";", "}" ]
Apply requested encoding type to string @link http://php.net/manual/en/function.mb-detect-encoding.php @link http://www.php.net/manual/en/function.mb-convert-encoding.php @param string $string un-encoded string @return string
[ "Apply", "requested", "encoding", "type", "to", "string" ]
2e8bbc30f9f292acae899608bf51a6541144a437
https://github.com/dcarbone/xml-writer-plus/blob/2e8bbc30f9f292acae899608bf51a6541144a437/src/XMLWriterPlus.php#L515-L536
223,983
adamlc/address-format
src/Adamlc/AddressFormat/Format.php
Format.setLocale
public function setLocale($locale) { //Check if we have information for this locale $file = __DIR__ . '/i18n/' . $locale . '.json'; if (file_exists($file)) { //Read the locale information from the file $meta = json_decode(file_get_contents($file), true); if (is_array($meta)) { $this->locale = $meta; return true; } else { throw new LocaleParseErrorException('Locale "' . $locale . '" could not be parsed correctly'); } } else { throw new LocaleNotSupportedException('Locale not supported by this library'); } }
php
public function setLocale($locale) { //Check if we have information for this locale $file = __DIR__ . '/i18n/' . $locale . '.json'; if (file_exists($file)) { //Read the locale information from the file $meta = json_decode(file_get_contents($file), true); if (is_array($meta)) { $this->locale = $meta; return true; } else { throw new LocaleParseErrorException('Locale "' . $locale . '" could not be parsed correctly'); } } else { throw new LocaleNotSupportedException('Locale not supported by this library'); } }
[ "public", "function", "setLocale", "(", "$", "locale", ")", "{", "//Check if we have information for this locale", "$", "file", "=", "__DIR__", ".", "'/i18n/'", ".", "$", "locale", ".", "'.json'", ";", "if", "(", "file_exists", "(", "$", "file", ")", ")", "{", "//Read the locale information from the file", "$", "meta", "=", "json_decode", "(", "file_get_contents", "(", "$", "file", ")", ",", "true", ")", ";", "if", "(", "is_array", "(", "$", "meta", ")", ")", "{", "$", "this", "->", "locale", "=", "$", "meta", ";", "return", "true", ";", "}", "else", "{", "throw", "new", "LocaleParseErrorException", "(", "'Locale \"'", ".", "$", "locale", ".", "'\" could not be parsed correctly'", ")", ";", "}", "}", "else", "{", "throw", "new", "LocaleNotSupportedException", "(", "'Locale not supported by this library'", ")", ";", "}", "}" ]
setLocale will set the locale. This is currently a 2 digit ISO country code @access public @param mixed $locale @return boolean
[ "setLocale", "will", "set", "the", "locale", ".", "This", "is", "currently", "a", "2", "digit", "ISO", "country", "code" ]
130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8
https://github.com/adamlc/address-format/blob/130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8/src/Adamlc/AddressFormat/Format.php#L66-L83
223,984
adamlc/address-format
src/Adamlc/AddressFormat/Format.php
Format.formatAddress
public function formatAddress($html = false) { //Check if this locale has a fmt field if (isset($this->locale['fmt'])) { $address_format = $this->locale['fmt']; //Loop through each address part and process it! $formatted_address = $address_format; //Replace the street values foreach ($this->address_map as $key => $value) { $formatted_address = str_replace('%' . $key, $this->input_map[$value], $formatted_address); } //Remove blank lines from the resulting address $formatted_address = preg_replace('((\%n)+)', '%n', $formatted_address); //Replace new lines! if ($html) { $formatted_address = htmlentities($formatted_address, ENT_QUOTES, 'UTF-8', false); $formatted_address = str_replace('%n', "\n" . '<br>', $formatted_address); } else { $formatted_address = trim(str_replace('%n', "\n", $formatted_address)); } return $formatted_address; } else { throw new LocaleMissingFormatException('Locale missing format'); } }
php
public function formatAddress($html = false) { //Check if this locale has a fmt field if (isset($this->locale['fmt'])) { $address_format = $this->locale['fmt']; //Loop through each address part and process it! $formatted_address = $address_format; //Replace the street values foreach ($this->address_map as $key => $value) { $formatted_address = str_replace('%' . $key, $this->input_map[$value], $formatted_address); } //Remove blank lines from the resulting address $formatted_address = preg_replace('((\%n)+)', '%n', $formatted_address); //Replace new lines! if ($html) { $formatted_address = htmlentities($formatted_address, ENT_QUOTES, 'UTF-8', false); $formatted_address = str_replace('%n', "\n" . '<br>', $formatted_address); } else { $formatted_address = trim(str_replace('%n', "\n", $formatted_address)); } return $formatted_address; } else { throw new LocaleMissingFormatException('Locale missing format'); } }
[ "public", "function", "formatAddress", "(", "$", "html", "=", "false", ")", "{", "//Check if this locale has a fmt field", "if", "(", "isset", "(", "$", "this", "->", "locale", "[", "'fmt'", "]", ")", ")", "{", "$", "address_format", "=", "$", "this", "->", "locale", "[", "'fmt'", "]", ";", "//Loop through each address part and process it!", "$", "formatted_address", "=", "$", "address_format", ";", "//Replace the street values", "foreach", "(", "$", "this", "->", "address_map", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "formatted_address", "=", "str_replace", "(", "'%'", ".", "$", "key", ",", "$", "this", "->", "input_map", "[", "$", "value", "]", ",", "$", "formatted_address", ")", ";", "}", "//Remove blank lines from the resulting address", "$", "formatted_address", "=", "preg_replace", "(", "'((\\%n)+)'", ",", "'%n'", ",", "$", "formatted_address", ")", ";", "//Replace new lines!", "if", "(", "$", "html", ")", "{", "$", "formatted_address", "=", "htmlentities", "(", "$", "formatted_address", ",", "ENT_QUOTES", ",", "'UTF-8'", ",", "false", ")", ";", "$", "formatted_address", "=", "str_replace", "(", "'%n'", ",", "\"\\n\"", ".", "'<br>'", ",", "$", "formatted_address", ")", ";", "}", "else", "{", "$", "formatted_address", "=", "trim", "(", "str_replace", "(", "'%n'", ",", "\"\\n\"", ",", "$", "formatted_address", ")", ")", ";", "}", "return", "$", "formatted_address", ";", "}", "else", "{", "throw", "new", "LocaleMissingFormatException", "(", "'Locale missing format'", ")", ";", "}", "}" ]
Return the formatted address, using the locale set. Optionally return HTML or plain text @access public @param bool $html (default: false) @return string $formatted_address
[ "Return", "the", "formatted", "address", "using", "the", "locale", "set", ".", "Optionally", "return", "HTML", "or", "plain", "text" ]
130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8
https://github.com/adamlc/address-format/blob/130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8/src/Adamlc/AddressFormat/Format.php#L92-L122
223,985
adamlc/address-format
src/Adamlc/AddressFormat/Format.php
Format.setAttribute
public function setAttribute($attribute, $value) { //Check this attribute is support if (isset($this->input_map[$attribute])) { $this->input_map[$attribute] = $value; return $value; } else { throw new AttributeInvalidException('Attribute not supported by this library'); } }
php
public function setAttribute($attribute, $value) { //Check this attribute is support if (isset($this->input_map[$attribute])) { $this->input_map[$attribute] = $value; return $value; } else { throw new AttributeInvalidException('Attribute not supported by this library'); } }
[ "public", "function", "setAttribute", "(", "$", "attribute", ",", "$", "value", ")", "{", "//Check this attribute is support", "if", "(", "isset", "(", "$", "this", "->", "input_map", "[", "$", "attribute", "]", ")", ")", "{", "$", "this", "->", "input_map", "[", "$", "attribute", "]", "=", "$", "value", ";", "return", "$", "value", ";", "}", "else", "{", "throw", "new", "AttributeInvalidException", "(", "'Attribute not supported by this library'", ")", ";", "}", "}" ]
Set an address attribute. @access public @param mixed $attribute @param mixed $value @return string $value
[ "Set", "an", "address", "attribute", "." ]
130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8
https://github.com/adamlc/address-format/blob/130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8/src/Adamlc/AddressFormat/Format.php#L132-L142
223,986
adamlc/address-format
src/Adamlc/AddressFormat/Format.php
Format.getAttribute
public function getAttribute($attribute) { //Check this attribute is support if (isset($this->input_map[$attribute])) { return $this->input_map[$attribute]; } else { throw new AttributeInvalidException('Attribute not supported by this library'); } }
php
public function getAttribute($attribute) { //Check this attribute is support if (isset($this->input_map[$attribute])) { return $this->input_map[$attribute]; } else { throw new AttributeInvalidException('Attribute not supported by this library'); } }
[ "public", "function", "getAttribute", "(", "$", "attribute", ")", "{", "//Check this attribute is support", "if", "(", "isset", "(", "$", "this", "->", "input_map", "[", "$", "attribute", "]", ")", ")", "{", "return", "$", "this", "->", "input_map", "[", "$", "attribute", "]", ";", "}", "else", "{", "throw", "new", "AttributeInvalidException", "(", "'Attribute not supported by this library'", ")", ";", "}", "}" ]
Get an address attribute. @access public @param mixed $attribute @return string
[ "Get", "an", "address", "attribute", "." ]
130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8
https://github.com/adamlc/address-format/blob/130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8/src/Adamlc/AddressFormat/Format.php#L151-L159
223,987
adamlc/address-format
src/Adamlc/AddressFormat/Format.php
Format.validAddressPieces
public function validAddressPieces() { $return = array(); if (isset($this->locale['fmt'])) { $address_format_array = explode("%", $this->locale['fmt']); foreach($address_format_array as $key => $value ) { $value = trim($value); if( !empty($value) && isset($this->address_map[$value]) ) { $return[]=$this->address_map[$value]; } } return $return; } else { throw new LocaleMissingFormatException('Locale missing format'); } }
php
public function validAddressPieces() { $return = array(); if (isset($this->locale['fmt'])) { $address_format_array = explode("%", $this->locale['fmt']); foreach($address_format_array as $key => $value ) { $value = trim($value); if( !empty($value) && isset($this->address_map[$value]) ) { $return[]=$this->address_map[$value]; } } return $return; } else { throw new LocaleMissingFormatException('Locale missing format'); } }
[ "public", "function", "validAddressPieces", "(", ")", "{", "$", "return", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "locale", "[", "'fmt'", "]", ")", ")", "{", "$", "address_format_array", "=", "explode", "(", "\"%\"", ",", "$", "this", "->", "locale", "[", "'fmt'", "]", ")", ";", "foreach", "(", "$", "address_format_array", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "value", "=", "trim", "(", "$", "value", ")", ";", "if", "(", "!", "empty", "(", "$", "value", ")", "&&", "isset", "(", "$", "this", "->", "address_map", "[", "$", "value", "]", ")", ")", "{", "$", "return", "[", "]", "=", "$", "this", "->", "address_map", "[", "$", "value", "]", ";", "}", "}", "return", "$", "return", ";", "}", "else", "{", "throw", "new", "LocaleMissingFormatException", "(", "'Locale missing format'", ")", ";", "}", "}" ]
Return the valid pieces @access public @return array
[ "Return", "the", "valid", "pieces" ]
130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8
https://github.com/adamlc/address-format/blob/130d8276d5cd8bf5cc046e00ccc4c59a3a8b8ac8/src/Adamlc/AddressFormat/Format.php#L202-L221
223,988
secrethash/trickster
src/Trickster.php
Trickster.truncator
public function truncator($text, $number, $suffix = ' ...see more') { if (!empty($text) && intval($number)) { if(strlen($text) > $number) { return mb_substr($text, 0, mb_strpos($text, ' ', $number, 'UTF-8'), 'UTF-8') . $suffix; } return $text; } return false; }
php
public function truncator($text, $number, $suffix = ' ...see more') { if (!empty($text) && intval($number)) { if(strlen($text) > $number) { return mb_substr($text, 0, mb_strpos($text, ' ', $number, 'UTF-8'), 'UTF-8') . $suffix; } return $text; } return false; }
[ "public", "function", "truncator", "(", "$", "text", ",", "$", "number", ",", "$", "suffix", "=", "' ...see more'", ")", "{", "if", "(", "!", "empty", "(", "$", "text", ")", "&&", "intval", "(", "$", "number", ")", ")", "{", "if", "(", "strlen", "(", "$", "text", ")", ">", "$", "number", ")", "{", "return", "mb_substr", "(", "$", "text", ",", "0", ",", "mb_strpos", "(", "$", "text", ",", "' '", ",", "$", "number", ",", "'UTF-8'", ")", ",", "'UTF-8'", ")", ".", "$", "suffix", ";", "}", "return", "$", "text", ";", "}", "return", "false", ";", "}" ]
Yo can truncate text and specify number of characters you want to show @param string $text Input the text that you want to cut @param int $number Number of characters you want to show @param string $suffix What do you want to show at the end @return mixed Return truncated text with suffix
[ "Yo", "can", "truncate", "text", "and", "specify", "number", "of", "characters", "you", "want", "to", "show" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L124-L133
223,989
secrethash/trickster
src/Trickster.php
Trickster.social
public function social($network, $url) { if (!empty($network) && !empty($url)) { if ($network == 'facebook') { $url_data = sprintf($this->_facebookUrl, $url); } switch ($network) { case 'facebook': $result = $this->_socialCurl($url_data); if (!$result[$url]['share']) { return '0'; } else { $data = array( 'comments'=>$result[$url]['share']['comment_count'], 'shares'=>$result[$url]['share']['share_count'] ); return (object)$data; } // print_r($result); // Classic Debugger :P break; default: return false; break; } } return false; }
php
public function social($network, $url) { if (!empty($network) && !empty($url)) { if ($network == 'facebook') { $url_data = sprintf($this->_facebookUrl, $url); } switch ($network) { case 'facebook': $result = $this->_socialCurl($url_data); if (!$result[$url]['share']) { return '0'; } else { $data = array( 'comments'=>$result[$url]['share']['comment_count'], 'shares'=>$result[$url]['share']['share_count'] ); return (object)$data; } // print_r($result); // Classic Debugger :P break; default: return false; break; } } return false; }
[ "public", "function", "social", "(", "$", "network", ",", "$", "url", ")", "{", "if", "(", "!", "empty", "(", "$", "network", ")", "&&", "!", "empty", "(", "$", "url", ")", ")", "{", "if", "(", "$", "network", "==", "'facebook'", ")", "{", "$", "url_data", "=", "sprintf", "(", "$", "this", "->", "_facebookUrl", ",", "$", "url", ")", ";", "}", "switch", "(", "$", "network", ")", "{", "case", "'facebook'", ":", "$", "result", "=", "$", "this", "->", "_socialCurl", "(", "$", "url_data", ")", ";", "if", "(", "!", "$", "result", "[", "$", "url", "]", "[", "'share'", "]", ")", "{", "return", "'0'", ";", "}", "else", "{", "$", "data", "=", "array", "(", "'comments'", "=>", "$", "result", "[", "$", "url", "]", "[", "'share'", "]", "[", "'comment_count'", "]", ",", "'shares'", "=>", "$", "result", "[", "$", "url", "]", "[", "'share'", "]", "[", "'share_count'", "]", ")", ";", "return", "(", "object", ")", "$", "data", ";", "}", "// print_r($result); // Classic Debugger :P", "break", ";", "default", ":", "return", "false", ";", "break", ";", "}", "}", "return", "false", ";", "}" ]
This function return number of shares or tweets of the specified page @param string $network Social network, facebook or twitter @param string $url Url for get shares or tweets @return mixed Return number of shares or tweets
[ "This", "function", "return", "number", "of", "shares", "or", "tweets", "of", "the", "specified", "page" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L221-L254
223,990
secrethash/trickster
src/Trickster.php
Trickster.shortenUrl
public function shortenUrl($url, $provider) { if (!empty($url) && !empty($provider)) { if ($provider == 'tinyurl') { $url_data = sprintf($this->_tinyUrlShortApiUrl, $url); } elseif ($provider == 'google') { $url_data = sprintf('%s/url', $this->_googleShortApiUrl); } switch ($provider) { case 'tinyurl': $ch = curl_init($url_data); $timeout = 5; curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $result = curl_exec($ch); curl_close($ch); return $result; break; case 'google': $ch = curl_init($url_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $requestData = array( 'longUrl' => $url ); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData)); $result = json_decode(curl_exec($ch), true); curl_close($ch); return $result['id']; break; default: return false; break; } } return false; }
php
public function shortenUrl($url, $provider) { if (!empty($url) && !empty($provider)) { if ($provider == 'tinyurl') { $url_data = sprintf($this->_tinyUrlShortApiUrl, $url); } elseif ($provider == 'google') { $url_data = sprintf('%s/url', $this->_googleShortApiUrl); } switch ($provider) { case 'tinyurl': $ch = curl_init($url_data); $timeout = 5; curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $result = curl_exec($ch); curl_close($ch); return $result; break; case 'google': $ch = curl_init($url_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $requestData = array( 'longUrl' => $url ); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData)); $result = json_decode(curl_exec($ch), true); curl_close($ch); return $result['id']; break; default: return false; break; } } return false; }
[ "public", "function", "shortenUrl", "(", "$", "url", ",", "$", "provider", ")", "{", "if", "(", "!", "empty", "(", "$", "url", ")", "&&", "!", "empty", "(", "$", "provider", ")", ")", "{", "if", "(", "$", "provider", "==", "'tinyurl'", ")", "{", "$", "url_data", "=", "sprintf", "(", "$", "this", "->", "_tinyUrlShortApiUrl", ",", "$", "url", ")", ";", "}", "elseif", "(", "$", "provider", "==", "'google'", ")", "{", "$", "url_data", "=", "sprintf", "(", "'%s/url'", ",", "$", "this", "->", "_googleShortApiUrl", ")", ";", "}", "switch", "(", "$", "provider", ")", "{", "case", "'tinyurl'", ":", "$", "ch", "=", "curl_init", "(", "$", "url_data", ")", ";", "$", "timeout", "=", "5", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CONNECTTIMEOUT", ",", "$", "timeout", ")", ";", "$", "result", "=", "curl_exec", "(", "$", "ch", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "return", "$", "result", ";", "break", ";", "case", "'google'", ":", "$", "ch", "=", "curl_init", "(", "$", "url_data", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "$", "requestData", "=", "array", "(", "'longUrl'", "=>", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "array", "(", "'Content-type: application/json'", ")", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "json_encode", "(", "$", "requestData", ")", ")", ";", "$", "result", "=", "json_decode", "(", "curl_exec", "(", "$", "ch", ")", ",", "true", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "return", "$", "result", "[", "'id'", "]", ";", "break", ";", "default", ":", "return", "false", ";", "break", ";", "}", "}", "return", "false", ";", "}" ]
If you want to generate a shorten url simply use this function @param string $url Used for shorten @param string $provider Used two providers, tinyurl and google @return mixed Return url shortened
[ "If", "you", "want", "to", "generate", "a", "shorten", "url", "simply", "use", "this", "function" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L262-L305
223,991
secrethash/trickster
src/Trickster.php
Trickster.youtube
public function youtube($url, $width = 400, $height = 250, $theme = 'dark') { if (!empty($url) && intval($width) && intval($height) && !empty($theme)) { preg_match('/(?<=v(\=|\/))([-a-zA-Z0-9_]+)|(?<=youtu\.be\/)([-a-zA-Z0-9_]+)/', $url, $v); return "<iframe src=\"https://www.youtube.com/embed/{$v[0]}?theme={$theme}&amp;iv_load_policy=3&amp;wmode=transparent\" allowfullscreen=\"\" frameborder=\"0\" width=\"{$width}\" height=\"{$height}\" ></iframe> "; } return false; }
php
public function youtube($url, $width = 400, $height = 250, $theme = 'dark') { if (!empty($url) && intval($width) && intval($height) && !empty($theme)) { preg_match('/(?<=v(\=|\/))([-a-zA-Z0-9_]+)|(?<=youtu\.be\/)([-a-zA-Z0-9_]+)/', $url, $v); return "<iframe src=\"https://www.youtube.com/embed/{$v[0]}?theme={$theme}&amp;iv_load_policy=3&amp;wmode=transparent\" allowfullscreen=\"\" frameborder=\"0\" width=\"{$width}\" height=\"{$height}\" ></iframe> "; } return false; }
[ "public", "function", "youtube", "(", "$", "url", ",", "$", "width", "=", "400", ",", "$", "height", "=", "250", ",", "$", "theme", "=", "'dark'", ")", "{", "if", "(", "!", "empty", "(", "$", "url", ")", "&&", "intval", "(", "$", "width", ")", "&&", "intval", "(", "$", "height", ")", "&&", "!", "empty", "(", "$", "theme", ")", ")", "{", "preg_match", "(", "'/(?<=v(\\=|\\/))([-a-zA-Z0-9_]+)|(?<=youtu\\.be\\/)([-a-zA-Z0-9_]+)/'", ",", "$", "url", ",", "$", "v", ")", ";", "return", "\"<iframe src=\\\"https://www.youtube.com/embed/{$v[0]}?theme={$theme}&amp;iv_load_policy=3&amp;wmode=transparent\\\"\n allowfullscreen=\\\"\\\" frameborder=\\\"0\\\" width=\\\"{$width}\\\" height=\\\"{$height}\\\" ></iframe>\n \"", ";", "}", "return", "false", ";", "}" ]
This function replaces all youtube link into videos @param string $url The url to the video @param integer $width The width of the player in pixels @param integer $height The height of the player in pixels @param string $theme Color of the player "dark" or "light" @return mixed Return youtube video player
[ "This", "function", "replaces", "all", "youtube", "link", "into", "videos" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L315-L325
223,992
secrethash/trickster
src/Trickster.php
Trickster.vimeo
public function vimeo($url, $width = 400, $height = 250) { if (!empty($url) && intval($width) && intval($height)) { preg_match('(\d+)', $url, $id); return "<iframe src=\"https://player.vimeo.com/video/$id[0]?title=0&amp;byline=0&amp;portrait=0\" webkitallowfullscreen=\"\" mozallowfullscreen=\"\" allowfullscreen=\"\" frameborder=\"0\" width=\"{$width}\" height=\"{$height}\"></iframe> "; } return false; }
php
public function vimeo($url, $width = 400, $height = 250) { if (!empty($url) && intval($width) && intval($height)) { preg_match('(\d+)', $url, $id); return "<iframe src=\"https://player.vimeo.com/video/$id[0]?title=0&amp;byline=0&amp;portrait=0\" webkitallowfullscreen=\"\" mozallowfullscreen=\"\" allowfullscreen=\"\" frameborder=\"0\" width=\"{$width}\" height=\"{$height}\"></iframe> "; } return false; }
[ "public", "function", "vimeo", "(", "$", "url", ",", "$", "width", "=", "400", ",", "$", "height", "=", "250", ")", "{", "if", "(", "!", "empty", "(", "$", "url", ")", "&&", "intval", "(", "$", "width", ")", "&&", "intval", "(", "$", "height", ")", ")", "{", "preg_match", "(", "'(\\d+)'", ",", "$", "url", ",", "$", "id", ")", ";", "return", "\"<iframe src=\\\"https://player.vimeo.com/video/$id[0]?title=0&amp;byline=0&amp;portrait=0\\\"\n webkitallowfullscreen=\\\"\\\" mozallowfullscreen=\\\"\\\" allowfullscreen=\\\"\\\" frameborder=\\\"0\\\"\n width=\\\"{$width}\\\" height=\\\"{$height}\\\"></iframe>\n \"", ";", "}", "return", "false", ";", "}" ]
This function replaces all vimeo link into videos @param string $url The url to the video @param integer $width The width of the player in pixels @param integer $height The height of the player in pixels @return mixed Return vimeo video player
[ "This", "function", "replaces", "all", "vimeo", "link", "into", "videos" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L334-L345
223,993
secrethash/trickster
src/Trickster.php
Trickster.encryptString
public function encryptString($algo, $string, $key = null) { if (!empty($algo) && !empty($string)) { if ($key == null) { $ctx = hash_init($algo); } else { $ctx = hash_init($algo, HASH_HMAC, $key); hash_update($ctx, $string); } return hash_final($ctx); } return false; }
php
public function encryptString($algo, $string, $key = null) { if (!empty($algo) && !empty($string)) { if ($key == null) { $ctx = hash_init($algo); } else { $ctx = hash_init($algo, HASH_HMAC, $key); hash_update($ctx, $string); } return hash_final($ctx); } return false; }
[ "public", "function", "encryptString", "(", "$", "algo", ",", "$", "string", ",", "$", "key", "=", "null", ")", "{", "if", "(", "!", "empty", "(", "$", "algo", ")", "&&", "!", "empty", "(", "$", "string", ")", ")", "{", "if", "(", "$", "key", "==", "null", ")", "{", "$", "ctx", "=", "hash_init", "(", "$", "algo", ")", ";", "}", "else", "{", "$", "ctx", "=", "hash_init", "(", "$", "algo", ",", "HASH_HMAC", ",", "$", "key", ")", ";", "hash_update", "(", "$", "ctx", ",", "$", "string", ")", ";", "}", "return", "hash_final", "(", "$", "ctx", ")", ";", "}", "return", "false", ";", "}" ]
Create an encryption string with a special algorithm and key @param string $algo The algorithm to use @param string $string The string to encrypt @param string $key A salt to apply to the encryption @return string Return encrypted key
[ "Create", "an", "encryption", "string", "with", "a", "special", "algorithm", "and", "key" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L354-L366
223,994
secrethash/trickster
src/Trickster.php
Trickster.bbcode
public function bbcode($string) { if (!empty($string)) { $search = array( '@\[(?i)b\](.*?)\[/(?i)b\]@si', '@\[(?i)i\](.*?)\[/(?i)i\]@si', '@\[(?i)u\](.*?)\[/(?i)u\]@si', '@\[(?i)img=(.*?)\](.*?)\[/(?i)img\]@si', '@\[(?i)youtube\](.*?)\[/(?i)youtube\]@si', '@\[(?i)vimeo\](.*?)\[/(?i)vimeo\]@si', '@\[(?i)p\](.*?)\[/(?i)p\]@si', '@\[(?i)br/\]@si', '@\[(?i)url=(.*?)\](.*?)\[/(?i)url\]@si', ); $replace = array( '<b>\\1</b>', '<i>\\1</i>', '<u>\\1</u>', '<img src="\\1" alt="\\2" />', '<iframe width="400" height="250" src="https://www.youtube.com/embed/\\1?theme=dark&iv_load_policy=3&wmode=transparent" frameborder="0" allowfullscreen></iframe>', '<iframe src="https://player.vimeo.com/video/\\1?title=0&amp;byline=0&amp;portrait=0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" frameborder="0" width="400" height="250"></iframe>', '<p>\\1</p>', '<br/>', '<a href="\\1">\\2</a>' ); return preg_replace($search , $replace, $string); } return false; }
php
public function bbcode($string) { if (!empty($string)) { $search = array( '@\[(?i)b\](.*?)\[/(?i)b\]@si', '@\[(?i)i\](.*?)\[/(?i)i\]@si', '@\[(?i)u\](.*?)\[/(?i)u\]@si', '@\[(?i)img=(.*?)\](.*?)\[/(?i)img\]@si', '@\[(?i)youtube\](.*?)\[/(?i)youtube\]@si', '@\[(?i)vimeo\](.*?)\[/(?i)vimeo\]@si', '@\[(?i)p\](.*?)\[/(?i)p\]@si', '@\[(?i)br/\]@si', '@\[(?i)url=(.*?)\](.*?)\[/(?i)url\]@si', ); $replace = array( '<b>\\1</b>', '<i>\\1</i>', '<u>\\1</u>', '<img src="\\1" alt="\\2" />', '<iframe width="400" height="250" src="https://www.youtube.com/embed/\\1?theme=dark&iv_load_policy=3&wmode=transparent" frameborder="0" allowfullscreen></iframe>', '<iframe src="https://player.vimeo.com/video/\\1?title=0&amp;byline=0&amp;portrait=0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" frameborder="0" width="400" height="250"></iframe>', '<p>\\1</p>', '<br/>', '<a href="\\1">\\2</a>' ); return preg_replace($search , $replace, $string); } return false; }
[ "public", "function", "bbcode", "(", "$", "string", ")", "{", "if", "(", "!", "empty", "(", "$", "string", ")", ")", "{", "$", "search", "=", "array", "(", "'@\\[(?i)b\\](.*?)\\[/(?i)b\\]@si'", ",", "'@\\[(?i)i\\](.*?)\\[/(?i)i\\]@si'", ",", "'@\\[(?i)u\\](.*?)\\[/(?i)u\\]@si'", ",", "'@\\[(?i)img=(.*?)\\](.*?)\\[/(?i)img\\]@si'", ",", "'@\\[(?i)youtube\\](.*?)\\[/(?i)youtube\\]@si'", ",", "'@\\[(?i)vimeo\\](.*?)\\[/(?i)vimeo\\]@si'", ",", "'@\\[(?i)p\\](.*?)\\[/(?i)p\\]@si'", ",", "'@\\[(?i)br/\\]@si'", ",", "'@\\[(?i)url=(.*?)\\](.*?)\\[/(?i)url\\]@si'", ",", ")", ";", "$", "replace", "=", "array", "(", "'<b>\\\\1</b>'", ",", "'<i>\\\\1</i>'", ",", "'<u>\\\\1</u>'", ",", "'<img src=\"\\\\1\" alt=\"\\\\2\" />'", ",", "'<iframe width=\"400\" height=\"250\" src=\"https://www.youtube.com/embed/\\\\1?theme=dark&iv_load_policy=3&wmode=transparent\" frameborder=\"0\" allowfullscreen></iframe>'", ",", "'<iframe src=\"https://player.vimeo.com/video/\\\\1?title=0&amp;byline=0&amp;portrait=0\" webkitallowfullscreen=\"\" mozallowfullscreen=\"\" allowfullscreen=\"\" frameborder=\"0\" width=\"400\" height=\"250\"></iframe>'", ",", "'<p>\\\\1</p>'", ",", "'<br/>'", ",", "'<a href=\"\\\\1\">\\\\2</a>'", ")", ";", "return", "preg_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "string", ")", ";", "}", "return", "false", ";", "}" ]
This function converts the following bbcodes into html @param string $string BBcodes you can to converts @return mixed Return html
[ "This", "function", "converts", "the", "following", "bbcodes", "into", "html" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L401-L430
223,995
secrethash/trickster
src/Trickster.php
Trickster.clean
public function clean($string) { if (!empty($string)) { $string = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $string); $string = htmlspecialchars(strip_tags($string, $this->_allowableTags)); $string = str_replace('href=', 'rel="nofollow" href=', $string); return $string; } return false; }
php
public function clean($string) { if (!empty($string)) { $string = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $string); $string = htmlspecialchars(strip_tags($string, $this->_allowableTags)); $string = str_replace('href=', 'rel="nofollow" href=', $string); return $string; } return false; }
[ "public", "function", "clean", "(", "$", "string", ")", "{", "if", "(", "!", "empty", "(", "$", "string", ")", ")", "{", "$", "string", "=", "preg_replace", "(", "'#<script(.*?)>(.*?)</script>#is'", ",", "''", ",", "$", "string", ")", ";", "$", "string", "=", "htmlspecialchars", "(", "strip_tags", "(", "$", "string", ",", "$", "this", "->", "_allowableTags", ")", ")", ";", "$", "string", "=", "str_replace", "(", "'href='", ",", "'rel=\"nofollow\" href='", ",", "$", "string", ")", ";", "return", "$", "string", ";", "}", "return", "false", ";", "}" ]
This function clean any text by removing unwanted tags @param string $string Text for removing unwanted tags @return mixed Return cleaned text
[ "This", "function", "clean", "any", "text", "by", "removing", "unwanted", "tags" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L450-L460
223,996
secrethash/trickster
src/Trickster.php
Trickster.wiki
public function wiki($keyword) { if (!empty($keyword)) { $ch = curl_init(sprintf($this->_wikiApiUrl, $keyword)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); $error = curl_errno($ch); curl_close($ch); // $xml = simplexml_load_string($result); // if ((string)$xml->Section->Item->Description) { // return array( // (string)$xml->Section->Item->Text, // (string)$xml->Section->Item->Description, // (string)$xml->Section->Item->Url // ); echo $result; if ($result) { $json = json_decode($result); if ($json->description) { return array($json->Text, $json->Description, $json->Url); } } else { echo $error; } return false; } return false; }
php
public function wiki($keyword) { if (!empty($keyword)) { $ch = curl_init(sprintf($this->_wikiApiUrl, $keyword)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); $error = curl_errno($ch); curl_close($ch); // $xml = simplexml_load_string($result); // if ((string)$xml->Section->Item->Description) { // return array( // (string)$xml->Section->Item->Text, // (string)$xml->Section->Item->Description, // (string)$xml->Section->Item->Url // ); echo $result; if ($result) { $json = json_decode($result); if ($json->description) { return array($json->Text, $json->Description, $json->Url); } } else { echo $error; } return false; } return false; }
[ "public", "function", "wiki", "(", "$", "keyword", ")", "{", "if", "(", "!", "empty", "(", "$", "keyword", ")", ")", "{", "$", "ch", "=", "curl_init", "(", "sprintf", "(", "$", "this", "->", "_wikiApiUrl", ",", "$", "keyword", ")", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "$", "result", "=", "curl_exec", "(", "$", "ch", ")", ";", "$", "error", "=", "curl_errno", "(", "$", "ch", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "// $xml = simplexml_load_string($result);", "// if ((string)$xml->Section->Item->Description) {", "// return array(", "// (string)$xml->Section->Item->Text,", "// (string)$xml->Section->Item->Description,", "// (string)$xml->Section->Item->Url", "// );", "echo", "$", "result", ";", "if", "(", "$", "result", ")", "{", "$", "json", "=", "json_decode", "(", "$", "result", ")", ";", "if", "(", "$", "json", "->", "description", ")", "{", "return", "array", "(", "$", "json", "->", "Text", ",", "$", "json", "->", "Description", ",", "$", "json", "->", "Url", ")", ";", "}", "}", "else", "{", "echo", "$", "error", ";", "}", "return", "false", ";", "}", "return", "false", ";", "}" ]
Get wikipedia definition @param string $keyword Keyword for get definition @return mixed Return array with description and url
[ "Get", "wikipedia", "definition" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L467-L497
223,997
secrethash/trickster
src/Trickster.php
Trickster.suggest
public function suggest($keyword) { if (!empty($keyword)) { $ch = curl_init(sprintf($this->_googleSuggestApiUrl, $keyword)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/json')); $result = json_decode(curl_exec($ch), true); curl_close($ch); return $result[1]; } return false; }
php
public function suggest($keyword) { if (!empty($keyword)) { $ch = curl_init(sprintf($this->_googleSuggestApiUrl, $keyword)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/json')); $result = json_decode(curl_exec($ch), true); curl_close($ch); return $result[1]; } return false; }
[ "public", "function", "suggest", "(", "$", "keyword", ")", "{", "if", "(", "!", "empty", "(", "$", "keyword", ")", ")", "{", "$", "ch", "=", "curl_init", "(", "sprintf", "(", "$", "this", "->", "_googleSuggestApiUrl", ",", "$", "keyword", ")", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "array", "(", "'Content-Type: text/json'", ")", ")", ";", "$", "result", "=", "json_decode", "(", "curl_exec", "(", "$", "ch", ")", ",", "true", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "return", "$", "result", "[", "1", "]", ";", "}", "return", "false", ";", "}" ]
Get google suggest for keywords @param string $keyword Keyword for get suggest @return mixed Return array with suggest data
[ "Get", "google", "suggest", "for", "keywords" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L504-L517
223,998
secrethash/trickster
src/Trickster.php
Trickster.ip
public function ip() { if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && ! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') > 0) { $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']); return trim($addr[0]); } else { return $_SERVER['HTTP_X_FORWARDED_FOR']; } } else { return $_SERVER['REMOTE_ADDR']; } }
php
public function ip() { if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && ! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') > 0) { $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']); return trim($addr[0]); } else { return $_SERVER['HTTP_X_FORWARDED_FOR']; } } else { return $_SERVER['REMOTE_ADDR']; } }
[ "public", "function", "ip", "(", ")", "{", "if", "(", "array_key_exists", "(", "'HTTP_X_FORWARDED_FOR'", ",", "$", "_SERVER", ")", "&&", "!", "empty", "(", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_FOR'", "]", ")", ")", "{", "if", "(", "strpos", "(", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_FOR'", "]", ",", "','", ")", ">", "0", ")", "{", "$", "addr", "=", "explode", "(", "\",\"", ",", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_FOR'", "]", ")", ";", "return", "trim", "(", "$", "addr", "[", "0", "]", ")", ";", "}", "else", "{", "return", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_FOR'", "]", ";", "}", "}", "else", "{", "return", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ";", "}", "}" ]
This function get real ip address @return int return ip
[ "This", "function", "get", "real", "ip", "address" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L523-L535
223,999
secrethash/trickster
src/Trickster.php
Trickster.getVideoInfo
public function getVideoInfo($url) { if (!empty($url)) { if (strpos($url, 'youtube')) { preg_match('/(?<=v(\=|\/))([-a-zA-Z0-9_]+)|(?<=youtu\.be\/)([-a-zA-Z0-9_]+)/', $url, $v); $provider = 'youtube'; $url_data = sprintf($this->_youtubeVideoApi, $v[0]); } elseif (strpos($url, 'vimeo')) { preg_match('(\d+)', $url, $id); $provider = 'vimeo'; $url_data = sprintf($this->_vimeoVideoApi, $id[0]); } switch ($provider) { case 'youtube': $ch = curl_init($url_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/json')); $result = json_decode(curl_exec($ch), true); curl_close($ch); return array( 'title' => $result['entry']['title']['$t'], 'description' => $result['entry']['media$group']['media$description']['$t'], 'thumbnail' => $result['entry']['media$group']['media$thumbnail'][0]['url'], 'duration' => $result['entry']['media$group']['media$content'][0]['duration'], 'upload_date' => $result['entry']['media$group']['yt$uploaded']['$t'], ); break; case 'vimeo': $ch = curl_init($url_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/json')); $result = json_decode(curl_exec($ch), true); curl_close($ch); return array( 'title' => $result[0]['title'], 'description' => $result[0]['description'], 'thumbnail' => $result[0]['thumbnail_small'], 'duration' => $result[0]['duration'], 'upload_date' => $result[0]['upload_date'] ); break; default: return false; break; } } return false; }
php
public function getVideoInfo($url) { if (!empty($url)) { if (strpos($url, 'youtube')) { preg_match('/(?<=v(\=|\/))([-a-zA-Z0-9_]+)|(?<=youtu\.be\/)([-a-zA-Z0-9_]+)/', $url, $v); $provider = 'youtube'; $url_data = sprintf($this->_youtubeVideoApi, $v[0]); } elseif (strpos($url, 'vimeo')) { preg_match('(\d+)', $url, $id); $provider = 'vimeo'; $url_data = sprintf($this->_vimeoVideoApi, $id[0]); } switch ($provider) { case 'youtube': $ch = curl_init($url_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/json')); $result = json_decode(curl_exec($ch), true); curl_close($ch); return array( 'title' => $result['entry']['title']['$t'], 'description' => $result['entry']['media$group']['media$description']['$t'], 'thumbnail' => $result['entry']['media$group']['media$thumbnail'][0]['url'], 'duration' => $result['entry']['media$group']['media$content'][0]['duration'], 'upload_date' => $result['entry']['media$group']['yt$uploaded']['$t'], ); break; case 'vimeo': $ch = curl_init($url_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/json')); $result = json_decode(curl_exec($ch), true); curl_close($ch); return array( 'title' => $result[0]['title'], 'description' => $result[0]['description'], 'thumbnail' => $result[0]['thumbnail_small'], 'duration' => $result[0]['duration'], 'upload_date' => $result[0]['upload_date'] ); break; default: return false; break; } } return false; }
[ "public", "function", "getVideoInfo", "(", "$", "url", ")", "{", "if", "(", "!", "empty", "(", "$", "url", ")", ")", "{", "if", "(", "strpos", "(", "$", "url", ",", "'youtube'", ")", ")", "{", "preg_match", "(", "'/(?<=v(\\=|\\/))([-a-zA-Z0-9_]+)|(?<=youtu\\.be\\/)([-a-zA-Z0-9_]+)/'", ",", "$", "url", ",", "$", "v", ")", ";", "$", "provider", "=", "'youtube'", ";", "$", "url_data", "=", "sprintf", "(", "$", "this", "->", "_youtubeVideoApi", ",", "$", "v", "[", "0", "]", ")", ";", "}", "elseif", "(", "strpos", "(", "$", "url", ",", "'vimeo'", ")", ")", "{", "preg_match", "(", "'(\\d+)'", ",", "$", "url", ",", "$", "id", ")", ";", "$", "provider", "=", "'vimeo'", ";", "$", "url_data", "=", "sprintf", "(", "$", "this", "->", "_vimeoVideoApi", ",", "$", "id", "[", "0", "]", ")", ";", "}", "switch", "(", "$", "provider", ")", "{", "case", "'youtube'", ":", "$", "ch", "=", "curl_init", "(", "$", "url_data", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "array", "(", "'Content-Type: text/json'", ")", ")", ";", "$", "result", "=", "json_decode", "(", "curl_exec", "(", "$", "ch", ")", ",", "true", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "return", "array", "(", "'title'", "=>", "$", "result", "[", "'entry'", "]", "[", "'title'", "]", "[", "'$t'", "]", ",", "'description'", "=>", "$", "result", "[", "'entry'", "]", "[", "'media$group'", "]", "[", "'media$description'", "]", "[", "'$t'", "]", ",", "'thumbnail'", "=>", "$", "result", "[", "'entry'", "]", "[", "'media$group'", "]", "[", "'media$thumbnail'", "]", "[", "0", "]", "[", "'url'", "]", ",", "'duration'", "=>", "$", "result", "[", "'entry'", "]", "[", "'media$group'", "]", "[", "'media$content'", "]", "[", "0", "]", "[", "'duration'", "]", ",", "'upload_date'", "=>", "$", "result", "[", "'entry'", "]", "[", "'media$group'", "]", "[", "'yt$uploaded'", "]", "[", "'$t'", "]", ",", ")", ";", "break", ";", "case", "'vimeo'", ":", "$", "ch", "=", "curl_init", "(", "$", "url_data", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "array", "(", "'Content-Type: text/json'", ")", ")", ";", "$", "result", "=", "json_decode", "(", "curl_exec", "(", "$", "ch", ")", ",", "true", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "return", "array", "(", "'title'", "=>", "$", "result", "[", "0", "]", "[", "'title'", "]", ",", "'description'", "=>", "$", "result", "[", "0", "]", "[", "'description'", "]", ",", "'thumbnail'", "=>", "$", "result", "[", "0", "]", "[", "'thumbnail_small'", "]", ",", "'duration'", "=>", "$", "result", "[", "0", "]", "[", "'duration'", "]", ",", "'upload_date'", "=>", "$", "result", "[", "0", "]", "[", "'upload_date'", "]", ")", ";", "break", ";", "default", ":", "return", "false", ";", "break", ";", "}", "}", "return", "false", ";", "}" ]
Get video info from youtube and vimeo @param string $url Url for video info, youtube or vimeo @return mixed Return array with video information
[ "Get", "video", "info", "from", "youtube", "and", "vimeo" ]
8105dc7c028bc9b56988a339a4422c19e2185d83
https://github.com/secrethash/trickster/blob/8105dc7c028bc9b56988a339a4422c19e2185d83/src/Trickster.php#L542-L594