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
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.httpVersion
public function httpVersion($version) { if(false === defined($version)) { return trigger_error(sprintf('Argument 1 passed to %s() is not a valid HTTP protocol version', __METHOD__), E_USER_ERROR); } $this -> options[CURLOPT_HTTP_VERSION] = constant($version); return $this; }
php
public function httpVersion($version) { if(false === defined($version)) { return trigger_error(sprintf('Argument 1 passed to %s() is not a valid HTTP protocol version', __METHOD__), E_USER_ERROR); } $this -> options[CURLOPT_HTTP_VERSION] = constant($version); return $this; }
[ "public", "function", "httpVersion", "(", "$", "version", ")", "{", "if", "(", "false", "===", "defined", "(", "$", "version", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() is not a valid HTTP protocol version'", ",", "__METHOD__", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "options", "[", "CURLOPT_HTTP_VERSION", "]", "=", "constant", "(", "$", "version", ")", ";", "return", "$", "this", ";", "}" ]
Set the HTTP version protocol @param int $version @return sFire\HTTP\Client
[ "Set", "the", "HTTP", "version", "protocol" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L461-L470
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.addCookie
public function addCookie($key, $value) { if(false === is_string($key)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($key)), E_USER_ERROR); } if(false === is_string($value)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($value)), E_USER_ERROR); } $this -> cookies[] = sprintf('%s=%s', $key, $value); return $this; }
php
public function addCookie($key, $value) { if(false === is_string($key)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($key)), E_USER_ERROR); } if(false === is_string($value)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($value)), E_USER_ERROR); } $this -> cookies[] = sprintf('%s=%s', $key, $value); return $this; }
[ "public", "function", "addCookie", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "key", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "key", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "is_string", "(", "$", "value", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 2 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "value", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "cookies", "[", "]", "=", "sprintf", "(", "'%s=%s'", ",", "$", "key", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Add a cookie to the request @param string $key @param string $value @return sFire\HTTP\Client
[ "Add", "a", "cookie", "to", "the", "request" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L501-L514
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.formatUrl
private function formatUrl() { $jar = []; $query = $this -> url -> getQuery(); if(null !== $query) { $jar[] = $query; } $query = ''; if(count($this -> params) > 0 || count($jar) > 0) { if($this -> method === 'get') { foreach($this -> params as $param) { $key = $param -> encode ? urlencode($param -> key) : $param -> key; $value = $param -> encode ? urlencode($param -> value) : $param -> value; $jar[] = sprintf('%s=%s', $key, $value); } } $query = '?' . implode('&', $jar); } return $this -> url -> generate(URLParser :: UNTIL_PATH) . $query; }
php
private function formatUrl() { $jar = []; $query = $this -> url -> getQuery(); if(null !== $query) { $jar[] = $query; } $query = ''; if(count($this -> params) > 0 || count($jar) > 0) { if($this -> method === 'get') { foreach($this -> params as $param) { $key = $param -> encode ? urlencode($param -> key) : $param -> key; $value = $param -> encode ? urlencode($param -> value) : $param -> value; $jar[] = sprintf('%s=%s', $key, $value); } } $query = '?' . implode('&', $jar); } return $this -> url -> generate(URLParser :: UNTIL_PATH) . $query; }
[ "private", "function", "formatUrl", "(", ")", "{", "$", "jar", "=", "[", "]", ";", "$", "query", "=", "$", "this", "->", "url", "->", "getQuery", "(", ")", ";", "if", "(", "null", "!==", "$", "query", ")", "{", "$", "jar", "[", "]", "=", "$", "query", ";", "}", "$", "query", "=", "''", ";", "if", "(", "count", "(", "$", "this", "->", "params", ")", ">", "0", "||", "count", "(", "$", "jar", ")", ">", "0", ")", "{", "if", "(", "$", "this", "->", "method", "===", "'get'", ")", "{", "foreach", "(", "$", "this", "->", "params", "as", "$", "param", ")", "{", "$", "key", "=", "$", "param", "->", "encode", "?", "urlencode", "(", "$", "param", "->", "key", ")", ":", "$", "param", "->", "key", ";", "$", "value", "=", "$", "param", "->", "encode", "?", "urlencode", "(", "$", "param", "->", "value", ")", ":", "$", "param", "->", "value", ";", "$", "jar", "[", "]", "=", "sprintf", "(", "'%s=%s'", ",", "$", "key", ",", "$", "value", ")", ";", "}", "}", "$", "query", "=", "'?'", ".", "implode", "(", "'&'", ",", "$", "jar", ")", ";", "}", "return", "$", "this", "->", "url", "->", "generate", "(", "URLParser", "::", "UNTIL_PATH", ")", ".", "$", "query", ";", "}" ]
Adds new params to existing params to format the url @return string
[ "Adds", "new", "params", "to", "existing", "params", "to", "format", "the", "url" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L521-L549
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.formatParams
private function formatParams() { $params = []; //Params foreach($this -> params as $param) { $key = $param -> encode ? urlencode($param -> key) : $param -> key; $value = $param -> encode ? urlencode($param -> value) : $param -> value; $params[$key] = $value; } //Files foreach($this -> files as $file) { if(function_exists('curl_file_create')) { $value = curl_file_create($file -> file -> entity() -> getBasepath()); } else { $value = '@' . realpath($file -> file -> entity() -> getBasepath()); } $params[$file -> name] = $value; } return $params; }
php
private function formatParams() { $params = []; //Params foreach($this -> params as $param) { $key = $param -> encode ? urlencode($param -> key) : $param -> key; $value = $param -> encode ? urlencode($param -> value) : $param -> value; $params[$key] = $value; } //Files foreach($this -> files as $file) { if(function_exists('curl_file_create')) { $value = curl_file_create($file -> file -> entity() -> getBasepath()); } else { $value = '@' . realpath($file -> file -> entity() -> getBasepath()); } $params[$file -> name] = $value; } return $params; }
[ "private", "function", "formatParams", "(", ")", "{", "$", "params", "=", "[", "]", ";", "//Params\r", "foreach", "(", "$", "this", "->", "params", "as", "$", "param", ")", "{", "$", "key", "=", "$", "param", "->", "encode", "?", "urlencode", "(", "$", "param", "->", "key", ")", ":", "$", "param", "->", "key", ";", "$", "value", "=", "$", "param", "->", "encode", "?", "urlencode", "(", "$", "param", "->", "value", ")", ":", "$", "param", "->", "value", ";", "$", "params", "[", "$", "key", "]", "=", "$", "value", ";", "}", "//Files\r", "foreach", "(", "$", "this", "->", "files", "as", "$", "file", ")", "{", "if", "(", "function_exists", "(", "'curl_file_create'", ")", ")", "{", "$", "value", "=", "curl_file_create", "(", "$", "file", "->", "file", "->", "entity", "(", ")", "->", "getBasepath", "(", ")", ")", ";", "}", "else", "{", "$", "value", "=", "'@'", ".", "realpath", "(", "$", "file", "->", "file", "->", "entity", "(", ")", "->", "getBasepath", "(", ")", ")", ";", "}", "$", "params", "[", "$", "file", "->", "name", "]", "=", "$", "value", ";", "}", "return", "$", "params", ";", "}" ]
Formats all the parameters @return array
[ "Formats", "all", "the", "parameters" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L556-L583
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.send
public function send() { //Set default status $this -> response -> setStatus([ 'code' => 0, 'protocol' => '', 'status' => '', 'text' => '' ]); $curl = curl_init(); curl_setopt_array($curl, $this -> createOptions()); $response = curl_exec($curl); if(false !== $response) { $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $headers = substr($response, 0, $header_size); $headers = $this -> parseHeaders($headers); $body = substr($response, $header_size); $json = @json_decode($body, true); $this -> response -> setHeaders($headers['headers']); $this -> response -> setBody($body); $this -> response -> setStatus($headers['status']); $this -> response -> setCookies($this -> parseCookies($response)); $this -> response -> setResponse($response); if(true === (json_last_error() == JSON_ERROR_NONE)) { $this -> response -> setJson($json); } } $this -> response -> setInfo(curl_getinfo($curl)); curl_close($curl); return $this; }
php
public function send() { //Set default status $this -> response -> setStatus([ 'code' => 0, 'protocol' => '', 'status' => '', 'text' => '' ]); $curl = curl_init(); curl_setopt_array($curl, $this -> createOptions()); $response = curl_exec($curl); if(false !== $response) { $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $headers = substr($response, 0, $header_size); $headers = $this -> parseHeaders($headers); $body = substr($response, $header_size); $json = @json_decode($body, true); $this -> response -> setHeaders($headers['headers']); $this -> response -> setBody($body); $this -> response -> setStatus($headers['status']); $this -> response -> setCookies($this -> parseCookies($response)); $this -> response -> setResponse($response); if(true === (json_last_error() == JSON_ERROR_NONE)) { $this -> response -> setJson($json); } } $this -> response -> setInfo(curl_getinfo($curl)); curl_close($curl); return $this; }
[ "public", "function", "send", "(", ")", "{", "//Set default status\r", "$", "this", "->", "response", "->", "setStatus", "(", "[", "'code'", "=>", "0", ",", "'protocol'", "=>", "''", ",", "'status'", "=>", "''", ",", "'text'", "=>", "''", "]", ")", ";", "$", "curl", "=", "curl_init", "(", ")", ";", "curl_setopt_array", "(", "$", "curl", ",", "$", "this", "->", "createOptions", "(", ")", ")", ";", "$", "response", "=", "curl_exec", "(", "$", "curl", ")", ";", "if", "(", "false", "!==", "$", "response", ")", "{", "$", "header_size", "=", "curl_getinfo", "(", "$", "curl", ",", "CURLINFO_HEADER_SIZE", ")", ";", "$", "headers", "=", "substr", "(", "$", "response", ",", "0", ",", "$", "header_size", ")", ";", "$", "headers", "=", "$", "this", "->", "parseHeaders", "(", "$", "headers", ")", ";", "$", "body", "=", "substr", "(", "$", "response", ",", "$", "header_size", ")", ";", "$", "json", "=", "@", "json_decode", "(", "$", "body", ",", "true", ")", ";", "$", "this", "->", "response", "->", "setHeaders", "(", "$", "headers", "[", "'headers'", "]", ")", ";", "$", "this", "->", "response", "->", "setBody", "(", "$", "body", ")", ";", "$", "this", "->", "response", "->", "setStatus", "(", "$", "headers", "[", "'status'", "]", ")", ";", "$", "this", "->", "response", "->", "setCookies", "(", "$", "this", "->", "parseCookies", "(", "$", "response", ")", ")", ";", "$", "this", "->", "response", "->", "setResponse", "(", "$", "response", ")", ";", "if", "(", "true", "===", "(", "json_last_error", "(", ")", "==", "JSON_ERROR_NONE", ")", ")", "{", "$", "this", "->", "response", "->", "setJson", "(", "$", "json", ")", ";", "}", "}", "$", "this", "->", "response", "->", "setInfo", "(", "curl_getinfo", "(", "$", "curl", ")", ")", ";", "curl_close", "(", "$", "curl", ")", ";", "return", "$", "this", ";", "}" ]
Sends the request and sets all the response data @return array
[ "Sends", "the", "request", "and", "sets", "all", "the", "response", "data" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L599-L640
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.parseHeaders
private function parseHeaders($str) { if(false === is_string($str)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($str)), E_USER_ERROR); } $headers = []; $status = []; foreach(explode("\n", $str) as $header) { if(preg_match('/(:)/is', $header)) { list($key, $value) = preg_split('/(:)/is', $header, 2); } else { $key = $header; } if(trim($key) !== '') { if(preg_match('/(https?\/[0-9]\.[0-9])/i', $key, $http)) { $status['code'] = null; if(preg_match('/([0-9]+)/', ltrim($key, $http[0]), $code)) { $status['code'] = $code[0]; } $status['protocol'] = $http[0]; $status['status'] = trim($key); $status['text'] = trim(ltrim(trim(ltrim($key, $status['protocol'])), $status['code'])); } else { $headers[strtolower($key)] = trim($value); } } } return ['headers' => $headers, 'status' => $status]; }
php
private function parseHeaders($str) { if(false === is_string($str)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($str)), E_USER_ERROR); } $headers = []; $status = []; foreach(explode("\n", $str) as $header) { if(preg_match('/(:)/is', $header)) { list($key, $value) = preg_split('/(:)/is', $header, 2); } else { $key = $header; } if(trim($key) !== '') { if(preg_match('/(https?\/[0-9]\.[0-9])/i', $key, $http)) { $status['code'] = null; if(preg_match('/([0-9]+)/', ltrim($key, $http[0]), $code)) { $status['code'] = $code[0]; } $status['protocol'] = $http[0]; $status['status'] = trim($key); $status['text'] = trim(ltrim(trim(ltrim($key, $status['protocol'])), $status['code'])); } else { $headers[strtolower($key)] = trim($value); } } } return ['headers' => $headers, 'status' => $status]; }
[ "private", "function", "parseHeaders", "(", "$", "str", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "str", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "str", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "headers", "=", "[", "]", ";", "$", "status", "=", "[", "]", ";", "foreach", "(", "explode", "(", "\"\\n\"", ",", "$", "str", ")", "as", "$", "header", ")", "{", "if", "(", "preg_match", "(", "'/(:)/is'", ",", "$", "header", ")", ")", "{", "list", "(", "$", "key", ",", "$", "value", ")", "=", "preg_split", "(", "'/(:)/is'", ",", "$", "header", ",", "2", ")", ";", "}", "else", "{", "$", "key", "=", "$", "header", ";", "}", "if", "(", "trim", "(", "$", "key", ")", "!==", "''", ")", "{", "if", "(", "preg_match", "(", "'/(https?\\/[0-9]\\.[0-9])/i'", ",", "$", "key", ",", "$", "http", ")", ")", "{", "$", "status", "[", "'code'", "]", "=", "null", ";", "if", "(", "preg_match", "(", "'/([0-9]+)/'", ",", "ltrim", "(", "$", "key", ",", "$", "http", "[", "0", "]", ")", ",", "$", "code", ")", ")", "{", "$", "status", "[", "'code'", "]", "=", "$", "code", "[", "0", "]", ";", "}", "$", "status", "[", "'protocol'", "]", "=", "$", "http", "[", "0", "]", ";", "$", "status", "[", "'status'", "]", "=", "trim", "(", "$", "key", ")", ";", "$", "status", "[", "'text'", "]", "=", "trim", "(", "ltrim", "(", "trim", "(", "ltrim", "(", "$", "key", ",", "$", "status", "[", "'protocol'", "]", ")", ")", ",", "$", "status", "[", "'code'", "]", ")", ")", ";", "}", "else", "{", "$", "headers", "[", "strtolower", "(", "$", "key", ")", "]", "=", "trim", "(", "$", "value", ")", ";", "}", "}", "}", "return", "[", "'headers'", "=>", "$", "headers", ",", "'status'", "=>", "$", "status", "]", ";", "}" ]
Parses headers and forms it into an Array @param string $str @return array
[ "Parses", "headers", "and", "forms", "it", "into", "an", "Array" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L648-L688
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.parseCookies
private function parseCookies($str) { if(false === is_string($str)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($str)), E_USER_ERROR); } $jar = []; $headers = explode("\n", trim($str)); foreach($headers as $header) { if(preg_match('/^set-cookie: /i', $header)) { $cookie = []; //Match name and value preg_match('/^set-cookie: ([^=]+)=([^;]+)/i', $header, $match); if(count($match) === 3) { $cookie['name'] = $match[1]; $cookie['value'] = $match[2]; //Match expires $cookie['expires'] = null; preg_match('/; expires=([^;]+)/i', $header, $match); if(count($match) === 2) { $cookie['expires'] = strtotime(urldecode(trim($match[1]))); } //Match domain $cookie['domain'] = null; preg_match('/; domain=([^;]+)/i', $header, $match); if(count($match) === 2) { $cookie['domain'] = urldecode(trim($match[1])); } //Match secure $cookie['secure'] = false; preg_match('/; secure/i', $header, $match); if(count($match) === 1) { $cookie['secure'] = true; } //Match httponly $cookie['httponly'] = false; preg_match('/; httponly/i', $header, $match); if(count($match) === 1) { $cookie['httponly'] = true; } //Add cookie to the jar if(count($cookie) > 0) { $jar[] = $cookie; } } } } return $jar; }
php
private function parseCookies($str) { if(false === is_string($str)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($str)), E_USER_ERROR); } $jar = []; $headers = explode("\n", trim($str)); foreach($headers as $header) { if(preg_match('/^set-cookie: /i', $header)) { $cookie = []; //Match name and value preg_match('/^set-cookie: ([^=]+)=([^;]+)/i', $header, $match); if(count($match) === 3) { $cookie['name'] = $match[1]; $cookie['value'] = $match[2]; //Match expires $cookie['expires'] = null; preg_match('/; expires=([^;]+)/i', $header, $match); if(count($match) === 2) { $cookie['expires'] = strtotime(urldecode(trim($match[1]))); } //Match domain $cookie['domain'] = null; preg_match('/; domain=([^;]+)/i', $header, $match); if(count($match) === 2) { $cookie['domain'] = urldecode(trim($match[1])); } //Match secure $cookie['secure'] = false; preg_match('/; secure/i', $header, $match); if(count($match) === 1) { $cookie['secure'] = true; } //Match httponly $cookie['httponly'] = false; preg_match('/; httponly/i', $header, $match); if(count($match) === 1) { $cookie['httponly'] = true; } //Add cookie to the jar if(count($cookie) > 0) { $jar[] = $cookie; } } } } return $jar; }
[ "private", "function", "parseCookies", "(", "$", "str", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "str", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "str", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "jar", "=", "[", "]", ";", "$", "headers", "=", "explode", "(", "\"\\n\"", ",", "trim", "(", "$", "str", ")", ")", ";", "foreach", "(", "$", "headers", "as", "$", "header", ")", "{", "if", "(", "preg_match", "(", "'/^set-cookie: /i'", ",", "$", "header", ")", ")", "{", "$", "cookie", "=", "[", "]", ";", "//Match name and value\r", "preg_match", "(", "'/^set-cookie: ([^=]+)=([^;]+)/i'", ",", "$", "header", ",", "$", "match", ")", ";", "if", "(", "count", "(", "$", "match", ")", "===", "3", ")", "{", "$", "cookie", "[", "'name'", "]", "=", "$", "match", "[", "1", "]", ";", "$", "cookie", "[", "'value'", "]", "=", "$", "match", "[", "2", "]", ";", "//Match expires\r", "$", "cookie", "[", "'expires'", "]", "=", "null", ";", "preg_match", "(", "'/; expires=([^;]+)/i'", ",", "$", "header", ",", "$", "match", ")", ";", "if", "(", "count", "(", "$", "match", ")", "===", "2", ")", "{", "$", "cookie", "[", "'expires'", "]", "=", "strtotime", "(", "urldecode", "(", "trim", "(", "$", "match", "[", "1", "]", ")", ")", ")", ";", "}", "//Match domain\r", "$", "cookie", "[", "'domain'", "]", "=", "null", ";", "preg_match", "(", "'/; domain=([^;]+)/i'", ",", "$", "header", ",", "$", "match", ")", ";", "if", "(", "count", "(", "$", "match", ")", "===", "2", ")", "{", "$", "cookie", "[", "'domain'", "]", "=", "urldecode", "(", "trim", "(", "$", "match", "[", "1", "]", ")", ")", ";", "}", "//Match secure\r", "$", "cookie", "[", "'secure'", "]", "=", "false", ";", "preg_match", "(", "'/; secure/i'", ",", "$", "header", ",", "$", "match", ")", ";", "if", "(", "count", "(", "$", "match", ")", "===", "1", ")", "{", "$", "cookie", "[", "'secure'", "]", "=", "true", ";", "}", "//Match httponly\r", "$", "cookie", "[", "'httponly'", "]", "=", "false", ";", "preg_match", "(", "'/; httponly/i'", ",", "$", "header", ",", "$", "match", ")", ";", "if", "(", "count", "(", "$", "match", ")", "===", "1", ")", "{", "$", "cookie", "[", "'httponly'", "]", "=", "true", ";", "}", "//Add cookie to the jar\r", "if", "(", "count", "(", "$", "cookie", ")", ">", "0", ")", "{", "$", "jar", "[", "]", "=", "$", "cookie", ";", "}", "}", "}", "}", "return", "$", "jar", ";", "}" ]
Parses the cookies from the headers and forms it into an Array @param string $str @return array
[ "Parses", "the", "cookies", "from", "the", "headers", "and", "forms", "it", "into", "an", "Array" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L696-L764
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.createOptions
private function createOptions() { $default = [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_TIMEOUT => 30, CURLOPT_URL => $this -> formatUrl(), CURLOPT_COOKIE => $this -> formatCookies(), CURLOPT_HTTPHEADER => $this -> headers ]; if('get' !== $this -> method) { $this -> options[CURLOPT_POSTFIELDS] = $this -> formatParams(); } return $default + $this -> options; }
php
private function createOptions() { $default = [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_TIMEOUT => 30, CURLOPT_URL => $this -> formatUrl(), CURLOPT_COOKIE => $this -> formatCookies(), CURLOPT_HTTPHEADER => $this -> headers ]; if('get' !== $this -> method) { $this -> options[CURLOPT_POSTFIELDS] = $this -> formatParams(); } return $default + $this -> options; }
[ "private", "function", "createOptions", "(", ")", "{", "$", "default", "=", "[", "CURLOPT_RETURNTRANSFER", "=>", "true", ",", "CURLOPT_HEADER", "=>", "true", ",", "CURLOPT_TIMEOUT", "=>", "30", ",", "CURLOPT_URL", "=>", "$", "this", "->", "formatUrl", "(", ")", ",", "CURLOPT_COOKIE", "=>", "$", "this", "->", "formatCookies", "(", ")", ",", "CURLOPT_HTTPHEADER", "=>", "$", "this", "->", "headers", "]", ";", "if", "(", "'get'", "!==", "$", "this", "->", "method", ")", "{", "$", "this", "->", "options", "[", "CURLOPT_POSTFIELDS", "]", "=", "$", "this", "->", "formatParams", "(", ")", ";", "}", "return", "$", "default", "+", "$", "this", "->", "options", ";", "}" ]
Generates and returns all the options @return array
[ "Generates", "and", "returns", "all", "the", "options" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L771-L788
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.method
private function method($url, $closure, $method) { if(false === is_string($url)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($url)), E_USER_ERROR); } if(false === is_string($method)) { return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($method)), E_USER_ERROR); } $this -> method = $method; $this -> url = new URLParser($url); $this -> options[CURLOPT_CUSTOMREQUEST] = strtoupper($method); if(is_object($closure)) { call_user_func($closure, $this); } $this -> send(); return $this; }
php
private function method($url, $closure, $method) { if(false === is_string($url)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($url)), E_USER_ERROR); } if(false === is_string($method)) { return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($method)), E_USER_ERROR); } $this -> method = $method; $this -> url = new URLParser($url); $this -> options[CURLOPT_CUSTOMREQUEST] = strtoupper($method); if(is_object($closure)) { call_user_func($closure, $this); } $this -> send(); return $this; }
[ "private", "function", "method", "(", "$", "url", ",", "$", "closure", ",", "$", "method", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "url", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "url", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "is_string", "(", "$", "method", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 3 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "method", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "method", "=", "$", "method", ";", "$", "this", "->", "url", "=", "new", "URLParser", "(", "$", "url", ")", ";", "$", "this", "->", "options", "[", "CURLOPT_CUSTOMREQUEST", "]", "=", "strtoupper", "(", "$", "method", ")", ";", "if", "(", "is_object", "(", "$", "closure", ")", ")", "{", "call_user_func", "(", "$", "closure", ",", "$", "this", ")", ";", "}", "$", "this", "->", "send", "(", ")", ";", "return", "$", "this", ";", "}" ]
Sets the method and url and executes a user closure function if given @param string $url @param object $closure @param string $method @return sFire\HTTP\Client
[ "Sets", "the", "method", "and", "url", "and", "executes", "a", "user", "closure", "function", "if", "given" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L798-L819
train
wpsharks/dicer
src/includes/classes/Di.php
Di.addInstances
public function addInstances(array $instances): self { foreach ($instances as $_key => $_instance) { if (is_string($_key)) { $_class_name = ltrim($_key, '\\'); } else { $_class_name = get_class($_instance); } $_class_key = strtolower($_class_name); $this->instances[$_class_key] = $_instance; // Cache the instance. } // unset($_key, $_instance, $_class_name, $_class_key); return $this; }
php
public function addInstances(array $instances): self { foreach ($instances as $_key => $_instance) { if (is_string($_key)) { $_class_name = ltrim($_key, '\\'); } else { $_class_name = get_class($_instance); } $_class_key = strtolower($_class_name); $this->instances[$_class_key] = $_instance; // Cache the instance. } // unset($_key, $_instance, $_class_name, $_class_key); return $this; }
[ "public", "function", "addInstances", "(", "array", "$", "instances", ")", ":", "self", "{", "foreach", "(", "$", "instances", "as", "$", "_key", "=>", "$", "_instance", ")", "{", "if", "(", "is_string", "(", "$", "_key", ")", ")", "{", "$", "_class_name", "=", "ltrim", "(", "$", "_key", ",", "'\\\\'", ")", ";", "}", "else", "{", "$", "_class_name", "=", "get_class", "(", "$", "_instance", ")", ";", "}", "$", "_class_key", "=", "strtolower", "(", "$", "_class_name", ")", ";", "$", "this", "->", "instances", "[", "$", "_class_key", "]", "=", "$", "_instance", ";", "// Cache the instance.", "}", "// unset($_key, $_instance, $_class_name, $_class_key);", "return", "$", "this", ";", "}" ]
Add new instances. @since 151115 Initial release. @param array $instances Class instances. @return self Reference; for chaining.
[ "Add", "new", "instances", "." ]
72a4e1810b7f52265e192ecbcb30f57b9e994d04
https://github.com/wpsharks/dicer/blob/72a4e1810b7f52265e192ecbcb30f57b9e994d04/src/includes/classes/Di.php#L109-L122
train
wpsharks/dicer
src/includes/classes/Di.php
Di.addRule
public function addRule(string $name, array $rule): self { $name = ltrim($name, '\\'); $key = strtolower($name); $global_default_rule = $this->rules['*']; $this->rules[$key] = array_merge($global_default_rule, $rule); $this->rules[$key] = array_intersect_key($this->rules[$key], $global_default_rule); $this->rules[$key]['new_instances'] = (array) $this->rules[$key]['new_instances']; $this->rules[$key]['constructor_args'] = (array) $this->rules[$key]['constructor_args']; if ($key !== '*') { // Cannot contain this global-only key. unset($this->rules[$key]['new_instances']); // Not applicable. } $this->total_rules = count($this->rules); return $this; }
php
public function addRule(string $name, array $rule): self { $name = ltrim($name, '\\'); $key = strtolower($name); $global_default_rule = $this->rules['*']; $this->rules[$key] = array_merge($global_default_rule, $rule); $this->rules[$key] = array_intersect_key($this->rules[$key], $global_default_rule); $this->rules[$key]['new_instances'] = (array) $this->rules[$key]['new_instances']; $this->rules[$key]['constructor_args'] = (array) $this->rules[$key]['constructor_args']; if ($key !== '*') { // Cannot contain this global-only key. unset($this->rules[$key]['new_instances']); // Not applicable. } $this->total_rules = count($this->rules); return $this; }
[ "public", "function", "addRule", "(", "string", "$", "name", ",", "array", "$", "rule", ")", ":", "self", "{", "$", "name", "=", "ltrim", "(", "$", "name", ",", "'\\\\'", ")", ";", "$", "key", "=", "strtolower", "(", "$", "name", ")", ";", "$", "global_default_rule", "=", "$", "this", "->", "rules", "[", "'*'", "]", ";", "$", "this", "->", "rules", "[", "$", "key", "]", "=", "array_merge", "(", "$", "global_default_rule", ",", "$", "rule", ")", ";", "$", "this", "->", "rules", "[", "$", "key", "]", "=", "array_intersect_key", "(", "$", "this", "->", "rules", "[", "$", "key", "]", ",", "$", "global_default_rule", ")", ";", "$", "this", "->", "rules", "[", "$", "key", "]", "[", "'new_instances'", "]", "=", "(", "array", ")", "$", "this", "->", "rules", "[", "$", "key", "]", "[", "'new_instances'", "]", ";", "$", "this", "->", "rules", "[", "$", "key", "]", "[", "'constructor_args'", "]", "=", "(", "array", ")", "$", "this", "->", "rules", "[", "$", "key", "]", "[", "'constructor_args'", "]", ";", "if", "(", "$", "key", "!==", "'*'", ")", "{", "// Cannot contain this global-only key.", "unset", "(", "$", "this", "->", "rules", "[", "$", "key", "]", "[", "'new_instances'", "]", ")", ";", "// Not applicable.", "}", "$", "this", "->", "total_rules", "=", "count", "(", "$", "this", "->", "rules", ")", ";", "return", "$", "this", ";", "}" ]
Add a new rule. @since 151115 Initial release. @param string $name Rule name. @param array $rule Rule properties. @return self Reference; for chaining.
[ "Add", "a", "new", "rule", "." ]
72a4e1810b7f52265e192ecbcb30f57b9e994d04
https://github.com/wpsharks/dicer/blob/72a4e1810b7f52265e192ecbcb30f57b9e994d04/src/includes/classes/Di.php#L134-L152
train
wpsharks/dicer
src/includes/classes/Di.php
Di.getRule
protected function getRule(string $name, string $key, array $parent_names = []): array { if (isset($this->rules[$key])) { return $this->rules[$key]; } if ($this->total_rules === 1 || !$parent_names) { return $this->rules['*']; // Done here. } foreach (array_map('strtolower', $parent_names) as $_parent_key) { if (isset($this->rules[$_parent_key])) { return $this->rules[$_parent_key]; } } // unset($_parent_key); // Housekeeping. return $this->rules['*']; }
php
protected function getRule(string $name, string $key, array $parent_names = []): array { if (isset($this->rules[$key])) { return $this->rules[$key]; } if ($this->total_rules === 1 || !$parent_names) { return $this->rules['*']; // Done here. } foreach (array_map('strtolower', $parent_names) as $_parent_key) { if (isset($this->rules[$_parent_key])) { return $this->rules[$_parent_key]; } } // unset($_parent_key); // Housekeeping. return $this->rules['*']; }
[ "protected", "function", "getRule", "(", "string", "$", "name", ",", "string", "$", "key", ",", "array", "$", "parent_names", "=", "[", "]", ")", ":", "array", "{", "if", "(", "isset", "(", "$", "this", "->", "rules", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "rules", "[", "$", "key", "]", ";", "}", "if", "(", "$", "this", "->", "total_rules", "===", "1", "||", "!", "$", "parent_names", ")", "{", "return", "$", "this", "->", "rules", "[", "'*'", "]", ";", "// Done here.", "}", "foreach", "(", "array_map", "(", "'strtolower'", ",", "$", "parent_names", ")", "as", "$", "_parent_key", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "rules", "[", "$", "_parent_key", "]", ")", ")", "{", "return", "$", "this", "->", "rules", "[", "$", "_parent_key", "]", ";", "}", "}", "// unset($_parent_key); // Housekeeping.", "return", "$", "this", "->", "rules", "[", "'*'", "]", ";", "}" ]
Gets a specific rule. @since 151115 Initial release. @param string $name Rule name. @param string $key Rule key. @param array $parent_names Parent names. @return array An array of rule properties.
[ "Gets", "a", "specific", "rule", "." ]
72a4e1810b7f52265e192ecbcb30f57b9e994d04
https://github.com/wpsharks/dicer/blob/72a4e1810b7f52265e192ecbcb30f57b9e994d04/src/includes/classes/Di.php#L165-L180
train
wpsharks/dicer
src/includes/classes/Di.php
Di.resolveJitClosures
protected function resolveJitClosures(array $array) { if (isset($array['di::jit'])) { return $array['di::jit']($this); } foreach ($array as $_key => &$_value) { if (is_array($_value)) { $_value = $this->resolveJitClosures($_value); } } // unset($_key, $_value); return $array; }
php
protected function resolveJitClosures(array $array) { if (isset($array['di::jit'])) { return $array['di::jit']($this); } foreach ($array as $_key => &$_value) { if (is_array($_value)) { $_value = $this->resolveJitClosures($_value); } } // unset($_key, $_value); return $array; }
[ "protected", "function", "resolveJitClosures", "(", "array", "$", "array", ")", "{", "if", "(", "isset", "(", "$", "array", "[", "'di::jit'", "]", ")", ")", "{", "return", "$", "array", "[", "'di::jit'", "]", "(", "$", "this", ")", ";", "}", "foreach", "(", "$", "array", "as", "$", "_key", "=>", "&", "$", "_value", ")", "{", "if", "(", "is_array", "(", "$", "_value", ")", ")", "{", "$", "_value", "=", "$", "this", "->", "resolveJitClosures", "(", "$", "_value", ")", ";", "}", "}", "// unset($_key, $_value);", "return", "$", "array", ";", "}" ]
Resolve just-in-time closures. @since 151118 Resolve just-in-time closures. @param array Input array to scan for `di::jit` keys. @return array|mixed Output w/ resolved `di::jit` keys. @note Objects not iterated, on purpose! This avoids a deeper scan that really is unnecessary when trying to find `di::jit` keys.
[ "Resolve", "just", "-", "in", "-", "time", "closures", "." ]
72a4e1810b7f52265e192ecbcb30f57b9e994d04
https://github.com/wpsharks/dicer/blob/72a4e1810b7f52265e192ecbcb30f57b9e994d04/src/includes/classes/Di.php#L194-L205
train
wpsharks/dicer
src/includes/classes/Di.php
Di.getClosure
protected function getClosure(string $class_name, string $class_key): callable { $parent_class_names = class_parents($class_name); $all_class_names = $parent_class_names; $all_class_names[] = $class_name; $class = new \ReflectionClass($class_name); $constructor = $class->getConstructor(); // Null if no constructor. $class_rule = $this->getRule($class_name, $class_key, $parent_class_names); $constructor_params_closure = $constructor ? $this->getParamsClosure($constructor, $class_rule) : null; if (!$this->rules['*']['new_instances'] || !array_intersect($all_class_names, $this->rules['*']['new_instances'])) { return function (array $args) use ($class, $class_key, $constructor, $constructor_params_closure) { if ($constructor && $constructor_params_closure) { return $this->instances[$class_key] = $class->newInstanceArgs($constructor_params_closure($args)); } else { return $this->instances[$class_key] = $class->newInstanceWithoutConstructor(); } }; } elseif ($constructor && $constructor_params_closure) { return function (array $args) use ($class, $constructor_params_closure) { return $class->newInstanceArgs($constructor_params_closure($args)); }; } else { return function (array $args) use ($class) { return $class->newInstanceWithoutConstructor(); }; } }
php
protected function getClosure(string $class_name, string $class_key): callable { $parent_class_names = class_parents($class_name); $all_class_names = $parent_class_names; $all_class_names[] = $class_name; $class = new \ReflectionClass($class_name); $constructor = $class->getConstructor(); // Null if no constructor. $class_rule = $this->getRule($class_name, $class_key, $parent_class_names); $constructor_params_closure = $constructor ? $this->getParamsClosure($constructor, $class_rule) : null; if (!$this->rules['*']['new_instances'] || !array_intersect($all_class_names, $this->rules['*']['new_instances'])) { return function (array $args) use ($class, $class_key, $constructor, $constructor_params_closure) { if ($constructor && $constructor_params_closure) { return $this->instances[$class_key] = $class->newInstanceArgs($constructor_params_closure($args)); } else { return $this->instances[$class_key] = $class->newInstanceWithoutConstructor(); } }; } elseif ($constructor && $constructor_params_closure) { return function (array $args) use ($class, $constructor_params_closure) { return $class->newInstanceArgs($constructor_params_closure($args)); }; } else { return function (array $args) use ($class) { return $class->newInstanceWithoutConstructor(); }; } }
[ "protected", "function", "getClosure", "(", "string", "$", "class_name", ",", "string", "$", "class_key", ")", ":", "callable", "{", "$", "parent_class_names", "=", "class_parents", "(", "$", "class_name", ")", ";", "$", "all_class_names", "=", "$", "parent_class_names", ";", "$", "all_class_names", "[", "]", "=", "$", "class_name", ";", "$", "class", "=", "new", "\\", "ReflectionClass", "(", "$", "class_name", ")", ";", "$", "constructor", "=", "$", "class", "->", "getConstructor", "(", ")", ";", "// Null if no constructor.", "$", "class_rule", "=", "$", "this", "->", "getRule", "(", "$", "class_name", ",", "$", "class_key", ",", "$", "parent_class_names", ")", ";", "$", "constructor_params_closure", "=", "$", "constructor", "?", "$", "this", "->", "getParamsClosure", "(", "$", "constructor", ",", "$", "class_rule", ")", ":", "null", ";", "if", "(", "!", "$", "this", "->", "rules", "[", "'*'", "]", "[", "'new_instances'", "]", "||", "!", "array_intersect", "(", "$", "all_class_names", ",", "$", "this", "->", "rules", "[", "'*'", "]", "[", "'new_instances'", "]", ")", ")", "{", "return", "function", "(", "array", "$", "args", ")", "use", "(", "$", "class", ",", "$", "class_key", ",", "$", "constructor", ",", "$", "constructor_params_closure", ")", "{", "if", "(", "$", "constructor", "&&", "$", "constructor_params_closure", ")", "{", "return", "$", "this", "->", "instances", "[", "$", "class_key", "]", "=", "$", "class", "->", "newInstanceArgs", "(", "$", "constructor_params_closure", "(", "$", "args", ")", ")", ";", "}", "else", "{", "return", "$", "this", "->", "instances", "[", "$", "class_key", "]", "=", "$", "class", "->", "newInstanceWithoutConstructor", "(", ")", ";", "}", "}", ";", "}", "elseif", "(", "$", "constructor", "&&", "$", "constructor_params_closure", ")", "{", "return", "function", "(", "array", "$", "args", ")", "use", "(", "$", "class", ",", "$", "constructor_params_closure", ")", "{", "return", "$", "class", "->", "newInstanceArgs", "(", "$", "constructor_params_closure", "(", "$", "args", ")", ")", ";", "}", ";", "}", "else", "{", "return", "function", "(", "array", "$", "args", ")", "use", "(", "$", "class", ")", "{", "return", "$", "class", "->", "newInstanceWithoutConstructor", "(", ")", ";", "}", ";", "}", "}" ]
Get closure for a specific class. @since 151115 Initial release. @param string $class_name Class name. @param string $class_key Class key. @return callable Closure returns instance.
[ "Get", "closure", "for", "a", "specific", "class", "." ]
72a4e1810b7f52265e192ecbcb30f57b9e994d04
https://github.com/wpsharks/dicer/blob/72a4e1810b7f52265e192ecbcb30f57b9e994d04/src/includes/classes/Di.php#L217-L245
train
wpsharks/dicer
src/includes/classes/Di.php
Di.getParamsClosure
protected function getParamsClosure(\ReflectionMethod $constructor, array $class_rule): callable { $param_details = []; // Initialize parameter details. foreach ($constructor->getParameters() as $_parameter) { $_name = $_parameter->getName(); $_class = $_parameter->getClass(); $_class_name = $_class->name ?? ''; $_is_variadic = $_parameter->isVariadic(); $_has_default_value = $_parameter->isDefaultValueAvailable(); $_default_value = $_has_default_value ? $_parameter->getDefaultValue() : null; $param_details[] = [$_name, $_class_name, $_is_variadic, $_has_default_value, $_default_value]; } // unset($_parameter, $_name, $_class, $_class_name, $_is_variadic, $_has_default_value, $_default_value); return function (array $args) use ($constructor, $param_details, $class_rule) { $parameters = []; // Initialize parameters. if ($class_rule['constructor_args']) { // Note: `$args` take precedence here. $args = array_merge($this->resolveJitClosures($class_rule['constructor_args']), $args); } foreach ($param_details as list($_name, $_class_name, $_is_variadic, $_has_default_value, $_default_value)) { if ($args && array_key_exists($_name, $args)) { if ($_is_variadic && is_array($args[$_name])) { $parameters = array_merge($parameters, $args[$_name]); } else { $parameters[] = $args[$_name]; } } elseif ($_class_name && !$_has_default_value) { $parameters[] = $this->get($_class_name); } elseif ($_has_default_value) { $parameters[] = $_default_value; } else { throw new \Exception(sprintf('Missing `$%1$s` to `%2$s` constructor.', $_name, $constructor->class)); } } // unset($_name, $_class_name, $_is_variadic, $_has_default_value, $_default_value); return $parameters; // With deep dependency injection. }; }
php
protected function getParamsClosure(\ReflectionMethod $constructor, array $class_rule): callable { $param_details = []; // Initialize parameter details. foreach ($constructor->getParameters() as $_parameter) { $_name = $_parameter->getName(); $_class = $_parameter->getClass(); $_class_name = $_class->name ?? ''; $_is_variadic = $_parameter->isVariadic(); $_has_default_value = $_parameter->isDefaultValueAvailable(); $_default_value = $_has_default_value ? $_parameter->getDefaultValue() : null; $param_details[] = [$_name, $_class_name, $_is_variadic, $_has_default_value, $_default_value]; } // unset($_parameter, $_name, $_class, $_class_name, $_is_variadic, $_has_default_value, $_default_value); return function (array $args) use ($constructor, $param_details, $class_rule) { $parameters = []; // Initialize parameters. if ($class_rule['constructor_args']) { // Note: `$args` take precedence here. $args = array_merge($this->resolveJitClosures($class_rule['constructor_args']), $args); } foreach ($param_details as list($_name, $_class_name, $_is_variadic, $_has_default_value, $_default_value)) { if ($args && array_key_exists($_name, $args)) { if ($_is_variadic && is_array($args[$_name])) { $parameters = array_merge($parameters, $args[$_name]); } else { $parameters[] = $args[$_name]; } } elseif ($_class_name && !$_has_default_value) { $parameters[] = $this->get($_class_name); } elseif ($_has_default_value) { $parameters[] = $_default_value; } else { throw new \Exception(sprintf('Missing `$%1$s` to `%2$s` constructor.', $_name, $constructor->class)); } } // unset($_name, $_class_name, $_is_variadic, $_has_default_value, $_default_value); return $parameters; // With deep dependency injection. }; }
[ "protected", "function", "getParamsClosure", "(", "\\", "ReflectionMethod", "$", "constructor", ",", "array", "$", "class_rule", ")", ":", "callable", "{", "$", "param_details", "=", "[", "]", ";", "// Initialize parameter details.", "foreach", "(", "$", "constructor", "->", "getParameters", "(", ")", "as", "$", "_parameter", ")", "{", "$", "_name", "=", "$", "_parameter", "->", "getName", "(", ")", ";", "$", "_class", "=", "$", "_parameter", "->", "getClass", "(", ")", ";", "$", "_class_name", "=", "$", "_class", "->", "name", "??", "''", ";", "$", "_is_variadic", "=", "$", "_parameter", "->", "isVariadic", "(", ")", ";", "$", "_has_default_value", "=", "$", "_parameter", "->", "isDefaultValueAvailable", "(", ")", ";", "$", "_default_value", "=", "$", "_has_default_value", "?", "$", "_parameter", "->", "getDefaultValue", "(", ")", ":", "null", ";", "$", "param_details", "[", "]", "=", "[", "$", "_name", ",", "$", "_class_name", ",", "$", "_is_variadic", ",", "$", "_has_default_value", ",", "$", "_default_value", "]", ";", "}", "// unset($_parameter, $_name, $_class, $_class_name, $_is_variadic, $_has_default_value, $_default_value);", "return", "function", "(", "array", "$", "args", ")", "use", "(", "$", "constructor", ",", "$", "param_details", ",", "$", "class_rule", ")", "{", "$", "parameters", "=", "[", "]", ";", "// Initialize parameters.", "if", "(", "$", "class_rule", "[", "'constructor_args'", "]", ")", "{", "// Note: `$args` take precedence here.", "$", "args", "=", "array_merge", "(", "$", "this", "->", "resolveJitClosures", "(", "$", "class_rule", "[", "'constructor_args'", "]", ")", ",", "$", "args", ")", ";", "}", "foreach", "(", "$", "param_details", "as", "list", "(", "$", "_name", ",", "$", "_class_name", ",", "$", "_is_variadic", ",", "$", "_has_default_value", ",", "$", "_default_value", ")", ")", "{", "if", "(", "$", "args", "&&", "array_key_exists", "(", "$", "_name", ",", "$", "args", ")", ")", "{", "if", "(", "$", "_is_variadic", "&&", "is_array", "(", "$", "args", "[", "$", "_name", "]", ")", ")", "{", "$", "parameters", "=", "array_merge", "(", "$", "parameters", ",", "$", "args", "[", "$", "_name", "]", ")", ";", "}", "else", "{", "$", "parameters", "[", "]", "=", "$", "args", "[", "$", "_name", "]", ";", "}", "}", "elseif", "(", "$", "_class_name", "&&", "!", "$", "_has_default_value", ")", "{", "$", "parameters", "[", "]", "=", "$", "this", "->", "get", "(", "$", "_class_name", ")", ";", "}", "elseif", "(", "$", "_has_default_value", ")", "{", "$", "parameters", "[", "]", "=", "$", "_default_value", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "sprintf", "(", "'Missing `$%1$s` to `%2$s` constructor.'", ",", "$", "_name", ",", "$", "constructor", "->", "class", ")", ")", ";", "}", "}", "// unset($_name, $_class_name, $_is_variadic, $_has_default_value, $_default_value);", "return", "$", "parameters", ";", "// With deep dependency injection.", "}", ";", "}" ]
Magic happens here. @since 151115 Initial release. @param \ReflectionMethod $constructor Constructor. @param array $class_rule A class-specific rule. @return callable Closure that returns an array of parameters.
[ "Magic", "happens", "here", "." ]
72a4e1810b7f52265e192ecbcb30f57b9e994d04
https://github.com/wpsharks/dicer/blob/72a4e1810b7f52265e192ecbcb30f57b9e994d04/src/includes/classes/Di.php#L257-L298
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/caching/stores/FileCacheStore.php
FileCacheStore.file
protected function file($key) { return $this->dir . DIRECTORY_SEPARATOR . $this->key($key) . "." . $this->fileExtension; }
php
protected function file($key) { return $this->dir . DIRECTORY_SEPARATOR . $this->key($key) . "." . $this->fileExtension; }
[ "protected", "function", "file", "(", "$", "key", ")", "{", "return", "$", "this", "->", "dir", ".", "DIRECTORY_SEPARATOR", ".", "$", "this", "->", "key", "(", "$", "key", ")", ".", "\".\"", ".", "$", "this", "->", "fileExtension", ";", "}" ]
Generates the filename to store based on the cachePrefix and given key @param string $key The key we'll use to generate our key @return string A unique filename
[ "Generates", "the", "filename", "to", "store", "based", "on", "the", "cachePrefix", "and", "given", "key" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/caching/stores/FileCacheStore.php#L79-L82
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/caching/stores/FileCacheStore.php
FileCacheStore.isExpired
protected function isExpired($key, $storageArray = null) { if (!empty($key)) { // Item is expired if key doesn't exist if (!$this->containsKey($key)) return true; $storageArray = $this->readFile($this->file($key)); } if (is_array($storageArray)) { if ($storageArray['expires'] >= time() && $storageArray['duration'] > 0) return true; else return false; } else { throw new CacheException("isExpired called incorrectly. key = '{$key}', storageArray = '{$storageArray}'"); } }
php
protected function isExpired($key, $storageArray = null) { if (!empty($key)) { // Item is expired if key doesn't exist if (!$this->containsKey($key)) return true; $storageArray = $this->readFile($this->file($key)); } if (is_array($storageArray)) { if ($storageArray['expires'] >= time() && $storageArray['duration'] > 0) return true; else return false; } else { throw new CacheException("isExpired called incorrectly. key = '{$key}', storageArray = '{$storageArray}'"); } }
[ "protected", "function", "isExpired", "(", "$", "key", ",", "$", "storageArray", "=", "null", ")", "{", "if", "(", "!", "empty", "(", "$", "key", ")", ")", "{", "// Item is expired if key doesn't exist", "if", "(", "!", "$", "this", "->", "containsKey", "(", "$", "key", ")", ")", "return", "true", ";", "$", "storageArray", "=", "$", "this", "->", "readFile", "(", "$", "this", "->", "file", "(", "$", "key", ")", ")", ";", "}", "if", "(", "is_array", "(", "$", "storageArray", ")", ")", "{", "if", "(", "$", "storageArray", "[", "'expires'", "]", ">=", "time", "(", ")", "&&", "$", "storageArray", "[", "'duration'", "]", ">", "0", ")", "return", "true", ";", "else", "return", "false", ";", "}", "else", "{", "throw", "new", "CacheException", "(", "\"isExpired called incorrectly. key = '{$key}', storageArray = '{$storageArray}'\"", ")", ";", "}", "}" ]
Determines if the key or storage array specified is expired @param string $key The key used to lookup the data. If doesn't exist, item is expired, so true is returned. This value may be null if a value is specified for $storageArray @param array $storageArray The stored value to check (in case it's already loaded) @return boolean true if the data is expired, false otherwise
[ "Determines", "if", "the", "key", "or", "storage", "array", "specified", "is", "expired" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/caching/stores/FileCacheStore.php#L94-L112
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/caching/stores/FileCacheStore.php
FileCacheStore.getData
protected function getData($key) { $filename = $this->file($key); if (!file_exists($filename)) return false; else { $data = $this->readFile($filename); if ($this->isExpired(null, $data)) return false; else { // if going to expire in 10 seconds, extend the cache and let this request refresh it $expire = $data['expires']; $value = $data['value']; $duration = $data['duration']; $now = $this->DateFactory->newStorageDate(); if (!empty($value) && $duration > 0 && $now->toUnix() > ($expire - 10) ) { $this->put($key, $value, $duration); return false; } return $data; } } }
php
protected function getData($key) { $filename = $this->file($key); if (!file_exists($filename)) return false; else { $data = $this->readFile($filename); if ($this->isExpired(null, $data)) return false; else { // if going to expire in 10 seconds, extend the cache and let this request refresh it $expire = $data['expires']; $value = $data['value']; $duration = $data['duration']; $now = $this->DateFactory->newStorageDate(); if (!empty($value) && $duration > 0 && $now->toUnix() > ($expire - 10) ) { $this->put($key, $value, $duration); return false; } return $data; } } }
[ "protected", "function", "getData", "(", "$", "key", ")", "{", "$", "filename", "=", "$", "this", "->", "file", "(", "$", "key", ")", ";", "if", "(", "!", "file_exists", "(", "$", "filename", ")", ")", "return", "false", ";", "else", "{", "$", "data", "=", "$", "this", "->", "readFile", "(", "$", "filename", ")", ";", "if", "(", "$", "this", "->", "isExpired", "(", "null", ",", "$", "data", ")", ")", "return", "false", ";", "else", "{", "// if going to expire in 10 seconds, extend the cache and let this request refresh it", "$", "expire", "=", "$", "data", "[", "'expires'", "]", ";", "$", "value", "=", "$", "data", "[", "'value'", "]", ";", "$", "duration", "=", "$", "data", "[", "'duration'", "]", ";", "$", "now", "=", "$", "this", "->", "DateFactory", "->", "newStorageDate", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "value", ")", "&&", "$", "duration", ">", "0", "&&", "$", "now", "->", "toUnix", "(", ")", ">", "(", "$", "expire", "-", "10", ")", ")", "{", "$", "this", "->", "put", "(", "$", "key", ",", "$", "value", ",", "$", "duration", ")", ";", "return", "false", ";", "}", "return", "$", "data", ";", "}", "}", "}" ]
Performs a fetch of our data from the filecache without logging in the logger. That allows this method to be used in other locations. @param string $key The key to fetch @return mixed Data in this->storageFormat format or FALSE if data is invalid
[ "Performs", "a", "fetch", "of", "our", "data", "from", "the", "filecache", "without", "logging", "in", "the", "logger", ".", "That", "allows", "this", "method", "to", "be", "used", "in", "other", "locations", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/caching/stores/FileCacheStore.php#L123-L148
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/caching/stores/FileCacheStore.php
FileCacheStore.writeFile
protected function writeFile($filename, $value) { try { FileSystemUtils::safeFilePutContents($filename, serialize($value)); return true; } catch (Exception $e) { return false; } }
php
protected function writeFile($filename, $value) { try { FileSystemUtils::safeFilePutContents($filename, serialize($value)); return true; } catch (Exception $e) { return false; } }
[ "protected", "function", "writeFile", "(", "$", "filename", ",", "$", "value", ")", "{", "try", "{", "FileSystemUtils", "::", "safeFilePutContents", "(", "$", "filename", ",", "serialize", "(", "$", "value", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
Performs a write to the filesystem of our data. @param string $filename The filename to write to @param string $value The data to write. @return void
[ "Performs", "a", "write", "to", "the", "filesystem", "of", "our", "data", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/caching/stores/FileCacheStore.php#L173-L182
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/caching/stores/FileCacheStore.php
FileCacheStore.flushExpired
public function flushExpired() { $this->Logger->debug('Flush all expired called.'); try { foreach ( new DirectoryIterator($this->dir) as $item ) { $filename = $item->getPath() .DIRECTORY_SEPARATOR.$item->getFilename(); $pathinfo = pathinfo($filename); // Find all files ending with .cfcache and destroy them if expired! if ($pathinfo['extension'] == $this->fileExtension) $data = $this->readFile($filename); if ($this->isExpired(null, $data)) unlink($filename); } } catch (Exception $e) { $this->Logger->error("flushExpired error: " . $e->getMessage()); return false; } return true; }
php
public function flushExpired() { $this->Logger->debug('Flush all expired called.'); try { foreach ( new DirectoryIterator($this->dir) as $item ) { $filename = $item->getPath() .DIRECTORY_SEPARATOR.$item->getFilename(); $pathinfo = pathinfo($filename); // Find all files ending with .cfcache and destroy them if expired! if ($pathinfo['extension'] == $this->fileExtension) $data = $this->readFile($filename); if ($this->isExpired(null, $data)) unlink($filename); } } catch (Exception $e) { $this->Logger->error("flushExpired error: " . $e->getMessage()); return false; } return true; }
[ "public", "function", "flushExpired", "(", ")", "{", "$", "this", "->", "Logger", "->", "debug", "(", "'Flush all expired called.'", ")", ";", "try", "{", "foreach", "(", "new", "DirectoryIterator", "(", "$", "this", "->", "dir", ")", "as", "$", "item", ")", "{", "$", "filename", "=", "$", "item", "->", "getPath", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "$", "item", "->", "getFilename", "(", ")", ";", "$", "pathinfo", "=", "pathinfo", "(", "$", "filename", ")", ";", "// Find all files ending with .cfcache and destroy them if expired!", "if", "(", "$", "pathinfo", "[", "'extension'", "]", "==", "$", "this", "->", "fileExtension", ")", "$", "data", "=", "$", "this", "->", "readFile", "(", "$", "filename", ")", ";", "if", "(", "$", "this", "->", "isExpired", "(", "null", ",", "$", "data", ")", ")", "unlink", "(", "$", "filename", ")", ";", "}", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "this", "->", "Logger", "->", "error", "(", "\"flushExpired error: \"", ".", "$", "e", "->", "getMessage", "(", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Removes all expired items from the cache store @return boolean true on success, false on failure
[ "Removes", "all", "expired", "items", "from", "the", "cache", "store" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/caching/stores/FileCacheStore.php#L480-L501
train
itkg/core
src/Itkg/Core/Route/Route.php
Route.matches
public function matches($uri) { if (!preg_match($this->compiledRegex, $uri, $matches)) { return false; } $params = array(); foreach ($matches as $key => $value) { /** gestion des sous-repertoires : uniquement si controller contient des _ */ if ($key == 'controller' && substr_count($value, '_')) { $temp = explode('_', $value); $value = array_pop($temp); $params['directory'] = implode('/', $temp); } // Set the value for all matched keys $params[$key] = $value; } return array_merge($this->defaults, $params); }
php
public function matches($uri) { if (!preg_match($this->compiledRegex, $uri, $matches)) { return false; } $params = array(); foreach ($matches as $key => $value) { /** gestion des sous-repertoires : uniquement si controller contient des _ */ if ($key == 'controller' && substr_count($value, '_')) { $temp = explode('_', $value); $value = array_pop($temp); $params['directory'] = implode('/', $temp); } // Set the value for all matched keys $params[$key] = $value; } return array_merge($this->defaults, $params); }
[ "public", "function", "matches", "(", "$", "uri", ")", "{", "if", "(", "!", "preg_match", "(", "$", "this", "->", "compiledRegex", ",", "$", "uri", ",", "$", "matches", ")", ")", "{", "return", "false", ";", "}", "$", "params", "=", "array", "(", ")", ";", "foreach", "(", "$", "matches", "as", "$", "key", "=>", "$", "value", ")", "{", "/** gestion des sous-repertoires : uniquement si controller contient des _ */", "if", "(", "$", "key", "==", "'controller'", "&&", "substr_count", "(", "$", "value", ",", "'_'", ")", ")", "{", "$", "temp", "=", "explode", "(", "'_'", ",", "$", "value", ")", ";", "$", "value", "=", "array_pop", "(", "$", "temp", ")", ";", "$", "params", "[", "'directory'", "]", "=", "implode", "(", "'/'", ",", "$", "temp", ")", ";", "}", "// Set the value for all matched keys", "$", "params", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "array_merge", "(", "$", "this", "->", "defaults", ",", "$", "params", ")", ";", "}" ]
Tests if the route matches a given URI. A successful match will return all of the routed parameters as an array. A failed match will return boolean FALSE. // This route will only match if the <controller>, <action>, and <id> exist $params = self::factory('<controller>/<action>/<id>', array('id' => '\d+')) ->matches('users/edit/10'); // The parameters are now: controller = users, action = edit, id = 10 This method should almost always be used within an if/else block: if ($params = $route->matches($uri)) { // Parse the parameters } @param string $uri URI to match @return FALSE
[ "Tests", "if", "the", "route", "matches", "a", "given", "URI", ".", "A", "successful", "match", "will", "return", "all", "of", "the", "routed", "parameters", "as", "an", "array", ".", "A", "failed", "match", "will", "return", "boolean", "FALSE", "." ]
e5e4efb05feb4d23b0df41f2b21fd095103e593b
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Route/Route.php#L172-L192
train
itkg/core
src/Itkg/Core/Route/Route.php
Route.compile
protected function compile() { // The URI should be considered literal except for keys and optional parts // Escape everything preg_quote would escape except for : ( ) < > $regex = preg_replace('#' . self::REGEX_ESCAPE . '#', '\\\\$0', $this->uri); if (strpos($regex, '(') !== false) { // Make optional parts of the URI non-capturing and optional $regex = str_replace(array('(', ')'), array('(?:', ')?'), $regex); } // Insert default regex for keys $regex = str_replace(array('<', '>'), array('(?P<', '>' . self::REGEX_SEGMENT . ')'), $regex); $search = $replace = array(); foreach ($this->regex as $key => $value) { $search[] = "<$key>" . self::REGEX_SEGMENT; $replace[] = "<$key>$value"; } // Replace the default regex with the user-specified regex return sprintf('#^%s$#', str_replace($search, $replace, $regex)); }
php
protected function compile() { // The URI should be considered literal except for keys and optional parts // Escape everything preg_quote would escape except for : ( ) < > $regex = preg_replace('#' . self::REGEX_ESCAPE . '#', '\\\\$0', $this->uri); if (strpos($regex, '(') !== false) { // Make optional parts of the URI non-capturing and optional $regex = str_replace(array('(', ')'), array('(?:', ')?'), $regex); } // Insert default regex for keys $regex = str_replace(array('<', '>'), array('(?P<', '>' . self::REGEX_SEGMENT . ')'), $regex); $search = $replace = array(); foreach ($this->regex as $key => $value) { $search[] = "<$key>" . self::REGEX_SEGMENT; $replace[] = "<$key>$value"; } // Replace the default regex with the user-specified regex return sprintf('#^%s$#', str_replace($search, $replace, $regex)); }
[ "protected", "function", "compile", "(", ")", "{", "// The URI should be considered literal except for keys and optional parts", "// Escape everything preg_quote would escape except for : ( ) < >", "$", "regex", "=", "preg_replace", "(", "'#'", ".", "self", "::", "REGEX_ESCAPE", ".", "'#'", ",", "'\\\\\\\\$0'", ",", "$", "this", "->", "uri", ")", ";", "if", "(", "strpos", "(", "$", "regex", ",", "'('", ")", "!==", "false", ")", "{", "// Make optional parts of the URI non-capturing and optional", "$", "regex", "=", "str_replace", "(", "array", "(", "'('", ",", "')'", ")", ",", "array", "(", "'(?:'", ",", "')?'", ")", ",", "$", "regex", ")", ";", "}", "// Insert default regex for keys", "$", "regex", "=", "str_replace", "(", "array", "(", "'<'", ",", "'>'", ")", ",", "array", "(", "'(?P<'", ",", "'>'", ".", "self", "::", "REGEX_SEGMENT", ".", "')'", ")", ",", "$", "regex", ")", ";", "$", "search", "=", "$", "replace", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "regex", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "search", "[", "]", "=", "\"<$key>\"", ".", "self", "::", "REGEX_SEGMENT", ";", "$", "replace", "[", "]", "=", "\"<$key>$value\"", ";", "}", "// Replace the default regex with the user-specified regex", "return", "sprintf", "(", "'#^%s$#'", ",", "str_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "regex", ")", ")", ";", "}" ]
Returns the compiled regular expression for the route. This translates keys and optional groups to a proper PCRE regular expression. @access protected @return string
[ "Returns", "the", "compiled", "regular", "expression", "for", "the", "route", ".", "This", "translates", "keys", "and", "optional", "groups", "to", "a", "proper", "PCRE", "regular", "expression", "." ]
e5e4efb05feb4d23b0df41f2b21fd095103e593b
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Route/Route.php#L201-L223
train
shgysk8zer0/core_api
traits/datetime.php
DateTime._getTimeZone
final protected function _getTimeZone($timezone = null) { if ($timezone = strtoupper($timezone) and defined("\\DateTimeZone::{$timezone}")) { $timezone = new \DateTimeZone($timezone); } elseif (! ($timezone instanceof \DateTimeZone)) { @date_default_timezone_set(date_default_timezone_get()); $timezone = new \DateTimeZone(date_default_timezone_get()); } return $timezone; }
php
final protected function _getTimeZone($timezone = null) { if ($timezone = strtoupper($timezone) and defined("\\DateTimeZone::{$timezone}")) { $timezone = new \DateTimeZone($timezone); } elseif (! ($timezone instanceof \DateTimeZone)) { @date_default_timezone_set(date_default_timezone_get()); $timezone = new \DateTimeZone(date_default_timezone_get()); } return $timezone; }
[ "final", "protected", "function", "_getTimeZone", "(", "$", "timezone", "=", "null", ")", "{", "if", "(", "$", "timezone", "=", "strtoupper", "(", "$", "timezone", ")", "and", "defined", "(", "\"\\\\DateTimeZone::{$timezone}\"", ")", ")", "{", "$", "timezone", "=", "new", "\\", "DateTimeZone", "(", "$", "timezone", ")", ";", "}", "elseif", "(", "!", "(", "$", "timezone", "instanceof", "\\", "DateTimeZone", ")", ")", "{", "@", "date_default_timezone_set", "(", "date_default_timezone_get", "(", ")", ")", ";", "$", "timezone", "=", "new", "\\", "DateTimeZone", "(", "date_default_timezone_get", "(", ")", ")", ";", "}", "return", "$", "timezone", ";", "}" ]
Attempts to get timezone with fallback to default, which in turn defaults to UTC @param mixed $timezone Most likely a string or null, but could be a DateTimeZone @return DateTimeZone
[ "Attempts", "to", "get", "timezone", "with", "fallback", "to", "default", "which", "in", "turn", "defaults", "to", "UTC" ]
9e9b8baf761af874b95256ad2462e55fbb2b2e58
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/datetime.php#L51-L60
train
randomhost/icinga-check-minecraft
src/php/PlayerCount.php
PlayerCount.check
protected function check() { try { $options = $this->getOptions(); // retrieve player count $response = $this->mcStatus->query(true); if (!is_array($response) || !array_key_exists('player_count', $response) ) { $this->setMessage('No response from Minecraft server query.'); $this->setCode(self::STATE_UNKNOWN); return $this; } $playerCount = $response['player_count']; if ($playerCount >= (int)$options['thresholdCritical']) { $this->setMessage( sprintf( 'CRITICAL - %1$u players currently logged in|users=%1$u', $response['player_count'] ) ); $this->setCode(self::STATE_CRITICAL); return $this; } if ($playerCount >= (int)$options['thresholdWarning']) { $this->setMessage( sprintf( 'WARNING - %u players currently logged in|users=%1$u', $response['player_count'] ) ); $this->setCode(self::STATE_WARNING); return $this; } $this->setMessage( sprintf( 'OK - %u players currently logged in|users=%1$u', $playerCount ) ); $this->setCode(self::STATE_OK); return $this; } catch (\Exception $e) { $this->setMessage('Error from Mcstat: ' . $e->getMessage()); $this->setCode(self::STATE_UNKNOWN); return $this; } }
php
protected function check() { try { $options = $this->getOptions(); // retrieve player count $response = $this->mcStatus->query(true); if (!is_array($response) || !array_key_exists('player_count', $response) ) { $this->setMessage('No response from Minecraft server query.'); $this->setCode(self::STATE_UNKNOWN); return $this; } $playerCount = $response['player_count']; if ($playerCount >= (int)$options['thresholdCritical']) { $this->setMessage( sprintf( 'CRITICAL - %1$u players currently logged in|users=%1$u', $response['player_count'] ) ); $this->setCode(self::STATE_CRITICAL); return $this; } if ($playerCount >= (int)$options['thresholdWarning']) { $this->setMessage( sprintf( 'WARNING - %u players currently logged in|users=%1$u', $response['player_count'] ) ); $this->setCode(self::STATE_WARNING); return $this; } $this->setMessage( sprintf( 'OK - %u players currently logged in|users=%1$u', $playerCount ) ); $this->setCode(self::STATE_OK); return $this; } catch (\Exception $e) { $this->setMessage('Error from Mcstat: ' . $e->getMessage()); $this->setCode(self::STATE_UNKNOWN); return $this; } }
[ "protected", "function", "check", "(", ")", "{", "try", "{", "$", "options", "=", "$", "this", "->", "getOptions", "(", ")", ";", "// retrieve player count", "$", "response", "=", "$", "this", "->", "mcStatus", "->", "query", "(", "true", ")", ";", "if", "(", "!", "is_array", "(", "$", "response", ")", "||", "!", "array_key_exists", "(", "'player_count'", ",", "$", "response", ")", ")", "{", "$", "this", "->", "setMessage", "(", "'No response from Minecraft server query.'", ")", ";", "$", "this", "->", "setCode", "(", "self", "::", "STATE_UNKNOWN", ")", ";", "return", "$", "this", ";", "}", "$", "playerCount", "=", "$", "response", "[", "'player_count'", "]", ";", "if", "(", "$", "playerCount", ">=", "(", "int", ")", "$", "options", "[", "'thresholdCritical'", "]", ")", "{", "$", "this", "->", "setMessage", "(", "sprintf", "(", "'CRITICAL - %1$u players currently logged in|users=%1$u'", ",", "$", "response", "[", "'player_count'", "]", ")", ")", ";", "$", "this", "->", "setCode", "(", "self", "::", "STATE_CRITICAL", ")", ";", "return", "$", "this", ";", "}", "if", "(", "$", "playerCount", ">=", "(", "int", ")", "$", "options", "[", "'thresholdWarning'", "]", ")", "{", "$", "this", "->", "setMessage", "(", "sprintf", "(", "'WARNING - %u players currently logged in|users=%1$u'", ",", "$", "response", "[", "'player_count'", "]", ")", ")", ";", "$", "this", "->", "setCode", "(", "self", "::", "STATE_WARNING", ")", ";", "return", "$", "this", ";", "}", "$", "this", "->", "setMessage", "(", "sprintf", "(", "'OK - %u players currently logged in|users=%1$u'", ",", "$", "playerCount", ")", ")", ";", "$", "this", "->", "setCode", "(", "self", "::", "STATE_OK", ")", ";", "return", "$", "this", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "setMessage", "(", "'Error from Mcstat: '", ".", "$", "e", "->", "getMessage", "(", ")", ")", ";", "$", "this", "->", "setCode", "(", "self", "::", "STATE_UNKNOWN", ")", ";", "return", "$", "this", ";", "}", "}" ]
Check the amount of players on the Minecraft server. @see Base::check() @return $this
[ "Check", "the", "amount", "of", "players", "on", "the", "Minecraft", "server", "." ]
0587ea307b0706654b4a996d76e20e7ec04176a0
https://github.com/randomhost/icinga-check-minecraft/blob/0587ea307b0706654b4a996d76e20e7ec04176a0/src/php/PlayerCount.php#L44-L103
train
mossphp/moss-storage
Moss/Storage/Query/Relation/RelationFactory.php
RelationFactory.build
public function build(ModelInterface $model, $relation) { list($current, $further) = $this->splitRelationName($relation); $definition = $this->fetchDefinition($model, $current); switch ($definition->type()) { case self::RELATION_ONE: $instance = new OneRelation($this->storage, $definition, $this->bag, $this); break; case self::RELATION_MANY: $instance = new ManyRelation($this->storage, $definition, $this->bag, $this); break; case self::RELATION_ONE_TROUGH: $instance = new OneTroughRelation($this->storage, $definition, $this->bag, $this); break; case self::RELATION_MANY_TROUGH: $instance = new ManyTroughRelation($this->storage, $definition, $this->bag, $this); break; default: throw new RelationException(sprintf('Invalid relation type "%s" for "%s"', $definition->type(), $definition->entity())); } if ($further) { $instance->with($further); } return $instance; }
php
public function build(ModelInterface $model, $relation) { list($current, $further) = $this->splitRelationName($relation); $definition = $this->fetchDefinition($model, $current); switch ($definition->type()) { case self::RELATION_ONE: $instance = new OneRelation($this->storage, $definition, $this->bag, $this); break; case self::RELATION_MANY: $instance = new ManyRelation($this->storage, $definition, $this->bag, $this); break; case self::RELATION_ONE_TROUGH: $instance = new OneTroughRelation($this->storage, $definition, $this->bag, $this); break; case self::RELATION_MANY_TROUGH: $instance = new ManyTroughRelation($this->storage, $definition, $this->bag, $this); break; default: throw new RelationException(sprintf('Invalid relation type "%s" for "%s"', $definition->type(), $definition->entity())); } if ($further) { $instance->with($further); } return $instance; }
[ "public", "function", "build", "(", "ModelInterface", "$", "model", ",", "$", "relation", ")", "{", "list", "(", "$", "current", ",", "$", "further", ")", "=", "$", "this", "->", "splitRelationName", "(", "$", "relation", ")", ";", "$", "definition", "=", "$", "this", "->", "fetchDefinition", "(", "$", "model", ",", "$", "current", ")", ";", "switch", "(", "$", "definition", "->", "type", "(", ")", ")", "{", "case", "self", "::", "RELATION_ONE", ":", "$", "instance", "=", "new", "OneRelation", "(", "$", "this", "->", "storage", ",", "$", "definition", ",", "$", "this", "->", "bag", ",", "$", "this", ")", ";", "break", ";", "case", "self", "::", "RELATION_MANY", ":", "$", "instance", "=", "new", "ManyRelation", "(", "$", "this", "->", "storage", ",", "$", "definition", ",", "$", "this", "->", "bag", ",", "$", "this", ")", ";", "break", ";", "case", "self", "::", "RELATION_ONE_TROUGH", ":", "$", "instance", "=", "new", "OneTroughRelation", "(", "$", "this", "->", "storage", ",", "$", "definition", ",", "$", "this", "->", "bag", ",", "$", "this", ")", ";", "break", ";", "case", "self", "::", "RELATION_MANY_TROUGH", ":", "$", "instance", "=", "new", "ManyTroughRelation", "(", "$", "this", "->", "storage", ",", "$", "definition", ",", "$", "this", "->", "bag", ",", "$", "this", ")", ";", "break", ";", "default", ":", "throw", "new", "RelationException", "(", "sprintf", "(", "'Invalid relation type \"%s\" for \"%s\"'", ",", "$", "definition", "->", "type", "(", ")", ",", "$", "definition", "->", "entity", "(", ")", ")", ")", ";", "}", "if", "(", "$", "further", ")", "{", "$", "instance", "->", "with", "(", "$", "further", ")", ";", "}", "return", "$", "instance", ";", "}" ]
Sets model and its relation @param ModelInterface $model @param string $relation @return RelationInterface @throws RelationException
[ "Sets", "model", "and", "its", "relation" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/Relation/RelationFactory.php#L64-L91
train
DreadLabs/VantomasWebsite
src/CodeSnippet/SyntaxHighlighterParser.php
SyntaxHighlighterParser.toStringFromYaml
public function toStringFromYaml(array $parseResult) { $this->parameters = $parseResult; $this->removeNullValues(); $this->removeInvalidKeys(); $this->ensureDefaultBrush(); $brush = SyntaxHighlighterBrush::fromIdentifierOrAlias($this->parameters['brush']); $this->eventContext->dispatch( RegisterCodeSnippetBrush::fromBrush($brush) ); $this->formatValues(); return $this->formatPairs(); }
php
public function toStringFromYaml(array $parseResult) { $this->parameters = $parseResult; $this->removeNullValues(); $this->removeInvalidKeys(); $this->ensureDefaultBrush(); $brush = SyntaxHighlighterBrush::fromIdentifierOrAlias($this->parameters['brush']); $this->eventContext->dispatch( RegisterCodeSnippetBrush::fromBrush($brush) ); $this->formatValues(); return $this->formatPairs(); }
[ "public", "function", "toStringFromYaml", "(", "array", "$", "parseResult", ")", "{", "$", "this", "->", "parameters", "=", "$", "parseResult", ";", "$", "this", "->", "removeNullValues", "(", ")", ";", "$", "this", "->", "removeInvalidKeys", "(", ")", ";", "$", "this", "->", "ensureDefaultBrush", "(", ")", ";", "$", "brush", "=", "SyntaxHighlighterBrush", "::", "fromIdentifierOrAlias", "(", "$", "this", "->", "parameters", "[", "'brush'", "]", ")", ";", "$", "this", "->", "eventContext", "->", "dispatch", "(", "RegisterCodeSnippetBrush", "::", "fromBrush", "(", "$", "brush", ")", ")", ";", "$", "this", "->", "formatValues", "(", ")", ";", "return", "$", "this", "->", "formatPairs", "(", ")", ";", "}" ]
Parse to scalar string from YAML. @param array $parseResult @return string
[ "Parse", "to", "scalar", "string", "from", "YAML", "." ]
7f85f2b45bdf5ed9fa9d320c805c416bf99cd668
https://github.com/DreadLabs/VantomasWebsite/blob/7f85f2b45bdf5ed9fa9d320c805c416bf99cd668/src/CodeSnippet/SyntaxHighlighterParser.php#L113-L130
train
DreadLabs/VantomasWebsite
src/CodeSnippet/SyntaxHighlighterParser.php
SyntaxHighlighterParser.formatValues
private function formatValues() { array_walk($this->parameters, function (&$value, $key) { $parameterValue = $value; if (is_bool($parameterValue)) { $parameterValue = var_export($parameterValue, true); } $formattedValue = sprintf(self::DEFAULT_PAIR_FORMAT, $key, $parameterValue); if (isset($this->pairFormats[$key])) { $formattedValue = sprintf($this->pairFormats[$key], $key, $parameterValue); } $value = $formattedValue; }); }
php
private function formatValues() { array_walk($this->parameters, function (&$value, $key) { $parameterValue = $value; if (is_bool($parameterValue)) { $parameterValue = var_export($parameterValue, true); } $formattedValue = sprintf(self::DEFAULT_PAIR_FORMAT, $key, $parameterValue); if (isset($this->pairFormats[$key])) { $formattedValue = sprintf($this->pairFormats[$key], $key, $parameterValue); } $value = $formattedValue; }); }
[ "private", "function", "formatValues", "(", ")", "{", "array_walk", "(", "$", "this", "->", "parameters", ",", "function", "(", "&", "$", "value", ",", "$", "key", ")", "{", "$", "parameterValue", "=", "$", "value", ";", "if", "(", "is_bool", "(", "$", "parameterValue", ")", ")", "{", "$", "parameterValue", "=", "var_export", "(", "$", "parameterValue", ",", "true", ")", ";", "}", "$", "formattedValue", "=", "sprintf", "(", "self", "::", "DEFAULT_PAIR_FORMAT", ",", "$", "key", ",", "$", "parameterValue", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "pairFormats", "[", "$", "key", "]", ")", ")", "{", "$", "formattedValue", "=", "sprintf", "(", "$", "this", "->", "pairFormats", "[", "$", "key", "]", ",", "$", "key", ",", "$", "parameterValue", ")", ";", "}", "$", "value", "=", "$", "formattedValue", ";", "}", ")", ";", "}" ]
Applies formats formatting to values. @return void
[ "Applies", "formats", "formatting", "to", "values", "." ]
7f85f2b45bdf5ed9fa9d320c805c416bf99cd668
https://github.com/DreadLabs/VantomasWebsite/blob/7f85f2b45bdf5ed9fa9d320c805c416bf99cd668/src/CodeSnippet/SyntaxHighlighterParser.php#L172-L189
train
romm/configuration_object
Classes/ConfigurationObjectInstance.php
ConfigurationObjectInstance.getObject
public function getObject($forceInstance = false) { if (false === $forceInstance && true === $this->getValidationResult()->hasErrors() ) { throw new Exception( 'Trying to access a configuration object which contains errors. You should first check if it is error free, then use it: "$yourObject->getValidationResult()->hasErrors()".', 1471880442 ); } return $this->object; }
php
public function getObject($forceInstance = false) { if (false === $forceInstance && true === $this->getValidationResult()->hasErrors() ) { throw new Exception( 'Trying to access a configuration object which contains errors. You should first check if it is error free, then use it: "$yourObject->getValidationResult()->hasErrors()".', 1471880442 ); } return $this->object; }
[ "public", "function", "getObject", "(", "$", "forceInstance", "=", "false", ")", "{", "if", "(", "false", "===", "$", "forceInstance", "&&", "true", "===", "$", "this", "->", "getValidationResult", "(", ")", "->", "hasErrors", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Trying to access a configuration object which contains errors. You should first check if it is error free, then use it: \"$yourObject->getValidationResult()->hasErrors()\".'", ",", "1471880442", ")", ";", "}", "return", "$", "this", "->", "object", ";", "}" ]
Returns the real instance of the configuration object. Please note that you should always check the validation result before even getting the object. Use: `$myObject->getValidationResult()->hasErrors()` Warning: if you set `$forceInstance` to true, it means that the object will be returned even if it contain errors, so be careful if you intend to use it. @param bool $forceInstance If set to true, the instance will be returned even if the validation result contains errors. Should be used only if you know what you are doing. @return ConfigurationObjectInterface @throws Exception
[ "Returns", "the", "real", "instance", "of", "the", "configuration", "object", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/ConfigurationObjectInstance.php#L81-L93
train
romm/configuration_object
Classes/ConfigurationObjectInstance.php
ConfigurationObjectInstance.setValidationResult
public function setValidationResult(Result $result) { if (false === $this->mapperResult->hasErrors()) { $this->validationResult = $result; } }
php
public function setValidationResult(Result $result) { if (false === $this->mapperResult->hasErrors()) { $this->validationResult = $result; } }
[ "public", "function", "setValidationResult", "(", "Result", "$", "result", ")", "{", "if", "(", "false", "===", "$", "this", "->", "mapperResult", "->", "hasErrors", "(", ")", ")", "{", "$", "this", "->", "validationResult", "=", "$", "result", ";", "}", "}" ]
Manually set the validation result. Used in the cache service. Should only be internally used, please be careful if you need to use this function. Note that if the mapping result given as constructor argument of this object contains error, this function will do nothing. @param Result $result
[ "Manually", "set", "the", "validation", "result", ".", "Used", "in", "the", "cache", "service", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/ConfigurationObjectInstance.php#L120-L125
train
romm/configuration_object
Classes/ConfigurationObjectInstance.php
ConfigurationObjectInstance.refreshValidationResult
public function refreshValidationResult() { if (false === $this->mapperResult->hasErrors()) { $validator = Core::get()->getValidatorResolver() ->getBaseValidatorConjunction(get_class($this->object)); $this->validationResult = $validator->validate($this->object); } return $this; }
php
public function refreshValidationResult() { if (false === $this->mapperResult->hasErrors()) { $validator = Core::get()->getValidatorResolver() ->getBaseValidatorConjunction(get_class($this->object)); $this->validationResult = $validator->validate($this->object); } return $this; }
[ "public", "function", "refreshValidationResult", "(", ")", "{", "if", "(", "false", "===", "$", "this", "->", "mapperResult", "->", "hasErrors", "(", ")", ")", "{", "$", "validator", "=", "Core", "::", "get", "(", ")", "->", "getValidatorResolver", "(", ")", "->", "getBaseValidatorConjunction", "(", "get_class", "(", "$", "this", "->", "object", ")", ")", ";", "$", "this", "->", "validationResult", "=", "$", "validator", "->", "validate", "(", "$", "this", "->", "object", ")", ";", "}", "return", "$", "this", ";", "}" ]
If the mapping result which was passed as a constructor argument of this class contains error, the validation result will be the same. Otherwise a recursive validation of the object is processed. @return $this
[ "If", "the", "mapping", "result", "which", "was", "passed", "as", "a", "constructor", "argument", "of", "this", "class", "contains", "error", "the", "validation", "result", "will", "be", "the", "same", ".", "Otherwise", "a", "recursive", "validation", "of", "the", "object", "is", "processed", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/ConfigurationObjectInstance.php#L144-L154
train
blackknight467/AYAHBundle
Service/AYAHService.php
AYAHService.getPublisherHTML
public function getPublisherHTML($config = array()) { // Initialize. $session_secret = ""; $fields = array('config' => $config); $webservice_url = '/ws/setruntimeoptions/' . $this->publisherKey; // If necessary, process the config data. if ( ! empty($config)) { // Add the gameid to the options url. if (array_key_exists("gameid", $config)) { $webservice_url .= '/' . $config['gameid']; } } // Call the webservice and get the response. $resp = $this->doHttpsPostReturnJSONArray($this->webService, $webservice_url, $fields); if ($resp) { // Get the session secret from the response. $session_secret = $resp->session_secret; // Build the url to the AYAH webservice. $url = 'https://'; // The AYAH webservice API requires https. $url.= $this->webService; // Add the host. $url.= "/ws/script/"; // Add the path to the API script. $url.= urlencode($this->publisherKey); // Add the encoded publisher key. $url.= (empty($session_secret))? "" : "/".$session_secret; // If set, add the session_secret. // Build and return the needed HTML code. return "<div id='AYAH'></div><script src='". $url ."' type='text/javascript' language='JavaScript'></script>"; } else { // Build and log a detailed message. $url = "https://".$this->webService.$webservice_url; $message = "Unable to connect to the AYAH webservice server. url='$url'"; // Build and display a helpful message to the site user. $style = "padding: 10px; border: 1px solid #EED3D7; background: #F2DEDE; color: #B94A48;"; $message = "Unable to load the <i>Are You a Human</i> PlayThru&trade;. Please contact the site owner to report the problem."; echo "<p style=\"$style\">$message</p>\n"; } }
php
public function getPublisherHTML($config = array()) { // Initialize. $session_secret = ""; $fields = array('config' => $config); $webservice_url = '/ws/setruntimeoptions/' . $this->publisherKey; // If necessary, process the config data. if ( ! empty($config)) { // Add the gameid to the options url. if (array_key_exists("gameid", $config)) { $webservice_url .= '/' . $config['gameid']; } } // Call the webservice and get the response. $resp = $this->doHttpsPostReturnJSONArray($this->webService, $webservice_url, $fields); if ($resp) { // Get the session secret from the response. $session_secret = $resp->session_secret; // Build the url to the AYAH webservice. $url = 'https://'; // The AYAH webservice API requires https. $url.= $this->webService; // Add the host. $url.= "/ws/script/"; // Add the path to the API script. $url.= urlencode($this->publisherKey); // Add the encoded publisher key. $url.= (empty($session_secret))? "" : "/".$session_secret; // If set, add the session_secret. // Build and return the needed HTML code. return "<div id='AYAH'></div><script src='". $url ."' type='text/javascript' language='JavaScript'></script>"; } else { // Build and log a detailed message. $url = "https://".$this->webService.$webservice_url; $message = "Unable to connect to the AYAH webservice server. url='$url'"; // Build and display a helpful message to the site user. $style = "padding: 10px; border: 1px solid #EED3D7; background: #F2DEDE; color: #B94A48;"; $message = "Unable to load the <i>Are You a Human</i> PlayThru&trade;. Please contact the site owner to report the problem."; echo "<p style=\"$style\">$message</p>\n"; } }
[ "public", "function", "getPublisherHTML", "(", "$", "config", "=", "array", "(", ")", ")", "{", "// Initialize.", "$", "session_secret", "=", "\"\"", ";", "$", "fields", "=", "array", "(", "'config'", "=>", "$", "config", ")", ";", "$", "webservice_url", "=", "'/ws/setruntimeoptions/'", ".", "$", "this", "->", "publisherKey", ";", "// If necessary, process the config data.", "if", "(", "!", "empty", "(", "$", "config", ")", ")", "{", "// Add the gameid to the options url.", "if", "(", "array_key_exists", "(", "\"gameid\"", ",", "$", "config", ")", ")", "{", "$", "webservice_url", ".=", "'/'", ".", "$", "config", "[", "'gameid'", "]", ";", "}", "}", "// Call the webservice and get the response.", "$", "resp", "=", "$", "this", "->", "doHttpsPostReturnJSONArray", "(", "$", "this", "->", "webService", ",", "$", "webservice_url", ",", "$", "fields", ")", ";", "if", "(", "$", "resp", ")", "{", "// Get the session secret from the response.", "$", "session_secret", "=", "$", "resp", "->", "session_secret", ";", "// Build the url to the AYAH webservice.", "$", "url", "=", "'https://'", ";", "// The AYAH webservice API requires https.", "$", "url", ".=", "$", "this", "->", "webService", ";", "// Add the host.", "$", "url", ".=", "\"/ws/script/\"", ";", "// Add the path to the API script.", "$", "url", ".=", "urlencode", "(", "$", "this", "->", "publisherKey", ")", ";", "// Add the encoded publisher key.", "$", "url", ".=", "(", "empty", "(", "$", "session_secret", ")", ")", "?", "\"\"", ":", "\"/\"", ".", "$", "session_secret", ";", "// If set, add the session_secret.", "// Build and return the needed HTML code.", "return", "\"<div id='AYAH'></div><script src='\"", ".", "$", "url", ".", "\"' type='text/javascript' language='JavaScript'></script>\"", ";", "}", "else", "{", "// Build and log a detailed message.", "$", "url", "=", "\"https://\"", ".", "$", "this", "->", "webService", ".", "$", "webservice_url", ";", "$", "message", "=", "\"Unable to connect to the AYAH webservice server. url='$url'\"", ";", "// Build and display a helpful message to the site user.", "$", "style", "=", "\"padding: 10px; border: 1px solid #EED3D7; background: #F2DEDE; color: #B94A48;\"", ";", "$", "message", "=", "\"Unable to load the <i>Are You a Human</i> PlayThru&trade;. Please contact the site owner to report the problem.\"", ";", "echo", "\"<p style=\\\"$style\\\">$message</p>\\n\"", ";", "}", "}" ]
Returns the markup for PlayThru.= @param array $config @return string
[ "Returns", "the", "markup", "for", "PlayThru", ".", "=" ]
38a724c5e28d1d6a6dbe1d86125974498b3e4f00
https://github.com/blackknight467/AYAHBundle/blob/38a724c5e28d1d6a6dbe1d86125974498b3e4f00/Service/AYAHService.php#L82-L127
train
blackknight467/AYAHBundle
Service/AYAHService.php
AYAHService.scoreResult
public function scoreResult() { $result = false; if($this->sessionSecret) { $fields = array( 'session_secret' => urlencode($this->sessionSecret), 'scoring_key' => $this->scoringKey ); $resp = $this->doHttpsPostReturnJSONArray($this->webService, '/ws/scoreGame', $fields); if($resp) { $result = ($resp->status_code == 1); } } return $result; }
php
public function scoreResult() { $result = false; if($this->sessionSecret) { $fields = array( 'session_secret' => urlencode($this->sessionSecret), 'scoring_key' => $this->scoringKey ); $resp = $this->doHttpsPostReturnJSONArray($this->webService, '/ws/scoreGame', $fields); if($resp) { $result = ($resp->status_code == 1); } } return $result; }
[ "public", "function", "scoreResult", "(", ")", "{", "$", "result", "=", "false", ";", "if", "(", "$", "this", "->", "sessionSecret", ")", "{", "$", "fields", "=", "array", "(", "'session_secret'", "=>", "urlencode", "(", "$", "this", "->", "sessionSecret", ")", ",", "'scoring_key'", "=>", "$", "this", "->", "scoringKey", ")", ";", "$", "resp", "=", "$", "this", "->", "doHttpsPostReturnJSONArray", "(", "$", "this", "->", "webService", ",", "'/ws/scoreGame'", ",", "$", "fields", ")", ";", "if", "(", "$", "resp", ")", "{", "$", "result", "=", "(", "$", "resp", "->", "status_code", "==", "1", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Check whether the user is a human. Wrapper for the scoreGame API call @return boolean
[ "Check", "whether", "the", "user", "is", "a", "human", ".", "Wrapper", "for", "the", "scoreGame", "API", "call" ]
38a724c5e28d1d6a6dbe1d86125974498b3e4f00
https://github.com/blackknight467/AYAHBundle/blob/38a724c5e28d1d6a6dbe1d86125974498b3e4f00/Service/AYAHService.php#L133-L152
train
blackknight467/AYAHBundle
Service/AYAHService.php
AYAHService.doHttpsPostReturnJSONArray
protected function doHttpsPostReturnJSONArray($hostname, $path, $fields) { $result = $this->doHttpsPost($hostname, $path, $fields); if ($result) { $result = json_decode($result); } else { error_log("AYAH::doHttpsPostGetJSON: Post to https://$hostname$path returned no result."); $result = array(); } return $result; }
php
protected function doHttpsPostReturnJSONArray($hostname, $path, $fields) { $result = $this->doHttpsPost($hostname, $path, $fields); if ($result) { $result = json_decode($result); } else { error_log("AYAH::doHttpsPostGetJSON: Post to https://$hostname$path returned no result."); $result = array(); } return $result; }
[ "protected", "function", "doHttpsPostReturnJSONArray", "(", "$", "hostname", ",", "$", "path", ",", "$", "fields", ")", "{", "$", "result", "=", "$", "this", "->", "doHttpsPost", "(", "$", "hostname", ",", "$", "path", ",", "$", "fields", ")", ";", "if", "(", "$", "result", ")", "{", "$", "result", "=", "json_decode", "(", "$", "result", ")", ";", "}", "else", "{", "error_log", "(", "\"AYAH::doHttpsPostGetJSON: Post to https://$hostname$path returned no result.\"", ")", ";", "$", "result", "=", "array", "(", ")", ";", "}", "return", "$", "result", ";", "}" ]
Do an HTTPS POST, return some JSON decoded as array. @param $hostname hostname @param $path path @param $fields associative array of fields @return array|mixed Decoded json structure or empty data structure
[ "Do", "an", "HTTPS", "POST", "return", "some", "JSON", "decoded", "as", "array", "." ]
38a724c5e28d1d6a6dbe1d86125974498b3e4f00
https://github.com/blackknight467/AYAHBundle/blob/38a724c5e28d1d6a6dbe1d86125974498b3e4f00/Service/AYAHService.php#L178-L190
train
blackknight467/AYAHBundle
Service/AYAHService.php
AYAHService.doHttpsPost
protected function doHttpsPost($hostname, $path, $fields) { $result = ''; $fields_string = ''; //Url encode the string foreach($fields as $key => $value) { if (is_array($value)) { if (! empty($value)) { foreach ($value as $k => $v) { $fields_string .= $key . '['. $k .']=' . $v . '&'; } } else { $fields_string .= $key . '=&'; } } else { $fields_string .= $key.'='.$value.'&'; } } rtrim($fields_string,'&'); // cURL or something else if(function_exists('curl_init')) { $curlsession = curl_init(); curl_setopt($curlsession, CURLOPT_URL, 'https://' . $hostname . $path); curl_setopt($curlsession, CURLOPT_POST,count($fields)); curl_setopt($curlsession, CURLOPT_POSTFIELDS,$fields_string); curl_setopt($curlsession, CURLOPT_RETURNTRANSFER,1); curl_setopt($curlsession, CURLOPT_SSL_VERIFYHOST,0); curl_setopt($curlsession, CURLOPT_SSL_VERIFYPEER,false); $result = curl_exec($curlsession); } else { // Build a header $http_request = "POST $path HTTP/1.1\r\n"; $http_request .= "Host: $hostname\r\n"; $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $http_request .= "Content-Length: " . strlen($fields_string) . "\r\n"; $http_request .= "User-Agent: AreYouAHuman/PHP " . $this->version . "\r\n"; $http_request .= "Connection: Close\r\n"; $http_request .= "\r\n"; $http_request .= $fields_string ."\r\n"; $result = ''; $errno = $errstr = ""; $fs = fsockopen("ssl://" . $hostname, 443, $errno, $errstr, 10); if( false == $fs ) { error_log('Could not open socket'); } else { fwrite($fs, $http_request); while (!feof($fs)) { $result .= fgets($fs, 4096); } $result = explode("\r\n\r\n", $result, 2); $result = $result[1]; } } return $result; }
php
protected function doHttpsPost($hostname, $path, $fields) { $result = ''; $fields_string = ''; //Url encode the string foreach($fields as $key => $value) { if (is_array($value)) { if (! empty($value)) { foreach ($value as $k => $v) { $fields_string .= $key . '['. $k .']=' . $v . '&'; } } else { $fields_string .= $key . '=&'; } } else { $fields_string .= $key.'='.$value.'&'; } } rtrim($fields_string,'&'); // cURL or something else if(function_exists('curl_init')) { $curlsession = curl_init(); curl_setopt($curlsession, CURLOPT_URL, 'https://' . $hostname . $path); curl_setopt($curlsession, CURLOPT_POST,count($fields)); curl_setopt($curlsession, CURLOPT_POSTFIELDS,$fields_string); curl_setopt($curlsession, CURLOPT_RETURNTRANSFER,1); curl_setopt($curlsession, CURLOPT_SSL_VERIFYHOST,0); curl_setopt($curlsession, CURLOPT_SSL_VERIFYPEER,false); $result = curl_exec($curlsession); } else { // Build a header $http_request = "POST $path HTTP/1.1\r\n"; $http_request .= "Host: $hostname\r\n"; $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $http_request .= "Content-Length: " . strlen($fields_string) . "\r\n"; $http_request .= "User-Agent: AreYouAHuman/PHP " . $this->version . "\r\n"; $http_request .= "Connection: Close\r\n"; $http_request .= "\r\n"; $http_request .= $fields_string ."\r\n"; $result = ''; $errno = $errstr = ""; $fs = fsockopen("ssl://" . $hostname, 443, $errno, $errstr, 10); if( false == $fs ) { error_log('Could not open socket'); } else { fwrite($fs, $http_request); while (!feof($fs)) { $result .= fgets($fs, 4096); } $result = explode("\r\n\r\n", $result, 2); $result = $result[1]; } } return $result; }
[ "protected", "function", "doHttpsPost", "(", "$", "hostname", ",", "$", "path", ",", "$", "fields", ")", "{", "$", "result", "=", "''", ";", "$", "fields_string", "=", "''", ";", "//Url encode the string", "foreach", "(", "$", "fields", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "foreach", "(", "$", "value", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "fields_string", ".=", "$", "key", ".", "'['", ".", "$", "k", ".", "']='", ".", "$", "v", ".", "'&'", ";", "}", "}", "else", "{", "$", "fields_string", ".=", "$", "key", ".", "'=&'", ";", "}", "}", "else", "{", "$", "fields_string", ".=", "$", "key", ".", "'='", ".", "$", "value", ".", "'&'", ";", "}", "}", "rtrim", "(", "$", "fields_string", ",", "'&'", ")", ";", "// cURL or something else", "if", "(", "function_exists", "(", "'curl_init'", ")", ")", "{", "$", "curlsession", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "curlsession", ",", "CURLOPT_URL", ",", "'https://'", ".", "$", "hostname", ".", "$", "path", ")", ";", "curl_setopt", "(", "$", "curlsession", ",", "CURLOPT_POST", ",", "count", "(", "$", "fields", ")", ")", ";", "curl_setopt", "(", "$", "curlsession", ",", "CURLOPT_POSTFIELDS", ",", "$", "fields_string", ")", ";", "curl_setopt", "(", "$", "curlsession", ",", "CURLOPT_RETURNTRANSFER", ",", "1", ")", ";", "curl_setopt", "(", "$", "curlsession", ",", "CURLOPT_SSL_VERIFYHOST", ",", "0", ")", ";", "curl_setopt", "(", "$", "curlsession", ",", "CURLOPT_SSL_VERIFYPEER", ",", "false", ")", ";", "$", "result", "=", "curl_exec", "(", "$", "curlsession", ")", ";", "}", "else", "{", "// Build a header", "$", "http_request", "=", "\"POST $path HTTP/1.1\\r\\n\"", ";", "$", "http_request", ".=", "\"Host: $hostname\\r\\n\"", ";", "$", "http_request", ".=", "\"Content-Type: application/x-www-form-urlencoded;\\r\\n\"", ";", "$", "http_request", ".=", "\"Content-Length: \"", ".", "strlen", "(", "$", "fields_string", ")", ".", "\"\\r\\n\"", ";", "$", "http_request", ".=", "\"User-Agent: AreYouAHuman/PHP \"", ".", "$", "this", "->", "version", ".", "\"\\r\\n\"", ";", "$", "http_request", ".=", "\"Connection: Close\\r\\n\"", ";", "$", "http_request", ".=", "\"\\r\\n\"", ";", "$", "http_request", ".=", "$", "fields_string", ".", "\"\\r\\n\"", ";", "$", "result", "=", "''", ";", "$", "errno", "=", "$", "errstr", "=", "\"\"", ";", "$", "fs", "=", "fsockopen", "(", "\"ssl://\"", ".", "$", "hostname", ",", "443", ",", "$", "errno", ",", "$", "errstr", ",", "10", ")", ";", "if", "(", "false", "==", "$", "fs", ")", "{", "error_log", "(", "'Could not open socket'", ")", ";", "}", "else", "{", "fwrite", "(", "$", "fs", ",", "$", "http_request", ")", ";", "while", "(", "!", "feof", "(", "$", "fs", ")", ")", "{", "$", "result", ".=", "fgets", "(", "$", "fs", ",", "4096", ")", ";", "}", "$", "result", "=", "explode", "(", "\"\\r\\n\\r\\n\"", ",", "$", "result", ",", "2", ")", ";", "$", "result", "=", "$", "result", "[", "1", "]", ";", "}", "}", "return", "$", "result", ";", "}" ]
Initiate a request to the AYAH web service through curl or using a socket if the system does not have curl available. @param string $hostname @param string $path @param array $fields @return string|mixed
[ "Initiate", "a", "request", "to", "the", "AYAH", "web", "service", "through", "curl", "or", "using", "a", "socket", "if", "the", "system", "does", "not", "have", "curl", "available", "." ]
38a724c5e28d1d6a6dbe1d86125974498b3e4f00
https://github.com/blackknight467/AYAHBundle/blob/38a724c5e28d1d6a6dbe1d86125974498b3e4f00/Service/AYAHService.php#L200-L265
train
gangachris/potato-orm
src/Potato.php
Potato.tableExists
public static function tableExists($tableName) { $query = "SELECT 1 FROM $tableName LIMIT 1"; try { $result = Connection::db()->query($query); } catch (Exception $e) { return false; } return $result !== false; }
php
public static function tableExists($tableName) { $query = "SELECT 1 FROM $tableName LIMIT 1"; try { $result = Connection::db()->query($query); } catch (Exception $e) { return false; } return $result !== false; }
[ "public", "static", "function", "tableExists", "(", "$", "tableName", ")", "{", "$", "query", "=", "\"SELECT 1 FROM $tableName LIMIT 1\"", ";", "try", "{", "$", "result", "=", "Connection", "::", "db", "(", ")", "->", "query", "(", "$", "query", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "return", "$", "result", "!==", "false", ";", "}" ]
Checks if a given table exists in the database @param string $tableName name of the table to be checked @return bool true if table is found, false otherwise
[ "Checks", "if", "a", "given", "table", "exists", "in", "the", "database" ]
12bb25ca31716aac97bbe78596810220e39626b0
https://github.com/gangachris/potato-orm/blob/12bb25ca31716aac97bbe78596810220e39626b0/src/Potato.php#L53-L64
train
gangachris/potato-orm
src/Potato.php
Potato.getAll
public static function getAll($fields = null) { $table = self::getTableNameFromClass(); if ($fields != null && is_array($fields)) { $query = "SELECT ". implode(', ', $fields) ." FROM $table"; } else { $query = "SELECT * FROM $table"; } $res = []; $results = Connection::db()->query($query); $results->setFetchMode(PDO::FETCH_ASSOC); while ($row = $results->fetch()) { array_push($res, $row); } return $res; }
php
public static function getAll($fields = null) { $table = self::getTableNameFromClass(); if ($fields != null && is_array($fields)) { $query = "SELECT ". implode(', ', $fields) ." FROM $table"; } else { $query = "SELECT * FROM $table"; } $res = []; $results = Connection::db()->query($query); $results->setFetchMode(PDO::FETCH_ASSOC); while ($row = $results->fetch()) { array_push($res, $row); } return $res; }
[ "public", "static", "function", "getAll", "(", "$", "fields", "=", "null", ")", "{", "$", "table", "=", "self", "::", "getTableNameFromClass", "(", ")", ";", "if", "(", "$", "fields", "!=", "null", "&&", "is_array", "(", "$", "fields", ")", ")", "{", "$", "query", "=", "\"SELECT \"", ".", "implode", "(", "', '", ",", "$", "fields", ")", ".", "\" FROM $table\"", ";", "}", "else", "{", "$", "query", "=", "\"SELECT * FROM $table\"", ";", "}", "$", "res", "=", "[", "]", ";", "$", "results", "=", "Connection", "::", "db", "(", ")", "->", "query", "(", "$", "query", ")", ";", "$", "results", "->", "setFetchMode", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "while", "(", "$", "row", "=", "$", "results", "->", "fetch", "(", ")", ")", "{", "array_push", "(", "$", "res", ",", "$", "row", ")", ";", "}", "return", "$", "res", ";", "}" ]
Get all records from the record table @param array $fields array of fields to be retrieved @return array associative array of the records received from the database
[ "Get", "all", "records", "from", "the", "record", "table" ]
12bb25ca31716aac97bbe78596810220e39626b0
https://github.com/gangachris/potato-orm/blob/12bb25ca31716aac97bbe78596810220e39626b0/src/Potato.php#L100-L120
train
gangachris/potato-orm
src/Potato.php
Potato.getOne
public static function getOne($id, $fields = null) { $table = self::getTableNameFromClass(); if ($fields != null && is_array($fields)) { $query = "SELECT ". implode(', ', $fields) ." FROM $table WHERE id = $id"; } else { $query = "SELECT * FROM $table WHERE id = $id"; } $res = []; $results = Connection::db()->query($query); $results->setFetchMode(PDO::FETCH_ASSOC); while ($row = $results->fetch()) { array_push($res, $row); } if (!empty($res)) { return $res; } else { throw new PotatoException('There is no user with id '. $id); } }
php
public static function getOne($id, $fields = null) { $table = self::getTableNameFromClass(); if ($fields != null && is_array($fields)) { $query = "SELECT ". implode(', ', $fields) ." FROM $table WHERE id = $id"; } else { $query = "SELECT * FROM $table WHERE id = $id"; } $res = []; $results = Connection::db()->query($query); $results->setFetchMode(PDO::FETCH_ASSOC); while ($row = $results->fetch()) { array_push($res, $row); } if (!empty($res)) { return $res; } else { throw new PotatoException('There is no user with id '. $id); } }
[ "public", "static", "function", "getOne", "(", "$", "id", ",", "$", "fields", "=", "null", ")", "{", "$", "table", "=", "self", "::", "getTableNameFromClass", "(", ")", ";", "if", "(", "$", "fields", "!=", "null", "&&", "is_array", "(", "$", "fields", ")", ")", "{", "$", "query", "=", "\"SELECT \"", ".", "implode", "(", "', '", ",", "$", "fields", ")", ".", "\" FROM $table WHERE id = $id\"", ";", "}", "else", "{", "$", "query", "=", "\"SELECT * FROM $table WHERE id = $id\"", ";", "}", "$", "res", "=", "[", "]", ";", "$", "results", "=", "Connection", "::", "db", "(", ")", "->", "query", "(", "$", "query", ")", ";", "$", "results", "->", "setFetchMode", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "while", "(", "$", "row", "=", "$", "results", "->", "fetch", "(", ")", ")", "{", "array_push", "(", "$", "res", ",", "$", "row", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "res", ")", ")", "{", "return", "$", "res", ";", "}", "else", "{", "throw", "new", "PotatoException", "(", "'There is no user with id '", ".", "$", "id", ")", ";", "}", "}" ]
Get one record from the table based on the id provided @param integer $id id of the record to be retrieved @param array $fields array of fields to be retrieved @return array associative array of the record retrieved
[ "Get", "one", "record", "from", "the", "table", "based", "on", "the", "id", "provided" ]
12bb25ca31716aac97bbe78596810220e39626b0
https://github.com/gangachris/potato-orm/blob/12bb25ca31716aac97bbe78596810220e39626b0/src/Potato.php#L128-L152
train
gangachris/potato-orm
src/Potato.php
Potato.save
public function save() { $result; if (! self::$id) { // new record so we insert $query = "INSERT INTO $this->tableName (".implode(", ", array_keys($this->props)).") VALUES("; for ($i = 0; $i < count($this->props); $i++) { $query .= "?"; if ($i != count($this->props) - 1) { $query .= ","; } } $query .= ");"; $insert = Connection::db()->prepare($query); $result = $insert->execute(array_values($this->props)); } else { // existing record, se we update $query = "UPDATE $this->tableName SET "; $count = 0; foreach ($this->props as $key => $value) { $query .= "$key = '$value'"; if ($count != count($this->props) - 1) { $query .= ","; } $count++; } $query .= " WHERE id = ".self::$id; $result = Connection::db()->query($query); } if (! $result) { return false; } else { return true; } }
php
public function save() { $result; if (! self::$id) { // new record so we insert $query = "INSERT INTO $this->tableName (".implode(", ", array_keys($this->props)).") VALUES("; for ($i = 0; $i < count($this->props); $i++) { $query .= "?"; if ($i != count($this->props) - 1) { $query .= ","; } } $query .= ");"; $insert = Connection::db()->prepare($query); $result = $insert->execute(array_values($this->props)); } else { // existing record, se we update $query = "UPDATE $this->tableName SET "; $count = 0; foreach ($this->props as $key => $value) { $query .= "$key = '$value'"; if ($count != count($this->props) - 1) { $query .= ","; } $count++; } $query .= " WHERE id = ".self::$id; $result = Connection::db()->query($query); } if (! $result) { return false; } else { return true; } }
[ "public", "function", "save", "(", ")", "{", "$", "result", ";", "if", "(", "!", "self", "::", "$", "id", ")", "{", "// new record so we insert", "$", "query", "=", "\"INSERT INTO $this->tableName (\"", ".", "implode", "(", "\", \"", ",", "array_keys", "(", "$", "this", "->", "props", ")", ")", ".", "\") VALUES(\"", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "this", "->", "props", ")", ";", "$", "i", "++", ")", "{", "$", "query", ".=", "\"?\"", ";", "if", "(", "$", "i", "!=", "count", "(", "$", "this", "->", "props", ")", "-", "1", ")", "{", "$", "query", ".=", "\",\"", ";", "}", "}", "$", "query", ".=", "\");\"", ";", "$", "insert", "=", "Connection", "::", "db", "(", ")", "->", "prepare", "(", "$", "query", ")", ";", "$", "result", "=", "$", "insert", "->", "execute", "(", "array_values", "(", "$", "this", "->", "props", ")", ")", ";", "}", "else", "{", "// existing record, se we update", "$", "query", "=", "\"UPDATE $this->tableName SET \"", ";", "$", "count", "=", "0", ";", "foreach", "(", "$", "this", "->", "props", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "query", ".=", "\"$key = '$value'\"", ";", "if", "(", "$", "count", "!=", "count", "(", "$", "this", "->", "props", ")", "-", "1", ")", "{", "$", "query", ".=", "\",\"", ";", "}", "$", "count", "++", ";", "}", "$", "query", ".=", "\" WHERE id = \"", ".", "self", "::", "$", "id", ";", "$", "result", "=", "Connection", "::", "db", "(", ")", "->", "query", "(", "$", "query", ")", ";", "}", "if", "(", "!", "$", "result", ")", "{", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Save either a new or existing record @return integer 1 is successful, 0 if false
[ "Save", "either", "a", "new", "or", "existing", "record" ]
12bb25ca31716aac97bbe78596810220e39626b0
https://github.com/gangachris/potato-orm/blob/12bb25ca31716aac97bbe78596810220e39626b0/src/Potato.php#L158-L200
train
gangachris/potato-orm
src/Potato.php
Potato.destroy
public static function destroy($id) { $table = self::getTableNameFromClass(); self::getOne($id); $query = "DELETE FROM $table WHERE id = ".$id; try { Connection::db()->query($query); return true; } catch (Exception $e) { return false; } }
php
public static function destroy($id) { $table = self::getTableNameFromClass(); self::getOne($id); $query = "DELETE FROM $table WHERE id = ".$id; try { Connection::db()->query($query); return true; } catch (Exception $e) { return false; } }
[ "public", "static", "function", "destroy", "(", "$", "id", ")", "{", "$", "table", "=", "self", "::", "getTableNameFromClass", "(", ")", ";", "self", "::", "getOne", "(", "$", "id", ")", ";", "$", "query", "=", "\"DELETE FROM $table WHERE id = \"", ".", "$", "id", ";", "try", "{", "Connection", "::", "db", "(", ")", "->", "query", "(", "$", "query", ")", ";", "return", "true", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
Delete a record by id from the table in context @param id $id the id of the record to be deleted @return [type] [description]
[ "Delete", "a", "record", "by", "id", "from", "the", "table", "in", "context" ]
12bb25ca31716aac97bbe78596810220e39626b0
https://github.com/gangachris/potato-orm/blob/12bb25ca31716aac97bbe78596810220e39626b0/src/Potato.php#L219-L233
train
rollerworks/search-core
Extension/Core/DataTransformer/NumberToStringTransformer.php
NumberToStringTransformer.transform
public function transform($value): string { if (null === $value || '' === $value) { return ''; } if (!is_numeric($value)) { throw new TransformationFailedException('Expected a numeric or null.'); } if ($value >= PHP_INT_MAX || $value <= -PHP_INT_MAX) { throw new TransformationFailedException('I don\'t have a clear idea what infinity looks like.'); } return (string) $this->round($value); }
php
public function transform($value): string { if (null === $value || '' === $value) { return ''; } if (!is_numeric($value)) { throw new TransformationFailedException('Expected a numeric or null.'); } if ($value >= PHP_INT_MAX || $value <= -PHP_INT_MAX) { throw new TransformationFailedException('I don\'t have a clear idea what infinity looks like.'); } return (string) $this->round($value); }
[ "public", "function", "transform", "(", "$", "value", ")", ":", "string", "{", "if", "(", "null", "===", "$", "value", "||", "''", "===", "$", "value", ")", "{", "return", "''", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "throw", "new", "TransformationFailedException", "(", "'Expected a numeric or null.'", ")", ";", "}", "if", "(", "$", "value", ">=", "PHP_INT_MAX", "||", "$", "value", "<=", "-", "PHP_INT_MAX", ")", "{", "throw", "new", "TransformationFailedException", "(", "'I don\\'t have a clear idea what infinity looks like.'", ")", ";", "}", "return", "(", "string", ")", "$", "this", "->", "round", "(", "$", "value", ")", ";", "}" ]
Transforms a number type into number. @param int|float|string|null $value Number value @throws TransformationFailedException If the given value is not numeric or if the value can not be transformed
[ "Transforms", "a", "number", "type", "into", "number", "." ]
6b5671b8c4d6298906ded768261b0a59845140fb
https://github.com/rollerworks/search-core/blob/6b5671b8c4d6298906ded768261b0a59845140fb/Extension/Core/DataTransformer/NumberToStringTransformer.php#L33-L48
train
rollerworks/search-core
Extension/Core/DataTransformer/NumberToStringTransformer.php
NumberToStringTransformer.reverseTransform
public function reverseTransform($value) { if (!is_scalar($value)) { throw new TransformationFailedException('Expected a scalar.'); } if ('' === $value) { return null; } $result = $value; if (!is_numeric($result)) { throw new TransformationFailedException('Value is not numeric.'); } if (\is_string($result)) { if (false !== mb_strpos($result, '.')) { $result = (float) $result; } else { $result = (int) $result; } } if ($result >= PHP_INT_MAX || $result <= -PHP_INT_MAX) { throw new TransformationFailedException('I don\'t have a clear idea what infinity looks like.'); } return $this->round($result); }
php
public function reverseTransform($value) { if (!is_scalar($value)) { throw new TransformationFailedException('Expected a scalar.'); } if ('' === $value) { return null; } $result = $value; if (!is_numeric($result)) { throw new TransformationFailedException('Value is not numeric.'); } if (\is_string($result)) { if (false !== mb_strpos($result, '.')) { $result = (float) $result; } else { $result = (int) $result; } } if ($result >= PHP_INT_MAX || $result <= -PHP_INT_MAX) { throw new TransformationFailedException('I don\'t have a clear idea what infinity looks like.'); } return $this->round($result); }
[ "public", "function", "reverseTransform", "(", "$", "value", ")", "{", "if", "(", "!", "is_scalar", "(", "$", "value", ")", ")", "{", "throw", "new", "TransformationFailedException", "(", "'Expected a scalar.'", ")", ";", "}", "if", "(", "''", "===", "$", "value", ")", "{", "return", "null", ";", "}", "$", "result", "=", "$", "value", ";", "if", "(", "!", "is_numeric", "(", "$", "result", ")", ")", "{", "throw", "new", "TransformationFailedException", "(", "'Value is not numeric.'", ")", ";", "}", "if", "(", "\\", "is_string", "(", "$", "result", ")", ")", "{", "if", "(", "false", "!==", "mb_strpos", "(", "$", "result", ",", "'.'", ")", ")", "{", "$", "result", "=", "(", "float", ")", "$", "result", ";", "}", "else", "{", "$", "result", "=", "(", "int", ")", "$", "result", ";", "}", "}", "if", "(", "$", "result", ">=", "PHP_INT_MAX", "||", "$", "result", "<=", "-", "PHP_INT_MAX", ")", "{", "throw", "new", "TransformationFailedException", "(", "'I don\\'t have a clear idea what infinity looks like.'", ")", ";", "}", "return", "$", "this", "->", "round", "(", "$", "result", ")", ";", "}" ]
Transforms a normalized number into an integer or float. @param string $value The localized value @throws TransformationFailedException If the given value is not a string or if the value can not be transformed @return int|float|null The numeric value
[ "Transforms", "a", "normalized", "number", "into", "an", "integer", "or", "float", "." ]
6b5671b8c4d6298906ded768261b0a59845140fb
https://github.com/rollerworks/search-core/blob/6b5671b8c4d6298906ded768261b0a59845140fb/Extension/Core/DataTransformer/NumberToStringTransformer.php#L60-L89
train
miaoxing/plugin
src/Service/Asset.php
Asset.locateFile
protected function locateFile($file) { $this->locateFile && $file = call_user_func($this->locateFile, $file); return $file; }
php
protected function locateFile($file) { $this->locateFile && $file = call_user_func($this->locateFile, $file); return $file; }
[ "protected", "function", "locateFile", "(", "$", "file", ")", "{", "$", "this", "->", "locateFile", "&&", "$", "file", "=", "call_user_func", "(", "$", "this", "->", "locateFile", ",", "$", "file", ")", ";", "return", "$", "file", ";", "}" ]
Convert file name by callback @param string $file @return mixed
[ "Convert", "file", "name", "by", "callback" ]
f287a1e6c97abba6f06906255b8c26e8ab0afe61
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/Asset.php#L95-L100
train
miaoxing/plugin
src/Service/Asset.php
Asset.getRevMap
public function getRevMap() { if ($this->revMap === null) { if ($this->revFile && is_file($this->revFile)) { $this->revMap = (array) json_decode(file_get_contents($this->revFile)); } else { $this->revMap = []; } } return $this->revMap; }
php
public function getRevMap() { if ($this->revMap === null) { if ($this->revFile && is_file($this->revFile)) { $this->revMap = (array) json_decode(file_get_contents($this->revFile)); } else { $this->revMap = []; } } return $this->revMap; }
[ "public", "function", "getRevMap", "(", ")", "{", "if", "(", "$", "this", "->", "revMap", "===", "null", ")", "{", "if", "(", "$", "this", "->", "revFile", "&&", "is_file", "(", "$", "this", "->", "revFile", ")", ")", "{", "$", "this", "->", "revMap", "=", "(", "array", ")", "json_decode", "(", "file_get_contents", "(", "$", "this", "->", "revFile", ")", ")", ";", "}", "else", "{", "$", "this", "->", "revMap", "=", "[", "]", ";", "}", "}", "return", "$", "this", "->", "revMap", ";", "}" ]
Returns rev file content that parsed to array @return array
[ "Returns", "rev", "file", "content", "that", "parsed", "to", "array" ]
f287a1e6c97abba6f06906255b8c26e8ab0afe61
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/Asset.php#L118-L129
train
miaoxing/plugin
src/Service/Asset.php
Asset.addRevFile
public function addRevFile($file) { // Load default rev file $this->getRevMap(); if (is_file($file)) { $this->revMap = json_decode(file_get_contents($file), true) + $this->revMap; } return $this; }
php
public function addRevFile($file) { // Load default rev file $this->getRevMap(); if (is_file($file)) { $this->revMap = json_decode(file_get_contents($file), true) + $this->revMap; } return $this; }
[ "public", "function", "addRevFile", "(", "$", "file", ")", "{", "// Load default rev file", "$", "this", "->", "getRevMap", "(", ")", ";", "if", "(", "is_file", "(", "$", "file", ")", ")", "{", "$", "this", "->", "revMap", "=", "json_decode", "(", "file_get_contents", "(", "$", "file", ")", ",", "true", ")", "+", "$", "this", "->", "revMap", ";", "}", "return", "$", "this", ";", "}" ]
Add rev map from file @param string $file @return $this
[ "Add", "rev", "map", "from", "file" ]
f287a1e6c97abba6f06906255b8c26e8ab0afe61
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/Asset.php#L137-L147
train
miaoxing/plugin
src/Service/Asset.php
Asset.getRevFile
public function getRevFile($file) { $map = $this->getRevMap(); if (isset($map[$file])) { $index = strrpos($file, '.'); $file = $this->revPrefix . substr($file, 0, $index) . '-' . $map[$file] . substr($file, $index); } return $file; }
php
public function getRevFile($file) { $map = $this->getRevMap(); if (isset($map[$file])) { $index = strrpos($file, '.'); $file = $this->revPrefix . substr($file, 0, $index) . '-' . $map[$file] . substr($file, $index); } return $file; }
[ "public", "function", "getRevFile", "(", "$", "file", ")", "{", "$", "map", "=", "$", "this", "->", "getRevMap", "(", ")", ";", "if", "(", "isset", "(", "$", "map", "[", "$", "file", "]", ")", ")", "{", "$", "index", "=", "strrpos", "(", "$", "file", ",", "'.'", ")", ";", "$", "file", "=", "$", "this", "->", "revPrefix", ".", "substr", "(", "$", "file", ",", "0", ",", "$", "index", ")", ".", "'-'", ".", "$", "map", "[", "$", "file", "]", ".", "substr", "(", "$", "file", ",", "$", "index", ")", ";", "}", "return", "$", "file", ";", "}" ]
Returns the file path contains revision eg 'assets/article.js' => 'assets/article-a123b456.js' @param string $file @return string
[ "Returns", "the", "file", "path", "contains", "revision" ]
f287a1e6c97abba6f06906255b8c26e8ab0afe61
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/Asset.php#L157-L166
train
VTacius/ldapPM
src/Objetos/objetosLdap.php
objetosLdap.conectar
public function conectar($destino, $usuario, $password = false) { parent::conectar($destino, $usuario, $password); $this->destino = $destino; $this->usuario = $usuario; $this->password = $password; $this->objeto = 'objetosLdap'; }
php
public function conectar($destino, $usuario, $password = false) { parent::conectar($destino, $usuario, $password); $this->destino = $destino; $this->usuario = $usuario; $this->password = $password; $this->objeto = 'objetosLdap'; }
[ "public", "function", "conectar", "(", "$", "destino", ",", "$", "usuario", ",", "$", "password", "=", "false", ")", "{", "parent", "::", "conectar", "(", "$", "destino", ",", "$", "usuario", ",", "$", "password", ")", ";", "$", "this", "->", "destino", "=", "$", "destino", ";", "$", "this", "->", "usuario", "=", "$", "usuario", ";", "$", "this", "->", "password", "=", "$", "password", ";", "$", "this", "->", "objeto", "=", "'objetosLdap'", ";", "}" ]
Sobreescribirlo a este nivel obedece a que es en los objetos donde por ahora he visto la necesidad de acceder a las credenciales de conexion para tratar con diferentes objetos @param string $destino @param string $usuario @param string $password
[ "Sobreescribirlo", "a", "este", "nivel", "obedece", "a", "que", "es", "en", "los", "objetos", "donde", "por", "ahora", "he", "visto", "la", "necesidad", "de", "acceder", "a", "las", "credenciales", "de", "conexion", "para", "tratar", "con", "diferentes", "objetos" ]
728af24cd0a5ca4fbed76ffb52aa4800b118879f
https://github.com/VTacius/ldapPM/blob/728af24cd0a5ca4fbed76ffb52aa4800b118879f/src/Objetos/objetosLdap.php#L99-L105
train
VTacius/ldapPM
src/Objetos/objetosLdap.php
objetosLdap.actualizarObjetoLdap
public function actualizarObjetoLdap(){ if ($this->existe) { $dn = $this->entrada['dn']; $cambios = array(); foreach ($this->cambios as $atributos) { $cambios[$atributos] = $this->entrada[$atributos]; } return $this->modificarEntradaLdap($dn, $cambios); }else{ $this->configurarErrorLdap('Actualizacion', 'Esa entrada no existe'); return false; } }
php
public function actualizarObjetoLdap(){ if ($this->existe) { $dn = $this->entrada['dn']; $cambios = array(); foreach ($this->cambios as $atributos) { $cambios[$atributos] = $this->entrada[$atributos]; } return $this->modificarEntradaLdap($dn, $cambios); }else{ $this->configurarErrorLdap('Actualizacion', 'Esa entrada no existe'); return false; } }
[ "public", "function", "actualizarObjetoLdap", "(", ")", "{", "if", "(", "$", "this", "->", "existe", ")", "{", "$", "dn", "=", "$", "this", "->", "entrada", "[", "'dn'", "]", ";", "$", "cambios", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "cambios", "as", "$", "atributos", ")", "{", "$", "cambios", "[", "$", "atributos", "]", "=", "$", "this", "->", "entrada", "[", "$", "atributos", "]", ";", "}", "return", "$", "this", "->", "modificarEntradaLdap", "(", "$", "dn", ",", "$", "cambios", ")", ";", "}", "else", "{", "$", "this", "->", "configurarErrorLdap", "(", "'Actualizacion'", ",", "'Esa entrada no existe'", ")", ";", "return", "false", ";", "}", "}" ]
Actualiza una entrada LDAP existente @return string
[ "Actualiza", "una", "entrada", "LDAP", "existente" ]
728af24cd0a5ca4fbed76ffb52aa4800b118879f
https://github.com/VTacius/ldapPM/blob/728af24cd0a5ca4fbed76ffb52aa4800b118879f/src/Objetos/objetosLdap.php#L369-L381
train
VTacius/ldapPM
src/Objetos/objetosLdap.php
objetosLdap.borrarObjetoLdap
protected function borrarObjetoLdap(){ if ($this->existe) { $dn = $this->dnObjeto; return $this->borrarEntradaLdap($dn); }else{ $this->configurarErrorLdap('Actualizacion', 'Esa entrada no existe'); return false; } }
php
protected function borrarObjetoLdap(){ if ($this->existe) { $dn = $this->dnObjeto; return $this->borrarEntradaLdap($dn); }else{ $this->configurarErrorLdap('Actualizacion', 'Esa entrada no existe'); return false; } }
[ "protected", "function", "borrarObjetoLdap", "(", ")", "{", "if", "(", "$", "this", "->", "existe", ")", "{", "$", "dn", "=", "$", "this", "->", "dnObjeto", ";", "return", "$", "this", "->", "borrarEntradaLdap", "(", "$", "dn", ")", ";", "}", "else", "{", "$", "this", "->", "configurarErrorLdap", "(", "'Actualizacion'", ",", "'Esa entrada no existe'", ")", ";", "return", "false", ";", "}", "}" ]
Borra el objeto que se ha consultado @return boolean
[ "Borra", "el", "objeto", "que", "se", "ha", "consultado" ]
728af24cd0a5ca4fbed76ffb52aa4800b118879f
https://github.com/VTacius/ldapPM/blob/728af24cd0a5ca4fbed76ffb52aa4800b118879f/src/Objetos/objetosLdap.php#L423-L432
train
TuumPHP/Web
src/Web.php
Web.setAppRoot
public function setAppRoot(array $config) { $this->app_name = $config['app_name']; $this->app_dir = rtrim($config['app_dir'], '/'); $this->debug = $config['debug']; $this->config_dir = $config['config_dir']; $this->view_dir = $config['view_dir']; $this->vars_dir = $config['vars_dir']; return $this; }
php
public function setAppRoot(array $config) { $this->app_name = $config['app_name']; $this->app_dir = rtrim($config['app_dir'], '/'); $this->debug = $config['debug']; $this->config_dir = $config['config_dir']; $this->view_dir = $config['view_dir']; $this->vars_dir = $config['vars_dir']; return $this; }
[ "public", "function", "setAppRoot", "(", "array", "$", "config", ")", "{", "$", "this", "->", "app_name", "=", "$", "config", "[", "'app_name'", "]", ";", "$", "this", "->", "app_dir", "=", "rtrim", "(", "$", "config", "[", "'app_dir'", "]", ",", "'/'", ")", ";", "$", "this", "->", "debug", "=", "$", "config", "[", "'debug'", "]", ";", "$", "this", "->", "config_dir", "=", "$", "config", "[", "'config_dir'", "]", ";", "$", "this", "->", "view_dir", "=", "$", "config", "[", "'view_dir'", "]", ";", "$", "this", "->", "vars_dir", "=", "$", "config", "[", "'vars_dir'", "]", ";", "return", "$", "this", ";", "}" ]
set up working directories. @param array $config @return $this
[ "set", "up", "working", "directories", "." ]
8f296b6358aa93226ce08d6cc54a309f5b0a9820
https://github.com/TuumPHP/Web/blob/8f296b6358aa93226ce08d6cc54a309f5b0a9820/src/Web.php#L105-L114
train
TuumPHP/Web
src/Web.php
Web.loadConfig
public function loadConfig($env_file=null) { $this->configure($this->config_dir . '/configure'); if ($this->debug) { $this->configure($this->config_dir . '/configure-debug'); } $this->loadEnvironment($env_file); return $this; }
php
public function loadConfig($env_file=null) { $this->configure($this->config_dir . '/configure'); if ($this->debug) { $this->configure($this->config_dir . '/configure-debug'); } $this->loadEnvironment($env_file); return $this; }
[ "public", "function", "loadConfig", "(", "$", "env_file", "=", "null", ")", "{", "$", "this", "->", "configure", "(", "$", "this", "->", "config_dir", ".", "'/configure'", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "$", "this", "->", "configure", "(", "$", "this", "->", "config_dir", ".", "'/configure-debug'", ")", ";", "}", "$", "this", "->", "loadEnvironment", "(", "$", "env_file", ")", ";", "return", "$", "this", ";", "}" ]
loads the main configuration for the application. @param null|string $env_file @return $this
[ "loads", "the", "main", "configuration", "for", "the", "application", "." ]
8f296b6358aa93226ce08d6cc54a309f5b0a9820
https://github.com/TuumPHP/Web/blob/8f296b6358aa93226ce08d6cc54a309f5b0a9820/src/Web.php#L147-L155
train
TuumPHP/Web
src/Web.php
Web.loadEnvironment
public function loadEnvironment($env_file) { $env_file .= '.php'; if (!file_exists($env_file)) { return $this; } /** @noinspection PhpIncludeInspection */ $environments = (array)include($env_file); foreach ($environments as $env) { $this->configure($this->config_dir . "/{$env}/configure"); } return $this; }
php
public function loadEnvironment($env_file) { $env_file .= '.php'; if (!file_exists($env_file)) { return $this; } /** @noinspection PhpIncludeInspection */ $environments = (array)include($env_file); foreach ($environments as $env) { $this->configure($this->config_dir . "/{$env}/configure"); } return $this; }
[ "public", "function", "loadEnvironment", "(", "$", "env_file", ")", "{", "$", "env_file", ".=", "'.php'", ";", "if", "(", "!", "file_exists", "(", "$", "env_file", ")", ")", "{", "return", "$", "this", ";", "}", "/** @noinspection PhpIncludeInspection */", "$", "environments", "=", "(", "array", ")", "include", "(", "$", "env_file", ")", ";", "foreach", "(", "$", "environments", "as", "$", "env", ")", "{", "$", "this", "->", "configure", "(", "$", "this", "->", "config_dir", ".", "\"/{$env}/configure\"", ")", ";", "}", "return", "$", "this", ";", "}" ]
loads the environment based configuration. @param string $env_file @return $this
[ "loads", "the", "environment", "based", "configuration", "." ]
8f296b6358aa93226ce08d6cc54a309f5b0a9820
https://github.com/TuumPHP/Web/blob/8f296b6358aa93226ce08d6cc54a309f5b0a9820/src/Web.php#L163-L175
train
TuumPHP/Web
src/Web.php
Web.catchError
public function catchError(array $error_files) { $this->app->set(Web::ERROR_VIEWS, $error_files); $whoops = new Run; if ($this->debug) { error_reporting(E_ALL); $whoops->pushHandler(new PrettyPageHandler); } else { error_reporting(E_ERROR); $whoops->pushHandler($this->getErrorView()); } $whoops->register(); return $this; }
php
public function catchError(array $error_files) { $this->app->set(Web::ERROR_VIEWS, $error_files); $whoops = new Run; if ($this->debug) { error_reporting(E_ALL); $whoops->pushHandler(new PrettyPageHandler); } else { error_reporting(E_ERROR); $whoops->pushHandler($this->getErrorView()); } $whoops->register(); return $this; }
[ "public", "function", "catchError", "(", "array", "$", "error_files", ")", "{", "$", "this", "->", "app", "->", "set", "(", "Web", "::", "ERROR_VIEWS", ",", "$", "error_files", ")", ";", "$", "whoops", "=", "new", "Run", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "error_reporting", "(", "E_ALL", ")", ";", "$", "whoops", "->", "pushHandler", "(", "new", "PrettyPageHandler", ")", ";", "}", "else", "{", "error_reporting", "(", "E_ERROR", ")", ";", "$", "whoops", "->", "pushHandler", "(", "$", "this", "->", "getErrorView", "(", ")", ")", ";", "}", "$", "whoops", "->", "register", "(", ")", ";", "return", "$", "this", ";", "}" ]
set up global exception handler. @param array $error_files @return $this
[ "set", "up", "global", "exception", "handler", "." ]
8f296b6358aa93226ce08d6cc54a309f5b0a9820
https://github.com/TuumPHP/Web/blob/8f296b6358aa93226ce08d6cc54a309f5b0a9820/src/Web.php#L208-L221
train
TuumPHP/Web
src/Web.php
Web.getLog
public function getLog() { if($this->app->exists(LoggerInterface::class)) { return $this->app->get(LoggerInterface::class); } $var_dir = $this->vars_dir . '/log/app.log'; $logger = new Logger('log'); $logger->pushHandler( new FingersCrossedHandler(new StreamHandler($var_dir, Logger::DEBUG)) ); $this->app->set(LoggerInterface::class, $logger, true); return $logger; }
php
public function getLog() { if($this->app->exists(LoggerInterface::class)) { return $this->app->get(LoggerInterface::class); } $var_dir = $this->vars_dir . '/log/app.log'; $logger = new Logger('log'); $logger->pushHandler( new FingersCrossedHandler(new StreamHandler($var_dir, Logger::DEBUG)) ); $this->app->set(LoggerInterface::class, $logger, true); return $logger; }
[ "public", "function", "getLog", "(", ")", "{", "if", "(", "$", "this", "->", "app", "->", "exists", "(", "LoggerInterface", "::", "class", ")", ")", "{", "return", "$", "this", "->", "app", "->", "get", "(", "LoggerInterface", "::", "class", ")", ";", "}", "$", "var_dir", "=", "$", "this", "->", "vars_dir", ".", "'/log/app.log'", ";", "$", "logger", "=", "new", "Logger", "(", "'log'", ")", ";", "$", "logger", "->", "pushHandler", "(", "new", "FingersCrossedHandler", "(", "new", "StreamHandler", "(", "$", "var_dir", ",", "Logger", "::", "DEBUG", ")", ")", ")", ";", "$", "this", "->", "app", "->", "set", "(", "LoggerInterface", "::", "class", ",", "$", "logger", ",", "true", ")", ";", "return", "$", "logger", ";", "}" ]
get shared logger. use Monolog as default. @return LoggerInterface
[ "get", "shared", "logger", ".", "use", "Monolog", "as", "default", "." ]
8f296b6358aa93226ce08d6cc54a309f5b0a9820
https://github.com/TuumPHP/Web/blob/8f296b6358aa93226ce08d6cc54a309f5b0a9820/src/Web.php#L258-L270
train
jtreminio/Zimple
src/jtreminio/Zimple/Zimple.php
Zimple.lock
public function lock($id, $value, array $parameters = array()) { $id = ltrim($id, '\\'); $obj = $this->set($id, $value, $parameters); $this->offsetSet("lock.{$id}", true); return $obj; }
php
public function lock($id, $value, array $parameters = array()) { $id = ltrim($id, '\\'); $obj = $this->set($id, $value, $parameters); $this->offsetSet("lock.{$id}", true); return $obj; }
[ "public", "function", "lock", "(", "$", "id", ",", "$", "value", ",", "array", "$", "parameters", "=", "array", "(", ")", ")", "{", "$", "id", "=", "ltrim", "(", "$", "id", ",", "'\\\\'", ")", ";", "$", "obj", "=", "$", "this", "->", "set", "(", "$", "id", ",", "$", "value", ",", "$", "parameters", ")", ";", "$", "this", "->", "offsetSet", "(", "\"lock.{$id}\"", ",", "true", ")", ";", "return", "$", "obj", ";", "}" ]
Set a value and prevent modification to return value @param string $id The unique identifier for the parameter or object @param mixed $value The value of the parameter or a closure to defined an object @param array $parameters The default parameters to use when calling this object @return self
[ "Set", "a", "value", "and", "prevent", "modification", "to", "return", "value" ]
c116c42d22a9d27d5ad7853b591fd5903e029647
https://github.com/jtreminio/Zimple/blob/c116c42d22a9d27d5ad7853b591fd5903e029647/src/jtreminio/Zimple/Zimple.php#L101-L109
train
jtreminio/Zimple
src/jtreminio/Zimple/Zimple.php
Zimple.getUndefined
private function getUndefined($fqClassName, array $parameters) { // Only use ReflectionClass if parameters are needed in constructor if (!empty($parameters)) { $reflectionClass = new ReflectionClass($fqClassName); return $reflectionClass->newInstanceArgs($parameters); } return new $fqClassName; }
php
private function getUndefined($fqClassName, array $parameters) { // Only use ReflectionClass if parameters are needed in constructor if (!empty($parameters)) { $reflectionClass = new ReflectionClass($fqClassName); return $reflectionClass->newInstanceArgs($parameters); } return new $fqClassName; }
[ "private", "function", "getUndefined", "(", "$", "fqClassName", ",", "array", "$", "parameters", ")", "{", "// Only use ReflectionClass if parameters are needed in constructor", "if", "(", "!", "empty", "(", "$", "parameters", ")", ")", "{", "$", "reflectionClass", "=", "new", "ReflectionClass", "(", "$", "fqClassName", ")", ";", "return", "$", "reflectionClass", "->", "newInstanceArgs", "(", "$", "parameters", ")", ";", "}", "return", "new", "$", "fqClassName", ";", "}" ]
If the service has not been defined within the container, attempt to instantiate the class directly @param string $fqClassName Fully qualified class name @param array $parameters Parameters object may require for constructor @return object
[ "If", "the", "service", "has", "not", "been", "defined", "within", "the", "container", "attempt", "to", "instantiate", "the", "class", "directly" ]
c116c42d22a9d27d5ad7853b591fd5903e029647
https://github.com/jtreminio/Zimple/blob/c116c42d22a9d27d5ad7853b591fd5903e029647/src/jtreminio/Zimple/Zimple.php#L128-L137
train
itkg/core
src/Itkg/Core/Command/DatabaseUpdate/Locator.php
Locator.getFiles
private function getFiles($path) { $files = array(); foreach (new \DirectoryIterator($path) as $file) { if ($file->isDot() || (null != $this->scriptName && sprintf('%s.php', $this->scriptName) != $file->getFilename()) ) { continue; } $files[$file->getFilename()] = sprintf('%s/%s', $file->getPath(), $file->getFilename()); } sort($files); return $files; }
php
private function getFiles($path) { $files = array(); foreach (new \DirectoryIterator($path) as $file) { if ($file->isDot() || (null != $this->scriptName && sprintf('%s.php', $this->scriptName) != $file->getFilename()) ) { continue; } $files[$file->getFilename()] = sprintf('%s/%s', $file->getPath(), $file->getFilename()); } sort($files); return $files; }
[ "private", "function", "getFiles", "(", "$", "path", ")", "{", "$", "files", "=", "array", "(", ")", ";", "foreach", "(", "new", "\\", "DirectoryIterator", "(", "$", "path", ")", "as", "$", "file", ")", "{", "if", "(", "$", "file", "->", "isDot", "(", ")", "||", "(", "null", "!=", "$", "this", "->", "scriptName", "&&", "sprintf", "(", "'%s.php'", ",", "$", "this", "->", "scriptName", ")", "!=", "$", "file", "->", "getFilename", "(", ")", ")", ")", "{", "continue", ";", "}", "$", "files", "[", "$", "file", "->", "getFilename", "(", ")", "]", "=", "sprintf", "(", "'%s/%s'", ",", "$", "file", "->", "getPath", "(", ")", ",", "$", "file", "->", "getFilename", "(", ")", ")", ";", "}", "sort", "(", "$", "files", ")", ";", "return", "$", "files", ";", "}" ]
Get files for a specific path @param $path @return array
[ "Get", "files", "for", "a", "specific", "path" ]
e5e4efb05feb4d23b0df41f2b21fd095103e593b
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Command/DatabaseUpdate/Locator.php#L87-L103
train
dms-org/common.structure
src/DateTime/Date.php
Date.fromNative
public static function fromNative(\DateTimeInterface $dateTime) : Date { return new self((int)$dateTime->format('Y'), (int)$dateTime->format('m'), (int)$dateTime->format('d')); }
php
public static function fromNative(\DateTimeInterface $dateTime) : Date { return new self((int)$dateTime->format('Y'), (int)$dateTime->format('m'), (int)$dateTime->format('d')); }
[ "public", "static", "function", "fromNative", "(", "\\", "DateTimeInterface", "$", "dateTime", ")", ":", "Date", "{", "return", "new", "self", "(", "(", "int", ")", "$", "dateTime", "->", "format", "(", "'Y'", ")", ",", "(", "int", ")", "$", "dateTime", "->", "format", "(", "'m'", ")", ",", "(", "int", ")", "$", "dateTime", "->", "format", "(", "'d'", ")", ")", ";", "}" ]
Creates a date object from the date part of the supplied date time. @param \DateTimeInterface $dateTime @return Date
[ "Creates", "a", "date", "object", "from", "the", "date", "part", "of", "the", "supplied", "date", "time", "." ]
23f122182f60df5ec847047a81a39c8aab019ff1
https://github.com/dms-org/common.structure/blob/23f122182f60df5ec847047a81a39c8aab019ff1/src/DateTime/Date.php#L38-L41
train
dms-org/common.structure
src/DateTime/Date.php
Date.fromFormat
public static function fromFormat(string $format, string $dateString) : Date { return self::fromNative(\DateTimeImmutable::createFromFormat($format, $dateString)); }
php
public static function fromFormat(string $format, string $dateString) : Date { return self::fromNative(\DateTimeImmutable::createFromFormat($format, $dateString)); }
[ "public", "static", "function", "fromFormat", "(", "string", "$", "format", ",", "string", "$", "dateString", ")", ":", "Date", "{", "return", "self", "::", "fromNative", "(", "\\", "DateTimeImmutable", "::", "createFromFormat", "(", "$", "format", ",", "$", "dateString", ")", ")", ";", "}" ]
Creates a date object from the supplied format string @param string $format @param string $dateString @return Date
[ "Creates", "a", "date", "object", "from", "the", "supplied", "format", "string" ]
23f122182f60df5ec847047a81a39c8aab019ff1
https://github.com/dms-org/common.structure/blob/23f122182f60df5ec847047a81a39c8aab019ff1/src/DateTime/Date.php#L51-L54
train
dms-org/common.structure
src/DateTime/Date.php
Date.daysBetween
public function daysBetween(Date $other) : int { return $this->dateTime->diff($other->dateTime, true)->days; }
php
public function daysBetween(Date $other) : int { return $this->dateTime->diff($other->dateTime, true)->days; }
[ "public", "function", "daysBetween", "(", "Date", "$", "other", ")", ":", "int", "{", "return", "$", "this", "->", "dateTime", "->", "diff", "(", "$", "other", "->", "dateTime", ",", "true", ")", "->", "days", ";", "}" ]
Returns the amount of days between the supplied dates. @param Date $other @return int
[ "Returns", "the", "amount", "of", "days", "between", "the", "supplied", "dates", "." ]
23f122182f60df5ec847047a81a39c8aab019ff1
https://github.com/dms-org/common.structure/blob/23f122182f60df5ec847047a81a39c8aab019ff1/src/DateTime/Date.php#L135-L138
train
prolic/HumusMvc
src/HumusMvc/Service/ModuleManagerFactory.php
ModuleManagerFactory.createService
public function createService(ServiceLocatorInterface $serviceLocator) { if (!$serviceLocator->has('ServiceListener')) { $serviceLocator->setFactory('ServiceListener', 'HumusMvc\Service\ServiceListenerFactory'); } if (!$serviceLocator->has('Zf1MvcListener')) { $serviceLocator->setFactory('Zf1MvcListener', 'HumusMvc\Service\Zf1MvcListenerFactory'); } $configuration = $serviceLocator->get('ApplicationConfig'); $listenerOptions = new ListenerOptions($configuration['module_listener_options']); $defaultListeners = new DefaultListenerAggregate($listenerOptions); $serviceListener = $serviceLocator->get('ServiceListener'); $serviceListener->addServiceManager( $serviceLocator, 'service_manager', 'Zend\ModuleManager\Feature\ServiceProviderInterface', 'getServiceConfig' ); $serviceListener->addServiceManager( 'ViewHelperManager', 'view_helpers', 'Zend\ModuleManager\Feature\ViewHelperProviderInterface', 'getViewHelperConfig' ); $serviceListener->addServiceManager( 'ActionHelperManager', 'action_helpers', 'HumusMvc\ModuleManager\Feature\ActionHelperProviderInterface', 'getActionHelperConfig' ); $events = $serviceLocator->get('EventManager'); $events->attach($defaultListeners); $events->attach($serviceListener); $sharedEvents = $events->getSharedManager(); $sharedEvents->attach('HumusMvc\Application', 'bootstrap', new LocaleListener); $moduleEvent = new ModuleEvent; $moduleEvent->setParam('ServiceManager', $serviceLocator); $moduleManager = new ModuleManager($configuration['modules'], $events); $moduleManager->setEvent($moduleEvent); return $moduleManager; }
php
public function createService(ServiceLocatorInterface $serviceLocator) { if (!$serviceLocator->has('ServiceListener')) { $serviceLocator->setFactory('ServiceListener', 'HumusMvc\Service\ServiceListenerFactory'); } if (!$serviceLocator->has('Zf1MvcListener')) { $serviceLocator->setFactory('Zf1MvcListener', 'HumusMvc\Service\Zf1MvcListenerFactory'); } $configuration = $serviceLocator->get('ApplicationConfig'); $listenerOptions = new ListenerOptions($configuration['module_listener_options']); $defaultListeners = new DefaultListenerAggregate($listenerOptions); $serviceListener = $serviceLocator->get('ServiceListener'); $serviceListener->addServiceManager( $serviceLocator, 'service_manager', 'Zend\ModuleManager\Feature\ServiceProviderInterface', 'getServiceConfig' ); $serviceListener->addServiceManager( 'ViewHelperManager', 'view_helpers', 'Zend\ModuleManager\Feature\ViewHelperProviderInterface', 'getViewHelperConfig' ); $serviceListener->addServiceManager( 'ActionHelperManager', 'action_helpers', 'HumusMvc\ModuleManager\Feature\ActionHelperProviderInterface', 'getActionHelperConfig' ); $events = $serviceLocator->get('EventManager'); $events->attach($defaultListeners); $events->attach($serviceListener); $sharedEvents = $events->getSharedManager(); $sharedEvents->attach('HumusMvc\Application', 'bootstrap', new LocaleListener); $moduleEvent = new ModuleEvent; $moduleEvent->setParam('ServiceManager', $serviceLocator); $moduleManager = new ModuleManager($configuration['modules'], $events); $moduleManager->setEvent($moduleEvent); return $moduleManager; }
[ "public", "function", "createService", "(", "ServiceLocatorInterface", "$", "serviceLocator", ")", "{", "if", "(", "!", "$", "serviceLocator", "->", "has", "(", "'ServiceListener'", ")", ")", "{", "$", "serviceLocator", "->", "setFactory", "(", "'ServiceListener'", ",", "'HumusMvc\\Service\\ServiceListenerFactory'", ")", ";", "}", "if", "(", "!", "$", "serviceLocator", "->", "has", "(", "'Zf1MvcListener'", ")", ")", "{", "$", "serviceLocator", "->", "setFactory", "(", "'Zf1MvcListener'", ",", "'HumusMvc\\Service\\Zf1MvcListenerFactory'", ")", ";", "}", "$", "configuration", "=", "$", "serviceLocator", "->", "get", "(", "'ApplicationConfig'", ")", ";", "$", "listenerOptions", "=", "new", "ListenerOptions", "(", "$", "configuration", "[", "'module_listener_options'", "]", ")", ";", "$", "defaultListeners", "=", "new", "DefaultListenerAggregate", "(", "$", "listenerOptions", ")", ";", "$", "serviceListener", "=", "$", "serviceLocator", "->", "get", "(", "'ServiceListener'", ")", ";", "$", "serviceListener", "->", "addServiceManager", "(", "$", "serviceLocator", ",", "'service_manager'", ",", "'Zend\\ModuleManager\\Feature\\ServiceProviderInterface'", ",", "'getServiceConfig'", ")", ";", "$", "serviceListener", "->", "addServiceManager", "(", "'ViewHelperManager'", ",", "'view_helpers'", ",", "'Zend\\ModuleManager\\Feature\\ViewHelperProviderInterface'", ",", "'getViewHelperConfig'", ")", ";", "$", "serviceListener", "->", "addServiceManager", "(", "'ActionHelperManager'", ",", "'action_helpers'", ",", "'HumusMvc\\ModuleManager\\Feature\\ActionHelperProviderInterface'", ",", "'getActionHelperConfig'", ")", ";", "$", "events", "=", "$", "serviceLocator", "->", "get", "(", "'EventManager'", ")", ";", "$", "events", "->", "attach", "(", "$", "defaultListeners", ")", ";", "$", "events", "->", "attach", "(", "$", "serviceListener", ")", ";", "$", "sharedEvents", "=", "$", "events", "->", "getSharedManager", "(", ")", ";", "$", "sharedEvents", "->", "attach", "(", "'HumusMvc\\Application'", ",", "'bootstrap'", ",", "new", "LocaleListener", ")", ";", "$", "moduleEvent", "=", "new", "ModuleEvent", ";", "$", "moduleEvent", "->", "setParam", "(", "'ServiceManager'", ",", "$", "serviceLocator", ")", ";", "$", "moduleManager", "=", "new", "ModuleManager", "(", "$", "configuration", "[", "'modules'", "]", ",", "$", "events", ")", ";", "$", "moduleManager", "->", "setEvent", "(", "$", "moduleEvent", ")", ";", "return", "$", "moduleManager", ";", "}" ]
Creates and returns the module manager Instantiates the default module listeners, providing them configuration from the "module_listener_options" key of the ApplicationConfig service. Also sets the default config glob path. Module manager is instantiated and provided with an EventManager, to which the default listener aggregate is attached. The ModuleEvent is also created and attached to the module manager. @param ServiceLocatorInterface $serviceLocator @return ModuleManager
[ "Creates", "and", "returns", "the", "module", "manager" ]
09e8c6422d84b57745cc643047e10761be2a21a7
https://github.com/prolic/HumusMvc/blob/09e8c6422d84b57745cc643047e10761be2a21a7/src/HumusMvc/Service/ModuleManagerFactory.php#L50-L96
train
codeblanche/Web
src/Web/QueryString.php
QueryString.toArray
public function toArray($ignoreEmpty = false) { if (!$ignoreEmpty) { return $this->data; } return array_filter( $this->data, function ($value) { return !empty($value); } ); }
php
public function toArray($ignoreEmpty = false) { if (!$ignoreEmpty) { return $this->data; } return array_filter( $this->data, function ($value) { return !empty($value); } ); }
[ "public", "function", "toArray", "(", "$", "ignoreEmpty", "=", "false", ")", "{", "if", "(", "!", "$", "ignoreEmpty", ")", "{", "return", "$", "this", "->", "data", ";", "}", "return", "array_filter", "(", "$", "this", "->", "data", ",", "function", "(", "$", "value", ")", "{", "return", "!", "empty", "(", "$", "value", ")", ";", "}", ")", ";", "}" ]
Extract data to an array @param boolean $ignoreEmpty @return array
[ "Extract", "data", "to", "an", "array" ]
3e9ebf1943d3ea468f619ba99f7cc10714cb16e9
https://github.com/codeblanche/Web/blob/3e9ebf1943d3ea468f619ba99f7cc10714cb16e9/src/Web/QueryString.php#L156-L168
train
codeblanche/Web
src/Web/QueryString.php
QueryString.toString
public function toString($ignoreEmpty = false, $numPrefix = null, $separator = null) { if (empty($separator)) { $separator = '&'; } return http_build_query( $this->toArray($ignoreEmpty), $numPrefix, $separator ); }
php
public function toString($ignoreEmpty = false, $numPrefix = null, $separator = null) { if (empty($separator)) { $separator = '&'; } return http_build_query( $this->toArray($ignoreEmpty), $numPrefix, $separator ); }
[ "public", "function", "toString", "(", "$", "ignoreEmpty", "=", "false", ",", "$", "numPrefix", "=", "null", ",", "$", "separator", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "separator", ")", ")", "{", "$", "separator", "=", "'&'", ";", "}", "return", "http_build_query", "(", "$", "this", "->", "toArray", "(", "$", "ignoreEmpty", ")", ",", "$", "numPrefix", ",", "$", "separator", ")", ";", "}" ]
Extract data as a query string. @param boolean $ignoreEmpty Omit empty values. @param string $numPrefix Prefix numeric keys @param string $separator Query string value separator. @return string
[ "Extract", "data", "as", "a", "query", "string", "." ]
3e9ebf1943d3ea468f619ba99f7cc10714cb16e9
https://github.com/codeblanche/Web/blob/3e9ebf1943d3ea468f619ba99f7cc10714cb16e9/src/Web/QueryString.php#L179-L190
train
codeblanche/Web
src/Web/QueryString.php
QueryString.fromArray
protected function fromArray($data) { if (empty($data)) { return $this; } $this->data = array_replace_recursive($this->data, $data); return $this; }
php
protected function fromArray($data) { if (empty($data)) { return $this; } $this->data = array_replace_recursive($this->data, $data); return $this; }
[ "protected", "function", "fromArray", "(", "$", "data", ")", "{", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "return", "$", "this", ";", "}", "$", "this", "->", "data", "=", "array_replace_recursive", "(", "$", "this", "->", "data", ",", "$", "data", ")", ";", "return", "$", "this", ";", "}" ]
Set data from an array @param array $data @return QueryString
[ "Set", "data", "from", "an", "array" ]
3e9ebf1943d3ea468f619ba99f7cc10714cb16e9
https://github.com/codeblanche/Web/blob/3e9ebf1943d3ea468f619ba99f7cc10714cb16e9/src/Web/QueryString.php#L211-L220
train
codeblanche/Web
src/Web/QueryString.php
QueryString.fromString
protected function fromString($queryString) { if (empty($queryString)) { return $this; } $data = array(); parse_str($queryString, $data); $this->fromArray($data); return $this; }
php
protected function fromString($queryString) { if (empty($queryString)) { return $this; } $data = array(); parse_str($queryString, $data); $this->fromArray($data); return $this; }
[ "protected", "function", "fromString", "(", "$", "queryString", ")", "{", "if", "(", "empty", "(", "$", "queryString", ")", ")", "{", "return", "$", "this", ";", "}", "$", "data", "=", "array", "(", ")", ";", "parse_str", "(", "$", "queryString", ",", "$", "data", ")", ";", "$", "this", "->", "fromArray", "(", "$", "data", ")", ";", "return", "$", "this", ";", "}" ]
Set data from a query string @param string $queryString @return QueryString
[ "Set", "data", "from", "a", "query", "string" ]
3e9ebf1943d3ea468f619ba99f7cc10714cb16e9
https://github.com/codeblanche/Web/blob/3e9ebf1943d3ea468f619ba99f7cc10714cb16e9/src/Web/QueryString.php#L229-L242
train
ciims/ciims-modules-api
controllers/SettingController.php
SettingController.getThemeAttributes
private function getThemeAttributes() { $theme = Cii::getConfig('theme', 'default'); if (!file_exists(Yii::getPathOfAlias('webroot.themes.' . $theme) . DIRECTORY_SEPARATOR . 'Theme.php')) throw new CHttpException(400, Yii::t('Api.setting', 'The requested theme type is not set. Please set a theme before attempting to change theme settings.')); Yii::import('webroot.themes.' . $theme . '.Theme'); try { $model = new Theme(); } catch(Exception $e) { throw new CHttpException(400, Yii::t( 'Api.setting', 'The requested theme type is not set. Please set a theme before attempting to change theme settings.' )); } return $model; }
php
private function getThemeAttributes() { $theme = Cii::getConfig('theme', 'default'); if (!file_exists(Yii::getPathOfAlias('webroot.themes.' . $theme) . DIRECTORY_SEPARATOR . 'Theme.php')) throw new CHttpException(400, Yii::t('Api.setting', 'The requested theme type is not set. Please set a theme before attempting to change theme settings.')); Yii::import('webroot.themes.' . $theme . '.Theme'); try { $model = new Theme(); } catch(Exception $e) { throw new CHttpException(400, Yii::t( 'Api.setting', 'The requested theme type is not set. Please set a theme before attempting to change theme settings.' )); } return $model; }
[ "private", "function", "getThemeAttributes", "(", ")", "{", "$", "theme", "=", "Cii", "::", "getConfig", "(", "'theme'", ",", "'default'", ")", ";", "if", "(", "!", "file_exists", "(", "Yii", "::", "getPathOfAlias", "(", "'webroot.themes.'", ".", "$", "theme", ")", ".", "DIRECTORY_SEPARATOR", ".", "'Theme.php'", ")", ")", "throw", "new", "CHttpException", "(", "400", ",", "Yii", "::", "t", "(", "'Api.setting'", ",", "'The requested theme type is not set. Please set a theme before attempting to change theme settings.'", ")", ")", ";", "Yii", "::", "import", "(", "'webroot.themes.'", ".", "$", "theme", ".", "'.Theme'", ")", ";", "try", "{", "$", "model", "=", "new", "Theme", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "CHttpException", "(", "400", ",", "Yii", "::", "t", "(", "'Api.setting'", ",", "'The requested theme type is not set. Please set a theme before attempting to change theme settings.'", ")", ")", ";", "}", "return", "$", "model", ";", "}" ]
Retrieves the appropriate model for the theme @param string $type The data type to load @return Theme
[ "Retrieves", "the", "appropriate", "model", "for", "the", "theme" ]
4351855328da0b112ac27bde7e7e07e212be8689
https://github.com/ciims/ciims-modules-api/blob/4351855328da0b112ac27bde7e7e07e212be8689/controllers/SettingController.php#L186-L205
train
ciims/ciims-modules-api
controllers/SettingController.php
SettingController.loadData
private function loadData($post, &$model) { $model->populate($_POST, false); if ($model->save()) return $this->getModelAttributes($model); return $this->returnError(400, NULL, $model->getErrors()); }
php
private function loadData($post, &$model) { $model->populate($_POST, false); if ($model->save()) return $this->getModelAttributes($model); return $this->returnError(400, NULL, $model->getErrors()); }
[ "private", "function", "loadData", "(", "$", "post", ",", "&", "$", "model", ")", "{", "$", "model", "->", "populate", "(", "$", "_POST", ",", "false", ")", ";", "if", "(", "$", "model", "->", "save", "(", ")", ")", "return", "$", "this", "->", "getModelAttributes", "(", "$", "model", ")", ";", "return", "$", "this", "->", "returnError", "(", "400", ",", "NULL", ",", "$", "model", "->", "getErrors", "(", ")", ")", ";", "}" ]
Populates and saves model attributes @param $_POST $post $_POST data @param CiiSettingsModel $model The model we want to populate @return array The saved model attributes or an error message
[ "Populates", "and", "saves", "model", "attributes" ]
4351855328da0b112ac27bde7e7e07e212be8689
https://github.com/ciims/ciims-modules-api/blob/4351855328da0b112ac27bde7e7e07e212be8689/controllers/SettingController.php#L213-L221
train
ciims/ciims-modules-api
controllers/SettingController.php
SettingController.getModelAttributes
private function getModelAttributes(&$model) { $response = array(); $reflection = new ReflectionClass($model); $properties = $reflection->getProperties(ReflectionProperty::IS_PROTECTED); foreach ($properties as $property) $response[$property->name] = $model[$property->name]; return $response; }
php
private function getModelAttributes(&$model) { $response = array(); $reflection = new ReflectionClass($model); $properties = $reflection->getProperties(ReflectionProperty::IS_PROTECTED); foreach ($properties as $property) $response[$property->name] = $model[$property->name]; return $response; }
[ "private", "function", "getModelAttributes", "(", "&", "$", "model", ")", "{", "$", "response", "=", "array", "(", ")", ";", "$", "reflection", "=", "new", "ReflectionClass", "(", "$", "model", ")", ";", "$", "properties", "=", "$", "reflection", "->", "getProperties", "(", "ReflectionProperty", "::", "IS_PROTECTED", ")", ";", "foreach", "(", "$", "properties", "as", "$", "property", ")", "$", "response", "[", "$", "property", "->", "name", "]", "=", "$", "model", "[", "$", "property", "->", "name", "]", ";", "return", "$", "response", ";", "}" ]
Retrieves model attributes for a particular model @param CiiSettingsModel $model The model we want to query against @return array
[ "Retrieves", "model", "attributes", "for", "a", "particular", "model" ]
4351855328da0b112ac27bde7e7e07e212be8689
https://github.com/ciims/ciims-modules-api/blob/4351855328da0b112ac27bde7e7e07e212be8689/controllers/SettingController.php#L228-L238
train
agentmedia/phine-core
src/Core/Modules/Backend/TemplateForm.php
TemplateForm.InitModule
private function InitModule(array $idParts) { if (count($idParts) < 1 || count($idParts) > 2) { //TODO: Message Response::Redirect(BackendRouter::ModuleUrl(new TemplateList())); } $this->module = ClassFinder::CreateFrontendModule($idParts[0]); if (!$this->module instanceof FrontendModule || !$this->module->AllowCustomTemplates()) { //TODO: Message Response::Redirect(BackendRouter::ModuleUrl(new TemplateList())); } }
php
private function InitModule(array $idParts) { if (count($idParts) < 1 || count($idParts) > 2) { //TODO: Message Response::Redirect(BackendRouter::ModuleUrl(new TemplateList())); } $this->module = ClassFinder::CreateFrontendModule($idParts[0]); if (!$this->module instanceof FrontendModule || !$this->module->AllowCustomTemplates()) { //TODO: Message Response::Redirect(BackendRouter::ModuleUrl(new TemplateList())); } }
[ "private", "function", "InitModule", "(", "array", "$", "idParts", ")", "{", "if", "(", "count", "(", "$", "idParts", ")", "<", "1", "||", "count", "(", "$", "idParts", ")", ">", "2", ")", "{", "//TODO: Message", "Response", "::", "Redirect", "(", "BackendRouter", "::", "ModuleUrl", "(", "new", "TemplateList", "(", ")", ")", ")", ";", "}", "$", "this", "->", "module", "=", "ClassFinder", "::", "CreateFrontendModule", "(", "$", "idParts", "[", "0", "]", ")", ";", "if", "(", "!", "$", "this", "->", "module", "instanceof", "FrontendModule", "||", "!", "$", "this", "->", "module", "->", "AllowCustomTemplates", "(", ")", ")", "{", "//TODO: Message", "Response", "::", "Redirect", "(", "BackendRouter", "::", "ModuleUrl", "(", "new", "TemplateList", "(", ")", ")", ")", ";", "}", "}" ]
Initializes the bundle and module names @param array $idParts
[ "Initializes", "the", "bundle", "and", "module", "names" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Modules/Backend/TemplateForm.php#L64-L77
train
agentmedia/phine-core
src/Core/Modules/Backend/TemplateForm.php
TemplateForm.OnSuccess
protected function OnSuccess() { $newTemplate = $this->Value('Name'); $action = Action::Create(); if ($this->template) { $action = Action::Update(); $this->UpdateUsages($newTemplate); $oldFile = $this->CalcFile($this->template); if (File::Exists($oldFile)) { File::Delete($oldFile); } } $logger = new Logger(self::Guard()->GetUser()); $logger->ReportTemplateAction($this->module->MyType(), $newTemplate, $action); if (!Folder::Exists($this->folder)) { Folder::Create($this->folder); } File::CreateWithText($this->CalcFile($newTemplate), $this->Value('Contents', false)); Response::Redirect($this->BackLink()); }
php
protected function OnSuccess() { $newTemplate = $this->Value('Name'); $action = Action::Create(); if ($this->template) { $action = Action::Update(); $this->UpdateUsages($newTemplate); $oldFile = $this->CalcFile($this->template); if (File::Exists($oldFile)) { File::Delete($oldFile); } } $logger = new Logger(self::Guard()->GetUser()); $logger->ReportTemplateAction($this->module->MyType(), $newTemplate, $action); if (!Folder::Exists($this->folder)) { Folder::Create($this->folder); } File::CreateWithText($this->CalcFile($newTemplate), $this->Value('Contents', false)); Response::Redirect($this->BackLink()); }
[ "protected", "function", "OnSuccess", "(", ")", "{", "$", "newTemplate", "=", "$", "this", "->", "Value", "(", "'Name'", ")", ";", "$", "action", "=", "Action", "::", "Create", "(", ")", ";", "if", "(", "$", "this", "->", "template", ")", "{", "$", "action", "=", "Action", "::", "Update", "(", ")", ";", "$", "this", "->", "UpdateUsages", "(", "$", "newTemplate", ")", ";", "$", "oldFile", "=", "$", "this", "->", "CalcFile", "(", "$", "this", "->", "template", ")", ";", "if", "(", "File", "::", "Exists", "(", "$", "oldFile", ")", ")", "{", "File", "::", "Delete", "(", "$", "oldFile", ")", ";", "}", "}", "$", "logger", "=", "new", "Logger", "(", "self", "::", "Guard", "(", ")", "->", "GetUser", "(", ")", ")", ";", "$", "logger", "->", "ReportTemplateAction", "(", "$", "this", "->", "module", "->", "MyType", "(", ")", ",", "$", "newTemplate", ",", "$", "action", ")", ";", "if", "(", "!", "Folder", "::", "Exists", "(", "$", "this", "->", "folder", ")", ")", "{", "Folder", "::", "Create", "(", "$", "this", "->", "folder", ")", ";", "}", "File", "::", "CreateWithText", "(", "$", "this", "->", "CalcFile", "(", "$", "newTemplate", ")", ",", "$", "this", "->", "Value", "(", "'Contents'", ",", "false", ")", ")", ";", "Response", "::", "Redirect", "(", "$", "this", "->", "BackLink", "(", ")", ")", ";", "}" ]
Saves the template into the given file name
[ "Saves", "the", "template", "into", "the", "given", "file", "name" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Modules/Backend/TemplateForm.php#L121-L143
train
TiMESPLiNTER/tsfw-i18n
src/timesplinter/tsfw/i18n/common/Localizer.php
Localizer.getLocales
public function getLocales() { $currentLocales = array(); foreach($this->localeCategories as $category) { if($category === LC_ALL) continue; $currentLocales[$category] = setlocale($category, 0); } return $currentLocales; }
php
public function getLocales() { $currentLocales = array(); foreach($this->localeCategories as $category) { if($category === LC_ALL) continue; $currentLocales[$category] = setlocale($category, 0); } return $currentLocales; }
[ "public", "function", "getLocales", "(", ")", "{", "$", "currentLocales", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "localeCategories", "as", "$", "category", ")", "{", "if", "(", "$", "category", "===", "LC_ALL", ")", "continue", ";", "$", "currentLocales", "[", "$", "category", "]", "=", "setlocale", "(", "$", "category", ",", "0", ")", ";", "}", "return", "$", "currentLocales", ";", "}" ]
Get all categories with its corresponding locale set @return array List of set locales. Category as key and its corresponding locale as value.
[ "Get", "all", "categories", "with", "its", "corresponding", "locale", "set" ]
31769efe75ecab2757911a296ad4c5a9c6158b6d
https://github.com/TiMESPLiNTER/tsfw-i18n/blob/31769efe75ecab2757911a296ad4c5a9c6158b6d/src/timesplinter/tsfw/i18n/common/Localizer.php#L118-L130
train
recca0120/lodash-php
src/JString/PHP.php
PHP.pad
public function pad($length = 0, $chars = ' ', $type = STR_PAD_BOTH) { return new static(str_pad($this->subject, $length, $chars, $type)); }
php
public function pad($length = 0, $chars = ' ', $type = STR_PAD_BOTH) { return new static(str_pad($this->subject, $length, $chars, $type)); }
[ "public", "function", "pad", "(", "$", "length", "=", "0", ",", "$", "chars", "=", "' '", ",", "$", "type", "=", "STR_PAD_BOTH", ")", "{", "return", "new", "static", "(", "str_pad", "(", "$", "this", "->", "subject", ",", "$", "length", ",", "$", "chars", ",", "$", "type", ")", ")", ";", "}" ]
Pad a string to a certain length with another string. @param int $length @param string $chars @param int $type @return static
[ "Pad", "a", "string", "to", "a", "certain", "length", "with", "another", "string", "." ]
65f8c80accfc2b087abf6d0590a5bd9fd15b467d
https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/PHP.php#L239-L242
train
stubbles/stubbles-streams
src/main/php/ResourceInputStream.php
ResourceInputStream.doRead
private function doRead(string $read, int $length): string { if (null === $this->handle) { throw new \LogicException('Can not read from closed input stream.'); } $data = @$read($this->handle, $length); if (false === $data) { $error = lastErrorMessage('unknown error'); if (!@feof($this->handle)) { throw new StreamException( 'Can not read from input stream: ' . $error ); } return ''; } return $data; }
php
private function doRead(string $read, int $length): string { if (null === $this->handle) { throw new \LogicException('Can not read from closed input stream.'); } $data = @$read($this->handle, $length); if (false === $data) { $error = lastErrorMessage('unknown error'); if (!@feof($this->handle)) { throw new StreamException( 'Can not read from input stream: ' . $error ); } return ''; } return $data; }
[ "private", "function", "doRead", "(", "string", "$", "read", ",", "int", "$", "length", ")", ":", "string", "{", "if", "(", "null", "===", "$", "this", "->", "handle", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Can not read from closed input stream.'", ")", ";", "}", "$", "data", "=", "@", "$", "read", "(", "$", "this", "->", "handle", ",", "$", "length", ")", ";", "if", "(", "false", "===", "$", "data", ")", "{", "$", "error", "=", "lastErrorMessage", "(", "'unknown error'", ")", ";", "if", "(", "!", "@", "feof", "(", "$", "this", "->", "handle", ")", ")", "{", "throw", "new", "StreamException", "(", "'Can not read from input stream: '", ".", "$", "error", ")", ";", "}", "return", "''", ";", "}", "return", "$", "data", ";", "}" ]
do actual read @param string $read function to use for reading from handle @param int $length max amount of bytes to read @return string @throws \LogicException @throws \stubbles\streams\StreamException
[ "do", "actual", "read" ]
99b0dace5fcf71584d1456b4b5408017b896bdf5
https://github.com/stubbles/stubbles-streams/blob/99b0dace5fcf71584d1456b4b5408017b896bdf5/src/main/php/ResourceInputStream.php#L78-L97
train
stubbles/stubbles-streams
src/main/php/ResourceInputStream.php
ResourceInputStream.bytesLeft
public function bytesLeft(): int { if (null === $this->handle || !is_resource($this->handle)) { throw new \LogicException('Can not read from closed input stream.'); } $bytesRead = ftell($this->handle); if (!is_int($bytesRead)) { return 0; } return $this->getResourceLength() - $bytesRead; }
php
public function bytesLeft(): int { if (null === $this->handle || !is_resource($this->handle)) { throw new \LogicException('Can not read from closed input stream.'); } $bytesRead = ftell($this->handle); if (!is_int($bytesRead)) { return 0; } return $this->getResourceLength() - $bytesRead; }
[ "public", "function", "bytesLeft", "(", ")", ":", "int", "{", "if", "(", "null", "===", "$", "this", "->", "handle", "||", "!", "is_resource", "(", "$", "this", "->", "handle", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Can not read from closed input stream.'", ")", ";", "}", "$", "bytesRead", "=", "ftell", "(", "$", "this", "->", "handle", ")", ";", "if", "(", "!", "is_int", "(", "$", "bytesRead", ")", ")", "{", "return", "0", ";", "}", "return", "$", "this", "->", "getResourceLength", "(", ")", "-", "$", "bytesRead", ";", "}" ]
returns the amount of bytes left to be read @return int @throws \LogicException
[ "returns", "the", "amount", "of", "bytes", "left", "to", "be", "read" ]
99b0dace5fcf71584d1456b4b5408017b896bdf5
https://github.com/stubbles/stubbles-streams/blob/99b0dace5fcf71584d1456b4b5408017b896bdf5/src/main/php/ResourceInputStream.php#L105-L117
train
CanalTP/NavitiaIoApiComponent
src/NavitiaIoApiService.php
NavitiaIoApiService.getUser
public function getUser($id) { $request = $this->client->get($this->customer['url'].'/api/users/'.$id); $request->setAuth($this->customer['username'], $this->customer['password']); $response = $request->send(); return json_decode((string) $response->getBody(true)); }
php
public function getUser($id) { $request = $this->client->get($this->customer['url'].'/api/users/'.$id); $request->setAuth($this->customer['username'], $this->customer['password']); $response = $request->send(); return json_decode((string) $response->getBody(true)); }
[ "public", "function", "getUser", "(", "$", "id", ")", "{", "$", "request", "=", "$", "this", "->", "client", "->", "get", "(", "$", "this", "->", "customer", "[", "'url'", "]", ".", "'/api/users/'", ".", "$", "id", ")", ";", "$", "request", "->", "setAuth", "(", "$", "this", "->", "customer", "[", "'username'", "]", ",", "$", "this", "->", "customer", "[", "'password'", "]", ")", ";", "$", "response", "=", "$", "request", "->", "send", "(", ")", ";", "return", "json_decode", "(", "(", "string", ")", "$", "response", "->", "getBody", "(", "true", ")", ")", ";", "}" ]
Get a specific user @param int $id @return mixed
[ "Get", "a", "specific", "user" ]
c44d0fd73c20e892b8a0839cf83d25b7a1412aff
https://github.com/CanalTP/NavitiaIoApiComponent/blob/c44d0fd73c20e892b8a0839cf83d25b7a1412aff/src/NavitiaIoApiService.php#L101-L109
train
CanalTP/NavitiaIoApiComponent
src/NavitiaIoApiService.php
NavitiaIoApiService.patchUser
public function patchUser($id, array $fields) { $request = $this->client->patch($this->customer['url'].'/api/users/'.$id); $request->setAuth($this->customer['username'], $this->customer['password']); $request->setBody(json_encode($fields)); $response = $request->send(); return json_decode($response->getBody(true)); }
php
public function patchUser($id, array $fields) { $request = $this->client->patch($this->customer['url'].'/api/users/'.$id); $request->setAuth($this->customer['username'], $this->customer['password']); $request->setBody(json_encode($fields)); $response = $request->send(); return json_decode($response->getBody(true)); }
[ "public", "function", "patchUser", "(", "$", "id", ",", "array", "$", "fields", ")", "{", "$", "request", "=", "$", "this", "->", "client", "->", "patch", "(", "$", "this", "->", "customer", "[", "'url'", "]", ".", "'/api/users/'", ".", "$", "id", ")", ";", "$", "request", "->", "setAuth", "(", "$", "this", "->", "customer", "[", "'username'", "]", ",", "$", "this", "->", "customer", "[", "'password'", "]", ")", ";", "$", "request", "->", "setBody", "(", "json_encode", "(", "$", "fields", ")", ")", ";", "$", "response", "=", "$", "request", "->", "send", "(", ")", ";", "return", "json_decode", "(", "$", "response", "->", "getBody", "(", "true", ")", ")", ";", "}" ]
Edit an user fields. @param int $id @param array $fields @return mixed
[ "Edit", "an", "user", "fields", "." ]
c44d0fd73c20e892b8a0839cf83d25b7a1412aff
https://github.com/CanalTP/NavitiaIoApiComponent/blob/c44d0fd73c20e892b8a0839cf83d25b7a1412aff/src/NavitiaIoApiService.php#L119-L129
train
Wedeto/HTTP
src/Request.php
Request.setURLFromServerVars
public function setURLFromServerVars() { if ($this->server->get('REQUEST_SCHEME')) { $base = $this->server['REQUEST_SCHEME'] . '://' . $this->server['SERVER_NAME']; $this->url = new URL($base . $this->server['REQUEST_URI']); $this->webroot = new URL($base . rtrim(dirname($this->server->get('SCRIPT_NAME')), '/') . '/'); } else { $this->url = new URL($this->server->get('REQUEST_URI')); $host = $this->server['SERVER_NAME'] ?: $this->url->host; $port = $this->server['SERVER_PORT'] ?: $this->url->port; $this->webroot = !empty($host) ? new URL('http://' . $host) : new URL('/'); if ($port && $port != 80) $this->webroot->port = $port; } }
php
public function setURLFromServerVars() { if ($this->server->get('REQUEST_SCHEME')) { $base = $this->server['REQUEST_SCHEME'] . '://' . $this->server['SERVER_NAME']; $this->url = new URL($base . $this->server['REQUEST_URI']); $this->webroot = new URL($base . rtrim(dirname($this->server->get('SCRIPT_NAME')), '/') . '/'); } else { $this->url = new URL($this->server->get('REQUEST_URI')); $host = $this->server['SERVER_NAME'] ?: $this->url->host; $port = $this->server['SERVER_PORT'] ?: $this->url->port; $this->webroot = !empty($host) ? new URL('http://' . $host) : new URL('/'); if ($port && $port != 80) $this->webroot->port = $port; } }
[ "public", "function", "setURLFromServerVars", "(", ")", "{", "if", "(", "$", "this", "->", "server", "->", "get", "(", "'REQUEST_SCHEME'", ")", ")", "{", "$", "base", "=", "$", "this", "->", "server", "[", "'REQUEST_SCHEME'", "]", ".", "'://'", ".", "$", "this", "->", "server", "[", "'SERVER_NAME'", "]", ";", "$", "this", "->", "url", "=", "new", "URL", "(", "$", "base", ".", "$", "this", "->", "server", "[", "'REQUEST_URI'", "]", ")", ";", "$", "this", "->", "webroot", "=", "new", "URL", "(", "$", "base", ".", "rtrim", "(", "dirname", "(", "$", "this", "->", "server", "->", "get", "(", "'SCRIPT_NAME'", ")", ")", ",", "'/'", ")", ".", "'/'", ")", ";", "}", "else", "{", "$", "this", "->", "url", "=", "new", "URL", "(", "$", "this", "->", "server", "->", "get", "(", "'REQUEST_URI'", ")", ")", ";", "$", "host", "=", "$", "this", "->", "server", "[", "'SERVER_NAME'", "]", "?", ":", "$", "this", "->", "url", "->", "host", ";", "$", "port", "=", "$", "this", "->", "server", "[", "'SERVER_PORT'", "]", "?", ":", "$", "this", "->", "url", "->", "port", ";", "$", "this", "->", "webroot", "=", "!", "empty", "(", "$", "host", ")", "?", "new", "URL", "(", "'http://'", ".", "$", "host", ")", ":", "new", "URL", "(", "'/'", ")", ";", "if", "(", "$", "port", "&&", "$", "port", "!=", "80", ")", "$", "this", "->", "webroot", "->", "port", "=", "$", "port", ";", "}", "}" ]
Determine the webroot and the URL from server variables. Webroot is based on the location of the index.php that is executing, which we consider to be the webroot.
[ "Determine", "the", "webroot", "and", "the", "URL", "from", "server", "variables", ".", "Webroot", "is", "based", "on", "the", "location", "of", "the", "index", ".", "php", "that", "is", "executing", "which", "we", "consider", "to", "be", "the", "webroot", "." ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Request.php#L159-L177
train
Wedeto/HTTP
src/Request.php
Request.startSession
public function startSession(URL $domain, Dictionary $config) { if ($this->session === null) { $this->session = new Session($domain, $config, $this->server); $this->session->start(); } return $this; }
php
public function startSession(URL $domain, Dictionary $config) { if ($this->session === null) { $this->session = new Session($domain, $config, $this->server); $this->session->start(); } return $this; }
[ "public", "function", "startSession", "(", "URL", "$", "domain", ",", "Dictionary", "$", "config", ")", "{", "if", "(", "$", "this", "->", "session", "===", "null", ")", "{", "$", "this", "->", "session", "=", "new", "Session", "(", "$", "domain", ",", "$", "config", ",", "$", "this", "->", "server", ")", ";", "$", "this", "->", "session", "->", "start", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
Start the HTTP Session, and initalize the session object @param Wedeto\HTTP\Request Provides fluent interface
[ "Start", "the", "HTTP", "Session", "and", "initalize", "the", "session", "object" ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Request.php#L202-L210
train
holyshared/file-fixture
src/container/LoaderContainer.php
LoaderContainer.register
public function register(FixtureLoader $loader) { $value = new Pair($loader->getName(), $loader); $this->loaders->add($value); return $this; }
php
public function register(FixtureLoader $loader) { $value = new Pair($loader->getName(), $loader); $this->loaders->add($value); return $this; }
[ "public", "function", "register", "(", "FixtureLoader", "$", "loader", ")", "{", "$", "value", "=", "new", "Pair", "(", "$", "loader", "->", "getName", "(", ")", ",", "$", "loader", ")", ";", "$", "this", "->", "loaders", "->", "add", "(", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Register the loader of fixture @param \holyshared\fixture\FixtureLoader $loader @return holyshared\fixture\container\LoaderContainer
[ "Register", "the", "loader", "of", "fixture" ]
65bfc8def327362392eef1bdf2f6d822b70e7c33
https://github.com/holyshared/file-fixture/blob/65bfc8def327362392eef1bdf2f6d822b70e7c33/src/container/LoaderContainer.php#L63-L68
train
CodeMommy/DevelopPHP
command/PHPDepend.php
PHPDepend.getBasePath
private static function getBasePath() { if (empty(self::$basePath)) { self::$basePath = sprintf('%s%s%s', sys_get_temp_dir(), DIRECTORY_SEPARATOR, self::BASE_PATH_NAME); } return self::$basePath; }
php
private static function getBasePath() { if (empty(self::$basePath)) { self::$basePath = sprintf('%s%s%s', sys_get_temp_dir(), DIRECTORY_SEPARATOR, self::BASE_PATH_NAME); } return self::$basePath; }
[ "private", "static", "function", "getBasePath", "(", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "basePath", ")", ")", "{", "self", "::", "$", "basePath", "=", "sprintf", "(", "'%s%s%s'", ",", "sys_get_temp_dir", "(", ")", ",", "DIRECTORY_SEPARATOR", ",", "self", "::", "BASE_PATH_NAME", ")", ";", "}", "return", "self", "::", "$", "basePath", ";", "}" ]
Get Base Path @return string
[ "Get", "Base", "Path" ]
3e6da83965fe0dd18020ce5c4c3384c62de21fff
https://github.com/CodeMommy/DevelopPHP/blob/3e6da83965fe0dd18020ce5c4c3384c62de21fff/command/PHPDepend.php#L62-L68
train
CodeMommy/DevelopPHP
command/PHPDepend.php
PHPDepend.getWorkbenchPath
private static function getWorkbenchPath() { if (empty(self::$workbenchPath)) { self::$workbenchPath = sprintf( '%s%s%s%s', self::getBasePath(), DIRECTORY_SEPARATOR, time(), rand(100, 999) ); } return self::$workbenchPath; }
php
private static function getWorkbenchPath() { if (empty(self::$workbenchPath)) { self::$workbenchPath = sprintf( '%s%s%s%s', self::getBasePath(), DIRECTORY_SEPARATOR, time(), rand(100, 999) ); } return self::$workbenchPath; }
[ "private", "static", "function", "getWorkbenchPath", "(", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "workbenchPath", ")", ")", "{", "self", "::", "$", "workbenchPath", "=", "sprintf", "(", "'%s%s%s%s'", ",", "self", "::", "getBasePath", "(", ")", ",", "DIRECTORY_SEPARATOR", ",", "time", "(", ")", ",", "rand", "(", "100", ",", "999", ")", ")", ";", "}", "return", "self", "::", "$", "workbenchPath", ";", "}" ]
Get Workbench Path @return string
[ "Get", "Workbench", "Path" ]
3e6da83965fe0dd18020ce5c4c3384c62de21fff
https://github.com/CodeMommy/DevelopPHP/blob/3e6da83965fe0dd18020ce5c4c3384c62de21fff/command/PHPDepend.php#L74-L86
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericDatabases
protected function getGenericDatabases(array $databases) { $genericDatabases = array(); foreach ($databases as $database) { $genericDatabases[] = $this->getGenericDatabase($database); } return $genericDatabases; }
php
protected function getGenericDatabases(array $databases) { $genericDatabases = array(); foreach ($databases as $database) { $genericDatabases[] = $this->getGenericDatabase($database); } return $genericDatabases; }
[ "protected", "function", "getGenericDatabases", "(", "array", "$", "databases", ")", "{", "$", "genericDatabases", "=", "array", "(", ")", ";", "foreach", "(", "$", "databases", "as", "$", "database", ")", "{", "$", "genericDatabases", "[", "]", "=", "$", "this", "->", "getGenericDatabase", "(", "$", "database", ")", ";", "}", "return", "$", "genericDatabases", ";", "}" ]
Gets the generic databases. @param array $databases The databases. @return array The generic databases.
[ "Gets", "the", "generic", "databases", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L687-L696
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericSequences
protected function getGenericSequences(array $sequences) { $genericSequences = array(); foreach ($sequences as $sequence) { $genericSequences[] = $this->getGenericSequence($sequence); } return $genericSequences; }
php
protected function getGenericSequences(array $sequences) { $genericSequences = array(); foreach ($sequences as $sequence) { $genericSequences[] = $this->getGenericSequence($sequence); } return $genericSequences; }
[ "protected", "function", "getGenericSequences", "(", "array", "$", "sequences", ")", "{", "$", "genericSequences", "=", "array", "(", ")", ";", "foreach", "(", "$", "sequences", "as", "$", "sequence", ")", "{", "$", "genericSequences", "[", "]", "=", "$", "this", "->", "getGenericSequence", "(", "$", "sequence", ")", ";", "}", "return", "$", "genericSequences", ";", "}" ]
Gets the generic sequences. @param array $sequences The sequences. @return array The generic sequences.
[ "Gets", "the", "generic", "sequences", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L720-L729
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericSequence
protected function getGenericSequence($sequence) { $name = $sequence['name']; $initialValue = (int) $sequence['initial_value']; $incrementSize = (int) $sequence['increment_size']; return new Sequence($name, $initialValue, $incrementSize); }
php
protected function getGenericSequence($sequence) { $name = $sequence['name']; $initialValue = (int) $sequence['initial_value']; $incrementSize = (int) $sequence['increment_size']; return new Sequence($name, $initialValue, $incrementSize); }
[ "protected", "function", "getGenericSequence", "(", "$", "sequence", ")", "{", "$", "name", "=", "$", "sequence", "[", "'name'", "]", ";", "$", "initialValue", "=", "(", "int", ")", "$", "sequence", "[", "'initial_value'", "]", ";", "$", "incrementSize", "=", "(", "int", ")", "$", "sequence", "[", "'increment_size'", "]", ";", "return", "new", "Sequence", "(", "$", "name", ",", "$", "initialValue", ",", "$", "incrementSize", ")", ";", "}" ]
Gets the generic sequence. The $sequence parameter must contain: - name - initial_value - increment_size @param mixed $sequence The sequence. @return \Fridge\DBAL\Schema\Sequence The generic sequence.
[ "Gets", "the", "generic", "sequence", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L743-L750
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericViews
protected function getGenericViews(array $views) { $genericViews = array(); foreach ($views as $view) { $genericViews[] = $this->getGenericView($view); } return $genericViews; }
php
protected function getGenericViews(array $views) { $genericViews = array(); foreach ($views as $view) { $genericViews[] = $this->getGenericView($view); } return $genericViews; }
[ "protected", "function", "getGenericViews", "(", "array", "$", "views", ")", "{", "$", "genericViews", "=", "array", "(", ")", ";", "foreach", "(", "$", "views", "as", "$", "view", ")", "{", "$", "genericViews", "[", "]", "=", "$", "this", "->", "getGenericView", "(", "$", "view", ")", ";", "}", "return", "$", "genericViews", ";", "}" ]
Gets the generic views. @param array $views The views. @return array The generic views.
[ "Gets", "the", "generic", "views", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L759-L768
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericTableNames
protected function getGenericTableNames(array $tableNames) { $genericTableNames = array(); foreach ($tableNames as $tableName) { $genericTableNames[] = $this->getGenericTableName($tableName); } return $genericTableNames; }
php
protected function getGenericTableNames(array $tableNames) { $genericTableNames = array(); foreach ($tableNames as $tableName) { $genericTableNames[] = $this->getGenericTableName($tableName); } return $genericTableNames; }
[ "protected", "function", "getGenericTableNames", "(", "array", "$", "tableNames", ")", "{", "$", "genericTableNames", "=", "array", "(", ")", ";", "foreach", "(", "$", "tableNames", "as", "$", "tableName", ")", "{", "$", "genericTableNames", "[", "]", "=", "$", "this", "->", "getGenericTableName", "(", "$", "tableName", ")", ";", "}", "return", "$", "genericTableNames", ";", "}" ]
Gets the generic table names. @param array $tableNames The table names. @return array The generic table names.
[ "Gets", "the", "generic", "table", "names", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L793-L802
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericColumns
protected function getGenericColumns(array $columns) { $genericColumns = array(); foreach ($columns as $column) { $genericColumns[] = $this->getGenericColumn($column); } return $genericColumns; }
php
protected function getGenericColumns(array $columns) { $genericColumns = array(); foreach ($columns as $column) { $genericColumns[] = $this->getGenericColumn($column); } return $genericColumns; }
[ "protected", "function", "getGenericColumns", "(", "array", "$", "columns", ")", "{", "$", "genericColumns", "=", "array", "(", ")", ";", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "$", "genericColumns", "[", "]", "=", "$", "this", "->", "getGenericColumn", "(", "$", "column", ")", ";", "}", "return", "$", "genericColumns", ";", "}" ]
Gets the generic table columns. @param array $columns The columns. @return array The generic columns.
[ "Gets", "the", "generic", "table", "columns", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L826-L835
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericColumn
protected function getGenericColumn(array $column) { $name = $column['name']; list($column['comment'], $typeName) = $this->extractTypeFromComment($column['comment']); if ($typeName === null) { $typeName = $this->getConnection()->getPlatform()->getMappedType($column['type']); } $type = Type::getType($typeName); if ($column['default'] !== null) { $column['default'] = $type->convertToPHPValue($column['default'], $this->getConnection()->getPlatform()); } $options = array( 'length' => ($column['length'] !== null) ? (int) $column['length'] : null, 'precision' => ($column['precision'] !== null) ? (int) $column['precision'] : null, 'scale' => ($column['scale'] !== null) ? (int) $column['scale'] : null, 'unsigned' => ($column['unsigned'] !== null) ? (bool) $column['unsigned'] : null, 'fixed' => ($column['fixed'] !== null) ? (bool) $column['fixed'] : null, 'not_null' => (bool) $column['not_null'], 'default' => $column['default'], 'auto_increment' => ($column['auto_increment'] !== null) ? (bool) $column['auto_increment'] : null, 'comment' => $column['comment'], ); return new Column($name, $type, $options); }
php
protected function getGenericColumn(array $column) { $name = $column['name']; list($column['comment'], $typeName) = $this->extractTypeFromComment($column['comment']); if ($typeName === null) { $typeName = $this->getConnection()->getPlatform()->getMappedType($column['type']); } $type = Type::getType($typeName); if ($column['default'] !== null) { $column['default'] = $type->convertToPHPValue($column['default'], $this->getConnection()->getPlatform()); } $options = array( 'length' => ($column['length'] !== null) ? (int) $column['length'] : null, 'precision' => ($column['precision'] !== null) ? (int) $column['precision'] : null, 'scale' => ($column['scale'] !== null) ? (int) $column['scale'] : null, 'unsigned' => ($column['unsigned'] !== null) ? (bool) $column['unsigned'] : null, 'fixed' => ($column['fixed'] !== null) ? (bool) $column['fixed'] : null, 'not_null' => (bool) $column['not_null'], 'default' => $column['default'], 'auto_increment' => ($column['auto_increment'] !== null) ? (bool) $column['auto_increment'] : null, 'comment' => $column['comment'], ); return new Column($name, $type, $options); }
[ "protected", "function", "getGenericColumn", "(", "array", "$", "column", ")", "{", "$", "name", "=", "$", "column", "[", "'name'", "]", ";", "list", "(", "$", "column", "[", "'comment'", "]", ",", "$", "typeName", ")", "=", "$", "this", "->", "extractTypeFromComment", "(", "$", "column", "[", "'comment'", "]", ")", ";", "if", "(", "$", "typeName", "===", "null", ")", "{", "$", "typeName", "=", "$", "this", "->", "getConnection", "(", ")", "->", "getPlatform", "(", ")", "->", "getMappedType", "(", "$", "column", "[", "'type'", "]", ")", ";", "}", "$", "type", "=", "Type", "::", "getType", "(", "$", "typeName", ")", ";", "if", "(", "$", "column", "[", "'default'", "]", "!==", "null", ")", "{", "$", "column", "[", "'default'", "]", "=", "$", "type", "->", "convertToPHPValue", "(", "$", "column", "[", "'default'", "]", ",", "$", "this", "->", "getConnection", "(", ")", "->", "getPlatform", "(", ")", ")", ";", "}", "$", "options", "=", "array", "(", "'length'", "=>", "(", "$", "column", "[", "'length'", "]", "!==", "null", ")", "?", "(", "int", ")", "$", "column", "[", "'length'", "]", ":", "null", ",", "'precision'", "=>", "(", "$", "column", "[", "'precision'", "]", "!==", "null", ")", "?", "(", "int", ")", "$", "column", "[", "'precision'", "]", ":", "null", ",", "'scale'", "=>", "(", "$", "column", "[", "'scale'", "]", "!==", "null", ")", "?", "(", "int", ")", "$", "column", "[", "'scale'", "]", ":", "null", ",", "'unsigned'", "=>", "(", "$", "column", "[", "'unsigned'", "]", "!==", "null", ")", "?", "(", "bool", ")", "$", "column", "[", "'unsigned'", "]", ":", "null", ",", "'fixed'", "=>", "(", "$", "column", "[", "'fixed'", "]", "!==", "null", ")", "?", "(", "bool", ")", "$", "column", "[", "'fixed'", "]", ":", "null", ",", "'not_null'", "=>", "(", "bool", ")", "$", "column", "[", "'not_null'", "]", ",", "'default'", "=>", "$", "column", "[", "'default'", "]", ",", "'auto_increment'", "=>", "(", "$", "column", "[", "'auto_increment'", "]", "!==", "null", ")", "?", "(", "bool", ")", "$", "column", "[", "'auto_increment'", "]", ":", "null", ",", "'comment'", "=>", "$", "column", "[", "'comment'", "]", ",", ")", ";", "return", "new", "Column", "(", "$", "name", ",", "$", "type", ",", "$", "options", ")", ";", "}" ]
Gets the generic table column. The $column parameter must contain: - name - type - length - precision - scale - unisgned - fixed - not_null - default - auto_increment - comment @param array $column The column. @return \Fridge\DBAL\Schema\Column The generic column.
[ "Gets", "the", "generic", "table", "column", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L857-L886
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericPrimaryKey
protected function getGenericPrimaryKey(array $primaryKey) { $genericPrimaryKey = new PrimaryKey($primaryKey[0]['name']); foreach ($primaryKey as $primaryKeyColumn) { $genericPrimaryKey->addColumnName($primaryKeyColumn['column_name']); } return $genericPrimaryKey; }
php
protected function getGenericPrimaryKey(array $primaryKey) { $genericPrimaryKey = new PrimaryKey($primaryKey[0]['name']); foreach ($primaryKey as $primaryKeyColumn) { $genericPrimaryKey->addColumnName($primaryKeyColumn['column_name']); } return $genericPrimaryKey; }
[ "protected", "function", "getGenericPrimaryKey", "(", "array", "$", "primaryKey", ")", "{", "$", "genericPrimaryKey", "=", "new", "PrimaryKey", "(", "$", "primaryKey", "[", "0", "]", "[", "'name'", "]", ")", ";", "foreach", "(", "$", "primaryKey", "as", "$", "primaryKeyColumn", ")", "{", "$", "genericPrimaryKey", "->", "addColumnName", "(", "$", "primaryKeyColumn", "[", "'column_name'", "]", ")", ";", "}", "return", "$", "genericPrimaryKey", ";", "}" ]
Gets the generic table primary key. The $primaryKey parameter must contain: - name - column_name @param array $primaryKey The primary key. @return \Fridge\DBAL\Schema\PrimaryKey|null The generic primary key.
[ "Gets", "the", "generic", "table", "primary", "key", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L899-L908
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericForeignKeys
protected function getGenericForeignKeys(array $foreignKeys) { $genericForeignKeys = array(); foreach ($foreignKeys as $foreignKey) { $name = $foreignKey['name']; if (!isset($genericForeignKeys[$name])) { $genericForeignKeys[$name] = new ForeignKey( $foreignKey['name'], array($foreignKey['local_column_name']), $foreignKey['foreign_table_name'], array($foreignKey['foreign_column_name']), $foreignKey['on_delete'], $foreignKey['on_update'] ); } else { $genericForeignKeys[$name]->addLocalColumnName($foreignKey['local_column_name']); $genericForeignKeys[$name]->addForeignColumnName($foreignKey['foreign_column_name']); } } return array_values($genericForeignKeys); }
php
protected function getGenericForeignKeys(array $foreignKeys) { $genericForeignKeys = array(); foreach ($foreignKeys as $foreignKey) { $name = $foreignKey['name']; if (!isset($genericForeignKeys[$name])) { $genericForeignKeys[$name] = new ForeignKey( $foreignKey['name'], array($foreignKey['local_column_name']), $foreignKey['foreign_table_name'], array($foreignKey['foreign_column_name']), $foreignKey['on_delete'], $foreignKey['on_update'] ); } else { $genericForeignKeys[$name]->addLocalColumnName($foreignKey['local_column_name']); $genericForeignKeys[$name]->addForeignColumnName($foreignKey['foreign_column_name']); } } return array_values($genericForeignKeys); }
[ "protected", "function", "getGenericForeignKeys", "(", "array", "$", "foreignKeys", ")", "{", "$", "genericForeignKeys", "=", "array", "(", ")", ";", "foreach", "(", "$", "foreignKeys", "as", "$", "foreignKey", ")", "{", "$", "name", "=", "$", "foreignKey", "[", "'name'", "]", ";", "if", "(", "!", "isset", "(", "$", "genericForeignKeys", "[", "$", "name", "]", ")", ")", "{", "$", "genericForeignKeys", "[", "$", "name", "]", "=", "new", "ForeignKey", "(", "$", "foreignKey", "[", "'name'", "]", ",", "array", "(", "$", "foreignKey", "[", "'local_column_name'", "]", ")", ",", "$", "foreignKey", "[", "'foreign_table_name'", "]", ",", "array", "(", "$", "foreignKey", "[", "'foreign_column_name'", "]", ")", ",", "$", "foreignKey", "[", "'on_delete'", "]", ",", "$", "foreignKey", "[", "'on_update'", "]", ")", ";", "}", "else", "{", "$", "genericForeignKeys", "[", "$", "name", "]", "->", "addLocalColumnName", "(", "$", "foreignKey", "[", "'local_column_name'", "]", ")", ";", "$", "genericForeignKeys", "[", "$", "name", "]", "->", "addForeignColumnName", "(", "$", "foreignKey", "[", "'foreign_column_name'", "]", ")", ";", "}", "}", "return", "array_values", "(", "$", "genericForeignKeys", ")", ";", "}" ]
Gets the generic table foreign keys. The $foreignKeys parameter contains: - name - local_column_name - foreign_table_name - foreign_column_name - on_delete - on_update @param array $foreignKeys The foreign keys. @return array The generic foreign keys.
[ "Gets", "the", "generic", "table", "foreign", "keys", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L925-L948
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericIndexes
protected function getGenericIndexes(array $indexes) { $genericIndexes = array(); foreach ($indexes as $index) { $name = $index['name']; if (!isset($genericIndexes[$name])) { $genericIndexes[$name] = new Index($name, array($index['column_name']), (bool) $index['unique']); } else { $genericIndexes[$name]->addColumnName($index['column_name']); } } return array_values($genericIndexes); }
php
protected function getGenericIndexes(array $indexes) { $genericIndexes = array(); foreach ($indexes as $index) { $name = $index['name']; if (!isset($genericIndexes[$name])) { $genericIndexes[$name] = new Index($name, array($index['column_name']), (bool) $index['unique']); } else { $genericIndexes[$name]->addColumnName($index['column_name']); } } return array_values($genericIndexes); }
[ "protected", "function", "getGenericIndexes", "(", "array", "$", "indexes", ")", "{", "$", "genericIndexes", "=", "array", "(", ")", ";", "foreach", "(", "$", "indexes", "as", "$", "index", ")", "{", "$", "name", "=", "$", "index", "[", "'name'", "]", ";", "if", "(", "!", "isset", "(", "$", "genericIndexes", "[", "$", "name", "]", ")", ")", "{", "$", "genericIndexes", "[", "$", "name", "]", "=", "new", "Index", "(", "$", "name", ",", "array", "(", "$", "index", "[", "'column_name'", "]", ")", ",", "(", "bool", ")", "$", "index", "[", "'unique'", "]", ")", ";", "}", "else", "{", "$", "genericIndexes", "[", "$", "name", "]", "->", "addColumnName", "(", "$", "index", "[", "'column_name'", "]", ")", ";", "}", "}", "return", "array_values", "(", "$", "genericIndexes", ")", ";", "}" ]
Gets the generic table indexes. The $indexes parameter contains: - name - column_name - unique @param array $indexes The indexes. @return array The generic indexes.
[ "Gets", "the", "generic", "table", "indexes", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L962-L977
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.getGenericChecks
protected function getGenericChecks(array $checks) { $genericChecks = array(); foreach ($checks as $check) { $genericChecks[] = new Check($check['name'], $check['definition']); } return $genericChecks; }
php
protected function getGenericChecks(array $checks) { $genericChecks = array(); foreach ($checks as $check) { $genericChecks[] = new Check($check['name'], $check['definition']); } return $genericChecks; }
[ "protected", "function", "getGenericChecks", "(", "array", "$", "checks", ")", "{", "$", "genericChecks", "=", "array", "(", ")", ";", "foreach", "(", "$", "checks", "as", "$", "check", ")", "{", "$", "genericChecks", "[", "]", "=", "new", "Check", "(", "$", "check", "[", "'name'", "]", ",", "$", "check", "[", "'definition'", "]", ")", ";", "}", "return", "$", "genericChecks", ";", "}" ]
Gets the generic table checks. The $checks parameter contains: - name - definition @param array $checks The checks. @return array The generic checks.
[ "Gets", "the", "generic", "table", "checks", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L990-L999
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.extractTypeFromComment
protected function extractTypeFromComment($comment) { if (preg_match('/^(.*)\(FridgeType::([a-zA-Z0-9]+)\)$/', $comment, $matches)) { if (empty($matches[1])) { $matches[1] = null; } return array($matches[1], strtolower($matches[2])); } return array($comment, null); }
php
protected function extractTypeFromComment($comment) { if (preg_match('/^(.*)\(FridgeType::([a-zA-Z0-9]+)\)$/', $comment, $matches)) { if (empty($matches[1])) { $matches[1] = null; } return array($matches[1], strtolower($matches[2])); } return array($comment, null); }
[ "protected", "function", "extractTypeFromComment", "(", "$", "comment", ")", "{", "if", "(", "preg_match", "(", "'/^(.*)\\(FridgeType::([a-zA-Z0-9]+)\\)$/'", ",", "$", "comment", ",", "$", "matches", ")", ")", "{", "if", "(", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "{", "$", "matches", "[", "1", "]", "=", "null", ";", "}", "return", "array", "(", "$", "matches", "[", "1", "]", ",", "strtolower", "(", "$", "matches", "[", "2", "]", ")", ")", ";", "}", "return", "array", "(", "$", "comment", ",", "null", ")", ";", "}" ]
Extracts the type from the comment if it exists. @param string $comment The comment. @return array 0 => The extracted comment, 1 => The extracted type.
[ "Extracts", "the", "type", "from", "the", "comment", "if", "it", "exists", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L1008-L1019
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php
AbstractSchemaManager.tryMethod
protected function tryMethod($method, array $arguments = array()) { try { call_user_func_array(array($this, $method), $arguments); return true; } catch (\Exception $e) { return false; } }
php
protected function tryMethod($method, array $arguments = array()) { try { call_user_func_array(array($this, $method), $arguments); return true; } catch (\Exception $e) { return false; } }
[ "protected", "function", "tryMethod", "(", "$", "method", ",", "array", "$", "arguments", "=", "array", "(", ")", ")", "{", "try", "{", "call_user_func_array", "(", "array", "(", "$", "this", ",", "$", "method", ")", ",", "$", "arguments", ")", ";", "return", "true", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
Tries to execute a method. @param string $method The method name. @param array $arguments The method arguments. @return boolean TRUE if the method has been executed successfully else FALSE.
[ "Tries", "to", "execute", "a", "method", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/AbstractSchemaManager.php#L1029-L1038
train
fiiSoft/fiisoft-tasks-queue
src/TasksQueue/Task/AbstractTask.php
AbstractTask.restoreState
protected function restoreState(array $data) { if (isset($data['status'])) { $this->status = array_merge($this->status, $data['status']); } if (isset($data['jobUuid'])) { $this->jobUuid = $data['jobUuid']; $this->logContext['jobUuid'] = $data['jobUuid']; } else { $this->jobUuid = null; $this->logContext['jobUuid'] = null; } }
php
protected function restoreState(array $data) { if (isset($data['status'])) { $this->status = array_merge($this->status, $data['status']); } if (isset($data['jobUuid'])) { $this->jobUuid = $data['jobUuid']; $this->logContext['jobUuid'] = $data['jobUuid']; } else { $this->jobUuid = null; $this->logContext['jobUuid'] = null; } }
[ "protected", "function", "restoreState", "(", "array", "$", "data", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "'status'", "]", ")", ")", "{", "$", "this", "->", "status", "=", "array_merge", "(", "$", "this", "->", "status", ",", "$", "data", "[", "'status'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'jobUuid'", "]", ")", ")", "{", "$", "this", "->", "jobUuid", "=", "$", "data", "[", "'jobUuid'", "]", ";", "$", "this", "->", "logContext", "[", "'jobUuid'", "]", "=", "$", "data", "[", "'jobUuid'", "]", ";", "}", "else", "{", "$", "this", "->", "jobUuid", "=", "null", ";", "$", "this", "->", "logContext", "[", "'jobUuid'", "]", "=", "null", ";", "}", "}" ]
Restore state of task from data supplied by command @param array $data @return void
[ "Restore", "state", "of", "task", "from", "data", "supplied", "by", "command" ]
0c5d03f8e6f0fbe023f45e84d3db469dbea476ae
https://github.com/fiiSoft/fiisoft-tasks-queue/blob/0c5d03f8e6f0fbe023f45e84d3db469dbea476ae/src/TasksQueue/Task/AbstractTask.php#L131-L144
train
OpenConext/Stepup-bundle
src/EventListener/LocaleCookieListener.php
LocaleCookieListener.onKernelResponse
public function onKernelResponse(FilterResponseEvent $event) { $locale = $this->localeProvider->determinePreferredLocale(); // Unable to determine preferred locale? No need to hand out a cookie then. if (empty($locale)) { return; } // Did the request already contain the proper cookie value? No need to hand out a cookie then. $requestCookie = $this->cookieHelper->read($event->getRequest()); if ($requestCookie && $requestCookie->getValue() === $locale) { $this->logger->debug(sprintf( 'Locale cookie already set to "%s", nothing to do here', $locale )); return; } $this->cookieHelper->write($event->getResponse(), $locale); $this->logger->notice(sprintf("Set locale cookie to %s", $locale)); }
php
public function onKernelResponse(FilterResponseEvent $event) { $locale = $this->localeProvider->determinePreferredLocale(); // Unable to determine preferred locale? No need to hand out a cookie then. if (empty($locale)) { return; } // Did the request already contain the proper cookie value? No need to hand out a cookie then. $requestCookie = $this->cookieHelper->read($event->getRequest()); if ($requestCookie && $requestCookie->getValue() === $locale) { $this->logger->debug(sprintf( 'Locale cookie already set to "%s", nothing to do here', $locale )); return; } $this->cookieHelper->write($event->getResponse(), $locale); $this->logger->notice(sprintf("Set locale cookie to %s", $locale)); }
[ "public", "function", "onKernelResponse", "(", "FilterResponseEvent", "$", "event", ")", "{", "$", "locale", "=", "$", "this", "->", "localeProvider", "->", "determinePreferredLocale", "(", ")", ";", "// Unable to determine preferred locale? No need to hand out a cookie then.", "if", "(", "empty", "(", "$", "locale", ")", ")", "{", "return", ";", "}", "// Did the request already contain the proper cookie value? No need to hand out a cookie then.", "$", "requestCookie", "=", "$", "this", "->", "cookieHelper", "->", "read", "(", "$", "event", "->", "getRequest", "(", ")", ")", ";", "if", "(", "$", "requestCookie", "&&", "$", "requestCookie", "->", "getValue", "(", ")", "===", "$", "locale", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "sprintf", "(", "'Locale cookie already set to \"%s\", nothing to do here'", ",", "$", "locale", ")", ")", ";", "return", ";", "}", "$", "this", "->", "cookieHelper", "->", "write", "(", "$", "event", "->", "getResponse", "(", ")", ",", "$", "locale", ")", ";", "$", "this", "->", "logger", "->", "notice", "(", "sprintf", "(", "\"Set locale cookie to %s\"", ",", "$", "locale", ")", ")", ";", "}" ]
If there is a logged in user with a preferred language, set it as a cookie. @param FilterResponseEvent $event
[ "If", "there", "is", "a", "logged", "in", "user", "with", "a", "preferred", "language", "set", "it", "as", "a", "cookie", "." ]
94178ddb421889df9e068109293a8da880793ed2
https://github.com/OpenConext/Stepup-bundle/blob/94178ddb421889df9e068109293a8da880793ed2/src/EventListener/LocaleCookieListener.php#L59-L80
train
praxigento/mobi_mod_downline
Plugin/Magento/Customer/Model/AccountManagement.php
AccountManagement.beforeAuthenticate
public function beforeAuthenticate( \Magento\Customer\Model\AccountManagement $subject, $username, $password ) { try { $mlmId = trim($username); $found = $this->daoDwnlCust->getByMlmId($mlmId); if ($found) { $custId = $found->getCustomerRef(); $customer = $this->daoCust->getById($custId); if ($customer instanceof \Magento\Customer\Api\Data\CustomerInterface) { $username = $customer->getEmail(); } } } catch (\Throwable $e) { /* stealth exceptions */ } return [$username, $password]; }
php
public function beforeAuthenticate( \Magento\Customer\Model\AccountManagement $subject, $username, $password ) { try { $mlmId = trim($username); $found = $this->daoDwnlCust->getByMlmId($mlmId); if ($found) { $custId = $found->getCustomerRef(); $customer = $this->daoCust->getById($custId); if ($customer instanceof \Magento\Customer\Api\Data\CustomerInterface) { $username = $customer->getEmail(); } } } catch (\Throwable $e) { /* stealth exceptions */ } return [$username, $password]; }
[ "public", "function", "beforeAuthenticate", "(", "\\", "Magento", "\\", "Customer", "\\", "Model", "\\", "AccountManagement", "$", "subject", ",", "$", "username", ",", "$", "password", ")", "{", "try", "{", "$", "mlmId", "=", "trim", "(", "$", "username", ")", ";", "$", "found", "=", "$", "this", "->", "daoDwnlCust", "->", "getByMlmId", "(", "$", "mlmId", ")", ";", "if", "(", "$", "found", ")", "{", "$", "custId", "=", "$", "found", "->", "getCustomerRef", "(", ")", ";", "$", "customer", "=", "$", "this", "->", "daoCust", "->", "getById", "(", "$", "custId", ")", ";", "if", "(", "$", "customer", "instanceof", "\\", "Magento", "\\", "Customer", "\\", "Api", "\\", "Data", "\\", "CustomerInterface", ")", "{", "$", "username", "=", "$", "customer", "->", "getEmail", "(", ")", ";", "}", "}", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "/* stealth exceptions */", "}", "return", "[", "$", "username", ",", "$", "password", "]", ";", "}" ]
Look up for customer's email by MLM ID on authentication. @param \Magento\Customer\Model\AccountManagement $subject @param $username @param $password @return array
[ "Look", "up", "for", "customer", "s", "email", "by", "MLM", "ID", "on", "authentication", "." ]
0f3c276dfff1aa029f9fd205ccfc56f207a2e75b
https://github.com/praxigento/mobi_mod_downline/blob/0f3c276dfff1aa029f9fd205ccfc56f207a2e75b/Plugin/Magento/Customer/Model/AccountManagement.php#L36-L55
train
praxigento/mobi_mod_downline
Plugin/Magento/Customer/Model/AccountManagement.php
AccountManagement.beforeCreateAccount
public function beforeCreateAccount( \Magento\Customer\Model\AccountManagement $subject, \Magento\Customer\Api\Data\CustomerInterface $customer, $password = null, $redirectUrl = '' ) { $addrs = $customer->getAddresses(); if (is_array($addrs)) { foreach ($addrs as $addr) { $countryCode = $addr->getCountryId(); $this->hlpReg->putCustomerCountry($countryCode); $isBilling = $addr->isDefaultBilling(); if ($isBilling) break; // get any address but exit the loop if default billing } } return [$customer, $password, $redirectUrl]; }
php
public function beforeCreateAccount( \Magento\Customer\Model\AccountManagement $subject, \Magento\Customer\Api\Data\CustomerInterface $customer, $password = null, $redirectUrl = '' ) { $addrs = $customer->getAddresses(); if (is_array($addrs)) { foreach ($addrs as $addr) { $countryCode = $addr->getCountryId(); $this->hlpReg->putCustomerCountry($countryCode); $isBilling = $addr->isDefaultBilling(); if ($isBilling) break; // get any address but exit the loop if default billing } } return [$customer, $password, $redirectUrl]; }
[ "public", "function", "beforeCreateAccount", "(", "\\", "Magento", "\\", "Customer", "\\", "Model", "\\", "AccountManagement", "$", "subject", ",", "\\", "Magento", "\\", "Customer", "\\", "Api", "\\", "Data", "\\", "CustomerInterface", "$", "customer", ",", "$", "password", "=", "null", ",", "$", "redirectUrl", "=", "''", ")", "{", "$", "addrs", "=", "$", "customer", "->", "getAddresses", "(", ")", ";", "if", "(", "is_array", "(", "$", "addrs", ")", ")", "{", "foreach", "(", "$", "addrs", "as", "$", "addr", ")", "{", "$", "countryCode", "=", "$", "addr", "->", "getCountryId", "(", ")", ";", "$", "this", "->", "hlpReg", "->", "putCustomerCountry", "(", "$", "countryCode", ")", ";", "$", "isBilling", "=", "$", "addr", "->", "isDefaultBilling", "(", ")", ";", "if", "(", "$", "isBilling", ")", "break", ";", "// get any address but exit the loop if default billing", "}", "}", "return", "[", "$", "customer", ",", "$", "password", ",", "$", "redirectUrl", "]", ";", "}" ]
Extract country code and save into Magento registry when customer is created through adminhtml. @param \Magento\Customer\Model\AccountManagement $subject @param \Magento\Customer\Api\Data\CustomerInterface $customer @param null $password @param string $redirectUrl @return array
[ "Extract", "country", "code", "and", "save", "into", "Magento", "registry", "when", "customer", "is", "created", "through", "adminhtml", "." ]
0f3c276dfff1aa029f9fd205ccfc56f207a2e75b
https://github.com/praxigento/mobi_mod_downline/blob/0f3c276dfff1aa029f9fd205ccfc56f207a2e75b/Plugin/Magento/Customer/Model/AccountManagement.php#L66-L82
train
OxfordInfoLabs/kinikit-core
src/Util/NumberUtils.php
NumberUtils.formatAsMoney
public static function formatAsMoney($value, $currencySymbol = "&pound;", $roundToInteger = false) { if (is_numeric($value)) return $currencySymbol . number_format($value, $roundToInteger ? 0 : 2, ".", ""); else return null; }
php
public static function formatAsMoney($value, $currencySymbol = "&pound;", $roundToInteger = false) { if (is_numeric($value)) return $currencySymbol . number_format($value, $roundToInteger ? 0 : 2, ".", ""); else return null; }
[ "public", "static", "function", "formatAsMoney", "(", "$", "value", ",", "$", "currencySymbol", "=", "\"&pound;\"", ",", "$", "roundToInteger", "=", "false", ")", "{", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "return", "$", "currencySymbol", ".", "number_format", "(", "$", "value", ",", "$", "roundToInteger", "?", "0", ":", "2", ",", "\".\"", ",", "\"\"", ")", ";", "else", "return", "null", ";", "}" ]
Convenience function for formatting a number as money using the supplied currency symbol @param $value @param string $currencySymbol
[ "Convenience", "function", "for", "formatting", "a", "number", "as", "money", "using", "the", "supplied", "currency", "symbol" ]
edc1b2e6ffabd595c4c7d322279b3dd1e59ef359
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/NumberUtils.php#L16-L21
train
bkstg/resource-bundle
Timeline/EventSubscriber/CreatedResourceLinkSubscriber.php
CreatedResourceLinkSubscriber.setCreatedResourceLink
public function setCreatedResourceLink(TimelineLinkEvent $event): void { $action = $event->getAction(); if ('created_resource' != $action->getVerb()) { return; } $production = $action->getComponent('indirectComplement')->getData(); $resource = $action->getComponent('directComplement')->getData(); $event->setLink($this->url_generator->generate('bkstg_resource_read', [ 'id' => $resource->getId(), 'production_slug' => $production->getSlug(), ])); }
php
public function setCreatedResourceLink(TimelineLinkEvent $event): void { $action = $event->getAction(); if ('created_resource' != $action->getVerb()) { return; } $production = $action->getComponent('indirectComplement')->getData(); $resource = $action->getComponent('directComplement')->getData(); $event->setLink($this->url_generator->generate('bkstg_resource_read', [ 'id' => $resource->getId(), 'production_slug' => $production->getSlug(), ])); }
[ "public", "function", "setCreatedResourceLink", "(", "TimelineLinkEvent", "$", "event", ")", ":", "void", "{", "$", "action", "=", "$", "event", "->", "getAction", "(", ")", ";", "if", "(", "'created_resource'", "!=", "$", "action", "->", "getVerb", "(", ")", ")", "{", "return", ";", "}", "$", "production", "=", "$", "action", "->", "getComponent", "(", "'indirectComplement'", ")", "->", "getData", "(", ")", ";", "$", "resource", "=", "$", "action", "->", "getComponent", "(", "'directComplement'", ")", "->", "getData", "(", ")", ";", "$", "event", "->", "setLink", "(", "$", "this", "->", "url_generator", "->", "generate", "(", "'bkstg_resource_read'", ",", "[", "'id'", "=>", "$", "resource", "->", "getId", "(", ")", ",", "'production_slug'", "=>", "$", "production", "->", "getSlug", "(", ")", ",", "]", ")", ")", ";", "}" ]
Set the link for the created resource. @param TimelineLinkEvent $event The timeline link event. @return void
[ "Set", "the", "link", "for", "the", "created", "resource", "." ]
9d094366799a4df117a1dd747af9bb6debe14325
https://github.com/bkstg/resource-bundle/blob/9d094366799a4df117a1dd747af9bb6debe14325/Timeline/EventSubscriber/CreatedResourceLinkSubscriber.php#L53-L67
train
danielgp/common-lib
source/DomComponentsByDanielGP.php
DomComponentsByDanielGP.setTableCell
private function setTableCell($aElements, $features = null) { $sReturn = null; foreach ($aElements as $key => $value) { $value = str_replace(['& ', '\"', "\'"], ['&amp; ', '"', "'"], $value); if ((isset($features['grouping_cell'])) && ($features['grouping_cell'] == $key)) { // just skip } else { $sReturn .= '<td '; if (isset($features['column_formatting'][$key])) { switch ($features['column_formatting'][$key]) { case '@': $sReturn .= 'style="text-align:left;">' . $value; break; case 'right': $sReturn .= 'style="text-align:right;">' . $value; break; default: $sReturn .= '???'; break; } } else { if (is_numeric($value)) { $sReturn .= $this->setTableCellNumeric($key, $value, $features); } else { $outputet = false; if ((strpos($value, '-') !== false) && (strlen($value) == 10)) { if (preg_match("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $value, $regs)) { $outputet = true; $sReturn .= 'style="text-align:right;width: 10px;">' . $regs[3] . '.' . $regs[2] . '.' . $regs[1]; } } if (!$outputet) { $sReturn .= 'style="text-align:left;">' . $value; } } } $sReturn .= '</td>'; } } return $sReturn; }
php
private function setTableCell($aElements, $features = null) { $sReturn = null; foreach ($aElements as $key => $value) { $value = str_replace(['& ', '\"', "\'"], ['&amp; ', '"', "'"], $value); if ((isset($features['grouping_cell'])) && ($features['grouping_cell'] == $key)) { // just skip } else { $sReturn .= '<td '; if (isset($features['column_formatting'][$key])) { switch ($features['column_formatting'][$key]) { case '@': $sReturn .= 'style="text-align:left;">' . $value; break; case 'right': $sReturn .= 'style="text-align:right;">' . $value; break; default: $sReturn .= '???'; break; } } else { if (is_numeric($value)) { $sReturn .= $this->setTableCellNumeric($key, $value, $features); } else { $outputet = false; if ((strpos($value, '-') !== false) && (strlen($value) == 10)) { if (preg_match("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $value, $regs)) { $outputet = true; $sReturn .= 'style="text-align:right;width: 10px;">' . $regs[3] . '.' . $regs[2] . '.' . $regs[1]; } } if (!$outputet) { $sReturn .= 'style="text-align:left;">' . $value; } } } $sReturn .= '</td>'; } } return $sReturn; }
[ "private", "function", "setTableCell", "(", "$", "aElements", ",", "$", "features", "=", "null", ")", "{", "$", "sReturn", "=", "null", ";", "foreach", "(", "$", "aElements", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "value", "=", "str_replace", "(", "[", "'& '", ",", "'\\\"'", ",", "\"\\'\"", "]", ",", "[", "'&amp; '", ",", "'\"'", ",", "\"'\"", "]", ",", "$", "value", ")", ";", "if", "(", "(", "isset", "(", "$", "features", "[", "'grouping_cell'", "]", ")", ")", "&&", "(", "$", "features", "[", "'grouping_cell'", "]", "==", "$", "key", ")", ")", "{", "// just skip", "}", "else", "{", "$", "sReturn", ".=", "'<td '", ";", "if", "(", "isset", "(", "$", "features", "[", "'column_formatting'", "]", "[", "$", "key", "]", ")", ")", "{", "switch", "(", "$", "features", "[", "'column_formatting'", "]", "[", "$", "key", "]", ")", "{", "case", "'@'", ":", "$", "sReturn", ".=", "'style=\"text-align:left;\">'", ".", "$", "value", ";", "break", ";", "case", "'right'", ":", "$", "sReturn", ".=", "'style=\"text-align:right;\">'", ".", "$", "value", ";", "break", ";", "default", ":", "$", "sReturn", ".=", "'???'", ";", "break", ";", "}", "}", "else", "{", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "{", "$", "sReturn", ".=", "$", "this", "->", "setTableCellNumeric", "(", "$", "key", ",", "$", "value", ",", "$", "features", ")", ";", "}", "else", "{", "$", "outputet", "=", "false", ";", "if", "(", "(", "strpos", "(", "$", "value", ",", "'-'", ")", "!==", "false", ")", "&&", "(", "strlen", "(", "$", "value", ")", "==", "10", ")", ")", "{", "if", "(", "preg_match", "(", "\"([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})\"", ",", "$", "value", ",", "$", "regs", ")", ")", "{", "$", "outputet", "=", "true", ";", "$", "sReturn", ".=", "'style=\"text-align:right;width: 10px;\">'", ".", "$", "regs", "[", "3", "]", ".", "'.'", ".", "$", "regs", "[", "2", "]", ".", "'.'", ".", "$", "regs", "[", "1", "]", ";", "}", "}", "if", "(", "!", "$", "outputet", ")", "{", "$", "sReturn", ".=", "'style=\"text-align:left;\">'", ".", "$", "value", ";", "}", "}", "}", "$", "sReturn", ".=", "'</td>'", ";", "}", "}", "return", "$", "sReturn", ";", "}" ]
Generates a table cell @param array $aElements @param array $features @return string
[ "Generates", "a", "table", "cell" ]
627b99b4408414c7cd21a6c8016f6468dc9216b2
https://github.com/danielgp/common-lib/blob/627b99b4408414c7cd21a6c8016f6468dc9216b2/source/DomComponentsByDanielGP.php#L453-L495
train