repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
simbiosis-group/yii2-helper
models/ExcelImportForm.php
ExcelImportForm.import
public function import($modelName, $defaultValues = [], $updateMultipleModel = false, $queryConfigs = []) { $isSuccessful = true; $sheetData = $this->arrayFromExcel; $this->header = array_shift($sheetData); foreach ($sheetData as $record) { if ($updateMultipleModel) { $parentId = $this->getParentId($queryConfigs['parentModel'], $queryConfigs['parentKey'], $record, $modelName, $defaultValues); $childModel = new $queryConfigs['childModel']; foreach ($queryConfigs['childModelArray'] as $key=>$value) { if (!is_array($value)) { $childModel->$value = $this->getCellValue($value, $childModel, $record, $key, false); } else { $childModel->$value['attribute'] = $this->getCellValue($value, $childModel, $record, $key, false); } } $childModel->$queryConfigs['childForeignKey'] = $parentId; $childModel->save(); } else { $isSuccessful = $this->createModel($modelName, $defaultValues, $record); } } return $isSuccessful; }
php
public function import($modelName, $defaultValues = [], $updateMultipleModel = false, $queryConfigs = []) { $isSuccessful = true; $sheetData = $this->arrayFromExcel; $this->header = array_shift($sheetData); foreach ($sheetData as $record) { if ($updateMultipleModel) { $parentId = $this->getParentId($queryConfigs['parentModel'], $queryConfigs['parentKey'], $record, $modelName, $defaultValues); $childModel = new $queryConfigs['childModel']; foreach ($queryConfigs['childModelArray'] as $key=>$value) { if (!is_array($value)) { $childModel->$value = $this->getCellValue($value, $childModel, $record, $key, false); } else { $childModel->$value['attribute'] = $this->getCellValue($value, $childModel, $record, $key, false); } } $childModel->$queryConfigs['childForeignKey'] = $parentId; $childModel->save(); } else { $isSuccessful = $this->createModel($modelName, $defaultValues, $record); } } return $isSuccessful; }
[ "public", "function", "import", "(", "$", "modelName", ",", "$", "defaultValues", "=", "[", "]", ",", "$", "updateMultipleModel", "=", "false", ",", "$", "queryConfigs", "=", "[", "]", ")", "{", "$", "isSuccessful", "=", "true", ";", "$", "sheetData", "=", "$", "this", "->", "arrayFromExcel", ";", "$", "this", "->", "header", "=", "array_shift", "(", "$", "sheetData", ")", ";", "foreach", "(", "$", "sheetData", "as", "$", "record", ")", "{", "if", "(", "$", "updateMultipleModel", ")", "{", "$", "parentId", "=", "$", "this", "->", "getParentId", "(", "$", "queryConfigs", "[", "'parentModel'", "]", ",", "$", "queryConfigs", "[", "'parentKey'", "]", ",", "$", "record", ",", "$", "modelName", ",", "$", "defaultValues", ")", ";", "$", "childModel", "=", "new", "$", "queryConfigs", "[", "'childModel'", "]", ";", "foreach", "(", "$", "queryConfigs", "[", "'childModelArray'", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "$", "childModel", "->", "$", "value", "=", "$", "this", "->", "getCellValue", "(", "$", "value", ",", "$", "childModel", ",", "$", "record", ",", "$", "key", ",", "false", ")", ";", "}", "else", "{", "$", "childModel", "->", "$", "value", "[", "'attribute'", "]", "=", "$", "this", "->", "getCellValue", "(", "$", "value", ",", "$", "childModel", ",", "$", "record", ",", "$", "key", ",", "false", ")", ";", "}", "}", "$", "childModel", "->", "$", "queryConfigs", "[", "'childForeignKey'", "]", "=", "$", "parentId", ";", "$", "childModel", "->", "save", "(", ")", ";", "}", "else", "{", "$", "isSuccessful", "=", "$", "this", "->", "createModel", "(", "$", "modelName", ",", "$", "defaultValues", ",", "$", "record", ")", ";", "}", "}", "return", "$", "isSuccessful", ";", "}" ]
Import the excel to the model using active record @param string $model The model name to save the excel rows into @param array $defaultValues The default values to be assigned @return Return true if all records is saved
[ "Import", "the", "excel", "to", "the", "model", "using", "active", "record" ]
train
https://github.com/simbiosis-group/yii2-helper/blob/c85c4204dd06b16e54210e75fe6deb51869d1dd9/models/ExcelImportForm.php#L108-L139
simbiosis-group/yii2-helper
models/ExcelImportForm.php
ExcelImportForm.getCellValue
public function getCellValue($value, $model, $record, $key, $isParent = true) { if ($isParent) { if(isset($model->importSafeAttributes()[$value]) && is_array($model->importSafeAttributes()[$value])) { $array = $model->importSafeAttributes()[$value]; return $array['model']::find() ->andWhere([$array['fieldName'] => $record[$key]]) ->one() ->id; } return isset($record[$key]) ? $record[$key] : ''; } if (!is_array($value)) { return $record[array_search($key, $this->header)]; } return $value['model']::find() ->andWhere([$value['fieldName'] => $record[array_search($key, $this->header)]]) ->one() ->id; }
php
public function getCellValue($value, $model, $record, $key, $isParent = true) { if ($isParent) { if(isset($model->importSafeAttributes()[$value]) && is_array($model->importSafeAttributes()[$value])) { $array = $model->importSafeAttributes()[$value]; return $array['model']::find() ->andWhere([$array['fieldName'] => $record[$key]]) ->one() ->id; } return isset($record[$key]) ? $record[$key] : ''; } if (!is_array($value)) { return $record[array_search($key, $this->header)]; } return $value['model']::find() ->andWhere([$value['fieldName'] => $record[array_search($key, $this->header)]]) ->one() ->id; }
[ "public", "function", "getCellValue", "(", "$", "value", ",", "$", "model", ",", "$", "record", ",", "$", "key", ",", "$", "isParent", "=", "true", ")", "{", "if", "(", "$", "isParent", ")", "{", "if", "(", "isset", "(", "$", "model", "->", "importSafeAttributes", "(", ")", "[", "$", "value", "]", ")", "&&", "is_array", "(", "$", "model", "->", "importSafeAttributes", "(", ")", "[", "$", "value", "]", ")", ")", "{", "$", "array", "=", "$", "model", "->", "importSafeAttributes", "(", ")", "[", "$", "value", "]", ";", "return", "$", "array", "[", "'model'", "]", "::", "find", "(", ")", "->", "andWhere", "(", "[", "$", "array", "[", "'fieldName'", "]", "=>", "$", "record", "[", "$", "key", "]", "]", ")", "->", "one", "(", ")", "->", "id", ";", "}", "return", "isset", "(", "$", "record", "[", "$", "key", "]", ")", "?", "$", "record", "[", "$", "key", "]", ":", "''", ";", "}", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "return", "$", "record", "[", "array_search", "(", "$", "key", ",", "$", "this", "->", "header", ")", "]", ";", "}", "return", "$", "value", "[", "'model'", "]", "::", "find", "(", ")", "->", "andWhere", "(", "[", "$", "value", "[", "'fieldName'", "]", "=>", "$", "record", "[", "array_search", "(", "$", "key", ",", "$", "this", "->", "header", ")", "]", "]", ")", "->", "one", "(", ")", "->", "id", ";", "}" ]
Get excel cell value. If the import safe attributes has the model declared, it will grab the id from that model instead of the cell value @param string $model The model name to save the excel rows into @param array $value The values to be assigned @param string $record The model name to save the excel rows into @param string $key The key @return Return true if all records is saved
[ "Get", "excel", "cell", "value", ".", "If", "the", "import", "safe", "attributes", "has", "the", "model", "declared", "it", "will", "grab", "the", "id", "from", "that", "model", "instead", "of", "the", "cell", "value" ]
train
https://github.com/simbiosis-group/yii2-helper/blob/c85c4204dd06b16e54210e75fe6deb51869d1dd9/models/ExcelImportForm.php#L149-L172
phpnfe/tools
src/Soap/Wsdl.php
Wsdl.downLoadWsdl
public function downLoadWsdl($url, $priKeyPath, $pubKeyPath, $certKeyPath) { $soap = new CurlSoap($priKeyPath, $pubKeyPath, $certKeyPath); $resposta = $soap->getWsdl($url); if (! $resposta) { $this->soapDebug = $soap->soapDebug; return ''; } return $resposta; }
php
public function downLoadWsdl($url, $priKeyPath, $pubKeyPath, $certKeyPath) { $soap = new CurlSoap($priKeyPath, $pubKeyPath, $certKeyPath); $resposta = $soap->getWsdl($url); if (! $resposta) { $this->soapDebug = $soap->soapDebug; return ''; } return $resposta; }
[ "public", "function", "downLoadWsdl", "(", "$", "url", ",", "$", "priKeyPath", ",", "$", "pubKeyPath", ",", "$", "certKeyPath", ")", "{", "$", "soap", "=", "new", "CurlSoap", "(", "$", "priKeyPath", ",", "$", "pubKeyPath", ",", "$", "certKeyPath", ")", ";", "$", "resposta", "=", "$", "soap", "->", "getWsdl", "(", "$", "url", ")", ";", "if", "(", "!", "$", "resposta", ")", "{", "$", "this", "->", "soapDebug", "=", "$", "soap", "->", "soapDebug", ";", "return", "''", ";", "}", "return", "$", "resposta", ";", "}" ]
downloadWsdl Baixa o arquivo wsdl necessário para a comunicação SOAP nativa O WSDL pode também ser usado para verificar a mensagem SOAP com o uso do SOAPUI um recurso muito importante para testes off-line. @param string $url @param string $priKeyPath @param string $pubKeyPath @param string $certKeyPath @return string
[ "downloadWsdl", "Baixa", "o", "arquivo", "wsdl", "necessário", "para", "a", "comunicação", "SOAP", "nativa", "O", "WSDL", "pode", "também", "ser", "usado", "para", "verificar", "a", "mensagem", "SOAP", "com", "o", "uso", "do", "SOAPUI", "um", "recurso", "muito", "importante", "para", "testes", "off", "-", "line", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Soap/Wsdl.php#L31-L42
gregorybesson/PlaygroundCms
src/Entity/Slide.php
Slide.populate
public function populate($data = array()) { if (isset($data['title']) && $data['title'] != null) { $this->title = $data['title']; } if (isset($data['subtitle'])) { $this->subtitle = $data['subtitle']; } if (isset($data['type']) && $data['type'] != null) { $this->type = $data['type']; } if (isset($data['media']) && $data['media'] != null) { $this->media = $data['media']; } if (isset($data['position']) && $data['position'] != null) { $this->position = $data['position']; } if (isset($data['description'])) { $this->description = $data['description']; } if (isset($data['link'])) { $this->link = $data['link']; } if (isset($data['linkText'])) { $this->linkText = $data['linkText']; } }
php
public function populate($data = array()) { if (isset($data['title']) && $data['title'] != null) { $this->title = $data['title']; } if (isset($data['subtitle'])) { $this->subtitle = $data['subtitle']; } if (isset($data['type']) && $data['type'] != null) { $this->type = $data['type']; } if (isset($data['media']) && $data['media'] != null) { $this->media = $data['media']; } if (isset($data['position']) && $data['position'] != null) { $this->position = $data['position']; } if (isset($data['description'])) { $this->description = $data['description']; } if (isset($data['link'])) { $this->link = $data['link']; } if (isset($data['linkText'])) { $this->linkText = $data['linkText']; } }
[ "public", "function", "populate", "(", "$", "data", "=", "array", "(", ")", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "'title'", "]", ")", "&&", "$", "data", "[", "'title'", "]", "!=", "null", ")", "{", "$", "this", "->", "title", "=", "$", "data", "[", "'title'", "]", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'subtitle'", "]", ")", ")", "{", "$", "this", "->", "subtitle", "=", "$", "data", "[", "'subtitle'", "]", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'type'", "]", ")", "&&", "$", "data", "[", "'type'", "]", "!=", "null", ")", "{", "$", "this", "->", "type", "=", "$", "data", "[", "'type'", "]", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'media'", "]", ")", "&&", "$", "data", "[", "'media'", "]", "!=", "null", ")", "{", "$", "this", "->", "media", "=", "$", "data", "[", "'media'", "]", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'position'", "]", ")", "&&", "$", "data", "[", "'position'", "]", "!=", "null", ")", "{", "$", "this", "->", "position", "=", "$", "data", "[", "'position'", "]", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'description'", "]", ")", ")", "{", "$", "this", "->", "description", "=", "$", "data", "[", "'description'", "]", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'link'", "]", ")", ")", "{", "$", "this", "->", "link", "=", "$", "data", "[", "'link'", "]", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'linkText'", "]", ")", ")", "{", "$", "this", "->", "linkText", "=", "$", "data", "[", "'linkText'", "]", ";", "}", "}" ]
Populate from an array. @param array $data
[ "Populate", "from", "an", "array", "." ]
train
https://github.com/gregorybesson/PlaygroundCms/blob/e929a283f2a6e82d4f248c930f7aa454ce20cbc3/src/Entity/Slide.php#L387-L420
zhouyl/mellivora
Mellivora/Session/Session.php
Session.start
public function start() { if (!headers_sent()) { if (!$this->started && $this->status() !== PHP_SESSION_ACTIVE) { session_start(); $this->started = true; return true; } } return false; }
php
public function start() { if (!headers_sent()) { if (!$this->started && $this->status() !== PHP_SESSION_ACTIVE) { session_start(); $this->started = true; return true; } } return false; }
[ "public", "function", "start", "(", ")", "{", "if", "(", "!", "headers_sent", "(", ")", ")", "{", "if", "(", "!", "$", "this", "->", "started", "&&", "$", "this", "->", "status", "(", ")", "!==", "PHP_SESSION_ACTIVE", ")", "{", "session_start", "(", ")", ";", "$", "this", "->", "started", "=", "true", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
启动 session @return bool
[ "启动", "session" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Session/Session.php#L40-L52
zhouyl/mellivora
Mellivora/Session/Session.php
Session.set
public function set($key, $value = null) { $data = is_array($key) ? $key : [$key => $value]; foreach ($data as $key => $value) { Arr::set($_SESSION, $key, $value); } return $this; }
php
public function set($key, $value = null) { $data = is_array($key) ? $key : [$key => $value]; foreach ($data as $key => $value) { Arr::set($_SESSION, $key, $value); } return $this; }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", "=", "null", ")", "{", "$", "data", "=", "is_array", "(", "$", "key", ")", "?", "$", "key", ":", "[", "$", "key", "=>", "$", "value", "]", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "Arr", "::", "set", "(", "$", "_SESSION", ",", "$", "key", ",", "$", "value", ")", ";", "}", "return", "$", "this", ";", "}" ]
设定 session 数据 <code> $session->has("foo", "bar"); $session->has("foo.bar", 1); </code> @param string $key @param mixed $value @return \Mellivora\Session\Session
[ "设定", "session", "数据" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Session/Session.php#L105-L114
zhouyl/mellivora
Mellivora/Session/Session.php
Session.get
public function get($key, $default = null, $remove = false) { $data = Arr::get($_SESSION, $key, $default); if ($remove) { $this->delete($key); } return $data; }
php
public function get($key, $default = null, $remove = false) { $data = Arr::get($_SESSION, $key, $default); if ($remove) { $this->delete($key); } return $data; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "default", "=", "null", ",", "$", "remove", "=", "false", ")", "{", "$", "data", "=", "Arr", "::", "get", "(", "$", "_SESSION", ",", "$", "key", ",", "$", "default", ")", ";", "if", "(", "$", "remove", ")", "{", "$", "this", "->", "delete", "(", "$", "key", ")", ";", "}", "return", "$", "data", ";", "}" ]
获取 session 数据 <code> $session->get("foo"); $session->get("foo.bar"); </code> @param string $key @param mixed $default @param bool $remove @return mixed
[ "获取", "session", "数据" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Session/Session.php#L130-L139
zhouyl/mellivora
Mellivora/Session/Session.php
Session.destroy
public function destroy($removeData = false) { if ($removeData) { $_SESSION = []; } $this->started = false; session_destroy(); return $this; }
php
public function destroy($removeData = false) { if ($removeData) { $_SESSION = []; } $this->started = false; session_destroy(); return $this; }
[ "public", "function", "destroy", "(", "$", "removeData", "=", "false", ")", "{", "if", "(", "$", "removeData", ")", "{", "$", "_SESSION", "=", "[", "]", ";", "}", "$", "this", "->", "started", "=", "false", ";", "session_destroy", "(", ")", ";", "return", "$", "this", ";", "}" ]
销毁 session @param bool $removeData @return \Mellivora\Session\Session
[ "销毁", "session" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Session/Session.php#L240-L251
zhouyl/mellivora
Mellivora/Session/Session.php
Session.token
public function token($regenerate = false) { $key = '__token'; if (!$this->has($key) || $regenerate) { $this->set($key, Str::quickRandom(40)); } return $this->get($key); }
php
public function token($regenerate = false) { $key = '__token'; if (!$this->has($key) || $regenerate) { $this->set($key, Str::quickRandom(40)); } return $this->get($key); }
[ "public", "function", "token", "(", "$", "regenerate", "=", "false", ")", "{", "$", "key", "=", "'__token'", ";", "if", "(", "!", "$", "this", "->", "has", "(", "$", "key", ")", "||", "$", "regenerate", ")", "{", "$", "this", "->", "set", "(", "$", "key", ",", "Str", "::", "quickRandom", "(", "40", ")", ")", ";", "}", "return", "$", "this", "->", "get", "(", "$", "key", ")", ";", "}" ]
获取一个 token,如果不存在则自动生成 @param bool $regenerate @return string
[ "获取一个", "token,如果不存在则自动生成" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Session/Session.php#L270-L278
zhouyl/mellivora
Mellivora/Session/Session.php
Session.checkToken
public function checkToken($token, $once = true) { $check = $this->token() === $token; if ($once) { $this->delete('__token'); } return $check; }
php
public function checkToken($token, $once = true) { $check = $this->token() === $token; if ($once) { $this->delete('__token'); } return $check; }
[ "public", "function", "checkToken", "(", "$", "token", ",", "$", "once", "=", "true", ")", "{", "$", "check", "=", "$", "this", "->", "token", "(", ")", "===", "$", "token", ";", "if", "(", "$", "once", ")", "{", "$", "this", "->", "delete", "(", "'__token'", ")", ";", "}", "return", "$", "check", ";", "}" ]
校验 token @param string $token @param bool $once @return bool
[ "校验", "token" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Session/Session.php#L288-L297
TangoMan75/CallbackBundle
TwigExtension/Callback.php
Callback.callbackFunction
public function callbackFunction($route = null, $parameters = []) { if ($route === null || ! is_string($route)) { // Gets URI from current request $uri = $this->request->getUri(); } else { // Generates URI from '_route' $uri = $this->router->generate( $route, $parameters, Router::ABSOLUTE_URL ); } $result = parse_url($uri); // When uri contains query string if (isset($result['query'])) { parse_str($result['query'], $query); // Remove callback from query $query = array_diff_key($query, ['callback' => null]); } else { // Return unchanged uri return $uri; } return $result['scheme'].'://'. (isset($result['user']) ? $result['user'] : ''). (isset($result['pass']) ? ':'.$result['pass'].'@' : ''). $result['host']. (isset($result['port']) ? ':'.$result['port'] : ''). (isset($result['path']) ? $result['path'] : ''). ($query != [] ? '?'.http_build_query($query) : ''). (isset($result['fragment']) ? '#'.$result['fragment'] : ''); }
php
public function callbackFunction($route = null, $parameters = []) { if ($route === null || ! is_string($route)) { // Gets URI from current request $uri = $this->request->getUri(); } else { // Generates URI from '_route' $uri = $this->router->generate( $route, $parameters, Router::ABSOLUTE_URL ); } $result = parse_url($uri); // When uri contains query string if (isset($result['query'])) { parse_str($result['query'], $query); // Remove callback from query $query = array_diff_key($query, ['callback' => null]); } else { // Return unchanged uri return $uri; } return $result['scheme'].'://'. (isset($result['user']) ? $result['user'] : ''). (isset($result['pass']) ? ':'.$result['pass'].'@' : ''). $result['host']. (isset($result['port']) ? ':'.$result['port'] : ''). (isset($result['path']) ? $result['path'] : ''). ($query != [] ? '?'.http_build_query($query) : ''). (isset($result['fragment']) ? '#'.$result['fragment'] : ''); }
[ "public", "function", "callbackFunction", "(", "$", "route", "=", "null", ",", "$", "parameters", "=", "[", "]", ")", "{", "if", "(", "$", "route", "===", "null", "||", "!", "is_string", "(", "$", "route", ")", ")", "{", "// Gets URI from current request", "$", "uri", "=", "$", "this", "->", "request", "->", "getUri", "(", ")", ";", "}", "else", "{", "// Generates URI from '_route'", "$", "uri", "=", "$", "this", "->", "router", "->", "generate", "(", "$", "route", ",", "$", "parameters", ",", "Router", "::", "ABSOLUTE_URL", ")", ";", "}", "$", "result", "=", "parse_url", "(", "$", "uri", ")", ";", "// When uri contains query string", "if", "(", "isset", "(", "$", "result", "[", "'query'", "]", ")", ")", "{", "parse_str", "(", "$", "result", "[", "'query'", "]", ",", "$", "query", ")", ";", "// Remove callback from query", "$", "query", "=", "array_diff_key", "(", "$", "query", ",", "[", "'callback'", "=>", "null", "]", ")", ";", "}", "else", "{", "// Return unchanged uri", "return", "$", "uri", ";", "}", "return", "$", "result", "[", "'scheme'", "]", ".", "'://'", ".", "(", "isset", "(", "$", "result", "[", "'user'", "]", ")", "?", "$", "result", "[", "'user'", "]", ":", "''", ")", ".", "(", "isset", "(", "$", "result", "[", "'pass'", "]", ")", "?", "':'", ".", "$", "result", "[", "'pass'", "]", ".", "'@'", ":", "''", ")", ".", "$", "result", "[", "'host'", "]", ".", "(", "isset", "(", "$", "result", "[", "'port'", "]", ")", "?", "':'", ".", "$", "result", "[", "'port'", "]", ":", "''", ")", ".", "(", "isset", "(", "$", "result", "[", "'path'", "]", ")", "?", "$", "result", "[", "'path'", "]", ":", "''", ")", ".", "(", "$", "query", "!=", "[", "]", "?", "'?'", ".", "http_build_query", "(", "$", "query", ")", ":", "''", ")", ".", "(", "isset", "(", "$", "result", "[", "'fragment'", "]", ")", "?", "'#'", ".", "$", "result", "[", "'fragment'", "]", ":", "''", ")", ";", "}" ]
Removes callbacks from query @param string $route @param array $parameters @return string
[ "Removes", "callbacks", "from", "query" ]
train
https://github.com/TangoMan75/CallbackBundle/blob/a56f599c7786ee7a8134e4f7752da427036f8002/TwigExtension/Callback.php#L72-L108
php-lug/lug
src/Component/Resource/Domain/AbstractDomainManager.php
AbstractDomainManager.find
public function find($action, $repositoryMethod, array $criteria, array $sorting = []) { $event = new DomainEvent($this->resource, $action = 'find.'.$action); try { $this->dispatchEvent($event, $action, self::STATE_PRE); $event->setData($this->doFind($action, $repositoryMethod, $criteria, $sorting)); } catch (\Exception $e) { $this->dispatchEvent($event, $action, self::STATE_ERROR, $e); return; } $this->dispatchEvent($event, $action, self::STATE_POST); return $event->getData(); }
php
public function find($action, $repositoryMethod, array $criteria, array $sorting = []) { $event = new DomainEvent($this->resource, $action = 'find.'.$action); try { $this->dispatchEvent($event, $action, self::STATE_PRE); $event->setData($this->doFind($action, $repositoryMethod, $criteria, $sorting)); } catch (\Exception $e) { $this->dispatchEvent($event, $action, self::STATE_ERROR, $e); return; } $this->dispatchEvent($event, $action, self::STATE_POST); return $event->getData(); }
[ "public", "function", "find", "(", "$", "action", ",", "$", "repositoryMethod", ",", "array", "$", "criteria", ",", "array", "$", "sorting", "=", "[", "]", ")", "{", "$", "event", "=", "new", "DomainEvent", "(", "$", "this", "->", "resource", ",", "$", "action", "=", "'find.'", ".", "$", "action", ")", ";", "try", "{", "$", "this", "->", "dispatchEvent", "(", "$", "event", ",", "$", "action", ",", "self", "::", "STATE_PRE", ")", ";", "$", "event", "->", "setData", "(", "$", "this", "->", "doFind", "(", "$", "action", ",", "$", "repositoryMethod", ",", "$", "criteria", ",", "$", "sorting", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "dispatchEvent", "(", "$", "event", ",", "$", "action", ",", "self", "::", "STATE_ERROR", ",", "$", "e", ")", ";", "return", ";", "}", "$", "this", "->", "dispatchEvent", "(", "$", "event", ",", "$", "action", ",", "self", "::", "STATE_POST", ")", ";", "return", "$", "event", "->", "getData", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Resource/Domain/AbstractDomainManager.php#L50-L66
php-lug/lug
src/Component/Resource/Domain/AbstractDomainManager.php
AbstractDomainManager.create
public function create($object, $flush = true) { $event = new DomainEvent($this->resource, $action = 'create', $object); try { $this->dispatchEvent($event, $action, self::STATE_PRE); $this->doCreate($event->getData(), $flush); } catch (\Exception $e) { $this->dispatchEvent($event, $action, self::STATE_ERROR, $e); return; } $this->dispatchEvent($event, $action, self::STATE_POST); }
php
public function create($object, $flush = true) { $event = new DomainEvent($this->resource, $action = 'create', $object); try { $this->dispatchEvent($event, $action, self::STATE_PRE); $this->doCreate($event->getData(), $flush); } catch (\Exception $e) { $this->dispatchEvent($event, $action, self::STATE_ERROR, $e); return; } $this->dispatchEvent($event, $action, self::STATE_POST); }
[ "public", "function", "create", "(", "$", "object", ",", "$", "flush", "=", "true", ")", "{", "$", "event", "=", "new", "DomainEvent", "(", "$", "this", "->", "resource", ",", "$", "action", "=", "'create'", ",", "$", "object", ")", ";", "try", "{", "$", "this", "->", "dispatchEvent", "(", "$", "event", ",", "$", "action", ",", "self", "::", "STATE_PRE", ")", ";", "$", "this", "->", "doCreate", "(", "$", "event", "->", "getData", "(", ")", ",", "$", "flush", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "dispatchEvent", "(", "$", "event", ",", "$", "action", ",", "self", "::", "STATE_ERROR", ",", "$", "e", ")", ";", "return", ";", "}", "$", "this", "->", "dispatchEvent", "(", "$", "event", ",", "$", "action", ",", "self", "::", "STATE_POST", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Resource/Domain/AbstractDomainManager.php#L71-L85
php-lug/lug
src/Component/Resource/Domain/AbstractDomainManager.php
AbstractDomainManager.flush
public function flush($object = null) { $event = new DomainEvent($this->resource, $action = 'flush', $object); try { $this->dispatchEvent($event, $action, self::STATE_PRE); $this->doFlush(); } catch (\Exception $e) { $this->dispatchEvent($event, $action, self::STATE_ERROR, $e); return; } $this->dispatchEvent($event, $action, self::STATE_POST); }
php
public function flush($object = null) { $event = new DomainEvent($this->resource, $action = 'flush', $object); try { $this->dispatchEvent($event, $action, self::STATE_PRE); $this->doFlush(); } catch (\Exception $e) { $this->dispatchEvent($event, $action, self::STATE_ERROR, $e); return; } $this->dispatchEvent($event, $action, self::STATE_POST); }
[ "public", "function", "flush", "(", "$", "object", "=", "null", ")", "{", "$", "event", "=", "new", "DomainEvent", "(", "$", "this", "->", "resource", ",", "$", "action", "=", "'flush'", ",", "$", "object", ")", ";", "try", "{", "$", "this", "->", "dispatchEvent", "(", "$", "event", ",", "$", "action", ",", "self", "::", "STATE_PRE", ")", ";", "$", "this", "->", "doFlush", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "dispatchEvent", "(", "$", "event", ",", "$", "action", ",", "self", "::", "STATE_ERROR", ",", "$", "e", ")", ";", "return", ";", "}", "$", "this", "->", "dispatchEvent", "(", "$", "event", ",", "$", "action", ",", "self", "::", "STATE_POST", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Resource/Domain/AbstractDomainManager.php#L128-L142
zhouyl/mellivora
Mellivora/Database/Schema/Grammars/Grammar.php
Grammar.getCommandsByName
protected function getCommandsByName(Blueprint $blueprint, $name) { return array_filter($blueprint->getCommands(), function ($value) use ($name) { return $value->name === $name; }); }
php
protected function getCommandsByName(Blueprint $blueprint, $name) { return array_filter($blueprint->getCommands(), function ($value) use ($name) { return $value->name === $name; }); }
[ "protected", "function", "getCommandsByName", "(", "Blueprint", "$", "blueprint", ",", "$", "name", ")", "{", "return", "array_filter", "(", "$", "blueprint", "->", "getCommands", "(", ")", ",", "function", "(", "$", "value", ")", "use", "(", "$", "name", ")", "{", "return", "$", "value", "->", "name", "===", "$", "name", ";", "}", ")", ";", "}" ]
Get all of the commands with a given name. @param \Mellivora\Database\Schema\Blueprint $blueprint @param string $name @return array
[ "Get", "all", "of", "the", "commands", "with", "a", "given", "name", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Schema/Grammars/Grammar.php#L175-L180
zhouyl/mellivora
Mellivora/Database/Schema/Grammars/Grammar.php
Grammar.getDefaultValue
protected function getDefaultValue($value) { if ($value instanceof Expression) { return $value; } return is_bool($value) ? "'" . (int) $value . "'" : "'" . strval($value) . "'"; }
php
protected function getDefaultValue($value) { if ($value instanceof Expression) { return $value; } return is_bool($value) ? "'" . (int) $value . "'" : "'" . strval($value) . "'"; }
[ "protected", "function", "getDefaultValue", "(", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "Expression", ")", "{", "return", "$", "value", ";", "}", "return", "is_bool", "(", "$", "value", ")", "?", "\"'\"", ".", "(", "int", ")", "$", "value", ".", "\"'\"", ":", "\"'\"", ".", "strval", "(", "$", "value", ")", ".", "\"'\"", ";", "}" ]
Format a value so that it can be used in "default" clauses. @param mixed $value @return string
[ "Format", "a", "value", "so", "that", "it", "can", "be", "used", "in", "default", "clauses", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Schema/Grammars/Grammar.php#L234-L243
CupOfTea696/WordPress-Composer
src/PluginInteractor.php
PluginInteractor.activate
public function activate(Composer $composer, IOInterface $io, $pluginName) { $plugin = $this->prepare(__FUNCTION__, $composer, $io, $pluginName); if ($plugin) { $result = $this->wp(function () use ($plugin) { wp_cache_set('plugins', [], 'plugins'); return activate_plugin($plugin); }); $this->succeeded(__FUNCTION__, $pluginName, $result === null); } }
php
public function activate(Composer $composer, IOInterface $io, $pluginName) { $plugin = $this->prepare(__FUNCTION__, $composer, $io, $pluginName); if ($plugin) { $result = $this->wp(function () use ($plugin) { wp_cache_set('plugins', [], 'plugins'); return activate_plugin($plugin); }); $this->succeeded(__FUNCTION__, $pluginName, $result === null); } }
[ "public", "function", "activate", "(", "Composer", "$", "composer", ",", "IOInterface", "$", "io", ",", "$", "pluginName", ")", "{", "$", "plugin", "=", "$", "this", "->", "prepare", "(", "__FUNCTION__", ",", "$", "composer", ",", "$", "io", ",", "$", "pluginName", ")", ";", "if", "(", "$", "plugin", ")", "{", "$", "result", "=", "$", "this", "->", "wp", "(", "function", "(", ")", "use", "(", "$", "plugin", ")", "{", "wp_cache_set", "(", "'plugins'", ",", "[", "]", ",", "'plugins'", ")", ";", "return", "activate_plugin", "(", "$", "plugin", ")", ";", "}", ")", ";", "$", "this", "->", "succeeded", "(", "__FUNCTION__", ",", "$", "pluginName", ",", "$", "result", "===", "null", ")", ";", "}", "}" ]
Activate a plugin. @param \Composer\Composer $composer @param \Composer\IO\IOInterface $io @param string $plugin @return void
[ "Activate", "a", "plugin", "." ]
train
https://github.com/CupOfTea696/WordPress-Composer/blob/8c0abc10f82b8ce1db5354f6a041c7587ad3fb90/src/PluginInteractor.php#L67-L80
CupOfTea696/WordPress-Composer
src/PluginInteractor.php
PluginInteractor.deactivate
public function deactivate(Composer $composer, IOInterface $io, $pluginName) { $plugin = $this->prepare(__FUNCTION__, $composer, $io, $pluginName); if ($plugin) { $result = $this->wp(function () use ($plugin) { return deactivate_plugins($plugin); }); $this->succeeded(__FUNCTION__, $pluginName, $result === null); } }
php
public function deactivate(Composer $composer, IOInterface $io, $pluginName) { $plugin = $this->prepare(__FUNCTION__, $composer, $io, $pluginName); if ($plugin) { $result = $this->wp(function () use ($plugin) { return deactivate_plugins($plugin); }); $this->succeeded(__FUNCTION__, $pluginName, $result === null); } }
[ "public", "function", "deactivate", "(", "Composer", "$", "composer", ",", "IOInterface", "$", "io", ",", "$", "pluginName", ")", "{", "$", "plugin", "=", "$", "this", "->", "prepare", "(", "__FUNCTION__", ",", "$", "composer", ",", "$", "io", ",", "$", "pluginName", ")", ";", "if", "(", "$", "plugin", ")", "{", "$", "result", "=", "$", "this", "->", "wp", "(", "function", "(", ")", "use", "(", "$", "plugin", ")", "{", "return", "deactivate_plugins", "(", "$", "plugin", ")", ";", "}", ")", ";", "$", "this", "->", "succeeded", "(", "__FUNCTION__", ",", "$", "pluginName", ",", "$", "result", "===", "null", ")", ";", "}", "}" ]
Deactivate a plugin. @param \Composer\Composer $composer @param \Composer\IO\IOInterface $io @param string $plugin @return void
[ "Deactivate", "a", "plugin", "." ]
train
https://github.com/CupOfTea696/WordPress-Composer/blob/8c0abc10f82b8ce1db5354f6a041c7587ad3fb90/src/PluginInteractor.php#L90-L101
CupOfTea696/WordPress-Composer
src/PluginInteractor.php
PluginInteractor.uninstall
public function uninstall(Composer $composer, IOInterface $io, $pluginName) { $plugin = $this->prepare(__FUNCTION__, $composer, $io, $pluginName); if ($plugin) { $result = $this->wp(function () use ($plugin) { return uninstall_plugin($plugin); }); $this->succeeded(__FUNCTION__, $pluginName, $result === true || $result === null); } }
php
public function uninstall(Composer $composer, IOInterface $io, $pluginName) { $plugin = $this->prepare(__FUNCTION__, $composer, $io, $pluginName); if ($plugin) { $result = $this->wp(function () use ($plugin) { return uninstall_plugin($plugin); }); $this->succeeded(__FUNCTION__, $pluginName, $result === true || $result === null); } }
[ "public", "function", "uninstall", "(", "Composer", "$", "composer", ",", "IOInterface", "$", "io", ",", "$", "pluginName", ")", "{", "$", "plugin", "=", "$", "this", "->", "prepare", "(", "__FUNCTION__", ",", "$", "composer", ",", "$", "io", ",", "$", "pluginName", ")", ";", "if", "(", "$", "plugin", ")", "{", "$", "result", "=", "$", "this", "->", "wp", "(", "function", "(", ")", "use", "(", "$", "plugin", ")", "{", "return", "uninstall_plugin", "(", "$", "plugin", ")", ";", "}", ")", ";", "$", "this", "->", "succeeded", "(", "__FUNCTION__", ",", "$", "pluginName", ",", "$", "result", "===", "true", "||", "$", "result", "===", "null", ")", ";", "}", "}" ]
Uninstall a plugin. @param \Composer\Composer $composer @param \Composer\IO\IOInterface $io @param string $plugin @return void
[ "Uninstall", "a", "plugin", "." ]
train
https://github.com/CupOfTea696/WordPress-Composer/blob/8c0abc10f82b8ce1db5354f6a041c7587ad3fb90/src/PluginInteractor.php#L111-L122
CupOfTea696/WordPress-Composer
src/PluginInteractor.php
PluginInteractor.prepare
protected function prepare($action, Composer $composer, IOInterface $io, $pluginName) { $this->composer = $composer; $this->io = $io; if ($this->isPluginExcluded($action, $pluginName)) { return $this->excluded($action, $pluginName) && false; } $plugin = $this->getPlugin($pluginName); if (! $plugin) { return $this->failed($action, $pluginName) && false; } $this->executing($action, $pluginName); return $plugin; }
php
protected function prepare($action, Composer $composer, IOInterface $io, $pluginName) { $this->composer = $composer; $this->io = $io; if ($this->isPluginExcluded($action, $pluginName)) { return $this->excluded($action, $pluginName) && false; } $plugin = $this->getPlugin($pluginName); if (! $plugin) { return $this->failed($action, $pluginName) && false; } $this->executing($action, $pluginName); return $plugin; }
[ "protected", "function", "prepare", "(", "$", "action", ",", "Composer", "$", "composer", ",", "IOInterface", "$", "io", ",", "$", "pluginName", ")", "{", "$", "this", "->", "composer", "=", "$", "composer", ";", "$", "this", "->", "io", "=", "$", "io", ";", "if", "(", "$", "this", "->", "isPluginExcluded", "(", "$", "action", ",", "$", "pluginName", ")", ")", "{", "return", "$", "this", "->", "excluded", "(", "$", "action", ",", "$", "pluginName", ")", "&&", "false", ";", "}", "$", "plugin", "=", "$", "this", "->", "getPlugin", "(", "$", "pluginName", ")", ";", "if", "(", "!", "$", "plugin", ")", "{", "return", "$", "this", "->", "failed", "(", "$", "action", ",", "$", "pluginName", ")", "&&", "false", ";", "}", "$", "this", "->", "executing", "(", "$", "action", ",", "$", "pluginName", ")", ";", "return", "$", "plugin", ";", "}" ]
Prepare plugin interaction. @param string $action @param \Composer\Composer $composer @param \Composer\IO\IOInterface $io @param string $pluginName @return string|false
[ "Prepare", "plugin", "interaction", "." ]
train
https://github.com/CupOfTea696/WordPress-Composer/blob/8c0abc10f82b8ce1db5354f6a041c7587ad3fb90/src/PluginInteractor.php#L133-L151
CupOfTea696/WordPress-Composer
src/PluginInteractor.php
PluginInteractor.getPlugin
protected function getPlugin($plugin) { $path = $this->plugin->getPublicDirectory() . '/plugins/' . $plugin; if (file_exists($path) && is_dir($path)) { $files = scandir($path); foreach ($files as $file) { $pattern = defined('HHVM_VERSION') ? '/\.(php|hh)$/' : '/\.php$/'; if (preg_match($pattern, $file)) { $content = file_get_contents($path . '/' . $file); if (preg_match('/\/\*(?!.*\*\/.*Plugin Name).*Plugin Name/si', $content)) { return $plugin . '/' . $file; } } } } if (file_exists($path . '.php')) { return $plugin . '.php'; } if (defined('HHVM_VERSION') && file_exists($path . '.hh')) { return $plugin . '.hh'; } return false; }
php
protected function getPlugin($plugin) { $path = $this->plugin->getPublicDirectory() . '/plugins/' . $plugin; if (file_exists($path) && is_dir($path)) { $files = scandir($path); foreach ($files as $file) { $pattern = defined('HHVM_VERSION') ? '/\.(php|hh)$/' : '/\.php$/'; if (preg_match($pattern, $file)) { $content = file_get_contents($path . '/' . $file); if (preg_match('/\/\*(?!.*\*\/.*Plugin Name).*Plugin Name/si', $content)) { return $plugin . '/' . $file; } } } } if (file_exists($path . '.php')) { return $plugin . '.php'; } if (defined('HHVM_VERSION') && file_exists($path . '.hh')) { return $plugin . '.hh'; } return false; }
[ "protected", "function", "getPlugin", "(", "$", "plugin", ")", "{", "$", "path", "=", "$", "this", "->", "plugin", "->", "getPublicDirectory", "(", ")", ".", "'/plugins/'", ".", "$", "plugin", ";", "if", "(", "file_exists", "(", "$", "path", ")", "&&", "is_dir", "(", "$", "path", ")", ")", "{", "$", "files", "=", "scandir", "(", "$", "path", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "pattern", "=", "defined", "(", "'HHVM_VERSION'", ")", "?", "'/\\.(php|hh)$/'", ":", "'/\\.php$/'", ";", "if", "(", "preg_match", "(", "$", "pattern", ",", "$", "file", ")", ")", "{", "$", "content", "=", "file_get_contents", "(", "$", "path", ".", "'/'", ".", "$", "file", ")", ";", "if", "(", "preg_match", "(", "'/\\/\\*(?!.*\\*\\/.*Plugin Name).*Plugin Name/si'", ",", "$", "content", ")", ")", "{", "return", "$", "plugin", ".", "'/'", ".", "$", "file", ";", "}", "}", "}", "}", "if", "(", "file_exists", "(", "$", "path", ".", "'.php'", ")", ")", "{", "return", "$", "plugin", ".", "'.php'", ";", "}", "if", "(", "defined", "(", "'HHVM_VERSION'", ")", "&&", "file_exists", "(", "$", "path", ".", "'.hh'", ")", ")", "{", "return", "$", "plugin", ".", "'.hh'", ";", "}", "return", "false", ";", "}" ]
Get the main plugin file for a plugin. @param string $plugin @return string|false
[ "Get", "the", "main", "plugin", "file", "for", "a", "plugin", "." ]
train
https://github.com/CupOfTea696/WordPress-Composer/blob/8c0abc10f82b8ce1db5354f6a041c7587ad3fb90/src/PluginInteractor.php#L174-L203
CupOfTea696/WordPress-Composer
src/PluginInteractor.php
PluginInteractor.executing
protected function executing($action, $plugin) { $this->io->write(' - ' . ucfirst($this->getActionExecuting($action)) . ' plugin <info>' . $plugin . '</info>'); $this->io->write(''); }
php
protected function executing($action, $plugin) { $this->io->write(' - ' . ucfirst($this->getActionExecuting($action)) . ' plugin <info>' . $plugin . '</info>'); $this->io->write(''); }
[ "protected", "function", "executing", "(", "$", "action", ",", "$", "plugin", ")", "{", "$", "this", "->", "io", "->", "write", "(", "' - '", ".", "ucfirst", "(", "$", "this", "->", "getActionExecuting", "(", "$", "action", ")", ")", ".", "' plugin <info>'", ".", "$", "plugin", ".", "'</info>'", ")", ";", "$", "this", "->", "io", "->", "write", "(", "''", ")", ";", "}" ]
Write action executing. @param string $action @param string $plugin @return void
[ "Write", "action", "executing", "." ]
train
https://github.com/CupOfTea696/WordPress-Composer/blob/8c0abc10f82b8ce1db5354f6a041c7587ad3fb90/src/PluginInteractor.php#L224-L228
CupOfTea696/WordPress-Composer
src/PluginInteractor.php
PluginInteractor.failed
protected function failed($action, $plugin) { $this->io->write('<warning>The plugin ' . $plugin . ' could not be ' . $this->getActionPast($action) . '.</warning>'); $this->io->write(''); }
php
protected function failed($action, $plugin) { $this->io->write('<warning>The plugin ' . $plugin . ' could not be ' . $this->getActionPast($action) . '.</warning>'); $this->io->write(''); }
[ "protected", "function", "failed", "(", "$", "action", ",", "$", "plugin", ")", "{", "$", "this", "->", "io", "->", "write", "(", "'<warning>The plugin '", ".", "$", "plugin", ".", "' could not be '", ".", "$", "this", "->", "getActionPast", "(", "$", "action", ")", ".", "'.</warning>'", ")", ";", "$", "this", "->", "io", "->", "write", "(", "''", ")", ";", "}" ]
Write failed action warning. @param string $action @param string $plugin @return void
[ "Write", "failed", "action", "warning", "." ]
train
https://github.com/CupOfTea696/WordPress-Composer/blob/8c0abc10f82b8ce1db5354f6a041c7587ad3fb90/src/PluginInteractor.php#L237-L241
CupOfTea696/WordPress-Composer
src/PluginInteractor.php
PluginInteractor.excluded
protected function excluded($action, $plugin) { $this->io->write('<warning>The plugin ' . $plugin . ' was not ' . $this->getActionPast($action) . ' because it is known to cause issues.</warning>'); $this->io->write('<info>You can still activate this plugin manually.</info>'); $this->io->write(''); }
php
protected function excluded($action, $plugin) { $this->io->write('<warning>The plugin ' . $plugin . ' was not ' . $this->getActionPast($action) . ' because it is known to cause issues.</warning>'); $this->io->write('<info>You can still activate this plugin manually.</info>'); $this->io->write(''); }
[ "protected", "function", "excluded", "(", "$", "action", ",", "$", "plugin", ")", "{", "$", "this", "->", "io", "->", "write", "(", "'<warning>The plugin '", ".", "$", "plugin", ".", "' was not '", ".", "$", "this", "->", "getActionPast", "(", "$", "action", ")", ".", "' because it is known to cause issues.</warning>'", ")", ";", "$", "this", "->", "io", "->", "write", "(", "'<info>You can still activate this plugin manually.</info>'", ")", ";", "$", "this", "->", "io", "->", "write", "(", "''", ")", ";", "}" ]
Write failed action warning. @param string $action @param string $plugin @return void
[ "Write", "failed", "action", "warning", "." ]
train
https://github.com/CupOfTea696/WordPress-Composer/blob/8c0abc10f82b8ce1db5354f6a041c7587ad3fb90/src/PluginInteractor.php#L250-L255
CupOfTea696/WordPress-Composer
src/PluginInteractor.php
PluginInteractor.wp
protected function wp(Closure $cmd) { $cmd = new ReflectionFunction($cmd); $code = implode(array_slice(file($cmd->getFileName()), ($startLine = $cmd->getStartLine() - 1), $cmd->getEndLine() - $startLine)); preg_match('/\\{(.*)\\}/s', $code, $body); $vars = $cmd->getStaticVariables(); $cmd = trim(preg_replace_callback('/return(?:;|\s((?:[^;(]*(?:\(.*\))?)+);)/s', function ($matches) { if (! empty($matches[1])) { return "return print 'OUTPUT>>>' . serialize({$matches[1]});"; } return "return print 'OUTPUT>>>' . serialize(null);"; }, $body[1])); $config = [ '__host' => env('DB_HOST', 'localhost'), '__name' => env('DB_NAME', 'homestead'), '__user' => env('DB_USER', 'homestead'), '__pass' => env('DB_PASS', 'secret'), '__abspath' => $this->plugin->getPublicDirectory() . '/wp/', '__wp' => dirname(__FILE__) . '/wordpress.php', ]; $config = serialize($config); $vars = serialize($vars); $p = new PhpProcess("<?php extract(unserialize('$config')); try { \$db = new PDO('mysql:host=' . \$__host . ';dbname=' . \$__name, \$__user, \$__pass); } catch (PDOException \$e) { if (\$__host == 'localhost') { \$__host = '127.0.0.1'; } \$db = new PDO('mysql:host=' . \$__host . ';port=33060;dbname=' . \$__name, \$__user, \$__pass); \$__host = \$__host . ':33060'; } catch (PDOException \$e) { return; } define('DB_HOST', \$__host); define('ABSPATH', \$__abspath); \$_SERVER = [ 'HTTP_HOST' => 'http://mysite.com', 'SERVER_NAME' => 'http://mysite.com', 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'GET' ]; //require the WP bootstrap require_once ABSPATH . '/wp-admin/includes/plugin.php'; require_once ABSPATH . '/wp-load.php'; extract(unserialize('$vars')); $cmd "); $p->run(); if (preg_match('/OUTPUT>>>(.*)$/s', $p->getOutput(), $matches)) { return unserialize($matches[1]); } }
php
protected function wp(Closure $cmd) { $cmd = new ReflectionFunction($cmd); $code = implode(array_slice(file($cmd->getFileName()), ($startLine = $cmd->getStartLine() - 1), $cmd->getEndLine() - $startLine)); preg_match('/\\{(.*)\\}/s', $code, $body); $vars = $cmd->getStaticVariables(); $cmd = trim(preg_replace_callback('/return(?:;|\s((?:[^;(]*(?:\(.*\))?)+);)/s', function ($matches) { if (! empty($matches[1])) { return "return print 'OUTPUT>>>' . serialize({$matches[1]});"; } return "return print 'OUTPUT>>>' . serialize(null);"; }, $body[1])); $config = [ '__host' => env('DB_HOST', 'localhost'), '__name' => env('DB_NAME', 'homestead'), '__user' => env('DB_USER', 'homestead'), '__pass' => env('DB_PASS', 'secret'), '__abspath' => $this->plugin->getPublicDirectory() . '/wp/', '__wp' => dirname(__FILE__) . '/wordpress.php', ]; $config = serialize($config); $vars = serialize($vars); $p = new PhpProcess("<?php extract(unserialize('$config')); try { \$db = new PDO('mysql:host=' . \$__host . ';dbname=' . \$__name, \$__user, \$__pass); } catch (PDOException \$e) { if (\$__host == 'localhost') { \$__host = '127.0.0.1'; } \$db = new PDO('mysql:host=' . \$__host . ';port=33060;dbname=' . \$__name, \$__user, \$__pass); \$__host = \$__host . ':33060'; } catch (PDOException \$e) { return; } define('DB_HOST', \$__host); define('ABSPATH', \$__abspath); \$_SERVER = [ 'HTTP_HOST' => 'http://mysite.com', 'SERVER_NAME' => 'http://mysite.com', 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'GET' ]; //require the WP bootstrap require_once ABSPATH . '/wp-admin/includes/plugin.php'; require_once ABSPATH . '/wp-load.php'; extract(unserialize('$vars')); $cmd "); $p->run(); if (preg_match('/OUTPUT>>>(.*)$/s', $p->getOutput(), $matches)) { return unserialize($matches[1]); } }
[ "protected", "function", "wp", "(", "Closure", "$", "cmd", ")", "{", "$", "cmd", "=", "new", "ReflectionFunction", "(", "$", "cmd", ")", ";", "$", "code", "=", "implode", "(", "array_slice", "(", "file", "(", "$", "cmd", "->", "getFileName", "(", ")", ")", ",", "(", "$", "startLine", "=", "$", "cmd", "->", "getStartLine", "(", ")", "-", "1", ")", ",", "$", "cmd", "->", "getEndLine", "(", ")", "-", "$", "startLine", ")", ")", ";", "preg_match", "(", "'/\\\\{(.*)\\\\}/s'", ",", "$", "code", ",", "$", "body", ")", ";", "$", "vars", "=", "$", "cmd", "->", "getStaticVariables", "(", ")", ";", "$", "cmd", "=", "trim", "(", "preg_replace_callback", "(", "'/return(?:;|\\s((?:[^;(]*(?:\\(.*\\))?)+);)/s'", ",", "function", "(", "$", "matches", ")", "{", "if", "(", "!", "empty", "(", "$", "matches", "[", "1", "]", ")", ")", "{", "return", "\"return print 'OUTPUT>>>' . serialize({$matches[1]});\"", ";", "}", "return", "\"return print 'OUTPUT>>>' . serialize(null);\"", ";", "}", ",", "$", "body", "[", "1", "]", ")", ")", ";", "$", "config", "=", "[", "'__host'", "=>", "env", "(", "'DB_HOST'", ",", "'localhost'", ")", ",", "'__name'", "=>", "env", "(", "'DB_NAME'", ",", "'homestead'", ")", ",", "'__user'", "=>", "env", "(", "'DB_USER'", ",", "'homestead'", ")", ",", "'__pass'", "=>", "env", "(", "'DB_PASS'", ",", "'secret'", ")", ",", "'__abspath'", "=>", "$", "this", "->", "plugin", "->", "getPublicDirectory", "(", ")", ".", "'/wp/'", ",", "'__wp'", "=>", "dirname", "(", "__FILE__", ")", ".", "'/wordpress.php'", ",", "]", ";", "$", "config", "=", "serialize", "(", "$", "config", ")", ";", "$", "vars", "=", "serialize", "(", "$", "vars", ")", ";", "$", "p", "=", "new", "PhpProcess", "(", "\"<?php\n extract(unserialize('$config'));\n \n try {\n \\$db = new PDO('mysql:host=' . \\$__host . ';dbname=' . \\$__name, \\$__user, \\$__pass);\n } catch (PDOException \\$e) {\n if (\\$__host == 'localhost') {\n \\$__host = '127.0.0.1';\n }\n \n \\$db = new PDO('mysql:host=' . \\$__host . ';port=33060;dbname=' . \\$__name, \\$__user, \\$__pass);\n \n \\$__host = \\$__host . ':33060';\n } catch (PDOException \\$e) {\n return;\n }\n \n define('DB_HOST', \\$__host);\n define('ABSPATH', \\$__abspath);\n \n \\$_SERVER = [\n 'HTTP_HOST' => 'http://mysite.com',\n 'SERVER_NAME' => 'http://mysite.com',\n 'REQUEST_URI' => '/',\n 'REQUEST_METHOD' => 'GET'\n ];\n \n //require the WP bootstrap\n require_once ABSPATH . '/wp-admin/includes/plugin.php';\n require_once ABSPATH . '/wp-load.php';\n \n extract(unserialize('$vars'));\n $cmd\n \"", ")", ";", "$", "p", "->", "run", "(", ")", ";", "if", "(", "preg_match", "(", "'/OUTPUT>>>(.*)$/s'", ",", "$", "p", "->", "getOutput", "(", ")", ",", "$", "matches", ")", ")", "{", "return", "unserialize", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "}" ]
Run a closure in the WordPress environment. @param closure $cmd @return mixed
[ "Run", "a", "closure", "in", "the", "WordPress", "environment", "." ]
train
https://github.com/CupOfTea696/WordPress-Composer/blob/8c0abc10f82b8ce1db5354f6a041c7587ad3fb90/src/PluginInteractor.php#L305-L373
php-lug/lug
src/Component/Grid/Filter/Type/NumberType.php
NumberType.process
protected function process($field, $data, array $options) { $builder = $options['builder']; switch ($data['type']) { case self::TYPE_GREATER_THAN_OR_EQUALS: return $builder->getExpressionBuilder()->gte( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_GREATER_THAN: return $builder->getExpressionBuilder()->gt( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_LESS_THAN_OR_EQUALS: return $builder->getExpressionBuilder()->lte( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_LESS_THAN: return $builder->getExpressionBuilder()->lt( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_NOT_EQUALS: return $builder->getExpressionBuilder()->neq( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_BETWEEN: $expressionBuilder = $builder->getExpressionBuilder(); $property = $builder->getProperty($field); return $expressionBuilder->andX([ $expressionBuilder->gte( $property, $builder->createPlaceholder($field, $data['from']) ), $expressionBuilder->lte( $property, $builder->createPlaceholder($field, $data['to']) ), ]); case self::TYPE_NOT_BETWEEN: $expressionBuilder = $builder->getExpressionBuilder(); $property = $builder->getProperty($field); return $expressionBuilder->orX([ $expressionBuilder->lte( $property, $builder->createPlaceholder($field, $data['from']) ), $expressionBuilder->gte( $property, $builder->createPlaceholder($field, $data['to']) ), ]); case self::TYPE_EMPTY: return $builder->getExpressionBuilder()->isNull($builder->getProperty($field)); case self::TYPE_NOT_EMPTY: return $builder->getExpressionBuilder()->isNotNull($builder->getProperty($field)); } return $builder->getExpressionBuilder()->eq( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); }
php
protected function process($field, $data, array $options) { $builder = $options['builder']; switch ($data['type']) { case self::TYPE_GREATER_THAN_OR_EQUALS: return $builder->getExpressionBuilder()->gte( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_GREATER_THAN: return $builder->getExpressionBuilder()->gt( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_LESS_THAN_OR_EQUALS: return $builder->getExpressionBuilder()->lte( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_LESS_THAN: return $builder->getExpressionBuilder()->lt( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_NOT_EQUALS: return $builder->getExpressionBuilder()->neq( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); case self::TYPE_BETWEEN: $expressionBuilder = $builder->getExpressionBuilder(); $property = $builder->getProperty($field); return $expressionBuilder->andX([ $expressionBuilder->gte( $property, $builder->createPlaceholder($field, $data['from']) ), $expressionBuilder->lte( $property, $builder->createPlaceholder($field, $data['to']) ), ]); case self::TYPE_NOT_BETWEEN: $expressionBuilder = $builder->getExpressionBuilder(); $property = $builder->getProperty($field); return $expressionBuilder->orX([ $expressionBuilder->lte( $property, $builder->createPlaceholder($field, $data['from']) ), $expressionBuilder->gte( $property, $builder->createPlaceholder($field, $data['to']) ), ]); case self::TYPE_EMPTY: return $builder->getExpressionBuilder()->isNull($builder->getProperty($field)); case self::TYPE_NOT_EMPTY: return $builder->getExpressionBuilder()->isNotNull($builder->getProperty($field)); } return $builder->getExpressionBuilder()->eq( $builder->getProperty($field), $builder->createPlaceholder($field, $data['value']) ); }
[ "protected", "function", "process", "(", "$", "field", ",", "$", "data", ",", "array", "$", "options", ")", "{", "$", "builder", "=", "$", "options", "[", "'builder'", "]", ";", "switch", "(", "$", "data", "[", "'type'", "]", ")", "{", "case", "self", "::", "TYPE_GREATER_THAN_OR_EQUALS", ":", "return", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "gte", "(", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'value'", "]", ")", ")", ";", "case", "self", "::", "TYPE_GREATER_THAN", ":", "return", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "gt", "(", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'value'", "]", ")", ")", ";", "case", "self", "::", "TYPE_LESS_THAN_OR_EQUALS", ":", "return", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "lte", "(", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'value'", "]", ")", ")", ";", "case", "self", "::", "TYPE_LESS_THAN", ":", "return", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "lt", "(", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'value'", "]", ")", ")", ";", "case", "self", "::", "TYPE_NOT_EQUALS", ":", "return", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "neq", "(", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'value'", "]", ")", ")", ";", "case", "self", "::", "TYPE_BETWEEN", ":", "$", "expressionBuilder", "=", "$", "builder", "->", "getExpressionBuilder", "(", ")", ";", "$", "property", "=", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ";", "return", "$", "expressionBuilder", "->", "andX", "(", "[", "$", "expressionBuilder", "->", "gte", "(", "$", "property", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'from'", "]", ")", ")", ",", "$", "expressionBuilder", "->", "lte", "(", "$", "property", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'to'", "]", ")", ")", ",", "]", ")", ";", "case", "self", "::", "TYPE_NOT_BETWEEN", ":", "$", "expressionBuilder", "=", "$", "builder", "->", "getExpressionBuilder", "(", ")", ";", "$", "property", "=", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ";", "return", "$", "expressionBuilder", "->", "orX", "(", "[", "$", "expressionBuilder", "->", "lte", "(", "$", "property", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'from'", "]", ")", ")", ",", "$", "expressionBuilder", "->", "gte", "(", "$", "property", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'to'", "]", ")", ")", ",", "]", ")", ";", "case", "self", "::", "TYPE_EMPTY", ":", "return", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "isNull", "(", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ")", ";", "case", "self", "::", "TYPE_NOT_EMPTY", ":", "return", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "isNotNull", "(", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ")", ";", "}", "return", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "eq", "(", "$", "builder", "->", "getProperty", "(", "$", "field", ")", ",", "$", "builder", "->", "createPlaceholder", "(", "$", "field", ",", "$", "data", "[", "'value'", "]", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Grid/Filter/Type/NumberType.php#L86-L162
GrupaZero/api
src/Gzero/Api/Controller/Admin/RouteController.php
RouteController.store
public function store($contentId) { $content = $this->repository->getById($contentId); if (!empty($content)) { $this->authorize('create', $content); $this->authorize('update', $content); if ($content->type != 'category') { $input = $this->validator->validate('create'); $route = $this->repository->createRoute($content, $input['lang_code'], $input['url']); return $this->respondWithSuccess($route, new RouteTransformer); } else { // TODO categories children route update throw new RepositoryValidationException("You can't change category url", 500); } } return $this->respondNotFound(); }
php
public function store($contentId) { $content = $this->repository->getById($contentId); if (!empty($content)) { $this->authorize('create', $content); $this->authorize('update', $content); if ($content->type != 'category') { $input = $this->validator->validate('create'); $route = $this->repository->createRoute($content, $input['lang_code'], $input['url']); return $this->respondWithSuccess($route, new RouteTransformer); } else { // TODO categories children route update throw new RepositoryValidationException("You can't change category url", 500); } } return $this->respondNotFound(); }
[ "public", "function", "store", "(", "$", "contentId", ")", "{", "$", "content", "=", "$", "this", "->", "repository", "->", "getById", "(", "$", "contentId", ")", ";", "if", "(", "!", "empty", "(", "$", "content", ")", ")", "{", "$", "this", "->", "authorize", "(", "'create'", ",", "$", "content", ")", ";", "$", "this", "->", "authorize", "(", "'update'", ",", "$", "content", ")", ";", "if", "(", "$", "content", "->", "type", "!=", "'category'", ")", "{", "$", "input", "=", "$", "this", "->", "validator", "->", "validate", "(", "'create'", ")", ";", "$", "route", "=", "$", "this", "->", "repository", "->", "createRoute", "(", "$", "content", ",", "$", "input", "[", "'lang_code'", "]", ",", "$", "input", "[", "'url'", "]", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "route", ",", "new", "RouteTransformer", ")", ";", "}", "else", "{", "// TODO categories children route update", "throw", "new", "RepositoryValidationException", "(", "\"You can't change category url\"", ",", "500", ")", ";", "}", "}", "return", "$", "this", "->", "respondNotFound", "(", ")", ";", "}" ]
Stores newly created route for specified content entity in database. @param int $contentId Id of the content @return \Illuminate\Http\JsonResponse @throws RepositoryValidationException
[ "Stores", "newly", "created", "route", "for", "specified", "content", "entity", "in", "database", "." ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/RouteController.php#L62-L78
Litecms/Team
src/Providers/TeamServiceProvider.php
TeamServiceProvider.boot
public function boot() { // Load view $this->loadViewsFrom(__DIR__ . '/../../resources/views', 'team'); // Load translation $this->loadTranslationsFrom(__DIR__ . '/../../resources/lang', 'team'); // Load migrations $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations'); // Call pblish redources function $this->publishResources(); }
php
public function boot() { // Load view $this->loadViewsFrom(__DIR__ . '/../../resources/views', 'team'); // Load translation $this->loadTranslationsFrom(__DIR__ . '/../../resources/lang', 'team'); // Load migrations $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations'); // Call pblish redources function $this->publishResources(); }
[ "public", "function", "boot", "(", ")", "{", "// Load view", "$", "this", "->", "loadViewsFrom", "(", "__DIR__", ".", "'/../../resources/views'", ",", "'team'", ")", ";", "// Load translation", "$", "this", "->", "loadTranslationsFrom", "(", "__DIR__", ".", "'/../../resources/lang'", ",", "'team'", ")", ";", "// Load migrations", "$", "this", "->", "loadMigrationsFrom", "(", "__DIR__", ".", "'/../../database/migrations'", ")", ";", "// Call pblish redources function", "$", "this", "->", "publishResources", "(", ")", ";", "}" ]
Bootstrap the application events. @return void
[ "Bootstrap", "the", "application", "events", "." ]
train
https://github.com/Litecms/Team/blob/a444a6a6604c969df138ac0eb57ed5f4696b0f00/src/Providers/TeamServiceProvider.php#L21-L35
Litecms/Team
src/Providers/TeamServiceProvider.php
TeamServiceProvider.register
public function register() { $this->mergeConfigFrom(__DIR__ . '/../../config/config.php', 'litecms.team'); // Bind facade $this->app->bind('litecms.team', function ($app) { return $this->app->make('Litecms\Team\Team'); }); // Bind Team to repository $this->app->bind( 'Litecms\Team\Interfaces\TeamRepositoryInterface', \Litecms\Team\Repositories\Eloquent\TeamRepository::class ); $this->app->register(\Litecms\Team\Providers\AuthServiceProvider::class); $this->app->register(\Litecms\Team\Providers\RouteServiceProvider::class); }
php
public function register() { $this->mergeConfigFrom(__DIR__ . '/../../config/config.php', 'litecms.team'); // Bind facade $this->app->bind('litecms.team', function ($app) { return $this->app->make('Litecms\Team\Team'); }); // Bind Team to repository $this->app->bind( 'Litecms\Team\Interfaces\TeamRepositoryInterface', \Litecms\Team\Repositories\Eloquent\TeamRepository::class ); $this->app->register(\Litecms\Team\Providers\AuthServiceProvider::class); $this->app->register(\Litecms\Team\Providers\RouteServiceProvider::class); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "mergeConfigFrom", "(", "__DIR__", ".", "'/../../config/config.php'", ",", "'litecms.team'", ")", ";", "// Bind facade", "$", "this", "->", "app", "->", "bind", "(", "'litecms.team'", ",", "function", "(", "$", "app", ")", "{", "return", "$", "this", "->", "app", "->", "make", "(", "'Litecms\\Team\\Team'", ")", ";", "}", ")", ";", "// Bind Team to repository", "$", "this", "->", "app", "->", "bind", "(", "'Litecms\\Team\\Interfaces\\TeamRepositoryInterface'", ",", "\\", "Litecms", "\\", "Team", "\\", "Repositories", "\\", "Eloquent", "\\", "TeamRepository", "::", "class", ")", ";", "$", "this", "->", "app", "->", "register", "(", "\\", "Litecms", "\\", "Team", "\\", "Providers", "\\", "AuthServiceProvider", "::", "class", ")", ";", "$", "this", "->", "app", "->", "register", "(", "\\", "Litecms", "\\", "Team", "\\", "Providers", "\\", "RouteServiceProvider", "::", "class", ")", ";", "}" ]
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/Litecms/Team/blob/a444a6a6604c969df138ac0eb57ed5f4696b0f00/src/Providers/TeamServiceProvider.php#L42-L61
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/php_array/writer.php
ezcDbSchemaPhpArrayWriter.saveToFile
public function saveToFile( $file, ezcDbSchema $dbSchema ) { $schema = $dbSchema->getSchema(); $data = $dbSchema->getData(); $fileData = '<?php return '. var_export( array( $schema, $data ), true ) . '; ?>'; if ( ! @file_put_contents( $file, (string) $fileData ) ) { throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::WRITE ); } }
php
public function saveToFile( $file, ezcDbSchema $dbSchema ) { $schema = $dbSchema->getSchema(); $data = $dbSchema->getData(); $fileData = '<?php return '. var_export( array( $schema, $data ), true ) . '; ?>'; if ( ! @file_put_contents( $file, (string) $fileData ) ) { throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::WRITE ); } }
[ "public", "function", "saveToFile", "(", "$", "file", ",", "ezcDbSchema", "$", "dbSchema", ")", "{", "$", "schema", "=", "$", "dbSchema", "->", "getSchema", "(", ")", ";", "$", "data", "=", "$", "dbSchema", "->", "getData", "(", ")", ";", "$", "fileData", "=", "'<?php return '", ".", "var_export", "(", "array", "(", "$", "schema", ",", "$", "data", ")", ",", "true", ")", ".", "'; ?>'", ";", "if", "(", "!", "@", "file_put_contents", "(", "$", "file", ",", "(", "string", ")", "$", "fileData", ")", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "file", ",", "ezcBaseFileException", "::", "WRITE", ")", ";", "}", "}" ]
Saves the schema definition in $schema to the file $file. @todo throw exception when file can not be opened @param string $file @param ezcDbSchema $dbSchema
[ "Saves", "the", "schema", "definition", "in", "$schema", "to", "the", "file", "$file", ".", "@todo", "throw", "exception", "when", "file", "can", "not", "be", "opened" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/php_array/writer.php#L50-L60
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/php_array/writer.php
ezcDbSchemaPhpArrayWriter.saveDiffToFile
public function saveDiffToFile( $file, ezcDbSchemaDiff $dbSchemaDiff ) { $fileData = '<?php return '. var_export( $dbSchemaDiff, true ) . '; ?>'; if ( ! @file_put_contents( $file, (string) $fileData ) ) { throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::WRITE ); } }
php
public function saveDiffToFile( $file, ezcDbSchemaDiff $dbSchemaDiff ) { $fileData = '<?php return '. var_export( $dbSchemaDiff, true ) . '; ?>'; if ( ! @file_put_contents( $file, (string) $fileData ) ) { throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::WRITE ); } }
[ "public", "function", "saveDiffToFile", "(", "$", "file", ",", "ezcDbSchemaDiff", "$", "dbSchemaDiff", ")", "{", "$", "fileData", "=", "'<?php return '", ".", "var_export", "(", "$", "dbSchemaDiff", ",", "true", ")", ".", "'; ?>'", ";", "if", "(", "!", "@", "file_put_contents", "(", "$", "file", ",", "(", "string", ")", "$", "fileData", ")", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "file", ",", "ezcBaseFileException", "::", "WRITE", ")", ";", "}", "}" ]
Saves the differences in $schemaDiff to the file $file @todo throw exception when file can not be opened @param string $file @param ezcDbSchemaDiff $dbSchemaDiff
[ "Saves", "the", "differences", "in", "$schemaDiff", "to", "the", "file", "$file", "@todo", "throw", "exception", "when", "file", "can", "not", "be", "opened" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/php_array/writer.php#L69-L76
Eresus/EresusCMS
src/core/DB.php
Eresus_DB.connect
public static function connect($dsn, $name = false) { Eresus_Kernel::log(__METHOD__, LOG_DEBUG, '("%s", %s)', $dsn, $name); try { $db = ezcDbFactory::create($dsn); } catch (Exception $e) { throw new Eresus_DB_Exception("Can not connect to '$dsn'", 0, $e); } $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL); if (substr($dsn, 0, 5) == 'mysql' && preg_match('/charset=(.*?)(&|$)/', $dsn, $m)) { $db->query("SET NAMES {$m[1]}"); } ezcDbInstance::set($db, $name); return $db; }
php
public static function connect($dsn, $name = false) { Eresus_Kernel::log(__METHOD__, LOG_DEBUG, '("%s", %s)', $dsn, $name); try { $db = ezcDbFactory::create($dsn); } catch (Exception $e) { throw new Eresus_DB_Exception("Can not connect to '$dsn'", 0, $e); } $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL); if (substr($dsn, 0, 5) == 'mysql' && preg_match('/charset=(.*?)(&|$)/', $dsn, $m)) { $db->query("SET NAMES {$m[1]}"); } ezcDbInstance::set($db, $name); return $db; }
[ "public", "static", "function", "connect", "(", "$", "dsn", ",", "$", "name", "=", "false", ")", "{", "Eresus_Kernel", "::", "log", "(", "__METHOD__", ",", "LOG_DEBUG", ",", "'(\"%s\", %s)'", ",", "$", "dsn", ",", "$", "name", ")", ";", "try", "{", "$", "db", "=", "ezcDbFactory", "::", "create", "(", "$", "dsn", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "Eresus_DB_Exception", "(", "\"Can not connect to '$dsn'\"", ",", "0", ",", "$", "e", ")", ";", "}", "$", "db", "->", "setAttribute", "(", "PDO", "::", "ATTR_CASE", ",", "PDO", "::", "CASE_NATURAL", ")", ";", "if", "(", "substr", "(", "$", "dsn", ",", "0", ",", "5", ")", "==", "'mysql'", "&&", "preg_match", "(", "'/charset=(.*?)(&|$)/'", ",", "$", "dsn", ",", "$", "m", ")", ")", "{", "$", "db", "->", "query", "(", "\"SET NAMES {$m[1]}\"", ")", ";", "}", "ezcDbInstance", "::", "set", "(", "$", "db", ",", "$", "name", ")", ";", "return", "$", "db", ";", "}" ]
Создаёт подключение к БД @param string $dsn DSN @param string|bool $name опциональное имя соединения @throws Eresus_DB_Exception @return ezcDbHandler
[ "Создаёт", "подключение", "к", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/DB.php#L54-L76
Eresus/EresusCMS
src/core/DB.php
Eresus_DB.lazyConnection
public static function lazyConnection($dsn, $name = false) { Eresus_Kernel::log(__METHOD__, LOG_DEBUG, '("%s", %s)', $dsn, $name); self::$lazyConnectionDSNs[$name] = $dsn; }
php
public static function lazyConnection($dsn, $name = false) { Eresus_Kernel::log(__METHOD__, LOG_DEBUG, '("%s", %s)', $dsn, $name); self::$lazyConnectionDSNs[$name] = $dsn; }
[ "public", "static", "function", "lazyConnection", "(", "$", "dsn", ",", "$", "name", "=", "false", ")", "{", "Eresus_Kernel", "::", "log", "(", "__METHOD__", ",", "LOG_DEBUG", ",", "'(\"%s\", %s)'", ",", "$", "dsn", ",", "$", "name", ")", ";", "self", "::", "$", "lazyConnectionDSNs", "[", "$", "name", "]", "=", "$", "dsn", ";", "}" ]
Configures lazy connection to DB @param string $dsn Connection DSN string @param string|bool $name Optional connection name @return void
[ "Configures", "lazy", "connection", "to", "DB" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/DB.php#L85-L89
Eresus/EresusCMS
src/core/DB.php
Eresus_DB.configureObject
public static function configureObject($name) { Eresus_Kernel::log(__METHOD__, LOG_DEBUG, '(%s)', $name); if (!isset(self::$lazyConnectionDSNs[$name])) { throw new Eresus_DB_Exception('DSN for lazy connection "' . $name . '" not found'); } $dsn = self::$lazyConnectionDSNs[$name]; $db = self::connect($dsn, $name); return $db; }
php
public static function configureObject($name) { Eresus_Kernel::log(__METHOD__, LOG_DEBUG, '(%s)', $name); if (!isset(self::$lazyConnectionDSNs[$name])) { throw new Eresus_DB_Exception('DSN for lazy connection "' . $name . '" not found'); } $dsn = self::$lazyConnectionDSNs[$name]; $db = self::connect($dsn, $name); return $db; }
[ "public", "static", "function", "configureObject", "(", "$", "name", ")", "{", "Eresus_Kernel", "::", "log", "(", "__METHOD__", ",", "LOG_DEBUG", ",", "'(%s)'", ",", "$", "name", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "lazyConnectionDSNs", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "Eresus_DB_Exception", "(", "'DSN for lazy connection \"'", ".", "$", "name", ".", "'\" not found'", ")", ";", "}", "$", "dsn", "=", "self", "::", "$", "lazyConnectionDSNs", "[", "$", "name", "]", ";", "$", "db", "=", "self", "::", "connect", "(", "$", "dsn", ",", "$", "name", ")", ";", "return", "$", "db", ";", "}" ]
eZ Components lazy init @param bool|string $name Connection name @throws Eresus_DB_Exception @return ezcDbHandler
[ "eZ", "Components", "lazy", "init" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/DB.php#L123-L136
Eresus/EresusCMS
src/core/DB.php
DBQueryInsider.bindValue
public function bindValue($paramNo, $param, $type = null) { $this->values[$paramNo] = var_export($param, true); return true; }
php
public function bindValue($paramNo, $param, $type = null) { $this->values[$paramNo] = var_export($param, true); return true; }
[ "public", "function", "bindValue", "(", "$", "paramNo", ",", "$", "param", ",", "$", "type", "=", "null", ")", "{", "$", "this", "->", "values", "[", "$", "paramNo", "]", "=", "var_export", "(", "$", "param", ",", "true", ")", ";", "return", "true", ";", "}" ]
Bind value @param int $paramNo @param mixed $param @param int|null $type @return bool
[ "Bind", "value" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/DB.php#L213-L217
Eresus/EresusCMS
src/core/DB.php
DBQueryInsider.bindParam
public function bindParam($paramNo, &$param, $type = null, $maxLength = null, $driverData = null) { $this->bindValue($paramNo, $param, $type); return true; }
php
public function bindParam($paramNo, &$param, $type = null, $maxLength = null, $driverData = null) { $this->bindValue($paramNo, $param, $type); return true; }
[ "public", "function", "bindParam", "(", "$", "paramNo", ",", "&", "$", "param", ",", "$", "type", "=", "null", ",", "$", "maxLength", "=", "null", ",", "$", "driverData", "=", "null", ")", "{", "$", "this", "->", "bindValue", "(", "$", "paramNo", ",", "$", "param", ",", "$", "type", ")", ";", "return", "true", ";", "}" ]
Bind param @param int $paramNo @param mixed $param @param int $type @param int $maxLength @param mixed $driverData @return bool
[ "Bind", "param" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/DB.php#L230-L234
Eresus/EresusCMS
src/core/DB.php
DBQueryInsider.subst
public function subst($query) { foreach ($this->values as $key => $value) { $query = preg_replace("/$key(\s|,|$)/", "$value$1", $query); } return $query; }
php
public function subst($query) { foreach ($this->values as $key => $value) { $query = preg_replace("/$key(\s|,|$)/", "$value$1", $query); } return $query; }
[ "public", "function", "subst", "(", "$", "query", ")", "{", "foreach", "(", "$", "this", "->", "values", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "query", "=", "preg_replace", "(", "\"/$key(\\s|,|$)/\"", ",", "\"$value$1\"", ",", "$", "query", ")", ";", "}", "return", "$", "query", ";", "}" ]
Substitute values in query @param string $query @return string
[ "Substitute", "values", "in", "query" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/DB.php#L242-L250
mothership-ec/composer
src/Composer/Repository/Vcs/GitDriver.php
GitDriver.initialize
public function initialize() { if (Filesystem::isLocalPath($this->url)) { $this->repoDir = $this->url; $cacheUrl = realpath($this->url); } else { $this->repoDir = $this->config->get('cache-vcs-dir') . '/' . preg_replace('{[^a-z0-9.]}i', '-', $this->url) . '/'; GitUtil::cleanEnv(); $fs = new Filesystem(); $fs->ensureDirectoryExists(dirname($this->repoDir)); if (!is_writable(dirname($this->repoDir))) { throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.dirname($this->repoDir).'" directory is not writable by the current user.'); } if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $this->url)) { throw new \InvalidArgumentException('The source URL '.$this->url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://[email protected]:22/path or just [email protected]:path if you do not want to provide a password or custom port.'); } $gitUtil = new GitUtil($this->io, $this->config, $this->process, $fs); // update the repo if it is a valid git repository if (is_dir($this->repoDir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $this->repoDir) && trim($output) === '.') { try { $commandCallable = function ($url) { return sprintf('git remote set-url origin %s && git remote update --prune origin', ProcessExecutor::escape($url)); }; $gitUtil->runCommand($commandCallable, $this->url, $this->repoDir); } catch (\Exception $e) { $this->io->writeError('<error>Failed to update '.$this->url.', package information from this repository may be outdated ('.$e->getMessage().')</error>'); } } else { // clean up directory and do a fresh clone into it $fs->removeDirectory($this->repoDir); $repoDir = $this->repoDir; $commandCallable = function ($url) use ($repoDir) { return sprintf('git clone --mirror %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($repoDir)); }; $gitUtil->runCommand($commandCallable, $this->url, $this->repoDir, true); } $cacheUrl = $this->url; } $this->getTags(); $this->getBranches(); $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $cacheUrl)); }
php
public function initialize() { if (Filesystem::isLocalPath($this->url)) { $this->repoDir = $this->url; $cacheUrl = realpath($this->url); } else { $this->repoDir = $this->config->get('cache-vcs-dir') . '/' . preg_replace('{[^a-z0-9.]}i', '-', $this->url) . '/'; GitUtil::cleanEnv(); $fs = new Filesystem(); $fs->ensureDirectoryExists(dirname($this->repoDir)); if (!is_writable(dirname($this->repoDir))) { throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.dirname($this->repoDir).'" directory is not writable by the current user.'); } if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $this->url)) { throw new \InvalidArgumentException('The source URL '.$this->url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://[email protected]:22/path or just [email protected]:path if you do not want to provide a password or custom port.'); } $gitUtil = new GitUtil($this->io, $this->config, $this->process, $fs); // update the repo if it is a valid git repository if (is_dir($this->repoDir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $this->repoDir) && trim($output) === '.') { try { $commandCallable = function ($url) { return sprintf('git remote set-url origin %s && git remote update --prune origin', ProcessExecutor::escape($url)); }; $gitUtil->runCommand($commandCallable, $this->url, $this->repoDir); } catch (\Exception $e) { $this->io->writeError('<error>Failed to update '.$this->url.', package information from this repository may be outdated ('.$e->getMessage().')</error>'); } } else { // clean up directory and do a fresh clone into it $fs->removeDirectory($this->repoDir); $repoDir = $this->repoDir; $commandCallable = function ($url) use ($repoDir) { return sprintf('git clone --mirror %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($repoDir)); }; $gitUtil->runCommand($commandCallable, $this->url, $this->repoDir, true); } $cacheUrl = $this->url; } $this->getTags(); $this->getBranches(); $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $cacheUrl)); }
[ "public", "function", "initialize", "(", ")", "{", "if", "(", "Filesystem", "::", "isLocalPath", "(", "$", "this", "->", "url", ")", ")", "{", "$", "this", "->", "repoDir", "=", "$", "this", "->", "url", ";", "$", "cacheUrl", "=", "realpath", "(", "$", "this", "->", "url", ")", ";", "}", "else", "{", "$", "this", "->", "repoDir", "=", "$", "this", "->", "config", "->", "get", "(", "'cache-vcs-dir'", ")", ".", "'/'", ".", "preg_replace", "(", "'{[^a-z0-9.]}i'", ",", "'-'", ",", "$", "this", "->", "url", ")", ".", "'/'", ";", "GitUtil", "::", "cleanEnv", "(", ")", ";", "$", "fs", "=", "new", "Filesystem", "(", ")", ";", "$", "fs", "->", "ensureDirectoryExists", "(", "dirname", "(", "$", "this", "->", "repoDir", ")", ")", ";", "if", "(", "!", "is_writable", "(", "dirname", "(", "$", "this", "->", "repoDir", ")", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Can not clone '", ".", "$", "this", "->", "url", ".", "' to access package information. The \"'", ".", "dirname", "(", "$", "this", "->", "repoDir", ")", ".", "'\" directory is not writable by the current user.'", ")", ";", "}", "if", "(", "preg_match", "(", "'{^ssh://[^@]+@[^:]+:[^0-9]+}'", ",", "$", "this", "->", "url", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The source URL '", ".", "$", "this", "->", "url", ".", "' is invalid, ssh URLs should have a port number after \":\".'", ".", "\"\\n\"", ".", "'Use ssh://[email protected]:22/path or just [email protected]:path if you do not want to provide a password or custom port.'", ")", ";", "}", "$", "gitUtil", "=", "new", "GitUtil", "(", "$", "this", "->", "io", ",", "$", "this", "->", "config", ",", "$", "this", "->", "process", ",", "$", "fs", ")", ";", "// update the repo if it is a valid git repository", "if", "(", "is_dir", "(", "$", "this", "->", "repoDir", ")", "&&", "0", "===", "$", "this", "->", "process", "->", "execute", "(", "'git rev-parse --git-dir'", ",", "$", "output", ",", "$", "this", "->", "repoDir", ")", "&&", "trim", "(", "$", "output", ")", "===", "'.'", ")", "{", "try", "{", "$", "commandCallable", "=", "function", "(", "$", "url", ")", "{", "return", "sprintf", "(", "'git remote set-url origin %s && git remote update --prune origin'", ",", "ProcessExecutor", "::", "escape", "(", "$", "url", ")", ")", ";", "}", ";", "$", "gitUtil", "->", "runCommand", "(", "$", "commandCallable", ",", "$", "this", "->", "url", ",", "$", "this", "->", "repoDir", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "io", "->", "writeError", "(", "'<error>Failed to update '", ".", "$", "this", "->", "url", ".", "', package information from this repository may be outdated ('", ".", "$", "e", "->", "getMessage", "(", ")", ".", "')</error>'", ")", ";", "}", "}", "else", "{", "// clean up directory and do a fresh clone into it", "$", "fs", "->", "removeDirectory", "(", "$", "this", "->", "repoDir", ")", ";", "$", "repoDir", "=", "$", "this", "->", "repoDir", ";", "$", "commandCallable", "=", "function", "(", "$", "url", ")", "use", "(", "$", "repoDir", ")", "{", "return", "sprintf", "(", "'git clone --mirror %s %s'", ",", "ProcessExecutor", "::", "escape", "(", "$", "url", ")", ",", "ProcessExecutor", "::", "escape", "(", "$", "repoDir", ")", ")", ";", "}", ";", "$", "gitUtil", "->", "runCommand", "(", "$", "commandCallable", ",", "$", "this", "->", "url", ",", "$", "this", "->", "repoDir", ",", "true", ")", ";", "}", "$", "cacheUrl", "=", "$", "this", "->", "url", ";", "}", "$", "this", "->", "getTags", "(", ")", ";", "$", "this", "->", "getBranches", "(", ")", ";", "$", "this", "->", "cache", "=", "new", "Cache", "(", "$", "this", "->", "io", ",", "$", "this", "->", "config", "->", "get", "(", "'cache-repo-dir'", ")", ".", "'/'", ".", "preg_replace", "(", "'{[^a-z0-9.]}i'", ",", "'-'", ",", "$", "cacheUrl", ")", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Repository/Vcs/GitDriver.php#L38-L90
mothership-ec/composer
src/Composer/Repository/Vcs/GitDriver.php
GitDriver.getComposerInformation
public function getComposerInformation($identifier) { if (preg_match('{[a-f0-9]{40}}i', $identifier) && $res = $this->cache->read($identifier)) { $this->infoCache[$identifier] = JsonFile::parseJson($res); } if (!isset($this->infoCache[$identifier])) { $resource = sprintf('%s:composer.json', ProcessExecutor::escape($identifier)); $this->process->execute(sprintf('git show %s', $resource), $composer, $this->repoDir); if (!trim($composer)) { return; } $composer = JsonFile::parseJson($composer, $resource); if (empty($composer['time'])) { $this->process->execute(sprintf('git log -1 --format=%%at %s', ProcessExecutor::escape($identifier)), $output, $this->repoDir); $date = new \DateTime('@'.trim($output), new \DateTimeZone('UTC')); $composer['time'] = $date->format('Y-m-d H:i:s'); } if (preg_match('{[a-f0-9]{40}}i', $identifier)) { $this->cache->write($identifier, json_encode($composer)); } $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; }
php
public function getComposerInformation($identifier) { if (preg_match('{[a-f0-9]{40}}i', $identifier) && $res = $this->cache->read($identifier)) { $this->infoCache[$identifier] = JsonFile::parseJson($res); } if (!isset($this->infoCache[$identifier])) { $resource = sprintf('%s:composer.json', ProcessExecutor::escape($identifier)); $this->process->execute(sprintf('git show %s', $resource), $composer, $this->repoDir); if (!trim($composer)) { return; } $composer = JsonFile::parseJson($composer, $resource); if (empty($composer['time'])) { $this->process->execute(sprintf('git log -1 --format=%%at %s', ProcessExecutor::escape($identifier)), $output, $this->repoDir); $date = new \DateTime('@'.trim($output), new \DateTimeZone('UTC')); $composer['time'] = $date->format('Y-m-d H:i:s'); } if (preg_match('{[a-f0-9]{40}}i', $identifier)) { $this->cache->write($identifier, json_encode($composer)); } $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; }
[ "public", "function", "getComposerInformation", "(", "$", "identifier", ")", "{", "if", "(", "preg_match", "(", "'{[a-f0-9]{40}}i'", ",", "$", "identifier", ")", "&&", "$", "res", "=", "$", "this", "->", "cache", "->", "read", "(", "$", "identifier", ")", ")", "{", "$", "this", "->", "infoCache", "[", "$", "identifier", "]", "=", "JsonFile", "::", "parseJson", "(", "$", "res", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "infoCache", "[", "$", "identifier", "]", ")", ")", "{", "$", "resource", "=", "sprintf", "(", "'%s:composer.json'", ",", "ProcessExecutor", "::", "escape", "(", "$", "identifier", ")", ")", ";", "$", "this", "->", "process", "->", "execute", "(", "sprintf", "(", "'git show %s'", ",", "$", "resource", ")", ",", "$", "composer", ",", "$", "this", "->", "repoDir", ")", ";", "if", "(", "!", "trim", "(", "$", "composer", ")", ")", "{", "return", ";", "}", "$", "composer", "=", "JsonFile", "::", "parseJson", "(", "$", "composer", ",", "$", "resource", ")", ";", "if", "(", "empty", "(", "$", "composer", "[", "'time'", "]", ")", ")", "{", "$", "this", "->", "process", "->", "execute", "(", "sprintf", "(", "'git log -1 --format=%%at %s'", ",", "ProcessExecutor", "::", "escape", "(", "$", "identifier", ")", ")", ",", "$", "output", ",", "$", "this", "->", "repoDir", ")", ";", "$", "date", "=", "new", "\\", "DateTime", "(", "'@'", ".", "trim", "(", "$", "output", ")", ",", "new", "\\", "DateTimeZone", "(", "'UTC'", ")", ")", ";", "$", "composer", "[", "'time'", "]", "=", "$", "date", "->", "format", "(", "'Y-m-d H:i:s'", ")", ";", "}", "if", "(", "preg_match", "(", "'{[a-f0-9]{40}}i'", ",", "$", "identifier", ")", ")", "{", "$", "this", "->", "cache", "->", "write", "(", "$", "identifier", ",", "json_encode", "(", "$", "composer", ")", ")", ";", "}", "$", "this", "->", "infoCache", "[", "$", "identifier", "]", "=", "$", "composer", ";", "}", "return", "$", "this", "->", "infoCache", "[", "$", "identifier", "]", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Repository/Vcs/GitDriver.php#L143-L173
surebert/surebert-framework
src/sb/Cameras/Axis/Q6035.php
Q6035.takeSnapShot
public function takeSnapShot($user_agent='Surebert Kamera', $options=Array()){ $ch = curl_init($this->url.'/jpg/1/image.jpg?timestamp='.time()); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_setopt($ch, CURLOPT_USERPWD, $this->uname.':'.$this->pass); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2); curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //add any additional options passed foreach($options as $k=>$v){ curl_setopt($ch, $k, $v); } return curl_exec($ch); }
php
public function takeSnapShot($user_agent='Surebert Kamera', $options=Array()){ $ch = curl_init($this->url.'/jpg/1/image.jpg?timestamp='.time()); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_setopt($ch, CURLOPT_USERPWD, $this->uname.':'.$this->pass); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2); curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //add any additional options passed foreach($options as $k=>$v){ curl_setopt($ch, $k, $v); } return curl_exec($ch); }
[ "public", "function", "takeSnapShot", "(", "$", "user_agent", "=", "'Surebert Kamera'", ",", "$", "options", "=", "Array", "(", ")", ")", "{", "$", "ch", "=", "curl_init", "(", "$", "this", "->", "url", ".", "'/jpg/1/image.jpg?timestamp='", ".", "time", "(", ")", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPAUTH", ",", "CURLAUTH_DIGEST", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERPWD", ",", "$", "this", "->", "uname", ".", "':'", ".", "$", "this", "->", "pass", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYHOST", ",", "2", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "$", "user_agent", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_FOLLOWLOCATION", ",", "1", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CONNECTTIMEOUT", ",", "2", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "1", ")", ";", "//add any additional options passed", "foreach", "(", "$", "options", "as", "$", "k", "=>", "$", "v", ")", "{", "curl_setopt", "(", "$", "ch", ",", "$", "k", ",", "$", "v", ")", ";", "}", "return", "curl_exec", "(", "$", "ch", ")", ";", "}" ]
Retrives a current snapshot @return string jpeg data
[ "Retrives", "a", "current", "snapshot" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Cameras/Axis/Q6035.php#L49-L65
surebert/surebert-framework
src/sb/Cameras/Axis/Q6035.php
Q6035.saveSnapshot
public function saveSnapshot($dir){ if(!is_dir($dir)){ mkdir($dir, 0775, true); } $jpeg = $this->takeSnapShot(); $file = $dir.'/'.date('Y_m_d_H_i_s').'.jpg'; if(file_put_contents($file, $jpeg)){ return $file; } return ''; }
php
public function saveSnapshot($dir){ if(!is_dir($dir)){ mkdir($dir, 0775, true); } $jpeg = $this->takeSnapShot(); $file = $dir.'/'.date('Y_m_d_H_i_s').'.jpg'; if(file_put_contents($file, $jpeg)){ return $file; } return ''; }
[ "public", "function", "saveSnapshot", "(", "$", "dir", ")", "{", "if", "(", "!", "is_dir", "(", "$", "dir", ")", ")", "{", "mkdir", "(", "$", "dir", ",", "0775", ",", "true", ")", ";", "}", "$", "jpeg", "=", "$", "this", "->", "takeSnapShot", "(", ")", ";", "$", "file", "=", "$", "dir", ".", "'/'", ".", "date", "(", "'Y_m_d_H_i_s'", ")", ".", "'.jpg'", ";", "if", "(", "file_put_contents", "(", "$", "file", ",", "$", "jpeg", ")", ")", "{", "return", "$", "file", ";", "}", "return", "''", ";", "}" ]
Retrieves and stores a snapshot by date @param type $dir @return string Path if saved, empty string if not
[ "Retrieves", "and", "stores", "a", "snapshot", "by", "date" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Cameras/Axis/Q6035.php#L72-L85
Visithor/visithor
src/Visithor/Command/GoCommand.php
GoCommand.configure
protected function configure() { $this ->setName('visithor:go') ->setDescription('Visit all defined urls') ->addOption( 'config', 'c', InputOption::VALUE_OPTIONAL, "Config file directory", getcwd() ) ->addOption( 'format', 'f', InputOption::VALUE_OPTIONAL, "Format", Visithor::RENDERER_TYPE_PRETTY ); }
php
protected function configure() { $this ->setName('visithor:go') ->setDescription('Visit all defined urls') ->addOption( 'config', 'c', InputOption::VALUE_OPTIONAL, "Config file directory", getcwd() ) ->addOption( 'format', 'f', InputOption::VALUE_OPTIONAL, "Format", Visithor::RENDERER_TYPE_PRETTY ); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'visithor:go'", ")", "->", "setDescription", "(", "'Visit all defined urls'", ")", "->", "addOption", "(", "'config'", ",", "'c'", ",", "InputOption", "::", "VALUE_OPTIONAL", ",", "\"Config file directory\"", ",", "getcwd", "(", ")", ")", "->", "addOption", "(", "'format'", ",", "'f'", ",", "InputOption", "::", "VALUE_OPTIONAL", ",", "\"Format\"", ",", "Visithor", "::", "RENDERER_TYPE_PRETTY", ")", ";", "}" ]
configure
[ "configure" ]
train
https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Command/GoCommand.php#L40-L59
Visithor/visithor
src/Visithor/Command/GoCommand.php
GoCommand.execute
protected function execute( InputInterface $input, OutputInterface $output ) { $this->checkEnvironment( $input, $output ); $configPath = rtrim($input->getOption('config'), '/'); $format = $input->getOption('format'); $reader = new YamlConfigurationReader(); $config = $reader->read($configPath); if (!$config || !is_array($config)) { $output->writeln('Configuration file not found in ' . $configPath); return 1; } $output->writeln('Visithor by Marc Morera and contributors.'); $output->writeln(''); $output->writeln('Configuration read from ' . $configPath); $output->writeln(''); $output->writeln(''); $stopwatch = new Stopwatch(); $stopwatch->start('visithor.go'); $result = $this->executeVisithor( $output, $config, $format ); $event = $stopwatch->stop('visithor.go'); $output->writeln(''); $memory = round($event->getMemory() / 1048576, 2); $output->writeln('Time: ' . $event->getDuration() . ' ms, Memory: ' . $memory . 'Mb'); $output->writeln(''); $finalMessage = (0 === $result) ? '<bg=green> OK </bg=green>' : '<bg=red> FAIL </bg=red>'; $output->writeln($finalMessage); return $result; }
php
protected function execute( InputInterface $input, OutputInterface $output ) { $this->checkEnvironment( $input, $output ); $configPath = rtrim($input->getOption('config'), '/'); $format = $input->getOption('format'); $reader = new YamlConfigurationReader(); $config = $reader->read($configPath); if (!$config || !is_array($config)) { $output->writeln('Configuration file not found in ' . $configPath); return 1; } $output->writeln('Visithor by Marc Morera and contributors.'); $output->writeln(''); $output->writeln('Configuration read from ' . $configPath); $output->writeln(''); $output->writeln(''); $stopwatch = new Stopwatch(); $stopwatch->start('visithor.go'); $result = $this->executeVisithor( $output, $config, $format ); $event = $stopwatch->stop('visithor.go'); $output->writeln(''); $memory = round($event->getMemory() / 1048576, 2); $output->writeln('Time: ' . $event->getDuration() . ' ms, Memory: ' . $memory . 'Mb'); $output->writeln(''); $finalMessage = (0 === $result) ? '<bg=green> OK </bg=green>' : '<bg=red> FAIL </bg=red>'; $output->writeln($finalMessage); return $result; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "checkEnvironment", "(", "$", "input", ",", "$", "output", ")", ";", "$", "configPath", "=", "rtrim", "(", "$", "input", "->", "getOption", "(", "'config'", ")", ",", "'/'", ")", ";", "$", "format", "=", "$", "input", "->", "getOption", "(", "'format'", ")", ";", "$", "reader", "=", "new", "YamlConfigurationReader", "(", ")", ";", "$", "config", "=", "$", "reader", "->", "read", "(", "$", "configPath", ")", ";", "if", "(", "!", "$", "config", "||", "!", "is_array", "(", "$", "config", ")", ")", "{", "$", "output", "->", "writeln", "(", "'Configuration file not found in '", ".", "$", "configPath", ")", ";", "return", "1", ";", "}", "$", "output", "->", "writeln", "(", "'Visithor by Marc Morera and contributors.'", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "$", "output", "->", "writeln", "(", "'Configuration read from '", ".", "$", "configPath", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "$", "stopwatch", "=", "new", "Stopwatch", "(", ")", ";", "$", "stopwatch", "->", "start", "(", "'visithor.go'", ")", ";", "$", "result", "=", "$", "this", "->", "executeVisithor", "(", "$", "output", ",", "$", "config", ",", "$", "format", ")", ";", "$", "event", "=", "$", "stopwatch", "->", "stop", "(", "'visithor.go'", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "$", "memory", "=", "round", "(", "$", "event", "->", "getMemory", "(", ")", "/", "1048576", ",", "2", ")", ";", "$", "output", "->", "writeln", "(", "'Time: '", ".", "$", "event", "->", "getDuration", "(", ")", ".", "' ms, Memory: '", ".", "$", "memory", ".", "'Mb'", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "$", "finalMessage", "=", "(", "0", "===", "$", "result", ")", "?", "'<bg=green> OK </bg=green>'", ":", "'<bg=red> FAIL </bg=red>'", ";", "$", "output", "->", "writeln", "(", "$", "finalMessage", ")", ";", "return", "$", "result", ";", "}" ]
Execute command This method returns 0 if all executions passed. 1 otherwise. @param InputInterface $input Input @param OutputInterface $output Output @return integer Execution return @throws Exception
[ "Execute", "command" ]
train
https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Command/GoCommand.php#L73-L122
Visithor/visithor
src/Visithor/Command/GoCommand.php
GoCommand.executeVisithor
protected function executeVisithor( OutputInterface $output, array $config, $format ) { $client = new GuzzleClient(); $rendererFactory = new RendererFactory(); $renderer = $rendererFactory->create($format); $executor = new Executor($client); $executor->build(); $urlGenerator = new UrlGenerator( new UrlFactory(), new UrlChainFactory() ); $urlChain = $urlGenerator->generate($config); $result = $executor->execute( $urlChain, $renderer, $output ); $executor->build(); return $result; }
php
protected function executeVisithor( OutputInterface $output, array $config, $format ) { $client = new GuzzleClient(); $rendererFactory = new RendererFactory(); $renderer = $rendererFactory->create($format); $executor = new Executor($client); $executor->build(); $urlGenerator = new UrlGenerator( new UrlFactory(), new UrlChainFactory() ); $urlChain = $urlGenerator->generate($config); $result = $executor->execute( $urlChain, $renderer, $output ); $executor->build(); return $result; }
[ "protected", "function", "executeVisithor", "(", "OutputInterface", "$", "output", ",", "array", "$", "config", ",", "$", "format", ")", "{", "$", "client", "=", "new", "GuzzleClient", "(", ")", ";", "$", "rendererFactory", "=", "new", "RendererFactory", "(", ")", ";", "$", "renderer", "=", "$", "rendererFactory", "->", "create", "(", "$", "format", ")", ";", "$", "executor", "=", "new", "Executor", "(", "$", "client", ")", ";", "$", "executor", "->", "build", "(", ")", ";", "$", "urlGenerator", "=", "new", "UrlGenerator", "(", "new", "UrlFactory", "(", ")", ",", "new", "UrlChainFactory", "(", ")", ")", ";", "$", "urlChain", "=", "$", "urlGenerator", "->", "generate", "(", "$", "config", ")", ";", "$", "result", "=", "$", "executor", "->", "execute", "(", "$", "urlChain", ",", "$", "renderer", ",", "$", "output", ")", ";", "$", "executor", "->", "build", "(", ")", ";", "return", "$", "result", ";", "}" ]
Executes all business logic inside this command This method returns 0 if all executions passed. 1 otherwise. @param OutputInterface $output Output @param array $config Config @param string $format Format @return integer Execution return
[ "Executes", "all", "business", "logic", "inside", "this", "command" ]
train
https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Command/GoCommand.php#L135-L161
Visithor/visithor
src/Visithor/Command/GoCommand.php
GoCommand.checkEnvironment
protected function checkEnvironment( InputInterface $input, OutputInterface $output ) { $env = $input ->getParameterOption( ['--env', '-e'], getenv('SYMFONY_ENV') ?: 'dev' ); if ('test' != $env) { $output->writeln('<bg=red> </bg=red> <fg=red>Warning, make sure your tests are being run against testing environments</fg=red>'); } return $this; }
php
protected function checkEnvironment( InputInterface $input, OutputInterface $output ) { $env = $input ->getParameterOption( ['--env', '-e'], getenv('SYMFONY_ENV') ?: 'dev' ); if ('test' != $env) { $output->writeln('<bg=red> </bg=red> <fg=red>Warning, make sure your tests are being run against testing environments</fg=red>'); } return $this; }
[ "protected", "function", "checkEnvironment", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "env", "=", "$", "input", "->", "getParameterOption", "(", "[", "'--env'", ",", "'-e'", "]", ",", "getenv", "(", "'SYMFONY_ENV'", ")", "?", ":", "'dev'", ")", ";", "if", "(", "'test'", "!=", "$", "env", ")", "{", "$", "output", "->", "writeln", "(", "'<bg=red> </bg=red> <fg=red>Warning, make sure your tests are being run against testing environments</fg=red>'", ")", ";", "}", "return", "$", "this", ";", "}" ]
Check environment. If not test, add a notice @param InputInterface $input Input @param OutputInterface $output Output @return $this Self object
[ "Check", "environment", ".", "If", "not", "test", "add", "a", "notice" ]
train
https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Command/GoCommand.php#L171-L186
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.install
public function install() { $position = 250; $exists = array(); foreach (array( 'path' => array('text_input', '../../backups'), 'copy_paths' => array('text_input', '../'), 'exclude_files' => array('text_input', ''), 'ignore_tables' => array('text_input', ''), 'files_to_keep' => array('text_input', 0), ) as $name => $val) { $n = 'rah_backup_'.$name; $exists[] = $n; if (get_pref($n, false) === false) { set_pref($n, $val[1], 'rah_backup', PREF_ADVANCED, $val[0], $position); } $position++; } safe_delete( 'txp_prefs', "event = 'rah_backup' and name not in(".implode(',', quote_list($exists)).")" ); }
php
public function install() { $position = 250; $exists = array(); foreach (array( 'path' => array('text_input', '../../backups'), 'copy_paths' => array('text_input', '../'), 'exclude_files' => array('text_input', ''), 'ignore_tables' => array('text_input', ''), 'files_to_keep' => array('text_input', 0), ) as $name => $val) { $n = 'rah_backup_'.$name; $exists[] = $n; if (get_pref($n, false) === false) { set_pref($n, $val[1], 'rah_backup', PREF_ADVANCED, $val[0], $position); } $position++; } safe_delete( 'txp_prefs', "event = 'rah_backup' and name not in(".implode(',', quote_list($exists)).")" ); }
[ "public", "function", "install", "(", ")", "{", "$", "position", "=", "250", ";", "$", "exists", "=", "array", "(", ")", ";", "foreach", "(", "array", "(", "'path'", "=>", "array", "(", "'text_input'", ",", "'../../backups'", ")", ",", "'copy_paths'", "=>", "array", "(", "'text_input'", ",", "'../'", ")", ",", "'exclude_files'", "=>", "array", "(", "'text_input'", ",", "''", ")", ",", "'ignore_tables'", "=>", "array", "(", "'text_input'", ",", "''", ")", ",", "'files_to_keep'", "=>", "array", "(", "'text_input'", ",", "0", ")", ",", ")", "as", "$", "name", "=>", "$", "val", ")", "{", "$", "n", "=", "'rah_backup_'", ".", "$", "name", ";", "$", "exists", "[", "]", "=", "$", "n", ";", "if", "(", "get_pref", "(", "$", "n", ",", "false", ")", "===", "false", ")", "{", "set_pref", "(", "$", "n", ",", "$", "val", "[", "1", "]", ",", "'rah_backup'", ",", "PREF_ADVANCED", ",", "$", "val", "[", "0", "]", ",", "$", "position", ")", ";", "}", "$", "position", "++", ";", "}", "safe_delete", "(", "'txp_prefs'", ",", "\"event = 'rah_backup' and name not in(\"", ".", "implode", "(", "','", ",", "quote_list", "(", "$", "exists", ")", ")", ".", "\")\"", ")", ";", "}" ]
Installer.
[ "Installer", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L75-L101
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.takeBackup
public function takeBackup() { global $txpcfg; $directory = txpath . '/' . get_pref('rah_backup_path'); $fileMultiplier = 1; if (!get_pref('rah_backup_path') || !file_exists($directory) || !is_dir($directory) || !is_writable($directory)) { throw new Rah_Backup_Exception(gTxt('rah_backup_dir_not_writable', array('{path}' => $dir))); } @set_time_limit(0); @ignore_user_abort(true); callback_event('rah_backup.create'); $filestamp = '_'.safe_strtotime('now'); $name = $this->sanitize($txpcfg['db']); if (!$name) { $name = 'database'; } $path = $directory . '/' . $name . $filestamp . '.sql.gz'; $created = array(); $created[basename($path)] = $path; $dump = new \Rah\Danpu\Dump; $dump ->file($path) ->dsn('mysql:dbname='.$txpcfg['db'].';host='.$txpcfg['host']) ->user($txpcfg['user']) ->pass($txpcfg['pass']) ->tmp(get_pref('tempdir')); if (get_pref('rah_backup_ignore_tables')) { $ignore = array(); foreach (do_list(get_pref('rah_backup_ignore_tables')) as $table) { $ignore[] = PFX.$table; } $dump->ignore($ignore); } if (PFX) { $dump->prefix(PFX); } new \Rah\Danpu\Export($dump); if (get_pref('rah_backup_copy_paths') && !is_disabled('exec') && is_callable('exec')) { $fileMultiplier++; // Copied paths. $copy = array(); foreach (do_list(get_pref('rah_backup_copy_paths')) as $path) { if ($path) { $path = txpath . '/' . $path; if (file_exists($path) && is_readable($path) && $path = escapeshellarg($path)) { $copy[$path] = ' '.$path; } } } // Excluded paths. $exclude = array(); foreach (do_list(get_pref('rah_backup_exclude_files')) as $path) { if ($path && $path = escapeshellarg(txpath . '/' . $path)) { $exclude[$path] = ' --exclude='.$path; } } $name = $this->sanitize(get_pref('siteurl')); if (!$name) { $name = 'filesystem'; } $path = $directory . '/'. $name . $filestamp . '.tar.gz'; if (exec( 'tar -cvpzf '.escapeshellarg($path). implode('', $exclude). implode('', $copy) ) !== false) { $created[basename($path)] = $path; } } $offset = (int) get_pref('rah_backup_files_to_keep'); if ($offset) { $offset = max($fileMultiplier, $offset * $fileMultiplier); $deleted = array(); try { foreach ($this->getBackups('date', 'desc', $offset) as $name => $backup) { $deleted[$name] = $backup['path']; @unlink($backup['path']); } callback_event('rah_backup.deleted', '', 0, array('files' => $deleted)); } catch (Exception $e) { } } callback_event('rah_backup.created', '', 0, array( 'files' => $created, )); }
php
public function takeBackup() { global $txpcfg; $directory = txpath . '/' . get_pref('rah_backup_path'); $fileMultiplier = 1; if (!get_pref('rah_backup_path') || !file_exists($directory) || !is_dir($directory) || !is_writable($directory)) { throw new Rah_Backup_Exception(gTxt('rah_backup_dir_not_writable', array('{path}' => $dir))); } @set_time_limit(0); @ignore_user_abort(true); callback_event('rah_backup.create'); $filestamp = '_'.safe_strtotime('now'); $name = $this->sanitize($txpcfg['db']); if (!$name) { $name = 'database'; } $path = $directory . '/' . $name . $filestamp . '.sql.gz'; $created = array(); $created[basename($path)] = $path; $dump = new \Rah\Danpu\Dump; $dump ->file($path) ->dsn('mysql:dbname='.$txpcfg['db'].';host='.$txpcfg['host']) ->user($txpcfg['user']) ->pass($txpcfg['pass']) ->tmp(get_pref('tempdir')); if (get_pref('rah_backup_ignore_tables')) { $ignore = array(); foreach (do_list(get_pref('rah_backup_ignore_tables')) as $table) { $ignore[] = PFX.$table; } $dump->ignore($ignore); } if (PFX) { $dump->prefix(PFX); } new \Rah\Danpu\Export($dump); if (get_pref('rah_backup_copy_paths') && !is_disabled('exec') && is_callable('exec')) { $fileMultiplier++; // Copied paths. $copy = array(); foreach (do_list(get_pref('rah_backup_copy_paths')) as $path) { if ($path) { $path = txpath . '/' . $path; if (file_exists($path) && is_readable($path) && $path = escapeshellarg($path)) { $copy[$path] = ' '.$path; } } } // Excluded paths. $exclude = array(); foreach (do_list(get_pref('rah_backup_exclude_files')) as $path) { if ($path && $path = escapeshellarg(txpath . '/' . $path)) { $exclude[$path] = ' --exclude='.$path; } } $name = $this->sanitize(get_pref('siteurl')); if (!$name) { $name = 'filesystem'; } $path = $directory . '/'. $name . $filestamp . '.tar.gz'; if (exec( 'tar -cvpzf '.escapeshellarg($path). implode('', $exclude). implode('', $copy) ) !== false) { $created[basename($path)] = $path; } } $offset = (int) get_pref('rah_backup_files_to_keep'); if ($offset) { $offset = max($fileMultiplier, $offset * $fileMultiplier); $deleted = array(); try { foreach ($this->getBackups('date', 'desc', $offset) as $name => $backup) { $deleted[$name] = $backup['path']; @unlink($backup['path']); } callback_event('rah_backup.deleted', '', 0, array('files' => $deleted)); } catch (Exception $e) { } } callback_event('rah_backup.created', '', 0, array( 'files' => $created, )); }
[ "public", "function", "takeBackup", "(", ")", "{", "global", "$", "txpcfg", ";", "$", "directory", "=", "txpath", ".", "'/'", ".", "get_pref", "(", "'rah_backup_path'", ")", ";", "$", "fileMultiplier", "=", "1", ";", "if", "(", "!", "get_pref", "(", "'rah_backup_path'", ")", "||", "!", "file_exists", "(", "$", "directory", ")", "||", "!", "is_dir", "(", "$", "directory", ")", "||", "!", "is_writable", "(", "$", "directory", ")", ")", "{", "throw", "new", "Rah_Backup_Exception", "(", "gTxt", "(", "'rah_backup_dir_not_writable'", ",", "array", "(", "'{path}'", "=>", "$", "dir", ")", ")", ")", ";", "}", "@", "set_time_limit", "(", "0", ")", ";", "@", "ignore_user_abort", "(", "true", ")", ";", "callback_event", "(", "'rah_backup.create'", ")", ";", "$", "filestamp", "=", "'_'", ".", "safe_strtotime", "(", "'now'", ")", ";", "$", "name", "=", "$", "this", "->", "sanitize", "(", "$", "txpcfg", "[", "'db'", "]", ")", ";", "if", "(", "!", "$", "name", ")", "{", "$", "name", "=", "'database'", ";", "}", "$", "path", "=", "$", "directory", ".", "'/'", ".", "$", "name", ".", "$", "filestamp", ".", "'.sql.gz'", ";", "$", "created", "=", "array", "(", ")", ";", "$", "created", "[", "basename", "(", "$", "path", ")", "]", "=", "$", "path", ";", "$", "dump", "=", "new", "\\", "Rah", "\\", "Danpu", "\\", "Dump", ";", "$", "dump", "->", "file", "(", "$", "path", ")", "->", "dsn", "(", "'mysql:dbname='", ".", "$", "txpcfg", "[", "'db'", "]", ".", "';host='", ".", "$", "txpcfg", "[", "'host'", "]", ")", "->", "user", "(", "$", "txpcfg", "[", "'user'", "]", ")", "->", "pass", "(", "$", "txpcfg", "[", "'pass'", "]", ")", "->", "tmp", "(", "get_pref", "(", "'tempdir'", ")", ")", ";", "if", "(", "get_pref", "(", "'rah_backup_ignore_tables'", ")", ")", "{", "$", "ignore", "=", "array", "(", ")", ";", "foreach", "(", "do_list", "(", "get_pref", "(", "'rah_backup_ignore_tables'", ")", ")", "as", "$", "table", ")", "{", "$", "ignore", "[", "]", "=", "PFX", ".", "$", "table", ";", "}", "$", "dump", "->", "ignore", "(", "$", "ignore", ")", ";", "}", "if", "(", "PFX", ")", "{", "$", "dump", "->", "prefix", "(", "PFX", ")", ";", "}", "new", "\\", "Rah", "\\", "Danpu", "\\", "Export", "(", "$", "dump", ")", ";", "if", "(", "get_pref", "(", "'rah_backup_copy_paths'", ")", "&&", "!", "is_disabled", "(", "'exec'", ")", "&&", "is_callable", "(", "'exec'", ")", ")", "{", "$", "fileMultiplier", "++", ";", "// Copied paths.", "$", "copy", "=", "array", "(", ")", ";", "foreach", "(", "do_list", "(", "get_pref", "(", "'rah_backup_copy_paths'", ")", ")", "as", "$", "path", ")", "{", "if", "(", "$", "path", ")", "{", "$", "path", "=", "txpath", ".", "'/'", ".", "$", "path", ";", "if", "(", "file_exists", "(", "$", "path", ")", "&&", "is_readable", "(", "$", "path", ")", "&&", "$", "path", "=", "escapeshellarg", "(", "$", "path", ")", ")", "{", "$", "copy", "[", "$", "path", "]", "=", "' '", ".", "$", "path", ";", "}", "}", "}", "// Excluded paths.", "$", "exclude", "=", "array", "(", ")", ";", "foreach", "(", "do_list", "(", "get_pref", "(", "'rah_backup_exclude_files'", ")", ")", "as", "$", "path", ")", "{", "if", "(", "$", "path", "&&", "$", "path", "=", "escapeshellarg", "(", "txpath", ".", "'/'", ".", "$", "path", ")", ")", "{", "$", "exclude", "[", "$", "path", "]", "=", "' --exclude='", ".", "$", "path", ";", "}", "}", "$", "name", "=", "$", "this", "->", "sanitize", "(", "get_pref", "(", "'siteurl'", ")", ")", ";", "if", "(", "!", "$", "name", ")", "{", "$", "name", "=", "'filesystem'", ";", "}", "$", "path", "=", "$", "directory", ".", "'/'", ".", "$", "name", ".", "$", "filestamp", ".", "'.tar.gz'", ";", "if", "(", "exec", "(", "'tar -cvpzf '", ".", "escapeshellarg", "(", "$", "path", ")", ".", "implode", "(", "''", ",", "$", "exclude", ")", ".", "implode", "(", "''", ",", "$", "copy", ")", ")", "!==", "false", ")", "{", "$", "created", "[", "basename", "(", "$", "path", ")", "]", "=", "$", "path", ";", "}", "}", "$", "offset", "=", "(", "int", ")", "get_pref", "(", "'rah_backup_files_to_keep'", ")", ";", "if", "(", "$", "offset", ")", "{", "$", "offset", "=", "max", "(", "$", "fileMultiplier", ",", "$", "offset", "*", "$", "fileMultiplier", ")", ";", "$", "deleted", "=", "array", "(", ")", ";", "try", "{", "foreach", "(", "$", "this", "->", "getBackups", "(", "'date'", ",", "'desc'", ",", "$", "offset", ")", "as", "$", "name", "=>", "$", "backup", ")", "{", "$", "deleted", "[", "$", "name", "]", "=", "$", "backup", "[", "'path'", "]", ";", "@", "unlink", "(", "$", "backup", "[", "'path'", "]", ")", ";", "}", "callback_event", "(", "'rah_backup.deleted'", ",", "''", ",", "0", ",", "array", "(", "'files'", "=>", "$", "deleted", ")", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "}", "}", "callback_event", "(", "'rah_backup.created'", ",", "''", ",", "0", ",", "array", "(", "'files'", "=>", "$", "created", ",", ")", ")", ";", "}" ]
Takes a new set of backups. This method creates a new set of backups and it can be run by triggering 'rah_backup.backup' event. <code> callback_event('rah_backup.backup'); </code> On success it triggers two callback events 'rah_backup.create' and 'rah_backup.created', where the latter contains an data-map of created backup files: <code> register_callback('abc_my_handler', 'rah_backup.created'); function abc_my_handler($event, $step, $pre, $data) { print_r($data); } </code> @throws Exception
[ "Takes", "a", "new", "set", "of", "backups", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L138-L254
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.sanitize
private function sanitize($filename) { $filename = preg_replace('/[^A-Za-z0-9\-\._]/', '.', (string) $filename); return trim(substr(preg_replace('/[_\.\-]{2,}/', '.', $filename), 0, 40), '._-'); }
php
private function sanitize($filename) { $filename = preg_replace('/[^A-Za-z0-9\-\._]/', '.', (string) $filename); return trim(substr(preg_replace('/[_\.\-]{2,}/', '.', $filename), 0, 40), '._-'); }
[ "private", "function", "sanitize", "(", "$", "filename", ")", "{", "$", "filename", "=", "preg_replace", "(", "'/[^A-Za-z0-9\\-\\._]/'", ",", "'.'", ",", "(", "string", ")", "$", "filename", ")", ";", "return", "trim", "(", "substr", "(", "preg_replace", "(", "'/[_\\.\\-]{2,}/'", ",", "'.'", ",", "$", "filename", ")", ",", "0", ",", "40", ")", ",", "'._-'", ")", ";", "}" ]
Sanitizes filename. @param string $filename The filename @return string A safe filename
[ "Sanitizes", "filename", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L263-L267
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.pane
public function pane() { global $step; require_privs('rah_backup'); $steps = array( 'browser' => false, 'create' => true, 'download' => true, 'multi_edit' => true, ); if (!$step || !bouncer($step, $steps) || !has_privs('rah_backup_' . $step)) { $step = 'browser'; } $this->$step(); }
php
public function pane() { global $step; require_privs('rah_backup'); $steps = array( 'browser' => false, 'create' => true, 'download' => true, 'multi_edit' => true, ); if (!$step || !bouncer($step, $steps) || !has_privs('rah_backup_' . $step)) { $step = 'browser'; } $this->$step(); }
[ "public", "function", "pane", "(", ")", "{", "global", "$", "step", ";", "require_privs", "(", "'rah_backup'", ")", ";", "$", "steps", "=", "array", "(", "'browser'", "=>", "false", ",", "'create'", "=>", "true", ",", "'download'", "=>", "true", ",", "'multi_edit'", "=>", "true", ",", ")", ";", "if", "(", "!", "$", "step", "||", "!", "bouncer", "(", "$", "step", ",", "$", "steps", ")", "||", "!", "has_privs", "(", "'rah_backup_'", ".", "$", "step", ")", ")", "{", "$", "step", "=", "'browser'", ";", "}", "$", "this", "->", "$", "step", "(", ")", ";", "}" ]
Delivers panels.
[ "Delivers", "panels", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L273-L291
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.head
public function head() { global $event, $theme; if ($event != 'rah_backup') { return; } gTxtScript(array( 'rah_backup_confirm_backup', )); $msg = array( 'backup' => escape_js($theme->announce_async(gTxt('rah_backup_taking'))), 'error' => escape_js($theme->announce_async(gTxt('rah_backup_task_error'))), ); $js = <<<EOF $(function () { $('.rah_backup_take').on('click', function (e) { e.preventDefault(); var obj = $(this), href, spinner; if (obj.hasClass('disabled') || !verify(textpattern.gTxt('rah_backup_confirm_backup'))) { return false; } $.globalEval('{$msg['backup']}'); spinner = $('<span> <span class="spinner"></span> </span>'); href = obj.attr('href'); obj.addClass('disabled').attr('href', '#').after(spinner); $.ajax('index.php', { data: href.substr(1) + '&app_mode=async', dataType: 'script', timeout: 1800000 }).fail(function () { $.globalEval('{$msg['error']}'); }).always(function () { obj.removeClass('disabled').attr('href', href); spinner.remove(); }); }); }); EOF; echo script_js($js); }
php
public function head() { global $event, $theme; if ($event != 'rah_backup') { return; } gTxtScript(array( 'rah_backup_confirm_backup', )); $msg = array( 'backup' => escape_js($theme->announce_async(gTxt('rah_backup_taking'))), 'error' => escape_js($theme->announce_async(gTxt('rah_backup_task_error'))), ); $js = <<<EOF $(function () { $('.rah_backup_take').on('click', function (e) { e.preventDefault(); var obj = $(this), href, spinner; if (obj.hasClass('disabled') || !verify(textpattern.gTxt('rah_backup_confirm_backup'))) { return false; } $.globalEval('{$msg['backup']}'); spinner = $('<span> <span class="spinner"></span> </span>'); href = obj.attr('href'); obj.addClass('disabled').attr('href', '#').after(spinner); $.ajax('index.php', { data: href.substr(1) + '&app_mode=async', dataType: 'script', timeout: 1800000 }).fail(function () { $.globalEval('{$msg['error']}'); }).always(function () { obj.removeClass('disabled').attr('href', href); spinner.remove(); }); }); }); EOF; echo script_js($js); }
[ "public", "function", "head", "(", ")", "{", "global", "$", "event", ",", "$", "theme", ";", "if", "(", "$", "event", "!=", "'rah_backup'", ")", "{", "return", ";", "}", "gTxtScript", "(", "array", "(", "'rah_backup_confirm_backup'", ",", ")", ")", ";", "$", "msg", "=", "array", "(", "'backup'", "=>", "escape_js", "(", "$", "theme", "->", "announce_async", "(", "gTxt", "(", "'rah_backup_taking'", ")", ")", ")", ",", "'error'", "=>", "escape_js", "(", "$", "theme", "->", "announce_async", "(", "gTxt", "(", "'rah_backup_task_error'", ")", ")", ")", ",", ")", ";", "$", "js", "=", " <<<EOF\n $(function ()\n {\n $('.rah_backup_take').on('click', function (e)\n {\n e.preventDefault();\n var obj = $(this), href, spinner;\n\n if (obj.hasClass('disabled') || !verify(textpattern.gTxt('rah_backup_confirm_backup'))) {\n return false;\n }\n\n $.globalEval('{$msg['backup']}');\n\n spinner = $('<span> <span class=\"spinner\"></span> </span>');\n href = obj.attr('href');\n obj.addClass('disabled').attr('href', '#').after(spinner);\n\n $.ajax('index.php', {\n data: href.substr(1) + '&app_mode=async',\n dataType: 'script',\n timeout: 1800000\n }).fail(function ()\n {\n $.globalEval('{$msg['error']}');\n }).always(function ()\n {\n obj.removeClass('disabled').attr('href', href);\n spinner.remove();\n });\n });\n });\nEOF", ";", "echo", "script_js", "(", "$", "js", ")", ";", "}" ]
Adds the panel's CSS and JavaScript to the &lt;head&gt;.
[ "Adds", "the", "panel", "s", "CSS", "and", "JavaScript", "to", "the", "&lt", ";", "head&gt", ";", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L297-L349
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.browser
private function browser($message = '') { global $event, $app_mode, $theme; extract(gpsa(array( 'sort', 'dir', ))); $methods = array(); $path = get_pref('rah_backup_path'); $writeable = $path && file_exists($path) && is_dir($path) && is_writable($path); if (has_privs('rah_backup_delete') && $writeable) { $methods['delete'] = gTxt('rah_backup_delete'); } $columns = array('name', 'date', 'type', 'size'); if ($dir !== 'desc' && $dir !== 'asc') { $dir = get_pref($event.'_sort_dir', 'asc'); } if (!in_array((string) $sort, $columns)) { $sort = get_pref($event.'_sort_column', 'name'); } if ($methods) { $column[] = hCell( fInput('checkbox', 'select_all', 0, '', '', '', '', '', 'select_all'), '', ' title="'.gTxt('toggle_all_selected').'" class="multi-edit"' ); } foreach ($columns as $name) { $column[] = column_head( $event.'_'.$name, $name, $event, true, $name === $sort && $dir === 'asc' ? 'desc' : 'asc', '', '', $name === $sort ? $dir : '', 'browse' ); } set_pref($event.'_sort_column', $sort, 'rah_backup', 2, '', 0, PREF_PRIVATE); set_pref($event.'_sort_dir', $dir, 'rah_backup', 2, '', 0, PREF_PRIVATE); try { $backups = $this->getBackups($sort, $dir); foreach ($backups as $backup) { $td = array(); $name = txpspecialchars($backup['name']); if ($methods) { $td[] = td(fInput('checkbox', 'selected[]', $name), '', 'multi-edit'); } if (has_privs('rah_backup_download') && $backup['readable']) { $td[] = td('<a title="'.gTxt('rah_backup_download').'" href="?event='.$event.'&amp;step=download&amp;file='.urlencode($name).'&amp;_txp_token='.form_token().'">'.$name.'</a>'); } else { $td[] = td($name); } $td[] = td(safe_strftime(gTxt('rah_backup_dateformat'), $backup['date'])); $td[] = td(gTxt('rah_backup_type_'.$backup['type'])); $td[] = td(format_filesize($backup['size'])); $out[] = tr(implode(n, $td)); } if (!$backups) { $out[] = tr(tda(gTxt('rah_backup_no_backups'), 'colspan="'.count($column).'"')); } } catch (Rah_Backup_Exception $e) { $out[] = tr(tda($e->getMessage(), 'colspan="'.count($column).'"')); } $out = implode('', $out); if ($app_mode === 'async') { send_script_response($theme->announce_async($message).n.'$("#rah_backup_list").html("'.escape_js($out).'");'); return; } $pane[] = n.'<div class="txp-listtables">'. n.'<table class="txp-list">'. n.'<thead>'. tr(implode('', $column)). n.'</thead>'. n.'<tbody id="rah_backup_list">'. $out. n.'</tbody>'. n.'</table>'. n.'</div>'; if ($methods) { $pane[] = multi_edit($methods, $event, 'multi_edit'); } pagetop(gTxt('rah_backup'), $message); echo hed(gTxt('rah_backup'), 1, 'class="txp-heading"'). n.'<div class="txp-container">'. n.'<p class="txp-buttons">'; if (has_privs('rah_backup_create') && $writeable) { echo n.'<a class="rah_backup_take" href="?event='.$event. '&amp;step=create&amp;_txp_token='.form_token().'">'. gTxt('rah_backup_create').'</a>'; } if (has_privs('prefs') && has_privs('rah_backup_preferences')) { echo n.'<a href="?event=prefs#prefs-rah_backup_path">'.gTxt('rah_backup_preferences').'</a>'; } echo n.'</p>'. n.'<form action="index.php" method="post" class="multi_edit_form">'. tInput(). n.implode('', $pane). n.'</form>'. n.'<div>'; }
php
private function browser($message = '') { global $event, $app_mode, $theme; extract(gpsa(array( 'sort', 'dir', ))); $methods = array(); $path = get_pref('rah_backup_path'); $writeable = $path && file_exists($path) && is_dir($path) && is_writable($path); if (has_privs('rah_backup_delete') && $writeable) { $methods['delete'] = gTxt('rah_backup_delete'); } $columns = array('name', 'date', 'type', 'size'); if ($dir !== 'desc' && $dir !== 'asc') { $dir = get_pref($event.'_sort_dir', 'asc'); } if (!in_array((string) $sort, $columns)) { $sort = get_pref($event.'_sort_column', 'name'); } if ($methods) { $column[] = hCell( fInput('checkbox', 'select_all', 0, '', '', '', '', '', 'select_all'), '', ' title="'.gTxt('toggle_all_selected').'" class="multi-edit"' ); } foreach ($columns as $name) { $column[] = column_head( $event.'_'.$name, $name, $event, true, $name === $sort && $dir === 'asc' ? 'desc' : 'asc', '', '', $name === $sort ? $dir : '', 'browse' ); } set_pref($event.'_sort_column', $sort, 'rah_backup', 2, '', 0, PREF_PRIVATE); set_pref($event.'_sort_dir', $dir, 'rah_backup', 2, '', 0, PREF_PRIVATE); try { $backups = $this->getBackups($sort, $dir); foreach ($backups as $backup) { $td = array(); $name = txpspecialchars($backup['name']); if ($methods) { $td[] = td(fInput('checkbox', 'selected[]', $name), '', 'multi-edit'); } if (has_privs('rah_backup_download') && $backup['readable']) { $td[] = td('<a title="'.gTxt('rah_backup_download').'" href="?event='.$event.'&amp;step=download&amp;file='.urlencode($name).'&amp;_txp_token='.form_token().'">'.$name.'</a>'); } else { $td[] = td($name); } $td[] = td(safe_strftime(gTxt('rah_backup_dateformat'), $backup['date'])); $td[] = td(gTxt('rah_backup_type_'.$backup['type'])); $td[] = td(format_filesize($backup['size'])); $out[] = tr(implode(n, $td)); } if (!$backups) { $out[] = tr(tda(gTxt('rah_backup_no_backups'), 'colspan="'.count($column).'"')); } } catch (Rah_Backup_Exception $e) { $out[] = tr(tda($e->getMessage(), 'colspan="'.count($column).'"')); } $out = implode('', $out); if ($app_mode === 'async') { send_script_response($theme->announce_async($message).n.'$("#rah_backup_list").html("'.escape_js($out).'");'); return; } $pane[] = n.'<div class="txp-listtables">'. n.'<table class="txp-list">'. n.'<thead>'. tr(implode('', $column)). n.'</thead>'. n.'<tbody id="rah_backup_list">'. $out. n.'</tbody>'. n.'</table>'. n.'</div>'; if ($methods) { $pane[] = multi_edit($methods, $event, 'multi_edit'); } pagetop(gTxt('rah_backup'), $message); echo hed(gTxt('rah_backup'), 1, 'class="txp-heading"'). n.'<div class="txp-container">'. n.'<p class="txp-buttons">'; if (has_privs('rah_backup_create') && $writeable) { echo n.'<a class="rah_backup_take" href="?event='.$event. '&amp;step=create&amp;_txp_token='.form_token().'">'. gTxt('rah_backup_create').'</a>'; } if (has_privs('prefs') && has_privs('rah_backup_preferences')) { echo n.'<a href="?event=prefs#prefs-rah_backup_path">'.gTxt('rah_backup_preferences').'</a>'; } echo n.'</p>'. n.'<form action="index.php" method="post" class="multi_edit_form">'. tInput(). n.implode('', $pane). n.'</form>'. n.'<div>'; }
[ "private", "function", "browser", "(", "$", "message", "=", "''", ")", "{", "global", "$", "event", ",", "$", "app_mode", ",", "$", "theme", ";", "extract", "(", "gpsa", "(", "array", "(", "'sort'", ",", "'dir'", ",", ")", ")", ")", ";", "$", "methods", "=", "array", "(", ")", ";", "$", "path", "=", "get_pref", "(", "'rah_backup_path'", ")", ";", "$", "writeable", "=", "$", "path", "&&", "file_exists", "(", "$", "path", ")", "&&", "is_dir", "(", "$", "path", ")", "&&", "is_writable", "(", "$", "path", ")", ";", "if", "(", "has_privs", "(", "'rah_backup_delete'", ")", "&&", "$", "writeable", ")", "{", "$", "methods", "[", "'delete'", "]", "=", "gTxt", "(", "'rah_backup_delete'", ")", ";", "}", "$", "columns", "=", "array", "(", "'name'", ",", "'date'", ",", "'type'", ",", "'size'", ")", ";", "if", "(", "$", "dir", "!==", "'desc'", "&&", "$", "dir", "!==", "'asc'", ")", "{", "$", "dir", "=", "get_pref", "(", "$", "event", ".", "'_sort_dir'", ",", "'asc'", ")", ";", "}", "if", "(", "!", "in_array", "(", "(", "string", ")", "$", "sort", ",", "$", "columns", ")", ")", "{", "$", "sort", "=", "get_pref", "(", "$", "event", ".", "'_sort_column'", ",", "'name'", ")", ";", "}", "if", "(", "$", "methods", ")", "{", "$", "column", "[", "]", "=", "hCell", "(", "fInput", "(", "'checkbox'", ",", "'select_all'", ",", "0", ",", "''", ",", "''", ",", "''", ",", "''", ",", "''", ",", "'select_all'", ")", ",", "''", ",", "' title=\"'", ".", "gTxt", "(", "'toggle_all_selected'", ")", ".", "'\" class=\"multi-edit\"'", ")", ";", "}", "foreach", "(", "$", "columns", "as", "$", "name", ")", "{", "$", "column", "[", "]", "=", "column_head", "(", "$", "event", ".", "'_'", ".", "$", "name", ",", "$", "name", ",", "$", "event", ",", "true", ",", "$", "name", "===", "$", "sort", "&&", "$", "dir", "===", "'asc'", "?", "'desc'", ":", "'asc'", ",", "''", ",", "''", ",", "$", "name", "===", "$", "sort", "?", "$", "dir", ":", "''", ",", "'browse'", ")", ";", "}", "set_pref", "(", "$", "event", ".", "'_sort_column'", ",", "$", "sort", ",", "'rah_backup'", ",", "2", ",", "''", ",", "0", ",", "PREF_PRIVATE", ")", ";", "set_pref", "(", "$", "event", ".", "'_sort_dir'", ",", "$", "dir", ",", "'rah_backup'", ",", "2", ",", "''", ",", "0", ",", "PREF_PRIVATE", ")", ";", "try", "{", "$", "backups", "=", "$", "this", "->", "getBackups", "(", "$", "sort", ",", "$", "dir", ")", ";", "foreach", "(", "$", "backups", "as", "$", "backup", ")", "{", "$", "td", "=", "array", "(", ")", ";", "$", "name", "=", "txpspecialchars", "(", "$", "backup", "[", "'name'", "]", ")", ";", "if", "(", "$", "methods", ")", "{", "$", "td", "[", "]", "=", "td", "(", "fInput", "(", "'checkbox'", ",", "'selected[]'", ",", "$", "name", ")", ",", "''", ",", "'multi-edit'", ")", ";", "}", "if", "(", "has_privs", "(", "'rah_backup_download'", ")", "&&", "$", "backup", "[", "'readable'", "]", ")", "{", "$", "td", "[", "]", "=", "td", "(", "'<a title=\"'", ".", "gTxt", "(", "'rah_backup_download'", ")", ".", "'\" href=\"?event='", ".", "$", "event", ".", "'&amp;step=download&amp;file='", ".", "urlencode", "(", "$", "name", ")", ".", "'&amp;_txp_token='", ".", "form_token", "(", ")", ".", "'\">'", ".", "$", "name", ".", "'</a>'", ")", ";", "}", "else", "{", "$", "td", "[", "]", "=", "td", "(", "$", "name", ")", ";", "}", "$", "td", "[", "]", "=", "td", "(", "safe_strftime", "(", "gTxt", "(", "'rah_backup_dateformat'", ")", ",", "$", "backup", "[", "'date'", "]", ")", ")", ";", "$", "td", "[", "]", "=", "td", "(", "gTxt", "(", "'rah_backup_type_'", ".", "$", "backup", "[", "'type'", "]", ")", ")", ";", "$", "td", "[", "]", "=", "td", "(", "format_filesize", "(", "$", "backup", "[", "'size'", "]", ")", ")", ";", "$", "out", "[", "]", "=", "tr", "(", "implode", "(", "n", ",", "$", "td", ")", ")", ";", "}", "if", "(", "!", "$", "backups", ")", "{", "$", "out", "[", "]", "=", "tr", "(", "tda", "(", "gTxt", "(", "'rah_backup_no_backups'", ")", ",", "'colspan=\"'", ".", "count", "(", "$", "column", ")", ".", "'\"'", ")", ")", ";", "}", "}", "catch", "(", "Rah_Backup_Exception", "$", "e", ")", "{", "$", "out", "[", "]", "=", "tr", "(", "tda", "(", "$", "e", "->", "getMessage", "(", ")", ",", "'colspan=\"'", ".", "count", "(", "$", "column", ")", ".", "'\"'", ")", ")", ";", "}", "$", "out", "=", "implode", "(", "''", ",", "$", "out", ")", ";", "if", "(", "$", "app_mode", "===", "'async'", ")", "{", "send_script_response", "(", "$", "theme", "->", "announce_async", "(", "$", "message", ")", ".", "n", ".", "'$(\"#rah_backup_list\").html(\"'", ".", "escape_js", "(", "$", "out", ")", ".", "'\");'", ")", ";", "return", ";", "}", "$", "pane", "[", "]", "=", "n", ".", "'<div class=\"txp-listtables\">'", ".", "n", ".", "'<table class=\"txp-list\">'", ".", "n", ".", "'<thead>'", ".", "tr", "(", "implode", "(", "''", ",", "$", "column", ")", ")", ".", "n", ".", "'</thead>'", ".", "n", ".", "'<tbody id=\"rah_backup_list\">'", ".", "$", "out", ".", "n", ".", "'</tbody>'", ".", "n", ".", "'</table>'", ".", "n", ".", "'</div>'", ";", "if", "(", "$", "methods", ")", "{", "$", "pane", "[", "]", "=", "multi_edit", "(", "$", "methods", ",", "$", "event", ",", "'multi_edit'", ")", ";", "}", "pagetop", "(", "gTxt", "(", "'rah_backup'", ")", ",", "$", "message", ")", ";", "echo", "hed", "(", "gTxt", "(", "'rah_backup'", ")", ",", "1", ",", "'class=\"txp-heading\"'", ")", ".", "n", ".", "'<div class=\"txp-container\">'", ".", "n", ".", "'<p class=\"txp-buttons\">'", ";", "if", "(", "has_privs", "(", "'rah_backup_create'", ")", "&&", "$", "writeable", ")", "{", "echo", "n", ".", "'<a class=\"rah_backup_take\" href=\"?event='", ".", "$", "event", ".", "'&amp;step=create&amp;_txp_token='", ".", "form_token", "(", ")", ".", "'\">'", ".", "gTxt", "(", "'rah_backup_create'", ")", ".", "'</a>'", ";", "}", "if", "(", "has_privs", "(", "'prefs'", ")", "&&", "has_privs", "(", "'rah_backup_preferences'", ")", ")", "{", "echo", "n", ".", "'<a href=\"?event=prefs#prefs-rah_backup_path\">'", ".", "gTxt", "(", "'rah_backup_preferences'", ")", ".", "'</a>'", ";", "}", "echo", "n", ".", "'</p>'", ".", "n", ".", "'<form action=\"index.php\" method=\"post\" class=\"multi_edit_form\">'", ".", "tInput", "(", ")", ".", "n", ".", "implode", "(", "''", ",", "$", "pane", ")", ".", "n", ".", "'</form>'", ".", "n", ".", "'<div>'", ";", "}" ]
The main panel listing backups. @param string|array $message The activity message
[ "The", "main", "panel", "listing", "backups", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L357-L488
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.create
private function create() { try { callback_event('rah_backup.backup'); } catch (Rah_Backup_Exception $e) { $this->browser(array($e->getMessage(), E_ERROR)); return; } catch (Exception $e) { $this->browser(array(txpspecialchars($e->getMessage()), E_ERROR)); return; } $this->browser(gTxt('rah_backup_done')); }
php
private function create() { try { callback_event('rah_backup.backup'); } catch (Rah_Backup_Exception $e) { $this->browser(array($e->getMessage(), E_ERROR)); return; } catch (Exception $e) { $this->browser(array(txpspecialchars($e->getMessage()), E_ERROR)); return; } $this->browser(gTxt('rah_backup_done')); }
[ "private", "function", "create", "(", ")", "{", "try", "{", "callback_event", "(", "'rah_backup.backup'", ")", ";", "}", "catch", "(", "Rah_Backup_Exception", "$", "e", ")", "{", "$", "this", "->", "browser", "(", "array", "(", "$", "e", "->", "getMessage", "(", ")", ",", "E_ERROR", ")", ")", ";", "return", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "this", "->", "browser", "(", "array", "(", "txpspecialchars", "(", "$", "e", "->", "getMessage", "(", ")", ")", ",", "E_ERROR", ")", ")", ";", "return", ";", "}", "$", "this", "->", "browser", "(", "gTxt", "(", "'rah_backup_done'", ")", ")", ";", "}" ]
The panel that creates new backups.
[ "The", "panel", "that", "creates", "new", "backups", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L494-L507
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.download
private function download() { $file = (string) gps('file'); try { $backups = $this->getBackups(); } catch (Exception $e) { } if (empty($backups) || !isset($backups[$file])) { $this->browser(array(gTxt('rah_backup_can_not_download'), E_ERROR)); return; } extract($backups[$file]); @ini_set('zlib.output_compression', 'Off'); @set_time_limit(0); @ignore_user_abort(true); ob_clean(); header('Content-Description: File Download'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$name.'"; size="'.$size.'"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: private'); header('Content-Length: '.$size); ob_flush(); flush(); if ($f = fopen($path, 'rb')) { while(!feof($f) && connection_status() == 0) { echo fread($f, 1024*64); ob_flush(); flush(); } fclose($f); } exit; }
php
private function download() { $file = (string) gps('file'); try { $backups = $this->getBackups(); } catch (Exception $e) { } if (empty($backups) || !isset($backups[$file])) { $this->browser(array(gTxt('rah_backup_can_not_download'), E_ERROR)); return; } extract($backups[$file]); @ini_set('zlib.output_compression', 'Off'); @set_time_limit(0); @ignore_user_abort(true); ob_clean(); header('Content-Description: File Download'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$name.'"; size="'.$size.'"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: private'); header('Content-Length: '.$size); ob_flush(); flush(); if ($f = fopen($path, 'rb')) { while(!feof($f) && connection_status() == 0) { echo fread($f, 1024*64); ob_flush(); flush(); } fclose($f); } exit; }
[ "private", "function", "download", "(", ")", "{", "$", "file", "=", "(", "string", ")", "gps", "(", "'file'", ")", ";", "try", "{", "$", "backups", "=", "$", "this", "->", "getBackups", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "}", "if", "(", "empty", "(", "$", "backups", ")", "||", "!", "isset", "(", "$", "backups", "[", "$", "file", "]", ")", ")", "{", "$", "this", "->", "browser", "(", "array", "(", "gTxt", "(", "'rah_backup_can_not_download'", ")", ",", "E_ERROR", ")", ")", ";", "return", ";", "}", "extract", "(", "$", "backups", "[", "$", "file", "]", ")", ";", "@", "ini_set", "(", "'zlib.output_compression'", ",", "'Off'", ")", ";", "@", "set_time_limit", "(", "0", ")", ";", "@", "ignore_user_abort", "(", "true", ")", ";", "ob_clean", "(", ")", ";", "header", "(", "'Content-Description: File Download'", ")", ";", "header", "(", "'Content-Type: application/octet-stream'", ")", ";", "header", "(", "'Content-Disposition: attachment; filename=\"'", ".", "$", "name", ".", "'\"; size=\"'", ".", "$", "size", ".", "'\"'", ")", ";", "header", "(", "'Content-Transfer-Encoding: binary'", ")", ";", "header", "(", "'Expires: 0'", ")", ";", "header", "(", "'Cache-Control: private'", ")", ";", "header", "(", "'Content-Length: '", ".", "$", "size", ")", ";", "ob_flush", "(", ")", ";", "flush", "(", ")", ";", "if", "(", "$", "f", "=", "fopen", "(", "$", "path", ",", "'rb'", ")", ")", "{", "while", "(", "!", "feof", "(", "$", "f", ")", "&&", "connection_status", "(", ")", "==", "0", ")", "{", "echo", "fread", "(", "$", "f", ",", "1024", "*", "64", ")", ";", "ob_flush", "(", ")", ";", "flush", "(", ")", ";", "}", "fclose", "(", "$", "f", ")", ";", "}", "exit", ";", "}" ]
Streams backups for downloading.
[ "Streams", "backups", "for", "downloading", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L513-L555
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.multi_edit
private function multi_edit() { extract(psa(array( 'selected', 'edit_method', ))); require_privs('rah_backup_'.((string) $edit_method)); if (!is_string($edit_method) || empty($selected) || !is_array($selected)) { $this->browser(array(gTxt('rah_backup_select_something'), E_WARNING)); return; } $method = 'multi_option_' . $edit_method; if (!method_exists($this, $method)) { $method = 'browse'; } $this->$method(); }
php
private function multi_edit() { extract(psa(array( 'selected', 'edit_method', ))); require_privs('rah_backup_'.((string) $edit_method)); if (!is_string($edit_method) || empty($selected) || !is_array($selected)) { $this->browser(array(gTxt('rah_backup_select_something'), E_WARNING)); return; } $method = 'multi_option_' . $edit_method; if (!method_exists($this, $method)) { $method = 'browse'; } $this->$method(); }
[ "private", "function", "multi_edit", "(", ")", "{", "extract", "(", "psa", "(", "array", "(", "'selected'", ",", "'edit_method'", ",", ")", ")", ")", ";", "require_privs", "(", "'rah_backup_'", ".", "(", "(", "string", ")", "$", "edit_method", ")", ")", ";", "if", "(", "!", "is_string", "(", "$", "edit_method", ")", "||", "empty", "(", "$", "selected", ")", "||", "!", "is_array", "(", "$", "selected", ")", ")", "{", "$", "this", "->", "browser", "(", "array", "(", "gTxt", "(", "'rah_backup_select_something'", ")", ",", "E_WARNING", ")", ")", ";", "return", ";", "}", "$", "method", "=", "'multi_option_'", ".", "$", "edit_method", ";", "if", "(", "!", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "$", "method", "=", "'browse'", ";", "}", "$", "this", "->", "$", "method", "(", ")", ";", "}" ]
Multi-edit handler.
[ "Multi", "-", "edit", "handler", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L561-L582
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.multi_option_delete
private function multi_option_delete() { $selected = ps('selected'); $deleted = array(); try { foreach ($this->getBackups() as $name => $file) { if (in_array($name, $selected, true)) { $deleted[$name] = $file['path']; @unlink($file['path']); } } } catch (Exception $e) { } callback_event('rah_backup.deleted', '', 0, array( 'files' => $deleted, )); $this->browser(gTxt('rah_backup_removed')); }
php
private function multi_option_delete() { $selected = ps('selected'); $deleted = array(); try { foreach ($this->getBackups() as $name => $file) { if (in_array($name, $selected, true)) { $deleted[$name] = $file['path']; @unlink($file['path']); } } } catch (Exception $e) { } callback_event('rah_backup.deleted', '', 0, array( 'files' => $deleted, )); $this->browser(gTxt('rah_backup_removed')); }
[ "private", "function", "multi_option_delete", "(", ")", "{", "$", "selected", "=", "ps", "(", "'selected'", ")", ";", "$", "deleted", "=", "array", "(", ")", ";", "try", "{", "foreach", "(", "$", "this", "->", "getBackups", "(", ")", "as", "$", "name", "=>", "$", "file", ")", "{", "if", "(", "in_array", "(", "$", "name", ",", "$", "selected", ",", "true", ")", ")", "{", "$", "deleted", "[", "$", "name", "]", "=", "$", "file", "[", "'path'", "]", ";", "@", "unlink", "(", "$", "file", "[", "'path'", "]", ")", ";", "}", "}", "}", "catch", "(", "Exception", "$", "e", ")", "{", "}", "callback_event", "(", "'rah_backup.deleted'", ",", "''", ",", "0", ",", "array", "(", "'files'", "=>", "$", "deleted", ",", ")", ")", ";", "$", "this", "->", "browser", "(", "gTxt", "(", "'rah_backup_removed'", ")", ")", ";", "}" ]
Deletes selected backups.
[ "Deletes", "selected", "backups", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L588-L608
gocom/rah_backup
src/Rah/Backup.php
Rah_Backup.getBackups
private function getBackups($sort = 'name', $direction = 'asc', $offset = 0, $limit = null) { $directory = txpath . '/' . get_pref('rah_backup_path'); if (!get_pref('rah_backup_path') || !file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { throw new Rah_Backup_Exception( gTxt('rah_backup_dir_not_readable', array('{path}' => $directory)) ); } $order = $files = array(); $sort_crit = array( 'name' => SORT_REGULAR, 'ext' => SORT_REGULAR, 'date' => SORT_NUMERIC, 'size' => SORT_NUMERIC, 'type' => SORT_NUMERIC, ); if (!is_string($sort) || !isset($sort_crit[$sort])) { $sort = 'name'; } foreach (new DirectoryIterator($directory) as $file) { if (!$file->isFile() || !preg_match('/^[a-z0-9\-_\.]+\.(sql\.gz|tar\.gz)$/i', $file->getFilename())) { continue; } $backup = array( 'path' => $file->getPathname(), 'name' => $file->getFilename(), 'ext' => $file->getExtension(), 'date' => $file->getMTime(), 'size' => $file->getSize(), 'type' => self::BACKUP_FILESYSTEM, 'readable' => $file->isReadable(), 'writable' => $file->isWritable(), ); if (preg_match('/\.sql\.gz$/i', $backup['name'])) { $backup['type'] = self::BACKUP_DATABASE; } $files[$backup['name']] = $backup; $order[$backup['name']] = $backup[$sort]; } if (!$files) { return array(); } array_multisort($order, $sort_crit[$sort], $files); if ($direction === 'desc') { $files = array_reverse($files); } return array_slice($files, $offset, $limit); }
php
private function getBackups($sort = 'name', $direction = 'asc', $offset = 0, $limit = null) { $directory = txpath . '/' . get_pref('rah_backup_path'); if (!get_pref('rah_backup_path') || !file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { throw new Rah_Backup_Exception( gTxt('rah_backup_dir_not_readable', array('{path}' => $directory)) ); } $order = $files = array(); $sort_crit = array( 'name' => SORT_REGULAR, 'ext' => SORT_REGULAR, 'date' => SORT_NUMERIC, 'size' => SORT_NUMERIC, 'type' => SORT_NUMERIC, ); if (!is_string($sort) || !isset($sort_crit[$sort])) { $sort = 'name'; } foreach (new DirectoryIterator($directory) as $file) { if (!$file->isFile() || !preg_match('/^[a-z0-9\-_\.]+\.(sql\.gz|tar\.gz)$/i', $file->getFilename())) { continue; } $backup = array( 'path' => $file->getPathname(), 'name' => $file->getFilename(), 'ext' => $file->getExtension(), 'date' => $file->getMTime(), 'size' => $file->getSize(), 'type' => self::BACKUP_FILESYSTEM, 'readable' => $file->isReadable(), 'writable' => $file->isWritable(), ); if (preg_match('/\.sql\.gz$/i', $backup['name'])) { $backup['type'] = self::BACKUP_DATABASE; } $files[$backup['name']] = $backup; $order[$backup['name']] = $backup[$sort]; } if (!$files) { return array(); } array_multisort($order, $sort_crit[$sort], $files); if ($direction === 'desc') { $files = array_reverse($files); } return array_slice($files, $offset, $limit); }
[ "private", "function", "getBackups", "(", "$", "sort", "=", "'name'", ",", "$", "direction", "=", "'asc'", ",", "$", "offset", "=", "0", ",", "$", "limit", "=", "null", ")", "{", "$", "directory", "=", "txpath", ".", "'/'", ".", "get_pref", "(", "'rah_backup_path'", ")", ";", "if", "(", "!", "get_pref", "(", "'rah_backup_path'", ")", "||", "!", "file_exists", "(", "$", "directory", ")", "||", "!", "is_dir", "(", "$", "directory", ")", "||", "!", "is_readable", "(", "$", "directory", ")", ")", "{", "throw", "new", "Rah_Backup_Exception", "(", "gTxt", "(", "'rah_backup_dir_not_readable'", ",", "array", "(", "'{path}'", "=>", "$", "directory", ")", ")", ")", ";", "}", "$", "order", "=", "$", "files", "=", "array", "(", ")", ";", "$", "sort_crit", "=", "array", "(", "'name'", "=>", "SORT_REGULAR", ",", "'ext'", "=>", "SORT_REGULAR", ",", "'date'", "=>", "SORT_NUMERIC", ",", "'size'", "=>", "SORT_NUMERIC", ",", "'type'", "=>", "SORT_NUMERIC", ",", ")", ";", "if", "(", "!", "is_string", "(", "$", "sort", ")", "||", "!", "isset", "(", "$", "sort_crit", "[", "$", "sort", "]", ")", ")", "{", "$", "sort", "=", "'name'", ";", "}", "foreach", "(", "new", "DirectoryIterator", "(", "$", "directory", ")", "as", "$", "file", ")", "{", "if", "(", "!", "$", "file", "->", "isFile", "(", ")", "||", "!", "preg_match", "(", "'/^[a-z0-9\\-_\\.]+\\.(sql\\.gz|tar\\.gz)$/i'", ",", "$", "file", "->", "getFilename", "(", ")", ")", ")", "{", "continue", ";", "}", "$", "backup", "=", "array", "(", "'path'", "=>", "$", "file", "->", "getPathname", "(", ")", ",", "'name'", "=>", "$", "file", "->", "getFilename", "(", ")", ",", "'ext'", "=>", "$", "file", "->", "getExtension", "(", ")", ",", "'date'", "=>", "$", "file", "->", "getMTime", "(", ")", ",", "'size'", "=>", "$", "file", "->", "getSize", "(", ")", ",", "'type'", "=>", "self", "::", "BACKUP_FILESYSTEM", ",", "'readable'", "=>", "$", "file", "->", "isReadable", "(", ")", ",", "'writable'", "=>", "$", "file", "->", "isWritable", "(", ")", ",", ")", ";", "if", "(", "preg_match", "(", "'/\\.sql\\.gz$/i'", ",", "$", "backup", "[", "'name'", "]", ")", ")", "{", "$", "backup", "[", "'type'", "]", "=", "self", "::", "BACKUP_DATABASE", ";", "}", "$", "files", "[", "$", "backup", "[", "'name'", "]", "]", "=", "$", "backup", ";", "$", "order", "[", "$", "backup", "[", "'name'", "]", "]", "=", "$", "backup", "[", "$", "sort", "]", ";", "}", "if", "(", "!", "$", "files", ")", "{", "return", "array", "(", ")", ";", "}", "array_multisort", "(", "$", "order", ",", "$", "sort_crit", "[", "$", "sort", "]", ",", "$", "files", ")", ";", "if", "(", "$", "direction", "===", "'desc'", ")", "{", "$", "files", "=", "array_reverse", "(", "$", "files", ")", ";", "}", "return", "array_slice", "(", "$", "files", ",", "$", "offset", ",", "$", "limit", ")", ";", "}" ]
Gets a list of backups. @param string $sort Sorting criteria, either 'name', 'ext', 'date', 'size', 'type' @param string $direction Sorting direction, either 'asc' or 'desc' @param int $offset Offset @param int $limit Limit results @return array
[ "Gets", "a", "list", "of", "backups", "." ]
train
https://github.com/gocom/rah_backup/blob/1a757c0fd569f4baf59471da8b1b487472a71390/src/Rah/Backup.php#L620-L680
zhouyl/mellivora
Mellivora/Database/Eloquent/Collection.php
Collection.find
public function find($key, $default = null) { if ($key instanceof Model) { $key = $key->getKey(); } if (is_array($key)) { if ($this->isEmpty()) { return new static; } return $this->whereIn($this->first()->getKeyName(), $key); } return Arr::first($this->items, function ($model) use ($key) { return $model->getKey() === $key; }, $default); }
php
public function find($key, $default = null) { if ($key instanceof Model) { $key = $key->getKey(); } if (is_array($key)) { if ($this->isEmpty()) { return new static; } return $this->whereIn($this->first()->getKeyName(), $key); } return Arr::first($this->items, function ($model) use ($key) { return $model->getKey() === $key; }, $default); }
[ "public", "function", "find", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "key", "instanceof", "Model", ")", "{", "$", "key", "=", "$", "key", "->", "getKey", "(", ")", ";", "}", "if", "(", "is_array", "(", "$", "key", ")", ")", "{", "if", "(", "$", "this", "->", "isEmpty", "(", ")", ")", "{", "return", "new", "static", ";", "}", "return", "$", "this", "->", "whereIn", "(", "$", "this", "->", "first", "(", ")", "->", "getKeyName", "(", ")", ",", "$", "key", ")", ";", "}", "return", "Arr", "::", "first", "(", "$", "this", "->", "items", ",", "function", "(", "$", "model", ")", "use", "(", "$", "key", ")", "{", "return", "$", "model", "->", "getKey", "(", ")", "===", "$", "key", ";", "}", ",", "$", "default", ")", ";", "}" ]
Find a model in the collection by key. @param mixed $key @param mixed $default @return \Mellivora\Database\Eloquent\Model|static
[ "Find", "a", "model", "in", "the", "collection", "by", "key", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Collection.php#L20-L37
zhouyl/mellivora
Mellivora/Database/Eloquent/Collection.php
Collection.load
public function load($relations) { if (count($this->items) > 0) { if (is_string($relations)) { $relations = func_get_args(); } $query = $this->first()->newQuery()->with($relations); $this->items = $query->eagerLoadRelations($this->items); } return $this; }
php
public function load($relations) { if (count($this->items) > 0) { if (is_string($relations)) { $relations = func_get_args(); } $query = $this->first()->newQuery()->with($relations); $this->items = $query->eagerLoadRelations($this->items); } return $this; }
[ "public", "function", "load", "(", "$", "relations", ")", "{", "if", "(", "count", "(", "$", "this", "->", "items", ")", ">", "0", ")", "{", "if", "(", "is_string", "(", "$", "relations", ")", ")", "{", "$", "relations", "=", "func_get_args", "(", ")", ";", "}", "$", "query", "=", "$", "this", "->", "first", "(", ")", "->", "newQuery", "(", ")", "->", "with", "(", "$", "relations", ")", ";", "$", "this", "->", "items", "=", "$", "query", "->", "eagerLoadRelations", "(", "$", "this", "->", "items", ")", ";", "}", "return", "$", "this", ";", "}" ]
Load a set of relationships onto the collection. @param mixed $relations @return $this
[ "Load", "a", "set", "of", "relationships", "onto", "the", "collection", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Collection.php#L46-L59
arndtteunissen/column-layout
Classes/Hook/LayoutPreviewHook.php
LayoutPreviewHook.injectStylesAndScripts
public function injectStylesAndScripts(array $params, PageLayoutController $ref): string { $jsCallbackFunction = null; // The translation view is shown. Disable floating elements for that view. if ($ref->MOD_SETTINGS['function'] === '2') { $jsCallbackFunction = 'function(ColumnLayout) { ColumnLayout.settings.isTranslationView = true; }'; } $ref->getModuleTemplate()->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/ColumnLayout/ColumnLayout', $jsCallbackFunction); $ref->getModuleTemplate()->getPageRenderer()->addCssFile('EXT:column_layout/Resources/Public/Css/column_layout.css'); $ref->getModuleTemplate()->getPageRenderer()->addCssInlineBlock('column-layout', implode(LF, $this->inlineStyles), true); return ''; }
php
public function injectStylesAndScripts(array $params, PageLayoutController $ref): string { $jsCallbackFunction = null; // The translation view is shown. Disable floating elements for that view. if ($ref->MOD_SETTINGS['function'] === '2') { $jsCallbackFunction = 'function(ColumnLayout) { ColumnLayout.settings.isTranslationView = true; }'; } $ref->getModuleTemplate()->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/ColumnLayout/ColumnLayout', $jsCallbackFunction); $ref->getModuleTemplate()->getPageRenderer()->addCssFile('EXT:column_layout/Resources/Public/Css/column_layout.css'); $ref->getModuleTemplate()->getPageRenderer()->addCssInlineBlock('column-layout', implode(LF, $this->inlineStyles), true); return ''; }
[ "public", "function", "injectStylesAndScripts", "(", "array", "$", "params", ",", "PageLayoutController", "$", "ref", ")", ":", "string", "{", "$", "jsCallbackFunction", "=", "null", ";", "// The translation view is shown. Disable floating elements for that view.", "if", "(", "$", "ref", "->", "MOD_SETTINGS", "[", "'function'", "]", "===", "'2'", ")", "{", "$", "jsCallbackFunction", "=", "'function(ColumnLayout) {\n ColumnLayout.settings.isTranslationView = true;\n }'", ";", "}", "$", "ref", "->", "getModuleTemplate", "(", ")", "->", "getPageRenderer", "(", ")", "->", "loadRequireJsModule", "(", "'TYPO3/CMS/ColumnLayout/ColumnLayout'", ",", "$", "jsCallbackFunction", ")", ";", "$", "ref", "->", "getModuleTemplate", "(", ")", "->", "getPageRenderer", "(", ")", "->", "addCssFile", "(", "'EXT:column_layout/Resources/Public/Css/column_layout.css'", ")", ";", "$", "ref", "->", "getModuleTemplate", "(", ")", "->", "getPageRenderer", "(", ")", "->", "addCssInlineBlock", "(", "'column-layout'", ",", "implode", "(", "LF", ",", "$", "this", "->", "inlineStyles", ")", ",", "true", ")", ";", "return", "''", ";", "}" ]
Hook for header rendering of the PageLayoutController to inject stylesheet required for custom column layout display. @see PageLayoutController::renderContent() @param array $params @param PageLayoutController $ref @return string html to be added to the page layout
[ "Hook", "for", "header", "rendering", "of", "the", "PageLayoutController", "to", "inject", "stylesheet", "required", "for", "custom", "column", "layout", "display", "." ]
train
https://github.com/arndtteunissen/column-layout/blob/ad737068eef3b084d4d0e3a48e6a3d8277af9560/Classes/Hook/LayoutPreviewHook.php#L38-L54
arndtteunissen/column-layout
Classes/Hook/LayoutPreviewHook.php
LayoutPreviewHook.preProcess
public function preProcess(PageLayoutView &$parentObject, &$info, array &$row) { if ($this->skipRendering($parentObject, $row)) { return; } $renderer = GeneralUtility::makeInstance(ColumnRenderer::class, $row); if (!$renderer->skipRendering()) { list($html, $css) = $renderer->renderSingleColumn(); $info[] = $html; $this->inlineStyles[] = $css; } return; }
php
public function preProcess(PageLayoutView &$parentObject, &$info, array &$row) { if ($this->skipRendering($parentObject, $row)) { return; } $renderer = GeneralUtility::makeInstance(ColumnRenderer::class, $row); if (!$renderer->skipRendering()) { list($html, $css) = $renderer->renderSingleColumn(); $info[] = $html; $this->inlineStyles[] = $css; } return; }
[ "public", "function", "preProcess", "(", "PageLayoutView", "&", "$", "parentObject", ",", "&", "$", "info", ",", "array", "&", "$", "row", ")", "{", "if", "(", "$", "this", "->", "skipRendering", "(", "$", "parentObject", ",", "$", "row", ")", ")", "{", "return", ";", "}", "$", "renderer", "=", "GeneralUtility", "::", "makeInstance", "(", "ColumnRenderer", "::", "class", ",", "$", "row", ")", ";", "if", "(", "!", "$", "renderer", "->", "skipRendering", "(", ")", ")", "{", "list", "(", "$", "html", ",", "$", "css", ")", "=", "$", "renderer", "->", "renderSingleColumn", "(", ")", ";", "$", "info", "[", "]", "=", "$", "html", ";", "$", "this", "->", "inlineStyles", "[", "]", "=", "$", "css", ";", "}", "return", ";", "}" ]
{@inheritdoc} @param array $info
[ "{" ]
train
https://github.com/arndtteunissen/column-layout/blob/ad737068eef3b084d4d0e3a48e6a3d8277af9560/Classes/Hook/LayoutPreviewHook.php#L60-L76
arndtteunissen/column-layout
Classes/Hook/LayoutPreviewHook.php
LayoutPreviewHook.skipRendering
protected function skipRendering(PageLayoutView &$parentObject, array $row): bool { $tsConf = $parentObject->modTSconfig['column_layout'] ?? []; return ( $tsConf['hidePreview'] ?? false // Hidden via page TSConfig || empty($row['tx_column_layout_column_config']) // Not set || $tsConf['disabled'] ?? false // Hidden for this element ); }
php
protected function skipRendering(PageLayoutView &$parentObject, array $row): bool { $tsConf = $parentObject->modTSconfig['column_layout'] ?? []; return ( $tsConf['hidePreview'] ?? false // Hidden via page TSConfig || empty($row['tx_column_layout_column_config']) // Not set || $tsConf['disabled'] ?? false // Hidden for this element ); }
[ "protected", "function", "skipRendering", "(", "PageLayoutView", "&", "$", "parentObject", ",", "array", "$", "row", ")", ":", "bool", "{", "$", "tsConf", "=", "$", "parentObject", "->", "modTSconfig", "[", "'column_layout'", "]", "??", "[", "]", ";", "return", "(", "$", "tsConf", "[", "'hidePreview'", "]", "??", "false", "// Hidden via page TSConfig", "||", "empty", "(", "$", "row", "[", "'tx_column_layout_column_config'", "]", ")", "// Not set", "||", "$", "tsConf", "[", "'disabled'", "]", "??", "false", "// Hidden for this element", ")", ";", "}" ]
Checks if the rendering of the column markup should be skipped. @param PageLayoutView $parentObject @return bool
[ "Checks", "if", "the", "rendering", "of", "the", "column", "markup", "should", "be", "skipped", "." ]
train
https://github.com/arndtteunissen/column-layout/blob/ad737068eef3b084d4d0e3a48e6a3d8277af9560/Classes/Hook/LayoutPreviewHook.php#L84-L93
krakphp/job
src/Queue/Sync/SyncQueue.php
SyncQueue.enqueue
public function enqueue(Job\WrappedJob $job) { $serialized = Job\serializeJobs([$job->withQueueProvider('sync')]); $res = unserialize($this->worker->work($serialized)); if ($res[0]->isFailed()) { throw new \RuntimeException("Job Failed - " . json_encode($res[0], JSON_PRETTY_PRINT)); } }
php
public function enqueue(Job\WrappedJob $job) { $serialized = Job\serializeJobs([$job->withQueueProvider('sync')]); $res = unserialize($this->worker->work($serialized)); if ($res[0]->isFailed()) { throw new \RuntimeException("Job Failed - " . json_encode($res[0], JSON_PRETTY_PRINT)); } }
[ "public", "function", "enqueue", "(", "Job", "\\", "WrappedJob", "$", "job", ")", "{", "$", "serialized", "=", "Job", "\\", "serializeJobs", "(", "[", "$", "job", "->", "withQueueProvider", "(", "'sync'", ")", "]", ")", ";", "$", "res", "=", "unserialize", "(", "$", "this", "->", "worker", "->", "work", "(", "$", "serialized", ")", ")", ";", "if", "(", "$", "res", "[", "0", "]", "->", "isFailed", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Job Failed - \"", ".", "json_encode", "(", "$", "res", "[", "0", "]", ",", "JSON_PRETTY_PRINT", ")", ")", ";", "}", "}" ]
push a job onto the queue
[ "push", "a", "job", "onto", "the", "queue" ]
train
https://github.com/krakphp/job/blob/0c16020c1baa13d91f819ecba8334861ba7c4d6c/src/Queue/Sync/SyncQueue.php#L17-L23
HedronDev/hedron
src/Factory/ProjectTypeFactory.php
ProjectTypeFactory.createInstance
public function createInstance(PluginDefinitionInterface $definition, ...$constructors) { $class = $definition->getClass(); return new $class($definition->getPluginId(), $definition, ...$constructors); }
php
public function createInstance(PluginDefinitionInterface $definition, ...$constructors) { $class = $definition->getClass(); return new $class($definition->getPluginId(), $definition, ...$constructors); }
[ "public", "function", "createInstance", "(", "PluginDefinitionInterface", "$", "definition", ",", "...", "$", "constructors", ")", "{", "$", "class", "=", "$", "definition", "->", "getClass", "(", ")", ";", "return", "new", "$", "class", "(", "$", "definition", "->", "getPluginId", "(", ")", ",", "$", "definition", ",", "...", "$", "constructors", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/HedronDev/hedron/blob/3b4adec4912f2d7c0b7e7262dc36515fbc2e8e00/src/Factory/ProjectTypeFactory.php#L13-L16
surebert/surebert-framework
src/sb/Controller/HTTP/Proxy.php
Proxy.get
public function get() { if (!isset($this->request->args[0])) { exit; } $url = $this->request->args[0]; //add the $_GET vars to the request $query_string = http_build_query($this->request->get); $destination_url = $url . ($query_string ? '?'.$query_string : ''); //exit if onBeforeGet doesn't pass if($this->onBeforeGet($destination_url) === false){ return false; } //logs to file if enabled if($this->log_to_file){ $logger = new \sb\Logger\CommandLine(); $log_name = preg_replace("~[^\w+]~", "_", get_called_class()); $logger->{$log_name}(json_encode(["ip" => \sb\Gateway::$remote_addr, "url" => $destination_url, "get" => $query_string, "post" => $this->request->post])); } //proxy to site and return response $ch = curl_init(); //set the url to grab the data from curl_setopt($ch, CURLOPT_URL, $destination_url); //set the function to pass the headers from the destination back to the client curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'headerCallBack')); //set the agent to be used for request curl_setopt($ch, CURLOPT_USERAGENT, $this->agent); //wait 10 seconds for timeout curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout); //forward any post requests if they exist if(count($this->request->post)){ curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->request->post); } //follow any redirects curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //return the result curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //ignore ssl errors if set to true if($this->ignore_ssl_errors){ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } //set any additional curl_opts given foreach($this->curl_opts as $key=>$val){ curl_setopt($ch, $key, $val); } //display the output return curl_exec($ch); }
php
public function get() { if (!isset($this->request->args[0])) { exit; } $url = $this->request->args[0]; //add the $_GET vars to the request $query_string = http_build_query($this->request->get); $destination_url = $url . ($query_string ? '?'.$query_string : ''); //exit if onBeforeGet doesn't pass if($this->onBeforeGet($destination_url) === false){ return false; } //logs to file if enabled if($this->log_to_file){ $logger = new \sb\Logger\CommandLine(); $log_name = preg_replace("~[^\w+]~", "_", get_called_class()); $logger->{$log_name}(json_encode(["ip" => \sb\Gateway::$remote_addr, "url" => $destination_url, "get" => $query_string, "post" => $this->request->post])); } //proxy to site and return response $ch = curl_init(); //set the url to grab the data from curl_setopt($ch, CURLOPT_URL, $destination_url); //set the function to pass the headers from the destination back to the client curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'headerCallBack')); //set the agent to be used for request curl_setopt($ch, CURLOPT_USERAGENT, $this->agent); //wait 10 seconds for timeout curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout); //forward any post requests if they exist if(count($this->request->post)){ curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->request->post); } //follow any redirects curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //return the result curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //ignore ssl errors if set to true if($this->ignore_ssl_errors){ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } //set any additional curl_opts given foreach($this->curl_opts as $key=>$val){ curl_setopt($ch, $key, $val); } //display the output return curl_exec($ch); }
[ "public", "function", "get", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "request", "->", "args", "[", "0", "]", ")", ")", "{", "exit", ";", "}", "$", "url", "=", "$", "this", "->", "request", "->", "args", "[", "0", "]", ";", "//add the $_GET vars to the request", "$", "query_string", "=", "http_build_query", "(", "$", "this", "->", "request", "->", "get", ")", ";", "$", "destination_url", "=", "$", "url", ".", "(", "$", "query_string", "?", "'?'", ".", "$", "query_string", ":", "''", ")", ";", "//exit if onBeforeGet doesn't pass", "if", "(", "$", "this", "->", "onBeforeGet", "(", "$", "destination_url", ")", "===", "false", ")", "{", "return", "false", ";", "}", "//logs to file if enabled", "if", "(", "$", "this", "->", "log_to_file", ")", "{", "$", "logger", "=", "new", "\\", "sb", "\\", "Logger", "\\", "CommandLine", "(", ")", ";", "$", "log_name", "=", "preg_replace", "(", "\"~[^\\w+]~\"", ",", "\"_\"", ",", "get_called_class", "(", ")", ")", ";", "$", "logger", "->", "{", "$", "log_name", "}", "(", "json_encode", "(", "[", "\"ip\"", "=>", "\\", "sb", "\\", "Gateway", "::", "$", "remote_addr", ",", "\"url\"", "=>", "$", "destination_url", ",", "\"get\"", "=>", "$", "query_string", ",", "\"post\"", "=>", "$", "this", "->", "request", "->", "post", "]", ")", ")", ";", "}", "//proxy to site and return response", "$", "ch", "=", "curl_init", "(", ")", ";", "//set the url to grab the data from", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "destination_url", ")", ";", "//set the function to pass the headers from the destination back to the client", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADERFUNCTION", ",", "array", "(", "$", "this", ",", "'headerCallBack'", ")", ")", ";", "//set the agent to be used for request", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "$", "this", "->", "agent", ")", ";", "//wait 10 seconds for timeout", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_TIMEOUT", ",", "$", "this", "->", "timeout", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CONNECTTIMEOUT", ",", "$", "this", "->", "timeout", ")", ";", "//forward any post requests if they exist", "if", "(", "count", "(", "$", "this", "->", "request", "->", "post", ")", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "this", "->", "request", "->", "post", ")", ";", "}", "//follow any redirects", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_FOLLOWLOCATION", ",", "1", ")", ";", "//return the result", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "1", ")", ";", "//ignore ssl errors if set to true", "if", "(", "$", "this", "->", "ignore_ssl_errors", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYHOST", ",", "false", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "false", ")", ";", "}", "//set any additional curl_opts given", "foreach", "(", "$", "this", "->", "curl_opts", "as", "$", "key", "=>", "$", "val", ")", "{", "curl_setopt", "(", "$", "ch", ",", "$", "key", ",", "$", "val", ")", ";", "}", "//display the output", "return", "curl_exec", "(", "$", "ch", ")", ";", "}" ]
proxies request and responds It will proxy both GET and POST data and return respose @servable true e.g. SITE_URL/proxy/get/http://someothersite?test=rest&ff=gg
[ "proxies", "request", "and", "responds" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Controller/HTTP/Proxy.php#L77-L142
surebert/surebert-framework
src/sb/Controller/HTTP/Proxy.php
Proxy.headerCallBack
protected function headerCallBack($ch, $data){ if (!is_null($data)) { if (preg_match("~^HTTP/.*? 404~", $data)) { header(trim($data)); while (ob_get_level() > 0) { ob_end_flush(); } } if (preg_match("~^Content-disposition~", $data)) { header(str_replace("filename=", 'filename="', trim($data)) . '"'); while (ob_get_level() > 0) { ob_end_flush(); } } if (preg_match("~^Content-Type~i", $data)) { header(trim($data)); while (ob_get_level() > 0) { ob_end_flush(); } } } return strlen($data); //This means that we handled it, so cURL will keep processing }
php
protected function headerCallBack($ch, $data){ if (!is_null($data)) { if (preg_match("~^HTTP/.*? 404~", $data)) { header(trim($data)); while (ob_get_level() > 0) { ob_end_flush(); } } if (preg_match("~^Content-disposition~", $data)) { header(str_replace("filename=", 'filename="', trim($data)) . '"'); while (ob_get_level() > 0) { ob_end_flush(); } } if (preg_match("~^Content-Type~i", $data)) { header(trim($data)); while (ob_get_level() > 0) { ob_end_flush(); } } } return strlen($data); //This means that we handled it, so cURL will keep processing }
[ "protected", "function", "headerCallBack", "(", "$", "ch", ",", "$", "data", ")", "{", "if", "(", "!", "is_null", "(", "$", "data", ")", ")", "{", "if", "(", "preg_match", "(", "\"~^HTTP/.*? 404~\"", ",", "$", "data", ")", ")", "{", "header", "(", "trim", "(", "$", "data", ")", ")", ";", "while", "(", "ob_get_level", "(", ")", ">", "0", ")", "{", "ob_end_flush", "(", ")", ";", "}", "}", "if", "(", "preg_match", "(", "\"~^Content-disposition~\"", ",", "$", "data", ")", ")", "{", "header", "(", "str_replace", "(", "\"filename=\"", ",", "'filename=\"'", ",", "trim", "(", "$", "data", ")", ")", ".", "'\"'", ")", ";", "while", "(", "ob_get_level", "(", ")", ">", "0", ")", "{", "ob_end_flush", "(", ")", ";", "}", "}", "if", "(", "preg_match", "(", "\"~^Content-Type~i\"", ",", "$", "data", ")", ")", "{", "header", "(", "trim", "(", "$", "data", ")", ")", ";", "while", "(", "ob_get_level", "(", ")", ">", "0", ")", "{", "ob_end_flush", "(", ")", ";", "}", "}", "}", "return", "strlen", "(", "$", "data", ")", ";", "//This means that we handled it, so cURL will keep processing", "}" ]
Called to process headers from URL being proxied @param resource $ch The curl connection @param string $data The header data @return int length of the data from header
[ "Called", "to", "process", "headers", "from", "URL", "being", "proxied" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Controller/HTTP/Proxy.php#L150-L176
eghojansu/moe
src/tools/web/OpenID.php
OpenID.discover
protected function discover($proxy) { // Normalize if (!preg_match('/https?:\/\//i',$this->args['identity'])) $this->args['identity']='http://'.$this->args['identity']; $url=parse_url($this->args['identity']); // Remove fragment; reconnect parts $this->args['identity']=$url['scheme'].'://'. (isset($url['user'])? ($url['user']. (isset($url['pass'])?(':'.$url['pass']):'').'@'):''). strtolower($url['host']).(isset($url['path'])?$url['path']:'/'). (isset($url['query'])?('?'.$url['query']):''); // HTML-based discovery of OpenID provider $req=Web::instance()-> request($this->args['identity'],array('proxy'=>$proxy)); if (!$req) return FALSE; $type=array_values(preg_grep('/Content-Type:/',$req['headers'])); if ($type && preg_match('/application\/xrds\+xml|text\/xml/',$type[0]) && ($sxml=simplexml_load_string($req['body'])) && ($xrds=json_decode(json_encode($sxml),TRUE)) && isset($xrds['XRD'])) { // XRDS document $svc=$xrds['XRD']['Service']; if (isset($svc[0])) $svc=$svc[0]; if (preg_grep('/http:\/\/specs\.openid\.net\/auth\/2.0\/'. '(?:server|signon)/',$svc['Type'])) { $this->args['provider']=$svc['URI']; if (isset($svc['LocalID'])) $this->args['localidentity']=$svc['LocalID']; elseif (isset($svc['CanonicalID'])) $this->args['localidentity']=$svc['CanonicalID']; } $this->args['server']=$svc['URI']; if (isset($svc['Delegate'])) $this->args['delegate']=$svc['Delegate']; } else { $len=strlen($req['body']); $ptr=0; // Parse document while ($ptr<$len) if (preg_match( '/^<link\b((?:\h+\w+\h*=\h*'. '(?:"(?:.+?)"|\'(?:.+?)\'))*)\h*\/?>/is', substr($req['body'],$ptr),$parts)) { if ($parts[1] && // Process attributes preg_match_all('/\b(rel|href)\h*=\h*'. '(?:"(.+?)"|\'(.+?)\')/s',$parts[1],$attr, PREG_SET_ORDER)) { $node=array(); foreach ($attr as $kv) $node[$kv[1]]=isset($kv[2])?$kv[2]:$kv[3]; if (isset($node['rel']) && preg_match('/openid2?\.(\w+)/', $node['rel'],$var) && isset($node['href'])) $this->args[$var[1]]=$node['href']; } $ptr+=strlen($parts[0]); } else $ptr++; } // Get OpenID provider's endpoint URL if (isset($this->args['provider'])) { // OpenID 2.0 $this->args['ns']='http://specs.openid.net/auth/2.0'; if (isset($this->args['localidentity'])) $this->args['identity']=$this->args['localidentity']; if (isset($this->args['trust_root'])) $this->args['realm']=$this->args['trust_root']; } elseif (isset($this->args['server'])) { // OpenID 1.1 $this->args['ns']='http://openid.net/signon/1.1'; if (isset($this->args['delegate'])) $this->args['identity']=$this->args['delegate']; } if (isset($this->args['provider'])) { // OpenID 2.0 if (empty($this->args['claimed_id'])) $this->args['claimed_id']=$this->args['identity']; return $this->args['provider']; } elseif (isset($this->args['server'])) // OpenID 1.1 return $this->args['server']; else return FALSE; }
php
protected function discover($proxy) { // Normalize if (!preg_match('/https?:\/\//i',$this->args['identity'])) $this->args['identity']='http://'.$this->args['identity']; $url=parse_url($this->args['identity']); // Remove fragment; reconnect parts $this->args['identity']=$url['scheme'].'://'. (isset($url['user'])? ($url['user']. (isset($url['pass'])?(':'.$url['pass']):'').'@'):''). strtolower($url['host']).(isset($url['path'])?$url['path']:'/'). (isset($url['query'])?('?'.$url['query']):''); // HTML-based discovery of OpenID provider $req=Web::instance()-> request($this->args['identity'],array('proxy'=>$proxy)); if (!$req) return FALSE; $type=array_values(preg_grep('/Content-Type:/',$req['headers'])); if ($type && preg_match('/application\/xrds\+xml|text\/xml/',$type[0]) && ($sxml=simplexml_load_string($req['body'])) && ($xrds=json_decode(json_encode($sxml),TRUE)) && isset($xrds['XRD'])) { // XRDS document $svc=$xrds['XRD']['Service']; if (isset($svc[0])) $svc=$svc[0]; if (preg_grep('/http:\/\/specs\.openid\.net\/auth\/2.0\/'. '(?:server|signon)/',$svc['Type'])) { $this->args['provider']=$svc['URI']; if (isset($svc['LocalID'])) $this->args['localidentity']=$svc['LocalID']; elseif (isset($svc['CanonicalID'])) $this->args['localidentity']=$svc['CanonicalID']; } $this->args['server']=$svc['URI']; if (isset($svc['Delegate'])) $this->args['delegate']=$svc['Delegate']; } else { $len=strlen($req['body']); $ptr=0; // Parse document while ($ptr<$len) if (preg_match( '/^<link\b((?:\h+\w+\h*=\h*'. '(?:"(?:.+?)"|\'(?:.+?)\'))*)\h*\/?>/is', substr($req['body'],$ptr),$parts)) { if ($parts[1] && // Process attributes preg_match_all('/\b(rel|href)\h*=\h*'. '(?:"(.+?)"|\'(.+?)\')/s',$parts[1],$attr, PREG_SET_ORDER)) { $node=array(); foreach ($attr as $kv) $node[$kv[1]]=isset($kv[2])?$kv[2]:$kv[3]; if (isset($node['rel']) && preg_match('/openid2?\.(\w+)/', $node['rel'],$var) && isset($node['href'])) $this->args[$var[1]]=$node['href']; } $ptr+=strlen($parts[0]); } else $ptr++; } // Get OpenID provider's endpoint URL if (isset($this->args['provider'])) { // OpenID 2.0 $this->args['ns']='http://specs.openid.net/auth/2.0'; if (isset($this->args['localidentity'])) $this->args['identity']=$this->args['localidentity']; if (isset($this->args['trust_root'])) $this->args['realm']=$this->args['trust_root']; } elseif (isset($this->args['server'])) { // OpenID 1.1 $this->args['ns']='http://openid.net/signon/1.1'; if (isset($this->args['delegate'])) $this->args['identity']=$this->args['delegate']; } if (isset($this->args['provider'])) { // OpenID 2.0 if (empty($this->args['claimed_id'])) $this->args['claimed_id']=$this->args['identity']; return $this->args['provider']; } elseif (isset($this->args['server'])) // OpenID 1.1 return $this->args['server']; else return FALSE; }
[ "protected", "function", "discover", "(", "$", "proxy", ")", "{", "// Normalize", "if", "(", "!", "preg_match", "(", "'/https?:\\/\\//i'", ",", "$", "this", "->", "args", "[", "'identity'", "]", ")", ")", "$", "this", "->", "args", "[", "'identity'", "]", "=", "'http://'", ".", "$", "this", "->", "args", "[", "'identity'", "]", ";", "$", "url", "=", "parse_url", "(", "$", "this", "->", "args", "[", "'identity'", "]", ")", ";", "// Remove fragment; reconnect parts", "$", "this", "->", "args", "[", "'identity'", "]", "=", "$", "url", "[", "'scheme'", "]", ".", "'://'", ".", "(", "isset", "(", "$", "url", "[", "'user'", "]", ")", "?", "(", "$", "url", "[", "'user'", "]", ".", "(", "isset", "(", "$", "url", "[", "'pass'", "]", ")", "?", "(", "':'", ".", "$", "url", "[", "'pass'", "]", ")", ":", "''", ")", ".", "'@'", ")", ":", "''", ")", ".", "strtolower", "(", "$", "url", "[", "'host'", "]", ")", ".", "(", "isset", "(", "$", "url", "[", "'path'", "]", ")", "?", "$", "url", "[", "'path'", "]", ":", "'/'", ")", ".", "(", "isset", "(", "$", "url", "[", "'query'", "]", ")", "?", "(", "'?'", ".", "$", "url", "[", "'query'", "]", ")", ":", "''", ")", ";", "// HTML-based discovery of OpenID provider", "$", "req", "=", "Web", "::", "instance", "(", ")", "->", "request", "(", "$", "this", "->", "args", "[", "'identity'", "]", ",", "array", "(", "'proxy'", "=>", "$", "proxy", ")", ")", ";", "if", "(", "!", "$", "req", ")", "return", "FALSE", ";", "$", "type", "=", "array_values", "(", "preg_grep", "(", "'/Content-Type:/'", ",", "$", "req", "[", "'headers'", "]", ")", ")", ";", "if", "(", "$", "type", "&&", "preg_match", "(", "'/application\\/xrds\\+xml|text\\/xml/'", ",", "$", "type", "[", "0", "]", ")", "&&", "(", "$", "sxml", "=", "simplexml_load_string", "(", "$", "req", "[", "'body'", "]", ")", ")", "&&", "(", "$", "xrds", "=", "json_decode", "(", "json_encode", "(", "$", "sxml", ")", ",", "TRUE", ")", ")", "&&", "isset", "(", "$", "xrds", "[", "'XRD'", "]", ")", ")", "{", "// XRDS document", "$", "svc", "=", "$", "xrds", "[", "'XRD'", "]", "[", "'Service'", "]", ";", "if", "(", "isset", "(", "$", "svc", "[", "0", "]", ")", ")", "$", "svc", "=", "$", "svc", "[", "0", "]", ";", "if", "(", "preg_grep", "(", "'/http:\\/\\/specs\\.openid\\.net\\/auth\\/2.0\\/'", ".", "'(?:server|signon)/'", ",", "$", "svc", "[", "'Type'", "]", ")", ")", "{", "$", "this", "->", "args", "[", "'provider'", "]", "=", "$", "svc", "[", "'URI'", "]", ";", "if", "(", "isset", "(", "$", "svc", "[", "'LocalID'", "]", ")", ")", "$", "this", "->", "args", "[", "'localidentity'", "]", "=", "$", "svc", "[", "'LocalID'", "]", ";", "elseif", "(", "isset", "(", "$", "svc", "[", "'CanonicalID'", "]", ")", ")", "$", "this", "->", "args", "[", "'localidentity'", "]", "=", "$", "svc", "[", "'CanonicalID'", "]", ";", "}", "$", "this", "->", "args", "[", "'server'", "]", "=", "$", "svc", "[", "'URI'", "]", ";", "if", "(", "isset", "(", "$", "svc", "[", "'Delegate'", "]", ")", ")", "$", "this", "->", "args", "[", "'delegate'", "]", "=", "$", "svc", "[", "'Delegate'", "]", ";", "}", "else", "{", "$", "len", "=", "strlen", "(", "$", "req", "[", "'body'", "]", ")", ";", "$", "ptr", "=", "0", ";", "// Parse document", "while", "(", "$", "ptr", "<", "$", "len", ")", "if", "(", "preg_match", "(", "'/^<link\\b((?:\\h+\\w+\\h*=\\h*'", ".", "'(?:\"(?:.+?)\"|\\'(?:.+?)\\'))*)\\h*\\/?>/is'", ",", "substr", "(", "$", "req", "[", "'body'", "]", ",", "$", "ptr", ")", ",", "$", "parts", ")", ")", "{", "if", "(", "$", "parts", "[", "1", "]", "&&", "// Process attributes", "preg_match_all", "(", "'/\\b(rel|href)\\h*=\\h*'", ".", "'(?:\"(.+?)\"|\\'(.+?)\\')/s'", ",", "$", "parts", "[", "1", "]", ",", "$", "attr", ",", "PREG_SET_ORDER", ")", ")", "{", "$", "node", "=", "array", "(", ")", ";", "foreach", "(", "$", "attr", "as", "$", "kv", ")", "$", "node", "[", "$", "kv", "[", "1", "]", "]", "=", "isset", "(", "$", "kv", "[", "2", "]", ")", "?", "$", "kv", "[", "2", "]", ":", "$", "kv", "[", "3", "]", ";", "if", "(", "isset", "(", "$", "node", "[", "'rel'", "]", ")", "&&", "preg_match", "(", "'/openid2?\\.(\\w+)/'", ",", "$", "node", "[", "'rel'", "]", ",", "$", "var", ")", "&&", "isset", "(", "$", "node", "[", "'href'", "]", ")", ")", "$", "this", "->", "args", "[", "$", "var", "[", "1", "]", "]", "=", "$", "node", "[", "'href'", "]", ";", "}", "$", "ptr", "+=", "strlen", "(", "$", "parts", "[", "0", "]", ")", ";", "}", "else", "$", "ptr", "++", ";", "}", "// Get OpenID provider's endpoint URL", "if", "(", "isset", "(", "$", "this", "->", "args", "[", "'provider'", "]", ")", ")", "{", "// OpenID 2.0", "$", "this", "->", "args", "[", "'ns'", "]", "=", "'http://specs.openid.net/auth/2.0'", ";", "if", "(", "isset", "(", "$", "this", "->", "args", "[", "'localidentity'", "]", ")", ")", "$", "this", "->", "args", "[", "'identity'", "]", "=", "$", "this", "->", "args", "[", "'localidentity'", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "args", "[", "'trust_root'", "]", ")", ")", "$", "this", "->", "args", "[", "'realm'", "]", "=", "$", "this", "->", "args", "[", "'trust_root'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "this", "->", "args", "[", "'server'", "]", ")", ")", "{", "// OpenID 1.1", "$", "this", "->", "args", "[", "'ns'", "]", "=", "'http://openid.net/signon/1.1'", ";", "if", "(", "isset", "(", "$", "this", "->", "args", "[", "'delegate'", "]", ")", ")", "$", "this", "->", "args", "[", "'identity'", "]", "=", "$", "this", "->", "args", "[", "'delegate'", "]", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "args", "[", "'provider'", "]", ")", ")", "{", "// OpenID 2.0", "if", "(", "empty", "(", "$", "this", "->", "args", "[", "'claimed_id'", "]", ")", ")", "$", "this", "->", "args", "[", "'claimed_id'", "]", "=", "$", "this", "->", "args", "[", "'identity'", "]", ";", "return", "$", "this", "->", "args", "[", "'provider'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "this", "->", "args", "[", "'server'", "]", ")", ")", "// OpenID 1.1", "return", "$", "this", "->", "args", "[", "'server'", "]", ";", "else", "return", "FALSE", ";", "}" ]
Determine OpenID provider @return string|FALSE @param $proxy string
[ "Determine", "OpenID", "provider" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/tools/web/OpenID.php#L23-L117
eghojansu/moe
src/tools/web/OpenID.php
OpenID.auth
function auth($proxy=NULL,$attr=array(),array $reqd=NULL) { $fw=Base::instance(); $root=$fw->get('SCHEME').'://'.$fw->get('HOST'); if (empty($this->args['trust_root'])) $this->args['trust_root']=$root.$fw->get('BASE').'/'; if (empty($this->args['return_to'])) $this->args['return_to']=$root.$_SERVER['REQUEST_URI']; $this->args['mode']='checkid_setup'; if ($this->url=$this->discover($proxy)) { if ($attr) { $this->args['ns.ax']='http://openid.net/srv/ax/1.0'; $this->args['ax.mode']='fetch_request'; foreach ($attr as $key=>$val) $this->args['ax.type.'.$key]=$val; $this->args['ax.required']=is_string($reqd)? $reqd:implode(',',$reqd); } $var=array(); foreach ($this->args as $key=>$val) $var['openid.'.$key]=$val; $fw->reroute($this->url.'?'.http_build_query($var)); } return FALSE; }
php
function auth($proxy=NULL,$attr=array(),array $reqd=NULL) { $fw=Base::instance(); $root=$fw->get('SCHEME').'://'.$fw->get('HOST'); if (empty($this->args['trust_root'])) $this->args['trust_root']=$root.$fw->get('BASE').'/'; if (empty($this->args['return_to'])) $this->args['return_to']=$root.$_SERVER['REQUEST_URI']; $this->args['mode']='checkid_setup'; if ($this->url=$this->discover($proxy)) { if ($attr) { $this->args['ns.ax']='http://openid.net/srv/ax/1.0'; $this->args['ax.mode']='fetch_request'; foreach ($attr as $key=>$val) $this->args['ax.type.'.$key]=$val; $this->args['ax.required']=is_string($reqd)? $reqd:implode(',',$reqd); } $var=array(); foreach ($this->args as $key=>$val) $var['openid.'.$key]=$val; $fw->reroute($this->url.'?'.http_build_query($var)); } return FALSE; }
[ "function", "auth", "(", "$", "proxy", "=", "NULL", ",", "$", "attr", "=", "array", "(", ")", ",", "array", "$", "reqd", "=", "NULL", ")", "{", "$", "fw", "=", "Base", "::", "instance", "(", ")", ";", "$", "root", "=", "$", "fw", "->", "get", "(", "'SCHEME'", ")", ".", "'://'", ".", "$", "fw", "->", "get", "(", "'HOST'", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "args", "[", "'trust_root'", "]", ")", ")", "$", "this", "->", "args", "[", "'trust_root'", "]", "=", "$", "root", ".", "$", "fw", "->", "get", "(", "'BASE'", ")", ".", "'/'", ";", "if", "(", "empty", "(", "$", "this", "->", "args", "[", "'return_to'", "]", ")", ")", "$", "this", "->", "args", "[", "'return_to'", "]", "=", "$", "root", ".", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ";", "$", "this", "->", "args", "[", "'mode'", "]", "=", "'checkid_setup'", ";", "if", "(", "$", "this", "->", "url", "=", "$", "this", "->", "discover", "(", "$", "proxy", ")", ")", "{", "if", "(", "$", "attr", ")", "{", "$", "this", "->", "args", "[", "'ns.ax'", "]", "=", "'http://openid.net/srv/ax/1.0'", ";", "$", "this", "->", "args", "[", "'ax.mode'", "]", "=", "'fetch_request'", ";", "foreach", "(", "$", "attr", "as", "$", "key", "=>", "$", "val", ")", "$", "this", "->", "args", "[", "'ax.type.'", ".", "$", "key", "]", "=", "$", "val", ";", "$", "this", "->", "args", "[", "'ax.required'", "]", "=", "is_string", "(", "$", "reqd", ")", "?", "$", "reqd", ":", "implode", "(", "','", ",", "$", "reqd", ")", ";", "}", "$", "var", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "args", "as", "$", "key", "=>", "$", "val", ")", "$", "var", "[", "'openid.'", ".", "$", "key", "]", "=", "$", "val", ";", "$", "fw", "->", "reroute", "(", "$", "this", "->", "url", ".", "'?'", ".", "http_build_query", "(", "$", "var", ")", ")", ";", "}", "return", "FALSE", ";", "}" ]
Initiate OpenID authentication sequence; Return FALSE on failure or redirect to OpenID provider URL @return bool @param $proxy string @param $attr array @param $reqd string|array
[ "Initiate", "OpenID", "authentication", "sequence", ";", "Return", "FALSE", "on", "failure", "or", "redirect", "to", "OpenID", "provider", "URL" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/tools/web/OpenID.php#L127-L150
Isset/pushnotification
src/PushNotification/Type/Apple/AppleConnection.php
AppleConnection.getResponseData
public function getResponseData(): Response { $connectionResponse = new ConnectionResponseImpl(); $errorResponse = $this->streamSocket->read(); if ($errorResponse !== null) { $this->getLogger()->error('Send error: ' . $errorResponse); $this->streamSocket->disconnect(); $response = @unpack('Ccommand/Cstatus/Nidentifier', $errorResponse); if (!empty($response)) { $connectionResponse->setErrorResponse($response); } else { $connectionResponse->setErrorResponse(null); } } return $connectionResponse; }
php
public function getResponseData(): Response { $connectionResponse = new ConnectionResponseImpl(); $errorResponse = $this->streamSocket->read(); if ($errorResponse !== null) { $this->getLogger()->error('Send error: ' . $errorResponse); $this->streamSocket->disconnect(); $response = @unpack('Ccommand/Cstatus/Nidentifier', $errorResponse); if (!empty($response)) { $connectionResponse->setErrorResponse($response); } else { $connectionResponse->setErrorResponse(null); } } return $connectionResponse; }
[ "public", "function", "getResponseData", "(", ")", ":", "Response", "{", "$", "connectionResponse", "=", "new", "ConnectionResponseImpl", "(", ")", ";", "$", "errorResponse", "=", "$", "this", "->", "streamSocket", "->", "read", "(", ")", ";", "if", "(", "$", "errorResponse", "!==", "null", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "error", "(", "'Send error: '", ".", "$", "errorResponse", ")", ";", "$", "this", "->", "streamSocket", "->", "disconnect", "(", ")", ";", "$", "response", "=", "@", "unpack", "(", "'Ccommand/Cstatus/Nidentifier'", ",", "$", "errorResponse", ")", ";", "if", "(", "!", "empty", "(", "$", "response", ")", ")", "{", "$", "connectionResponse", "->", "setErrorResponse", "(", "$", "response", ")", ";", "}", "else", "{", "$", "connectionResponse", "->", "setErrorResponse", "(", "null", ")", ";", "}", "}", "return", "$", "connectionResponse", ";", "}" ]
@throws ConnectionHandlerException @return Response
[ "@throws", "ConnectionHandlerException" ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Type/Apple/AppleConnection.php#L86-L102
Isset/pushnotification
src/PushNotification/Type/Apple/AppleConnection.php
AppleConnection.send
public function send(Message $message) { /* @var AppleMessage $message */ $buildMessage = $this->buildMessage($message); $this->streamSocket->connect(); $bytesSend = $this->streamSocket->write($buildMessage); if (strlen($buildMessage) !== $bytesSend) { $this->streamSocket->disconnect(); throw new ConnectionExceptionImpl(); } usleep(self::SEND_INTERVAL); }
php
public function send(Message $message) { /* @var AppleMessage $message */ $buildMessage = $this->buildMessage($message); $this->streamSocket->connect(); $bytesSend = $this->streamSocket->write($buildMessage); if (strlen($buildMessage) !== $bytesSend) { $this->streamSocket->disconnect(); throw new ConnectionExceptionImpl(); } usleep(self::SEND_INTERVAL); }
[ "public", "function", "send", "(", "Message", "$", "message", ")", "{", "/* @var AppleMessage $message */", "$", "buildMessage", "=", "$", "this", "->", "buildMessage", "(", "$", "message", ")", ";", "$", "this", "->", "streamSocket", "->", "connect", "(", ")", ";", "$", "bytesSend", "=", "$", "this", "->", "streamSocket", "->", "write", "(", "$", "buildMessage", ")", ";", "if", "(", "strlen", "(", "$", "buildMessage", ")", "!==", "$", "bytesSend", ")", "{", "$", "this", "->", "streamSocket", "->", "disconnect", "(", ")", ";", "throw", "new", "ConnectionExceptionImpl", "(", ")", ";", "}", "usleep", "(", "self", "::", "SEND_INTERVAL", ")", ";", "}" ]
Send a message without waiting on response. @param Message $message @throws ConnectionException @throws ConnectionHandlerException
[ "Send", "a", "message", "without", "waiting", "on", "response", "." ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Type/Apple/AppleConnection.php#L112-L123
Isset/pushnotification
src/PushNotification/Type/Apple/AppleConnection.php
AppleConnection.buildMessage
private function buildMessage(AppleMessage $message): string { $jsonMessage = json_encode($message->getMessage()); $jsonMessageLength = strlen($jsonMessage); $payload = pack( 'CNNnH*n', self::COMMAND, $message->getIdentifier(), $message->getExpiresAt(), self::TOKEN_SIZE, $message->getDeviceToken(), $jsonMessageLength ); $payload .= $jsonMessage; return $payload; }
php
private function buildMessage(AppleMessage $message): string { $jsonMessage = json_encode($message->getMessage()); $jsonMessageLength = strlen($jsonMessage); $payload = pack( 'CNNnH*n', self::COMMAND, $message->getIdentifier(), $message->getExpiresAt(), self::TOKEN_SIZE, $message->getDeviceToken(), $jsonMessageLength ); $payload .= $jsonMessage; return $payload; }
[ "private", "function", "buildMessage", "(", "AppleMessage", "$", "message", ")", ":", "string", "{", "$", "jsonMessage", "=", "json_encode", "(", "$", "message", "->", "getMessage", "(", ")", ")", ";", "$", "jsonMessageLength", "=", "strlen", "(", "$", "jsonMessage", ")", ";", "$", "payload", "=", "pack", "(", "'CNNnH*n'", ",", "self", "::", "COMMAND", ",", "$", "message", "->", "getIdentifier", "(", ")", ",", "$", "message", "->", "getExpiresAt", "(", ")", ",", "self", "::", "TOKEN_SIZE", ",", "$", "message", "->", "getDeviceToken", "(", ")", ",", "$", "jsonMessageLength", ")", ";", "$", "payload", ".=", "$", "jsonMessage", ";", "return", "$", "payload", ";", "}" ]
@param AppleMessage $message @return string
[ "@param", "AppleMessage", "$message" ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Type/Apple/AppleConnection.php#L146-L164
nabab/bbn
src/bbn/appui/dbsync.php
dbsync.check
public static function check(){ return ( \is_object(self::$db) && \is_object(self::$dbs) && self::$db->check() && self::$dbs->check() ); }
php
public static function check(){ return ( \is_object(self::$db) && \is_object(self::$dbs) && self::$db->check() && self::$dbs->check() ); }
[ "public", "static", "function", "check", "(", ")", "{", "return", "(", "\\", "is_object", "(", "self", "::", "$", "db", ")", "&&", "\\", "is_object", "(", "self", "::", "$", "dbs", ")", "&&", "self", "::", "$", "db", "->", "check", "(", ")", "&&", "self", "::", "$", "dbs", "->", "check", "(", ")", ")", ";", "}" ]
Checks if the initialization has been all right @return bool
[ "Checks", "if", "the", "initialization", "has", "been", "all", "right" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/dbsync.php#L154-L156
nabab/bbn
src/bbn/appui/dbsync.php
dbsync.trigger
public static function trigger(array $cfg){ self::first_call(); if ( !isset($cfg['run']) ){ $cfg['run'] = 1; } if ( !isset($cfg['trig']) ){ $cfg['run'] = 1; } if ( !self::$disabled && self::check() && (count($cfg['tables']) === 1) && ($table = self::$db->tfn(current($cfg['tables']))) && \in_array($table, self::$tables, true) ){ if ( $cfg['moment'] === 'after' ){ // Case where we actually delete or restore through the $hcol column $values = []; if ( !empty($cfg['fields']) && !empty($cfg['values']) ){ foreach ( $cfg['fields'] as $i => $f ){ $values[$f] = $cfg['values'][$i]; } } self::$dbs->insert(self::$dbs_table, [ 'db' => self::$db->current, 'tab' => self::$db->tsn($table), 'action' => $cfg['kind'], 'chrono' => microtime(true), 'rows' => empty($cfg['where']) ? '[]' : bbn\x::json_base64_encode($cfg['where']), 'vals' => empty($values) ? '[]' : bbn\x::json_base64_encode($values) ]); } } return $cfg; }
php
public static function trigger(array $cfg){ self::first_call(); if ( !isset($cfg['run']) ){ $cfg['run'] = 1; } if ( !isset($cfg['trig']) ){ $cfg['run'] = 1; } if ( !self::$disabled && self::check() && (count($cfg['tables']) === 1) && ($table = self::$db->tfn(current($cfg['tables']))) && \in_array($table, self::$tables, true) ){ if ( $cfg['moment'] === 'after' ){ // Case where we actually delete or restore through the $hcol column $values = []; if ( !empty($cfg['fields']) && !empty($cfg['values']) ){ foreach ( $cfg['fields'] as $i => $f ){ $values[$f] = $cfg['values'][$i]; } } self::$dbs->insert(self::$dbs_table, [ 'db' => self::$db->current, 'tab' => self::$db->tsn($table), 'action' => $cfg['kind'], 'chrono' => microtime(true), 'rows' => empty($cfg['where']) ? '[]' : bbn\x::json_base64_encode($cfg['where']), 'vals' => empty($values) ? '[]' : bbn\x::json_base64_encode($values) ]); } } return $cfg; }
[ "public", "static", "function", "trigger", "(", "array", "$", "cfg", ")", "{", "self", "::", "first_call", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "cfg", "[", "'run'", "]", ")", ")", "{", "$", "cfg", "[", "'run'", "]", "=", "1", ";", "}", "if", "(", "!", "isset", "(", "$", "cfg", "[", "'trig'", "]", ")", ")", "{", "$", "cfg", "[", "'run'", "]", "=", "1", ";", "}", "if", "(", "!", "self", "::", "$", "disabled", "&&", "self", "::", "check", "(", ")", "&&", "(", "count", "(", "$", "cfg", "[", "'tables'", "]", ")", "===", "1", ")", "&&", "(", "$", "table", "=", "self", "::", "$", "db", "->", "tfn", "(", "current", "(", "$", "cfg", "[", "'tables'", "]", ")", ")", ")", "&&", "\\", "in_array", "(", "$", "table", ",", "self", "::", "$", "tables", ",", "true", ")", ")", "{", "if", "(", "$", "cfg", "[", "'moment'", "]", "===", "'after'", ")", "{", "// Case where we actually delete or restore through the $hcol column", "$", "values", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "cfg", "[", "'fields'", "]", ")", "&&", "!", "empty", "(", "$", "cfg", "[", "'values'", "]", ")", ")", "{", "foreach", "(", "$", "cfg", "[", "'fields'", "]", "as", "$", "i", "=>", "$", "f", ")", "{", "$", "values", "[", "$", "f", "]", "=", "$", "cfg", "[", "'values'", "]", "[", "$", "i", "]", ";", "}", "}", "self", "::", "$", "dbs", "->", "insert", "(", "self", "::", "$", "dbs_table", ",", "[", "'db'", "=>", "self", "::", "$", "db", "->", "current", ",", "'tab'", "=>", "self", "::", "$", "db", "->", "tsn", "(", "$", "table", ")", ",", "'action'", "=>", "$", "cfg", "[", "'kind'", "]", ",", "'chrono'", "=>", "microtime", "(", "true", ")", ",", "'rows'", "=>", "empty", "(", "$", "cfg", "[", "'where'", "]", ")", "?", "'[]'", ":", "bbn", "\\", "x", "::", "json_base64_encode", "(", "$", "cfg", "[", "'where'", "]", ")", ",", "'vals'", "=>", "empty", "(", "$", "values", ")", "?", "'[]'", ":", "bbn", "\\", "x", "::", "json_base64_encode", "(", "$", "values", ")", "]", ")", ";", "}", "}", "return", "$", "cfg", ";", "}" ]
Gets all information about a given table @param array $cfg Configuration array @return array Resulting configuration
[ "Gets", "all", "information", "about", "a", "given", "table" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/dbsync.php#L172-L205
nabab/bbn
src/bbn/appui/dbsync.php
dbsync.sync
public static function sync(bbn\db $db, $dbs='', $dbs_table='', $num_try = 0){ if ( !$num_try ){ self::def($dbs, $dbs_table); self::first_call(); self::disable(); $mode_db = self::$db->get_error_mode(); $mode_dbs = self::$dbs->get_error_mode(); self::$db->set_error_mode("continue"); self::$dbs->set_error_mode("continue"); } $num_try++; $to_log = [ 'deleted_sync' => 0, 'deleted_real' => 0, 'updated_sync' => 0, 'updated_real' => 0, 'inserted_sync' => 0, 'inserted_real' => 0, 'num_problems' => 0, 'problems' => [] ]; $retry = false; $start = ( $test = self::$dbs->get_one(" SELECT MIN(chrono) FROM ".self::$dbs->escape(self::$dbs_table)." WHERE db NOT LIKE ? AND state = 0", self::$db->current) ) ? $test : time(); // Deleting the entries prior to this sync we produced and have been seen by the twin process $to_log['deleted_sync'] = self::$dbs->delete(self::$dbs_table, [ ['db', '=', self::$db->current], ['state', '=', 1], ['chrono', '<', $start] ]); // Selecting the entries inserted $ds = self::$dbs->rselect_all(self::$dbs_table, ['id', 'tab', 'vals', 'chrono'], [ ['db', '!=', self::$db->current], ['state', '=', 0], ['action', '=', 'insert'] ], [ 'chrono' => 'ASC', 'id' => 'ASC' ]); // They just have to be inserted foreach ( $ds as $i => $d ){ if ( isset(self::$methods['cbf1']) ){ self::cbf1($d); } $vals = \bbn\x::json_base64_decode($d['vals']); if ( !\is_array($vals) ){ $to_log['num_problems']++; $to_log['problems'][] = "Hey, look urgently at the row $d[id]!"; } else if ( self::$db->insert($d['tab'], $vals) ){ if ( isset(self::$methods['cbf2']) ){ self::cbf2($d); } $to_log['inserted_sync']++; self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); } else if ( self::$db->select($d['tab'], [], $vals) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); } else{ if ( $num_try > self::$max_retry ){ $to_log['num_problems']++; $to_log['problems'][] = "Problem while syncing (insert), check data with status 5 and ID ".$d['id']; self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]); } $retry = 1; } } // Selecting the entries modified and deleted in the twin DB, // ordered by table and rows (so the same go together) $ds = self::$dbs->rselect_all(self::$dbs_table, ['id', 'tab', 'action', 'rows', 'vals', 'chrono'], [ ['db', '!=', self::$db->current], ['state', '=', 0], ['rows', '!=', '[]'], ['action', '!=', 'insert'] ], [ 'tab' => 'ASC', 'rows' => 'ASC', 'chrono' => 'ASC', 'id' => 'ASC' ]); foreach ( $ds as $i => $d ){ // Executing the first callback $d['rows'] = bbn\x::json_base64_decode($d['rows']); $d['vals'] = bbn\x::json_base64_decode($d['vals']); if ( isset(self::$methods['cbf1']) ){ self::cbf1($d); } // Proceeding to the actions: delete is before if ( strtolower($d['action']) === 'delete' ){ if ( self::$db->delete($d['tab'], $d['rows']) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); $to_log['deleted_real']++; } else if ( !self::$db->select($d['tab'], [], $d['rows']) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); } else{ if ( $num_try > self::$max_retry ){ self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]); $to_log['num_problems']++; $to_log['problems'][] = "Problem while syncing (delete), check data with status 5 and ID ".$d['id']; } $retry = 1; } } // Checking if there is another change done to this record and when in the twin DB $next_time = ( isset($ds[$i+1]) && ($ds[$i+1]['tab'] === $d['tab']) && ($ds[$i+1]['rows'] === $d['rows']) ) ? $ds[$i+1]['chrono'] : microtime(); // Looking for the actions done on this specific record in our database // between the twin change and the next (or now if there is no other change) $each = self::$dbs->rselect_all(self::$dbs_table, ['id', 'chrono', 'action', 'vals'], [ ['db', '=', self::$db->current], ['tab', '=', $d['tab']], ['rows', '=', $d['rows']], ['chrono', '>=', $d['chrono']], ['chrono', '<', $next_time], ]); if ( \count($each) > 0 ){ $to_log['num_problems']++; $to_log['problems'][] = "Conflict!"; $to_log['problems'][] = $d; foreach ( $each as $e ){ // If it's deleted locally and updated on the twin we restore if ( strtolower($e['action']) === 'delete' ){ if ( strtolower($d['action']) === 'update' ){ if ( !self::$db->insert_update( $d['tab'], bbn\x::merge_arrays( $e['vals'], $d['vals'] )) ){ $to_log['num_problems']++; $to_log['problems'][] = "insert_update number 1 had a problem"; } } } // If it's updated locally and deleted in the twin we restore else if ( strtolower($e['action']) === 'update' ){ if ( strtolower($d['action']) === 'delete' ){ if ( !self::$db->insert_update($d['tab'], bbn\x::merge_arrays($d['vals'], $e['vals'])) ){ $to_log['num_problems']++; $to_log['problems'][] = "insert_update had a problem"; } } // If it's updated locally and in the twin we merge the values for the update else if ( strtolower($d['action']) === 'update' ){ $d['vals'] = bbn\x::merge_arrays($d['vals'], $e['vals']); } } } } // Proceeding to the actions update is after in case we needed to restore if ( strtolower($d['action']) === 'update' ){ if ( self::$db->update($d['tab'], $d['vals'], $d['rows']) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); $to_log['updated_real']++; } else if ( self::$db->select($d['tab'], [], bbn\x::merge_arrays($d['rows'], $d['vals'])) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); } else{ if ( $num_try > self::$max_retry ){ self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]); $to_log['num_problems']++; $to_log['problems'][] = "Problem while syncing (update), check data with status 5 and ID ".$d['id']; } $retry = 1; } } // Callback number 2 if ( isset(self::$methods['cbf2']) ){ self::cbf2($d); } } $res = []; foreach ( $to_log as $k => $v ){ if ( !empty($v) ){ $res[$k] = $v; } } if ( $retry && ( $num_try <= self::$max_retry ) ){ $res = bbn\x::merge_arrays($res, self::sync($db, $dbs, $dbs_table, $num_try)); } else{ self::$db->set_error_mode($mode_db); self::$dbs->set_error_mode($mode_dbs); self::enable(); } return $res; }
php
public static function sync(bbn\db $db, $dbs='', $dbs_table='', $num_try = 0){ if ( !$num_try ){ self::def($dbs, $dbs_table); self::first_call(); self::disable(); $mode_db = self::$db->get_error_mode(); $mode_dbs = self::$dbs->get_error_mode(); self::$db->set_error_mode("continue"); self::$dbs->set_error_mode("continue"); } $num_try++; $to_log = [ 'deleted_sync' => 0, 'deleted_real' => 0, 'updated_sync' => 0, 'updated_real' => 0, 'inserted_sync' => 0, 'inserted_real' => 0, 'num_problems' => 0, 'problems' => [] ]; $retry = false; $start = ( $test = self::$dbs->get_one(" SELECT MIN(chrono) FROM ".self::$dbs->escape(self::$dbs_table)." WHERE db NOT LIKE ? AND state = 0", self::$db->current) ) ? $test : time(); // Deleting the entries prior to this sync we produced and have been seen by the twin process $to_log['deleted_sync'] = self::$dbs->delete(self::$dbs_table, [ ['db', '=', self::$db->current], ['state', '=', 1], ['chrono', '<', $start] ]); // Selecting the entries inserted $ds = self::$dbs->rselect_all(self::$dbs_table, ['id', 'tab', 'vals', 'chrono'], [ ['db', '!=', self::$db->current], ['state', '=', 0], ['action', '=', 'insert'] ], [ 'chrono' => 'ASC', 'id' => 'ASC' ]); // They just have to be inserted foreach ( $ds as $i => $d ){ if ( isset(self::$methods['cbf1']) ){ self::cbf1($d); } $vals = \bbn\x::json_base64_decode($d['vals']); if ( !\is_array($vals) ){ $to_log['num_problems']++; $to_log['problems'][] = "Hey, look urgently at the row $d[id]!"; } else if ( self::$db->insert($d['tab'], $vals) ){ if ( isset(self::$methods['cbf2']) ){ self::cbf2($d); } $to_log['inserted_sync']++; self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); } else if ( self::$db->select($d['tab'], [], $vals) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); } else{ if ( $num_try > self::$max_retry ){ $to_log['num_problems']++; $to_log['problems'][] = "Problem while syncing (insert), check data with status 5 and ID ".$d['id']; self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]); } $retry = 1; } } // Selecting the entries modified and deleted in the twin DB, // ordered by table and rows (so the same go together) $ds = self::$dbs->rselect_all(self::$dbs_table, ['id', 'tab', 'action', 'rows', 'vals', 'chrono'], [ ['db', '!=', self::$db->current], ['state', '=', 0], ['rows', '!=', '[]'], ['action', '!=', 'insert'] ], [ 'tab' => 'ASC', 'rows' => 'ASC', 'chrono' => 'ASC', 'id' => 'ASC' ]); foreach ( $ds as $i => $d ){ // Executing the first callback $d['rows'] = bbn\x::json_base64_decode($d['rows']); $d['vals'] = bbn\x::json_base64_decode($d['vals']); if ( isset(self::$methods['cbf1']) ){ self::cbf1($d); } // Proceeding to the actions: delete is before if ( strtolower($d['action']) === 'delete' ){ if ( self::$db->delete($d['tab'], $d['rows']) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); $to_log['deleted_real']++; } else if ( !self::$db->select($d['tab'], [], $d['rows']) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); } else{ if ( $num_try > self::$max_retry ){ self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]); $to_log['num_problems']++; $to_log['problems'][] = "Problem while syncing (delete), check data with status 5 and ID ".$d['id']; } $retry = 1; } } // Checking if there is another change done to this record and when in the twin DB $next_time = ( isset($ds[$i+1]) && ($ds[$i+1]['tab'] === $d['tab']) && ($ds[$i+1]['rows'] === $d['rows']) ) ? $ds[$i+1]['chrono'] : microtime(); // Looking for the actions done on this specific record in our database // between the twin change and the next (or now if there is no other change) $each = self::$dbs->rselect_all(self::$dbs_table, ['id', 'chrono', 'action', 'vals'], [ ['db', '=', self::$db->current], ['tab', '=', $d['tab']], ['rows', '=', $d['rows']], ['chrono', '>=', $d['chrono']], ['chrono', '<', $next_time], ]); if ( \count($each) > 0 ){ $to_log['num_problems']++; $to_log['problems'][] = "Conflict!"; $to_log['problems'][] = $d; foreach ( $each as $e ){ // If it's deleted locally and updated on the twin we restore if ( strtolower($e['action']) === 'delete' ){ if ( strtolower($d['action']) === 'update' ){ if ( !self::$db->insert_update( $d['tab'], bbn\x::merge_arrays( $e['vals'], $d['vals'] )) ){ $to_log['num_problems']++; $to_log['problems'][] = "insert_update number 1 had a problem"; } } } // If it's updated locally and deleted in the twin we restore else if ( strtolower($e['action']) === 'update' ){ if ( strtolower($d['action']) === 'delete' ){ if ( !self::$db->insert_update($d['tab'], bbn\x::merge_arrays($d['vals'], $e['vals'])) ){ $to_log['num_problems']++; $to_log['problems'][] = "insert_update had a problem"; } } // If it's updated locally and in the twin we merge the values for the update else if ( strtolower($d['action']) === 'update' ){ $d['vals'] = bbn\x::merge_arrays($d['vals'], $e['vals']); } } } } // Proceeding to the actions update is after in case we needed to restore if ( strtolower($d['action']) === 'update' ){ if ( self::$db->update($d['tab'], $d['vals'], $d['rows']) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); $to_log['updated_real']++; } else if ( self::$db->select($d['tab'], [], bbn\x::merge_arrays($d['rows'], $d['vals'])) ){ self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]); } else{ if ( $num_try > self::$max_retry ){ self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]); $to_log['num_problems']++; $to_log['problems'][] = "Problem while syncing (update), check data with status 5 and ID ".$d['id']; } $retry = 1; } } // Callback number 2 if ( isset(self::$methods['cbf2']) ){ self::cbf2($d); } } $res = []; foreach ( $to_log as $k => $v ){ if ( !empty($v) ){ $res[$k] = $v; } } if ( $retry && ( $num_try <= self::$max_retry ) ){ $res = bbn\x::merge_arrays($res, self::sync($db, $dbs, $dbs_table, $num_try)); } else{ self::$db->set_error_mode($mode_db); self::$dbs->set_error_mode($mode_dbs); self::enable(); } return $res; }
[ "public", "static", "function", "sync", "(", "bbn", "\\", "db", "$", "db", ",", "$", "dbs", "=", "''", ",", "$", "dbs_table", "=", "''", ",", "$", "num_try", "=", "0", ")", "{", "if", "(", "!", "$", "num_try", ")", "{", "self", "::", "def", "(", "$", "dbs", ",", "$", "dbs_table", ")", ";", "self", "::", "first_call", "(", ")", ";", "self", "::", "disable", "(", ")", ";", "$", "mode_db", "=", "self", "::", "$", "db", "->", "get_error_mode", "(", ")", ";", "$", "mode_dbs", "=", "self", "::", "$", "dbs", "->", "get_error_mode", "(", ")", ";", "self", "::", "$", "db", "->", "set_error_mode", "(", "\"continue\"", ")", ";", "self", "::", "$", "dbs", "->", "set_error_mode", "(", "\"continue\"", ")", ";", "}", "$", "num_try", "++", ";", "$", "to_log", "=", "[", "'deleted_sync'", "=>", "0", ",", "'deleted_real'", "=>", "0", ",", "'updated_sync'", "=>", "0", ",", "'updated_real'", "=>", "0", ",", "'inserted_sync'", "=>", "0", ",", "'inserted_real'", "=>", "0", ",", "'num_problems'", "=>", "0", ",", "'problems'", "=>", "[", "]", "]", ";", "$", "retry", "=", "false", ";", "$", "start", "=", "(", "$", "test", "=", "self", "::", "$", "dbs", "->", "get_one", "(", "\"\n SELECT MIN(chrono)\n FROM \"", ".", "self", "::", "$", "dbs", "->", "escape", "(", "self", "::", "$", "dbs_table", ")", ".", "\"\n WHERE db NOT LIKE ?\n AND state = 0\"", ",", "self", "::", "$", "db", "->", "current", ")", ")", "?", "$", "test", ":", "time", "(", ")", ";", "// Deleting the entries prior to this sync we produced and have been seen by the twin process", "$", "to_log", "[", "'deleted_sync'", "]", "=", "self", "::", "$", "dbs", "->", "delete", "(", "self", "::", "$", "dbs_table", ",", "[", "[", "'db'", ",", "'='", ",", "self", "::", "$", "db", "->", "current", "]", ",", "[", "'state'", ",", "'='", ",", "1", "]", ",", "[", "'chrono'", ",", "'<'", ",", "$", "start", "]", "]", ")", ";", "// Selecting the entries inserted", "$", "ds", "=", "self", "::", "$", "dbs", "->", "rselect_all", "(", "self", "::", "$", "dbs_table", ",", "[", "'id'", ",", "'tab'", ",", "'vals'", ",", "'chrono'", "]", ",", "[", "[", "'db'", ",", "'!='", ",", "self", "::", "$", "db", "->", "current", "]", ",", "[", "'state'", ",", "'='", ",", "0", "]", ",", "[", "'action'", ",", "'='", ",", "'insert'", "]", "]", ",", "[", "'chrono'", "=>", "'ASC'", ",", "'id'", "=>", "'ASC'", "]", ")", ";", "// They just have to be inserted", "foreach", "(", "$", "ds", "as", "$", "i", "=>", "$", "d", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "methods", "[", "'cbf1'", "]", ")", ")", "{", "self", "::", "cbf1", "(", "$", "d", ")", ";", "}", "$", "vals", "=", "\\", "bbn", "\\", "x", "::", "json_base64_decode", "(", "$", "d", "[", "'vals'", "]", ")", ";", "if", "(", "!", "\\", "is_array", "(", "$", "vals", ")", ")", "{", "$", "to_log", "[", "'num_problems'", "]", "++", ";", "$", "to_log", "[", "'problems'", "]", "[", "]", "=", "\"Hey, look urgently at the row $d[id]!\"", ";", "}", "else", "if", "(", "self", "::", "$", "db", "->", "insert", "(", "$", "d", "[", "'tab'", "]", ",", "$", "vals", ")", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "methods", "[", "'cbf2'", "]", ")", ")", "{", "self", "::", "cbf2", "(", "$", "d", ")", ";", "}", "$", "to_log", "[", "'inserted_sync'", "]", "++", ";", "self", "::", "$", "dbs", "->", "update", "(", "self", "::", "$", "dbs_table", ",", "[", "\"state\"", "=>", "1", "]", ",", "[", "\"id\"", "=>", "$", "d", "[", "'id'", "]", "]", ")", ";", "}", "else", "if", "(", "self", "::", "$", "db", "->", "select", "(", "$", "d", "[", "'tab'", "]", ",", "[", "]", ",", "$", "vals", ")", ")", "{", "self", "::", "$", "dbs", "->", "update", "(", "self", "::", "$", "dbs_table", ",", "[", "\"state\"", "=>", "1", "]", ",", "[", "\"id\"", "=>", "$", "d", "[", "'id'", "]", "]", ")", ";", "}", "else", "{", "if", "(", "$", "num_try", ">", "self", "::", "$", "max_retry", ")", "{", "$", "to_log", "[", "'num_problems'", "]", "++", ";", "$", "to_log", "[", "'problems'", "]", "[", "]", "=", "\"Problem while syncing (insert), check data with status 5 and ID \"", ".", "$", "d", "[", "'id'", "]", ";", "self", "::", "$", "dbs", "->", "update", "(", "self", "::", "$", "dbs_table", ",", "[", "\"state\"", "=>", "5", "]", ",", "[", "\"id\"", "=>", "$", "d", "[", "'id'", "]", "]", ")", ";", "}", "$", "retry", "=", "1", ";", "}", "}", "// Selecting the entries modified and deleted in the twin DB,", "// ordered by table and rows (so the same go together)", "$", "ds", "=", "self", "::", "$", "dbs", "->", "rselect_all", "(", "self", "::", "$", "dbs_table", ",", "[", "'id'", ",", "'tab'", ",", "'action'", ",", "'rows'", ",", "'vals'", ",", "'chrono'", "]", ",", "[", "[", "'db'", ",", "'!='", ",", "self", "::", "$", "db", "->", "current", "]", ",", "[", "'state'", ",", "'='", ",", "0", "]", ",", "[", "'rows'", ",", "'!='", ",", "'[]'", "]", ",", "[", "'action'", ",", "'!='", ",", "'insert'", "]", "]", ",", "[", "'tab'", "=>", "'ASC'", ",", "'rows'", "=>", "'ASC'", ",", "'chrono'", "=>", "'ASC'", ",", "'id'", "=>", "'ASC'", "]", ")", ";", "foreach", "(", "$", "ds", "as", "$", "i", "=>", "$", "d", ")", "{", "// Executing the first callback", "$", "d", "[", "'rows'", "]", "=", "bbn", "\\", "x", "::", "json_base64_decode", "(", "$", "d", "[", "'rows'", "]", ")", ";", "$", "d", "[", "'vals'", "]", "=", "bbn", "\\", "x", "::", "json_base64_decode", "(", "$", "d", "[", "'vals'", "]", ")", ";", "if", "(", "isset", "(", "self", "::", "$", "methods", "[", "'cbf1'", "]", ")", ")", "{", "self", "::", "cbf1", "(", "$", "d", ")", ";", "}", "// Proceeding to the actions: delete is before", "if", "(", "strtolower", "(", "$", "d", "[", "'action'", "]", ")", "===", "'delete'", ")", "{", "if", "(", "self", "::", "$", "db", "->", "delete", "(", "$", "d", "[", "'tab'", "]", ",", "$", "d", "[", "'rows'", "]", ")", ")", "{", "self", "::", "$", "dbs", "->", "update", "(", "self", "::", "$", "dbs_table", ",", "[", "\"state\"", "=>", "1", "]", ",", "[", "\"id\"", "=>", "$", "d", "[", "'id'", "]", "]", ")", ";", "$", "to_log", "[", "'deleted_real'", "]", "++", ";", "}", "else", "if", "(", "!", "self", "::", "$", "db", "->", "select", "(", "$", "d", "[", "'tab'", "]", ",", "[", "]", ",", "$", "d", "[", "'rows'", "]", ")", ")", "{", "self", "::", "$", "dbs", "->", "update", "(", "self", "::", "$", "dbs_table", ",", "[", "\"state\"", "=>", "1", "]", ",", "[", "\"id\"", "=>", "$", "d", "[", "'id'", "]", "]", ")", ";", "}", "else", "{", "if", "(", "$", "num_try", ">", "self", "::", "$", "max_retry", ")", "{", "self", "::", "$", "dbs", "->", "update", "(", "self", "::", "$", "dbs_table", ",", "[", "\"state\"", "=>", "5", "]", ",", "[", "\"id\"", "=>", "$", "d", "[", "'id'", "]", "]", ")", ";", "$", "to_log", "[", "'num_problems'", "]", "++", ";", "$", "to_log", "[", "'problems'", "]", "[", "]", "=", "\"Problem while syncing (delete), check data with status 5 and ID \"", ".", "$", "d", "[", "'id'", "]", ";", "}", "$", "retry", "=", "1", ";", "}", "}", "// Checking if there is another change done to this record and when in the twin DB", "$", "next_time", "=", "(", "isset", "(", "$", "ds", "[", "$", "i", "+", "1", "]", ")", "&&", "(", "$", "ds", "[", "$", "i", "+", "1", "]", "[", "'tab'", "]", "===", "$", "d", "[", "'tab'", "]", ")", "&&", "(", "$", "ds", "[", "$", "i", "+", "1", "]", "[", "'rows'", "]", "===", "$", "d", "[", "'rows'", "]", ")", ")", "?", "$", "ds", "[", "$", "i", "+", "1", "]", "[", "'chrono'", "]", ":", "microtime", "(", ")", ";", "// Looking for the actions done on this specific record in our database", "// between the twin change and the next (or now if there is no other change)", "$", "each", "=", "self", "::", "$", "dbs", "->", "rselect_all", "(", "self", "::", "$", "dbs_table", ",", "[", "'id'", ",", "'chrono'", ",", "'action'", ",", "'vals'", "]", ",", "[", "[", "'db'", ",", "'='", ",", "self", "::", "$", "db", "->", "current", "]", ",", "[", "'tab'", ",", "'='", ",", "$", "d", "[", "'tab'", "]", "]", ",", "[", "'rows'", ",", "'='", ",", "$", "d", "[", "'rows'", "]", "]", ",", "[", "'chrono'", ",", "'>='", ",", "$", "d", "[", "'chrono'", "]", "]", ",", "[", "'chrono'", ",", "'<'", ",", "$", "next_time", "]", ",", "]", ")", ";", "if", "(", "\\", "count", "(", "$", "each", ")", ">", "0", ")", "{", "$", "to_log", "[", "'num_problems'", "]", "++", ";", "$", "to_log", "[", "'problems'", "]", "[", "]", "=", "\"Conflict!\"", ";", "$", "to_log", "[", "'problems'", "]", "[", "]", "=", "$", "d", ";", "foreach", "(", "$", "each", "as", "$", "e", ")", "{", "// If it's deleted locally and updated on the twin we restore", "if", "(", "strtolower", "(", "$", "e", "[", "'action'", "]", ")", "===", "'delete'", ")", "{", "if", "(", "strtolower", "(", "$", "d", "[", "'action'", "]", ")", "===", "'update'", ")", "{", "if", "(", "!", "self", "::", "$", "db", "->", "insert_update", "(", "$", "d", "[", "'tab'", "]", ",", "bbn", "\\", "x", "::", "merge_arrays", "(", "$", "e", "[", "'vals'", "]", ",", "$", "d", "[", "'vals'", "]", ")", ")", ")", "{", "$", "to_log", "[", "'num_problems'", "]", "++", ";", "$", "to_log", "[", "'problems'", "]", "[", "]", "=", "\"insert_update number 1 had a problem\"", ";", "}", "}", "}", "// If it's updated locally and deleted in the twin we restore", "else", "if", "(", "strtolower", "(", "$", "e", "[", "'action'", "]", ")", "===", "'update'", ")", "{", "if", "(", "strtolower", "(", "$", "d", "[", "'action'", "]", ")", "===", "'delete'", ")", "{", "if", "(", "!", "self", "::", "$", "db", "->", "insert_update", "(", "$", "d", "[", "'tab'", "]", ",", "bbn", "\\", "x", "::", "merge_arrays", "(", "$", "d", "[", "'vals'", "]", ",", "$", "e", "[", "'vals'", "]", ")", ")", ")", "{", "$", "to_log", "[", "'num_problems'", "]", "++", ";", "$", "to_log", "[", "'problems'", "]", "[", "]", "=", "\"insert_update had a problem\"", ";", "}", "}", "// If it's updated locally and in the twin we merge the values for the update", "else", "if", "(", "strtolower", "(", "$", "d", "[", "'action'", "]", ")", "===", "'update'", ")", "{", "$", "d", "[", "'vals'", "]", "=", "bbn", "\\", "x", "::", "merge_arrays", "(", "$", "d", "[", "'vals'", "]", ",", "$", "e", "[", "'vals'", "]", ")", ";", "}", "}", "}", "}", "// Proceeding to the actions update is after in case we needed to restore", "if", "(", "strtolower", "(", "$", "d", "[", "'action'", "]", ")", "===", "'update'", ")", "{", "if", "(", "self", "::", "$", "db", "->", "update", "(", "$", "d", "[", "'tab'", "]", ",", "$", "d", "[", "'vals'", "]", ",", "$", "d", "[", "'rows'", "]", ")", ")", "{", "self", "::", "$", "dbs", "->", "update", "(", "self", "::", "$", "dbs_table", ",", "[", "\"state\"", "=>", "1", "]", ",", "[", "\"id\"", "=>", "$", "d", "[", "'id'", "]", "]", ")", ";", "$", "to_log", "[", "'updated_real'", "]", "++", ";", "}", "else", "if", "(", "self", "::", "$", "db", "->", "select", "(", "$", "d", "[", "'tab'", "]", ",", "[", "]", ",", "bbn", "\\", "x", "::", "merge_arrays", "(", "$", "d", "[", "'rows'", "]", ",", "$", "d", "[", "'vals'", "]", ")", ")", ")", "{", "self", "::", "$", "dbs", "->", "update", "(", "self", "::", "$", "dbs_table", ",", "[", "\"state\"", "=>", "1", "]", ",", "[", "\"id\"", "=>", "$", "d", "[", "'id'", "]", "]", ")", ";", "}", "else", "{", "if", "(", "$", "num_try", ">", "self", "::", "$", "max_retry", ")", "{", "self", "::", "$", "dbs", "->", "update", "(", "self", "::", "$", "dbs_table", ",", "[", "\"state\"", "=>", "5", "]", ",", "[", "\"id\"", "=>", "$", "d", "[", "'id'", "]", "]", ")", ";", "$", "to_log", "[", "'num_problems'", "]", "++", ";", "$", "to_log", "[", "'problems'", "]", "[", "]", "=", "\"Problem while syncing (update), check data with status 5 and ID \"", ".", "$", "d", "[", "'id'", "]", ";", "}", "$", "retry", "=", "1", ";", "}", "}", "// Callback number 2", "if", "(", "isset", "(", "self", "::", "$", "methods", "[", "'cbf2'", "]", ")", ")", "{", "self", "::", "cbf2", "(", "$", "d", ")", ";", "}", "}", "$", "res", "=", "[", "]", ";", "foreach", "(", "$", "to_log", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "!", "empty", "(", "$", "v", ")", ")", "{", "$", "res", "[", "$", "k", "]", "=", "$", "v", ";", "}", "}", "if", "(", "$", "retry", "&&", "(", "$", "num_try", "<=", "self", "::", "$", "max_retry", ")", ")", "{", "$", "res", "=", "bbn", "\\", "x", "::", "merge_arrays", "(", "$", "res", ",", "self", "::", "sync", "(", "$", "db", ",", "$", "dbs", ",", "$", "dbs_table", ",", "$", "num_try", ")", ")", ";", "}", "else", "{", "self", "::", "$", "db", "->", "set_error_mode", "(", "$", "mode_db", ")", ";", "self", "::", "$", "dbs", "->", "set_error_mode", "(", "$", "mode_dbs", ")", ";", "self", "::", "enable", "(", ")", ";", "}", "return", "$", "res", ";", "}" ]
Deleting the rows from this DB which have state = 1
[ "Deleting", "the", "rows", "from", "this", "DB", "which", "have", "state", "=", "1" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/dbsync.php#L218-L427
cultuurnet/deserializer
src/JSONDeserializer.php
JSONDeserializer.deserialize
public function deserialize(StringLiteral $data) { $data = json_decode($data->toNative(), $this->assoc); if (null === $data) { throw new NotWellFormedException('Invalid JSON'); } return $data; }
php
public function deserialize(StringLiteral $data) { $data = json_decode($data->toNative(), $this->assoc); if (null === $data) { throw new NotWellFormedException('Invalid JSON'); } return $data; }
[ "public", "function", "deserialize", "(", "StringLiteral", "$", "data", ")", "{", "$", "data", "=", "json_decode", "(", "$", "data", "->", "toNative", "(", ")", ",", "$", "this", "->", "assoc", ")", ";", "if", "(", "null", "===", "$", "data", ")", "{", "throw", "new", "NotWellFormedException", "(", "'Invalid JSON'", ")", ";", "}", "return", "$", "data", ";", "}" ]
Decodes a JSON string into a generic PHP object. @param StringLiteral $data @return \stdClass
[ "Decodes", "a", "JSON", "string", "into", "a", "generic", "PHP", "object", "." ]
train
https://github.com/cultuurnet/deserializer/blob/ec7830eb860ea83f7c28c38649b0057177ade784/src/JSONDeserializer.php#L30-L39
GrupaZero/social
src/Gzero/Social/SocialLoginService.php
SocialLoginService.login
public function login($serviceName, AbstractUser $response) { $userId = $this->repo->getUserIdBySocialId($response->id, $serviceName); if (auth()->check()) { // user already logged and service has not been connected $user = auth()->user(); if ($userId) { // This service has already been connected session()->put('url.intended', route('connectedServices')); throw new SocialException( trans( 'gzero-social::common.service_already_connected_message', ['service_name' => title_case($serviceName)] ) ); } else { // create connection for new service $this->repo->addUserSocialAccount($user, $serviceName, $response); } } else { if ($userId) { // login user with this service $this->auth->loginUsingId($userId); } else { // create new user $user = $this->repo->createNewUser($serviceName, $response); $this->auth->login($user); session()->put('showWelcomePage', true); session()->put('url.intended', route('account.welcome', ['method' => title_case($serviceName)])); } } }
php
public function login($serviceName, AbstractUser $response) { $userId = $this->repo->getUserIdBySocialId($response->id, $serviceName); if (auth()->check()) { // user already logged and service has not been connected $user = auth()->user(); if ($userId) { // This service has already been connected session()->put('url.intended', route('connectedServices')); throw new SocialException( trans( 'gzero-social::common.service_already_connected_message', ['service_name' => title_case($serviceName)] ) ); } else { // create connection for new service $this->repo->addUserSocialAccount($user, $serviceName, $response); } } else { if ($userId) { // login user with this service $this->auth->loginUsingId($userId); } else { // create new user $user = $this->repo->createNewUser($serviceName, $response); $this->auth->login($user); session()->put('showWelcomePage', true); session()->put('url.intended', route('account.welcome', ['method' => title_case($serviceName)])); } } }
[ "public", "function", "login", "(", "$", "serviceName", ",", "AbstractUser", "$", "response", ")", "{", "$", "userId", "=", "$", "this", "->", "repo", "->", "getUserIdBySocialId", "(", "$", "response", "->", "id", ",", "$", "serviceName", ")", ";", "if", "(", "auth", "(", ")", "->", "check", "(", ")", ")", "{", "// user already logged and service has not been connected", "$", "user", "=", "auth", "(", ")", "->", "user", "(", ")", ";", "if", "(", "$", "userId", ")", "{", "// This service has already been connected", "session", "(", ")", "->", "put", "(", "'url.intended'", ",", "route", "(", "'connectedServices'", ")", ")", ";", "throw", "new", "SocialException", "(", "trans", "(", "'gzero-social::common.service_already_connected_message'", ",", "[", "'service_name'", "=>", "title_case", "(", "$", "serviceName", ")", "]", ")", ")", ";", "}", "else", "{", "// create connection for new service", "$", "this", "->", "repo", "->", "addUserSocialAccount", "(", "$", "user", ",", "$", "serviceName", ",", "$", "response", ")", ";", "}", "}", "else", "{", "if", "(", "$", "userId", ")", "{", "// login user with this service", "$", "this", "->", "auth", "->", "loginUsingId", "(", "$", "userId", ")", ";", "}", "else", "{", "// create new user", "$", "user", "=", "$", "this", "->", "repo", "->", "createNewUser", "(", "$", "serviceName", ",", "$", "response", ")", ";", "$", "this", "->", "auth", "->", "login", "(", "$", "user", ")", ";", "session", "(", ")", "->", "put", "(", "'showWelcomePage'", ",", "true", ")", ";", "session", "(", ")", "->", "put", "(", "'url.intended'", ",", "route", "(", "'account.welcome'", ",", "[", "'method'", "=>", "title_case", "(", "$", "serviceName", ")", "]", ")", ")", ";", "}", "}", "}" ]
Login using social service. @param $serviceName string social service name @param $response AbstractUser response data @throws SocialException
[ "Login", "using", "social", "service", "." ]
train
https://github.com/GrupaZero/social/blob/f7cbf50765bd228010a2c61d950f915828306cf7/src/Gzero/Social/SocialLoginService.php#L50-L76
windwork/wf-db
lib/QueryBuilder.php
QueryBuilder.quoteInputVar
public static function quoteInputVar($str, $allowArray = true) { // 字符串进行转义 if (is_string($str)) { return '\'' . addcslashes($str, "\n\r\\'\"\032") . '\''; } // 数字 if (is_numeric($str)) { return '\'' . $str . '\''; } // 数组 if (is_array($str)) { if($allowArray) { foreach ($str as &$v) { $v = static::quoteInputVar($v, true); } return $str; } else { return '\'\''; } } // 布尔型转成0/1(统一使用tinyint来保存bool类型) if (is_bool($str)) { return $str ? '1' : '0'; } // 其他类型返回空字符 return '\'\''; }
php
public static function quoteInputVar($str, $allowArray = true) { // 字符串进行转义 if (is_string($str)) { return '\'' . addcslashes($str, "\n\r\\'\"\032") . '\''; } // 数字 if (is_numeric($str)) { return '\'' . $str . '\''; } // 数组 if (is_array($str)) { if($allowArray) { foreach ($str as &$v) { $v = static::quoteInputVar($v, true); } return $str; } else { return '\'\''; } } // 布尔型转成0/1(统一使用tinyint来保存bool类型) if (is_bool($str)) { return $str ? '1' : '0'; } // 其他类型返回空字符 return '\'\''; }
[ "public", "static", "function", "quoteInputVar", "(", "$", "str", ",", "$", "allowArray", "=", "true", ")", "{", "// 字符串进行转义", "if", "(", "is_string", "(", "$", "str", ")", ")", "{", "return", "'\\''", ".", "addcslashes", "(", "$", "str", ",", "\"\\n\\r\\\\'\\\"\\032\"", ")", ".", "'\\''", ";", "}", "// 数字", "if", "(", "is_numeric", "(", "$", "str", ")", ")", "{", "return", "'\\''", ".", "$", "str", ".", "'\\''", ";", "}", "// 数组", "if", "(", "is_array", "(", "$", "str", ")", ")", "{", "if", "(", "$", "allowArray", ")", "{", "foreach", "(", "$", "str", "as", "&", "$", "v", ")", "{", "$", "v", "=", "static", "::", "quoteInputVar", "(", "$", "v", ",", "true", ")", ";", "}", "return", "$", "str", ";", "}", "else", "{", "return", "'\\'\\''", ";", "}", "}", "// 布尔型转成0/1(统一使用tinyint来保存bool类型)", "if", "(", "is_bool", "(", "$", "str", ")", ")", "{", "return", "$", "str", "?", "'1'", ":", "'0'", ";", "}", "// 其他类型返回空字符", "return", "'\\'\\''", ";", "}" ]
变量进行注入转义并加上引号 @param mixed $str @param bool $allowArray = true @return string
[ "变量进行注入转义并加上引号" ]
train
https://github.com/windwork/wf-db/blob/b9ee5740a42d572ce728907ea24ba22c158863f5/lib/QueryBuilder.php#L42-L75
windwork/wf-db
lib/QueryBuilder.php
QueryBuilder.quoteFieldName
public static function quoteFieldName($field) { $field = trim($field); if(!$field || is_numeric($field)) { return $field; } if (strpos($field, '`') !== false) { $field = str_replace('`', '', $field); } $field = preg_replace("/(\\s+)/", '` `', $field); $field = preg_replace("/(\\.)/", '`.`', $field); $field = '`' . $field . '`'; $field = str_ireplace(array('`as` ', '`distinct` ', '`*`', '`+`', '`-`', '`/`'), array('AS ', 'DISTINCT ', '*', '+', '-', '/'), $field); return $field; }
php
public static function quoteFieldName($field) { $field = trim($field); if(!$field || is_numeric($field)) { return $field; } if (strpos($field, '`') !== false) { $field = str_replace('`', '', $field); } $field = preg_replace("/(\\s+)/", '` `', $field); $field = preg_replace("/(\\.)/", '`.`', $field); $field = '`' . $field . '`'; $field = str_ireplace(array('`as` ', '`distinct` ', '`*`', '`+`', '`-`', '`/`'), array('AS ', 'DISTINCT ', '*', '+', '-', '/'), $field); return $field; }
[ "public", "static", "function", "quoteFieldName", "(", "$", "field", ")", "{", "$", "field", "=", "trim", "(", "$", "field", ")", ";", "if", "(", "!", "$", "field", "||", "is_numeric", "(", "$", "field", ")", ")", "{", "return", "$", "field", ";", "}", "if", "(", "strpos", "(", "$", "field", ",", "'`'", ")", "!==", "false", ")", "{", "$", "field", "=", "str_replace", "(", "'`'", ",", "''", ",", "$", "field", ")", ";", "}", "$", "field", "=", "preg_replace", "(", "\"/(\\\\s+)/\"", ",", "'` `'", ",", "$", "field", ")", ";", "$", "field", "=", "preg_replace", "(", "\"/(\\\\.)/\"", ",", "'`.`'", ",", "$", "field", ")", ";", "$", "field", "=", "'`'", ".", "$", "field", ".", "'`'", ";", "$", "field", "=", "str_ireplace", "(", "array", "(", "'`as` '", ",", "'`distinct` '", ",", "'`*`'", ",", "'`+`'", ",", "'`-`'", ",", "'`/`'", ")", ",", "array", "(", "'AS '", ",", "'DISTINCT '", ",", "'*'", ",", "'+'", ",", "'-'", ",", "'/'", ")", ",", "$", "field", ")", ";", "return", "$", "field", ";", "}" ]
字段转义 @param string $field @return string
[ "字段转义" ]
train
https://github.com/windwork/wf-db/blob/b9ee5740a42d572ce728907ea24ba22c158863f5/lib/QueryBuilder.php#L83-L100
windwork/wf-db
lib/QueryBuilder.php
QueryBuilder.quoteFieldNames
public static function quoteFieldNames($fields) { $fieldArr = is_string($fields) ? explode(',', trim($fields)) : (array)$fields; foreach ($fieldArr as $k => $field) { $field = preg_replace("/(\s+)/", ' ', trim($field)); if ($field == '*') { // do nothing } elseif (false !== strpos($field, '(')) { if (preg_match("/(.*?)\\((.*?)\\)(.*)/i", $field, $match)) { // xx() | xx(xx) | xx(xx)xx $field = $match[1] . '(' . QueryBuilder::quoteFieldName($match[2]).')' . QueryBuilder::quoteFieldName($match[3]); } else { // xx( | xx(xx $field = preg_replace_callback( "/\\((.+)/i", function($match) { return '('.QueryBuilder::quoteFieldName($match[1]); }, $field ); } $fieldArr[$k] = $field; } elseif (false !== strpos($field, ')')) { // xx) $field = preg_replace_callback( "/(.*)\\)/i", function($match) { return QueryBuilder::quoteFieldName($match[1]) . ')'; }, $field ); $fieldArr[$k] = QueryBuilder::quoteFieldName(substr($field, 0, strlen($field) - 1)) . ')'; } else { $fieldArr[$k] = QueryBuilder::quoteFieldName($field); } } $rFields = implode(',', $fieldArr); return $rFields; }
php
public static function quoteFieldNames($fields) { $fieldArr = is_string($fields) ? explode(',', trim($fields)) : (array)$fields; foreach ($fieldArr as $k => $field) { $field = preg_replace("/(\s+)/", ' ', trim($field)); if ($field == '*') { // do nothing } elseif (false !== strpos($field, '(')) { if (preg_match("/(.*?)\\((.*?)\\)(.*)/i", $field, $match)) { // xx() | xx(xx) | xx(xx)xx $field = $match[1] . '(' . QueryBuilder::quoteFieldName($match[2]).')' . QueryBuilder::quoteFieldName($match[3]); } else { // xx( | xx(xx $field = preg_replace_callback( "/\\((.+)/i", function($match) { return '('.QueryBuilder::quoteFieldName($match[1]); }, $field ); } $fieldArr[$k] = $field; } elseif (false !== strpos($field, ')')) { // xx) $field = preg_replace_callback( "/(.*)\\)/i", function($match) { return QueryBuilder::quoteFieldName($match[1]) . ')'; }, $field ); $fieldArr[$k] = QueryBuilder::quoteFieldName(substr($field, 0, strlen($field) - 1)) . ')'; } else { $fieldArr[$k] = QueryBuilder::quoteFieldName($field); } } $rFields = implode(',', $fieldArr); return $rFields; }
[ "public", "static", "function", "quoteFieldNames", "(", "$", "fields", ")", "{", "$", "fieldArr", "=", "is_string", "(", "$", "fields", ")", "?", "explode", "(", "','", ",", "trim", "(", "$", "fields", ")", ")", ":", "(", "array", ")", "$", "fields", ";", "foreach", "(", "$", "fieldArr", "as", "$", "k", "=>", "$", "field", ")", "{", "$", "field", "=", "preg_replace", "(", "\"/(\\s+)/\"", ",", "' '", ",", "trim", "(", "$", "field", ")", ")", ";", "if", "(", "$", "field", "==", "'*'", ")", "{", "// do nothing", "}", "elseif", "(", "false", "!==", "strpos", "(", "$", "field", ",", "'('", ")", ")", "{", "if", "(", "preg_match", "(", "\"/(.*?)\\\\((.*?)\\\\)(.*)/i\"", ",", "$", "field", ",", "$", "match", ")", ")", "{", "// xx() | xx(xx) | xx(xx)xx", "$", "field", "=", "$", "match", "[", "1", "]", ".", "'('", ".", "QueryBuilder", "::", "quoteFieldName", "(", "$", "match", "[", "2", "]", ")", ".", "')'", ".", "QueryBuilder", "::", "quoteFieldName", "(", "$", "match", "[", "3", "]", ")", ";", "}", "else", "{", "// xx( | xx(xx", "$", "field", "=", "preg_replace_callback", "(", "\"/\\\\((.+)/i\"", ",", "function", "(", "$", "match", ")", "{", "return", "'('", ".", "QueryBuilder", "::", "quoteFieldName", "(", "$", "match", "[", "1", "]", ")", ";", "}", ",", "$", "field", ")", ";", "}", "$", "fieldArr", "[", "$", "k", "]", "=", "$", "field", ";", "}", "elseif", "(", "false", "!==", "strpos", "(", "$", "field", ",", "')'", ")", ")", "{", "// xx)", "$", "field", "=", "preg_replace_callback", "(", "\"/(.*)\\\\)/i\"", ",", "function", "(", "$", "match", ")", "{", "return", "QueryBuilder", "::", "quoteFieldName", "(", "$", "match", "[", "1", "]", ")", ".", "')'", ";", "}", ",", "$", "field", ")", ";", "$", "fieldArr", "[", "$", "k", "]", "=", "QueryBuilder", "::", "quoteFieldName", "(", "substr", "(", "$", "field", ",", "0", ",", "strlen", "(", "$", "field", ")", "-", "1", ")", ")", ".", "')'", ";", "}", "else", "{", "$", "fieldArr", "[", "$", "k", "]", "=", "QueryBuilder", "::", "quoteFieldName", "(", "$", "field", ")", ";", "}", "}", "$", "rFields", "=", "implode", "(", "','", ",", "$", "fieldArr", ")", ";", "return", "$", "rFields", ";", "}" ]
字段名转义 可以是多个字段一起,如:table.field1 或 a.f1, b.f2, c.* @param string|array $fields @return string
[ "字段名转义" ]
train
https://github.com/windwork/wf-db/blob/b9ee5740a42d572ce728907ea24ba22c158863f5/lib/QueryBuilder.php#L110-L153
windwork/wf-db
lib/QueryBuilder.php
QueryBuilder.quoteOrder
protected static function quoteOrder($str) { if ($str && is_array($str) && isset($str[1])) { $str = $str[1]; } if ($str && !is_string($str)) { throw new \wf\db\Exception('Order fields must be string!'); } if ($str && strtolower($str) != 'asc' && strtolower($str) != 'desc') { $str = static::quoteFieldNames($str); } return $str; }
php
protected static function quoteOrder($str) { if ($str && is_array($str) && isset($str[1])) { $str = $str[1]; } if ($str && !is_string($str)) { throw new \wf\db\Exception('Order fields must be string!'); } if ($str && strtolower($str) != 'asc' && strtolower($str) != 'desc') { $str = static::quoteFieldNames($str); } return $str; }
[ "protected", "static", "function", "quoteOrder", "(", "$", "str", ")", "{", "if", "(", "$", "str", "&&", "is_array", "(", "$", "str", ")", "&&", "isset", "(", "$", "str", "[", "1", "]", ")", ")", "{", "$", "str", "=", "$", "str", "[", "1", "]", ";", "}", "if", "(", "$", "str", "&&", "!", "is_string", "(", "$", "str", ")", ")", "{", "throw", "new", "\\", "wf", "\\", "db", "\\", "Exception", "(", "'Order fields must be string!'", ")", ";", "}", "if", "(", "$", "str", "&&", "strtolower", "(", "$", "str", ")", "!=", "'asc'", "&&", "strtolower", "(", "$", "str", ")", "!=", "'desc'", ")", "{", "$", "str", "=", "static", "::", "quoteFieldNames", "(", "$", "str", ")", ";", "}", "return", "$", "str", ";", "}" ]
排序参数过滤 @param string $str @return string @throws \wf\db\Exception
[ "排序参数过滤" ]
train
https://github.com/windwork/wf-db/blob/b9ee5740a42d572ce728907ea24ba22c158863f5/lib/QueryBuilder.php#L162-L177
windwork/wf-db
lib/QueryBuilder.php
QueryBuilder.where
public static function where($field, $val, $glue = '=', $type = 'string') { $glue = strtolower($glue); $glue = str_replace(' ', '', $glue); $type = str_replace(' ', '', $type); $field = static::quoteFieldNames($field); if (is_array($val)) { $glue = $glue == 'in' ? 'in' : 'notin'; } elseif ($type != 'sql') { // 值不是数组类型,'in' => '=', 'notin' => '!=' if($glue == 'in') { $glue = '='; } elseif($glue == 'notin') { $glue = '!='; } } if ($type == 'sql') { $where = ''; switch ($glue) { case 'like': $where = "{$field} LIKE {$val}"; break; case 'in': $where = "{$field} IN({$val})"; break; case 'notin': $where = "{$field} NOT IN({$val})"; break; default: $where = "{$field} {$glue} {$val}"; break; } return $where; } $glue || $glue = '='; $val = $type == 'field' ? static::quoteFieldNames($val) : static::quoteInputVar($val); switch ($glue) { case '=': return $field . $glue . $val; break; case '-': case '+': case '|': case '&': case '^': return $field . '=' . $field . $glue . $val; break; case '>': case '<': case '!=': case '<>': case '<=': case '>=': return $field . $glue . $val; break; case 'like': return $field . ' LIKE(' . $val . ')'; break; case 'in': case 'notin': $val = $val ? implode(',', $val) : '\'\''; return $field . ($glue == 'notin' ? ' NOT' : '') . ' IN(' . $val . ')'; break; default: throw new \wf\db\Exception('Not allow this glue between field and value: "' . $glue . '"'); } }
php
public static function where($field, $val, $glue = '=', $type = 'string') { $glue = strtolower($glue); $glue = str_replace(' ', '', $glue); $type = str_replace(' ', '', $type); $field = static::quoteFieldNames($field); if (is_array($val)) { $glue = $glue == 'in' ? 'in' : 'notin'; } elseif ($type != 'sql') { // 值不是数组类型,'in' => '=', 'notin' => '!=' if($glue == 'in') { $glue = '='; } elseif($glue == 'notin') { $glue = '!='; } } if ($type == 'sql') { $where = ''; switch ($glue) { case 'like': $where = "{$field} LIKE {$val}"; break; case 'in': $where = "{$field} IN({$val})"; break; case 'notin': $where = "{$field} NOT IN({$val})"; break; default: $where = "{$field} {$glue} {$val}"; break; } return $where; } $glue || $glue = '='; $val = $type == 'field' ? static::quoteFieldNames($val) : static::quoteInputVar($val); switch ($glue) { case '=': return $field . $glue . $val; break; case '-': case '+': case '|': case '&': case '^': return $field . '=' . $field . $glue . $val; break; case '>': case '<': case '!=': case '<>': case '<=': case '>=': return $field . $glue . $val; break; case 'like': return $field . ' LIKE(' . $val . ')'; break; case 'in': case 'notin': $val = $val ? implode(',', $val) : '\'\''; return $field . ($glue == 'notin' ? ' NOT' : '') . ' IN(' . $val . ')'; break; default: throw new \wf\db\Exception('Not allow this glue between field and value: "' . $glue . '"'); } }
[ "public", "static", "function", "where", "(", "$", "field", ",", "$", "val", ",", "$", "glue", "=", "'='", ",", "$", "type", "=", "'string'", ")", "{", "$", "glue", "=", "strtolower", "(", "$", "glue", ")", ";", "$", "glue", "=", "str_replace", "(", "' '", ",", "''", ",", "$", "glue", ")", ";", "$", "type", "=", "str_replace", "(", "' '", ",", "''", ",", "$", "type", ")", ";", "$", "field", "=", "static", "::", "quoteFieldNames", "(", "$", "field", ")", ";", "if", "(", "is_array", "(", "$", "val", ")", ")", "{", "$", "glue", "=", "$", "glue", "==", "'in'", "?", "'in'", ":", "'notin'", ";", "}", "elseif", "(", "$", "type", "!=", "'sql'", ")", "{", "// 值不是数组类型,'in' => '=', 'notin' => '!='", "if", "(", "$", "glue", "==", "'in'", ")", "{", "$", "glue", "=", "'='", ";", "}", "elseif", "(", "$", "glue", "==", "'notin'", ")", "{", "$", "glue", "=", "'!='", ";", "}", "}", "if", "(", "$", "type", "==", "'sql'", ")", "{", "$", "where", "=", "''", ";", "switch", "(", "$", "glue", ")", "{", "case", "'like'", ":", "$", "where", "=", "\"{$field} LIKE {$val}\"", ";", "break", ";", "case", "'in'", ":", "$", "where", "=", "\"{$field} IN({$val})\"", ";", "break", ";", "case", "'notin'", ":", "$", "where", "=", "\"{$field} NOT IN({$val})\"", ";", "break", ";", "default", ":", "$", "where", "=", "\"{$field} {$glue} {$val}\"", ";", "break", ";", "}", "return", "$", "where", ";", "}", "$", "glue", "||", "$", "glue", "=", "'='", ";", "$", "val", "=", "$", "type", "==", "'field'", "?", "static", "::", "quoteFieldNames", "(", "$", "val", ")", ":", "static", "::", "quoteInputVar", "(", "$", "val", ")", ";", "switch", "(", "$", "glue", ")", "{", "case", "'='", ":", "return", "$", "field", ".", "$", "glue", ".", "$", "val", ";", "break", ";", "case", "'-'", ":", "case", "'+'", ":", "case", "'|'", ":", "case", "'&'", ":", "case", "'^'", ":", "return", "$", "field", ".", "'='", ".", "$", "field", ".", "$", "glue", ".", "$", "val", ";", "break", ";", "case", "'>'", ":", "case", "'<'", ":", "case", "'!='", ":", "case", "'<>'", ":", "case", "'<='", ":", "case", "'>='", ":", "return", "$", "field", ".", "$", "glue", ".", "$", "val", ";", "break", ";", "case", "'like'", ":", "return", "$", "field", ".", "' LIKE('", ".", "$", "val", ".", "')'", ";", "break", ";", "case", "'in'", ":", "case", "'notin'", ":", "$", "val", "=", "$", "val", "?", "implode", "(", "','", ",", "$", "val", ")", ":", "'\\'\\''", ";", "return", "$", "field", ".", "(", "$", "glue", "==", "'notin'", "?", "' NOT'", ":", "''", ")", ".", "' IN('", ".", "$", "val", ".", "')'", ";", "break", ";", "default", ":", "throw", "new", "\\", "wf", "\\", "db", "\\", "Exception", "(", "'Not allow this glue between field and value: \"'", ".", "$", "glue", ".", "'\"'", ")", ";", "}", "}" ]
查询条件 @param string $field 字段名 @param string|array $val 值,使用in/notin的时候为array类型 @param string $glue =,+,-,|,&,^,like,in,notin,not in,>,<,<>,>=,<=,!= @param string $type $val参数值的类型,string:字符串,field:字段,int:整形,float:浮点型,sql:sql语句 @throws \wf\db\Exception @return string
[ "查询条件" ]
train
https://github.com/windwork/wf-db/blob/b9ee5740a42d572ce728907ea24ba22c158863f5/lib/QueryBuilder.php#L189-L263
windwork/wf-db
lib/QueryBuilder.php
QueryBuilder.whereArr
public static function whereArr($options) { if (!is_array($options) || empty($options[0]) || !(is_string($options[0]) || is_array($options[0]))) { throw new \wf\db\Exception('Illegal param, the param should be array, but string has given: $options = ' . var_export($options, 1)); } if (is_array($options[0])) { // [[], [], [] ...] => ['and', [], [], [] ...] array_unshift($options, 'AND'); return static::whereArr($options); } // ['and|or', [], [] ...] 或 ['field', 'value' ...] $logic = strtoupper(trim($options[0])); if($logic == 'AND' || $logic == 'OR') { // ['and|or', [], [] ...] unset($options[0]); $pieces = []; foreach ($options as $item) { $pieces[] = static::whereArr($item); } $ret = implode(" {$logic} ", $pieces); $ret = " ({$ret}) "; return $ret; } else { // ['field', 'value', 'glue', 'type'] empty($options[2]) && $options[2] = '='; isset($options[3]) || $options[3] = ''; return static::where($options[0], $options[1], $options[2], $options[3]); } }
php
public static function whereArr($options) { if (!is_array($options) || empty($options[0]) || !(is_string($options[0]) || is_array($options[0]))) { throw new \wf\db\Exception('Illegal param, the param should be array, but string has given: $options = ' . var_export($options, 1)); } if (is_array($options[0])) { // [[], [], [] ...] => ['and', [], [], [] ...] array_unshift($options, 'AND'); return static::whereArr($options); } // ['and|or', [], [] ...] 或 ['field', 'value' ...] $logic = strtoupper(trim($options[0])); if($logic == 'AND' || $logic == 'OR') { // ['and|or', [], [] ...] unset($options[0]); $pieces = []; foreach ($options as $item) { $pieces[] = static::whereArr($item); } $ret = implode(" {$logic} ", $pieces); $ret = " ({$ret}) "; return $ret; } else { // ['field', 'value', 'glue', 'type'] empty($options[2]) && $options[2] = '='; isset($options[3]) || $options[3] = ''; return static::where($options[0], $options[1], $options[2], $options[3]); } }
[ "public", "static", "function", "whereArr", "(", "$", "options", ")", "{", "if", "(", "!", "is_array", "(", "$", "options", ")", "||", "empty", "(", "$", "options", "[", "0", "]", ")", "||", "!", "(", "is_string", "(", "$", "options", "[", "0", "]", ")", "||", "is_array", "(", "$", "options", "[", "0", "]", ")", ")", ")", "{", "throw", "new", "\\", "wf", "\\", "db", "\\", "Exception", "(", "'Illegal param, the param should be array, but string has given: $options = '", ".", "var_export", "(", "$", "options", ",", "1", ")", ")", ";", "}", "if", "(", "is_array", "(", "$", "options", "[", "0", "]", ")", ")", "{", "// [[], [], [] ...] => ['and', [], [], [] ...]", "array_unshift", "(", "$", "options", ",", "'AND'", ")", ";", "return", "static", "::", "whereArr", "(", "$", "options", ")", ";", "}", "// ['and|or', [], [] ...] 或 ['field', 'value' ...]", "$", "logic", "=", "strtoupper", "(", "trim", "(", "$", "options", "[", "0", "]", ")", ")", ";", "if", "(", "$", "logic", "==", "'AND'", "||", "$", "logic", "==", "'OR'", ")", "{", "// ['and|or', [], [] ...]", "unset", "(", "$", "options", "[", "0", "]", ")", ";", "$", "pieces", "=", "[", "]", ";", "foreach", "(", "$", "options", "as", "$", "item", ")", "{", "$", "pieces", "[", "]", "=", "static", "::", "whereArr", "(", "$", "item", ")", ";", "}", "$", "ret", "=", "implode", "(", "\" {$logic} \"", ",", "$", "pieces", ")", ";", "$", "ret", "=", "\" ({$ret}) \"", ";", "return", "$", "ret", ";", "}", "else", "{", "// ['field', 'value', 'glue', 'type']", "empty", "(", "$", "options", "[", "2", "]", ")", "&&", "$", "options", "[", "2", "]", "=", "'='", ";", "isset", "(", "$", "options", "[", "3", "]", ")", "||", "$", "options", "[", "3", "]", "=", "''", ";", "return", "static", "::", "where", "(", "$", "options", "[", "0", "]", ",", "$", "options", "[", "1", "]", ",", "$", "options", "[", "2", "]", ",", "$", "options", "[", "3", "]", ")", ";", "}", "}" ]
构造sql多个查询条件 <div> <b>规则:</b>查询条件有两部分构成 <ul> <li>一个是查询元素(比较表达式), array('字段', '值', '比较逻辑 = > < ...')</li> <li>一个是查询条件之间的逻辑关系 AND|OR 字符,这个不是必须的。如果指定and/or,必须放在数组的第一位,即下标为0。</li> </ul> </div> <b>构造格式为:</b> <ul> <li>不指定and/or(默认and):array(比较表达式1,比较表达式2, ...)</li> <li>指定and/or:array('AND|OR', 比较表达式1,比较表达式2, ...)</li> <li>嵌套混合:array('AND|OR', array('AND|OR', 比较表达式11,比较表达式12, ...), 比较表达式2, ...)</li> </ul> <b>例如允许格式如下:</b> <ul> <li>一个条件 $options = array('field', 'val', 'glue', 'type')</li> <li>多个不指定and/or的条件 $options = array(array('field', 'val', 'glue'), array('field', 'val', 'glue'), ...)</li> <li>多个指定and/or的条件$options = array('and', array('field', 'val', 'glue'), array('field', 'val', 'glue'), ...)</li> <li>$options = array('and|or', array('field', 'val', 'glue'), array('and|or', array('field1', 'val1', 'glue1'), array('field2', 'val2', 'glue2'), ...), array('field3', 'val', 'glue'), ...);</li> </ul> @param array $options 查询条件 array('and|or', array('字段1', '值', '=,+,-,|,&,^,like,in,notin,>,<,<>,>=,<=,!='), array('字段1', '值', '逻辑'), ...) @throws \wf\db\Exception @return string
[ "构造sql多个查询条件" ]
train
https://github.com/windwork/wf-db/blob/b9ee5740a42d572ce728907ea24ba22c158863f5/lib/QueryBuilder.php#L293-L328
windwork/wf-db
lib/QueryBuilder.php
QueryBuilder.format
public static function format($sql, $arg) { $arg = (array)$arg; if(preg_match('/(\"|\')/', $sql)) { throw new \wf\db\Exception('SQL string format error! It\'s Unsafe to take "|\' in SQL.'); } $count = substr_count($sql, '%'); if (!$count) { return $sql; } elseif ($count > count($arg)) { throw new \wf\db\Exception('SQL string format error! This SQL need "' . $count . '" vars to replace into.', 0, $sql); } // 格式化类型检查 if(preg_match('/%[^tcnifsx]/', $sql, $m)) { throw new \wf\db\Exception('SQL string format error! Not allowed type (' . $m[0] . ') found.'); } $ret = preg_replace_callback('/%([tcnifsx])/i', function($matchs) use($arg) { static $find = 0; $m = $matchs[1]; if ($m == 'c' || $m == 't') { $val = static::quoteFieldNames($arg[$find]); } elseif ($m == 'n') { // 只能有1个点 $val = preg_replace("/(.*?\\..*?)\\..*/", '\\1', $arg[$find]); $val = preg_replace("/[^0-9\\.].*/", '', $val); // 非数字或.后面全部清掉 } elseif ($m == 'i') { $val = (int)$arg[$find]; } elseif ($m == 'f') { $val = (float)$arg[$find]; } elseif ($m == 's') { $val = static::quoteInputVar($arg[$find]); if (is_array($val)) { $val = implode(',', $val); } } elseif ($m == 'x') { $val = $arg[$find]; } $find ++; return $val; }, $sql); return $ret; }
php
public static function format($sql, $arg) { $arg = (array)$arg; if(preg_match('/(\"|\')/', $sql)) { throw new \wf\db\Exception('SQL string format error! It\'s Unsafe to take "|\' in SQL.'); } $count = substr_count($sql, '%'); if (!$count) { return $sql; } elseif ($count > count($arg)) { throw new \wf\db\Exception('SQL string format error! This SQL need "' . $count . '" vars to replace into.', 0, $sql); } // 格式化类型检查 if(preg_match('/%[^tcnifsx]/', $sql, $m)) { throw new \wf\db\Exception('SQL string format error! Not allowed type (' . $m[0] . ') found.'); } $ret = preg_replace_callback('/%([tcnifsx])/i', function($matchs) use($arg) { static $find = 0; $m = $matchs[1]; if ($m == 'c' || $m == 't') { $val = static::quoteFieldNames($arg[$find]); } elseif ($m == 'n') { // 只能有1个点 $val = preg_replace("/(.*?\\..*?)\\..*/", '\\1', $arg[$find]); $val = preg_replace("/[^0-9\\.].*/", '', $val); // 非数字或.后面全部清掉 } elseif ($m == 'i') { $val = (int)$arg[$find]; } elseif ($m == 'f') { $val = (float)$arg[$find]; } elseif ($m == 's') { $val = static::quoteInputVar($arg[$find]); if (is_array($val)) { $val = implode(',', $val); } } elseif ($m == 'x') { $val = $arg[$find]; } $find ++; return $val; }, $sql); return $ret; }
[ "public", "static", "function", "format", "(", "$", "sql", ",", "$", "arg", ")", "{", "$", "arg", "=", "(", "array", ")", "$", "arg", ";", "if", "(", "preg_match", "(", "'/(\\\"|\\')/'", ",", "$", "sql", ")", ")", "{", "throw", "new", "\\", "wf", "\\", "db", "\\", "Exception", "(", "'SQL string format error! It\\'s Unsafe to take \"|\\' in SQL.'", ")", ";", "}", "$", "count", "=", "substr_count", "(", "$", "sql", ",", "'%'", ")", ";", "if", "(", "!", "$", "count", ")", "{", "return", "$", "sql", ";", "}", "elseif", "(", "$", "count", ">", "count", "(", "$", "arg", ")", ")", "{", "throw", "new", "\\", "wf", "\\", "db", "\\", "Exception", "(", "'SQL string format error! This SQL need \"'", ".", "$", "count", ".", "'\" vars to replace into.'", ",", "0", ",", "$", "sql", ")", ";", "}", "// 格式化类型检查", "if", "(", "preg_match", "(", "'/%[^tcnifsx]/'", ",", "$", "sql", ",", "$", "m", ")", ")", "{", "throw", "new", "\\", "wf", "\\", "db", "\\", "Exception", "(", "'SQL string format error! Not allowed type ('", ".", "$", "m", "[", "0", "]", ".", "') found.'", ")", ";", "}", "$", "ret", "=", "preg_replace_callback", "(", "'/%([tcnifsx])/i'", ",", "function", "(", "$", "matchs", ")", "use", "(", "$", "arg", ")", "{", "static", "$", "find", "=", "0", ";", "$", "m", "=", "$", "matchs", "[", "1", "]", ";", "if", "(", "$", "m", "==", "'c'", "||", "$", "m", "==", "'t'", ")", "{", "$", "val", "=", "static", "::", "quoteFieldNames", "(", "$", "arg", "[", "$", "find", "]", ")", ";", "}", "elseif", "(", "$", "m", "==", "'n'", ")", "{", "// 只能有1个点", "$", "val", "=", "preg_replace", "(", "\"/(.*?\\\\..*?)\\\\..*/\"", ",", "'\\\\1'", ",", "$", "arg", "[", "$", "find", "]", ")", ";", "$", "val", "=", "preg_replace", "(", "\"/[^0-9\\\\.].*/\"", ",", "''", ",", "$", "val", ")", ";", "// 非数字或.后面全部清掉", "}", "elseif", "(", "$", "m", "==", "'i'", ")", "{", "$", "val", "=", "(", "int", ")", "$", "arg", "[", "$", "find", "]", ";", "}", "elseif", "(", "$", "m", "==", "'f'", ")", "{", "$", "val", "=", "(", "float", ")", "$", "arg", "[", "$", "find", "]", ";", "}", "elseif", "(", "$", "m", "==", "'s'", ")", "{", "$", "val", "=", "static", "::", "quoteInputVar", "(", "$", "arg", "[", "$", "find", "]", ")", ";", "if", "(", "is_array", "(", "$", "val", ")", ")", "{", "$", "val", "=", "implode", "(", "','", ",", "$", "val", ")", ";", "}", "}", "elseif", "(", "$", "m", "==", "'x'", ")", "{", "$", "val", "=", "$", "arg", "[", "$", "find", "]", ";", "}", "$", "find", "++", ";", "return", "$", "val", ";", "}", ",", "$", "sql", ")", ";", "return", "$", "ret", ";", "}" ]
sql格式化 在$sql参数中加入"%参数类型字符"的格式,并在$arg参数设置该格式的值,$sql中的第n个参数对应$arg中的第n个元素。 <pre> $exp = "SELECT `uid`,`uname`,`password` FROM `user` WHERE `uid` = 100 AND `checked` = 1"; $sql = "SELECT %c FROM %t WHERE %c = %i AND `checked` = %i"; $arg = [ 'uid,uname,password', // %c 'user', // %t 'uid', // %c 100, // %i 1 // %i ]; $ret = \wf\db\QueryBuilder::format($sql, $arg); // $ret == $exp </pre> @param string $sql <pre>SQL格式化参数类型: %t:表名(Table),将被进行数据表名称反注入处理 %c:字段名(Column),将被进行数据表字段名反注入处理 %n:数字值(Number),将被过滤掉非数字和.的字符 %i:整形(Int),将被强制转换为整形 %f:浮点型(Float),将被强制转换为浮点型 %s:字符串值(String),将被进行字符串值反注入处理 %x:保留不处理 </pre> @param array $arg $sql参数对应的值 @throws \wf\db\Exception @return string
[ "sql格式化" ]
train
https://github.com/windwork/wf-db/blob/b9ee5740a42d572ce728907ea24ba22c158863f5/lib/QueryBuilder.php#L362-L412
windwork/wf-db
lib/QueryBuilder.php
QueryBuilder.buildQueryOptions
public static function buildQueryOptions($options = []) { if(!is_array($options)) { throw new \wf\db\Exception('The param must be array!'); } isset($options['field']) or $options['field'] = '*'; isset($options['join']) or $options['join'] = []; isset($options['where']) or $options['where'] = []; $result = []; if (!empty($options['fieldRaw'])) { $result['field'] = $options['fieldRaw']; } else { $result['field'] = static::buildOptionField(@$options['field']); } $result['table'] = static::buildOptionTable(@$options['table']); // 可选 $result['join'] = empty($options['join']) ? '' : static::buildOptionJoins((array)@$options['join']); $result['where'] = empty($options['where']) ? '' : static::buildOptionWhere((array)@$options['where']); $result['group'] = empty($options['group']) ? '' : static::buildOptionGroup(@$options['group']); $result['having'] = empty($options['having']) ? '' : static::buildOptionHaving(@$options['having']); $result['order'] = empty($options['order']) ? '' : static::buildOptionOrder(@$options['order']); $result['limit'] = empty($options['limit']) ? '' : static::buildOptionLimit(@$options['limit']); return $result; }
php
public static function buildQueryOptions($options = []) { if(!is_array($options)) { throw new \wf\db\Exception('The param must be array!'); } isset($options['field']) or $options['field'] = '*'; isset($options['join']) or $options['join'] = []; isset($options['where']) or $options['where'] = []; $result = []; if (!empty($options['fieldRaw'])) { $result['field'] = $options['fieldRaw']; } else { $result['field'] = static::buildOptionField(@$options['field']); } $result['table'] = static::buildOptionTable(@$options['table']); // 可选 $result['join'] = empty($options['join']) ? '' : static::buildOptionJoins((array)@$options['join']); $result['where'] = empty($options['where']) ? '' : static::buildOptionWhere((array)@$options['where']); $result['group'] = empty($options['group']) ? '' : static::buildOptionGroup(@$options['group']); $result['having'] = empty($options['having']) ? '' : static::buildOptionHaving(@$options['having']); $result['order'] = empty($options['order']) ? '' : static::buildOptionOrder(@$options['order']); $result['limit'] = empty($options['limit']) ? '' : static::buildOptionLimit(@$options['limit']); return $result; }
[ "public", "static", "function", "buildQueryOptions", "(", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "is_array", "(", "$", "options", ")", ")", "{", "throw", "new", "\\", "wf", "\\", "db", "\\", "Exception", "(", "'The param must be array!'", ")", ";", "}", "isset", "(", "$", "options", "[", "'field'", "]", ")", "or", "$", "options", "[", "'field'", "]", "=", "'*'", ";", "isset", "(", "$", "options", "[", "'join'", "]", ")", "or", "$", "options", "[", "'join'", "]", "=", "[", "]", ";", "isset", "(", "$", "options", "[", "'where'", "]", ")", "or", "$", "options", "[", "'where'", "]", "=", "[", "]", ";", "$", "result", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "options", "[", "'fieldRaw'", "]", ")", ")", "{", "$", "result", "[", "'field'", "]", "=", "$", "options", "[", "'fieldRaw'", "]", ";", "}", "else", "{", "$", "result", "[", "'field'", "]", "=", "static", "::", "buildOptionField", "(", "@", "$", "options", "[", "'field'", "]", ")", ";", "}", "$", "result", "[", "'table'", "]", "=", "static", "::", "buildOptionTable", "(", "@", "$", "options", "[", "'table'", "]", ")", ";", "// 可选", "$", "result", "[", "'join'", "]", "=", "empty", "(", "$", "options", "[", "'join'", "]", ")", "?", "''", ":", "static", "::", "buildOptionJoins", "(", "(", "array", ")", "@", "$", "options", "[", "'join'", "]", ")", ";", "$", "result", "[", "'where'", "]", "=", "empty", "(", "$", "options", "[", "'where'", "]", ")", "?", "''", ":", "static", "::", "buildOptionWhere", "(", "(", "array", ")", "@", "$", "options", "[", "'where'", "]", ")", ";", "$", "result", "[", "'group'", "]", "=", "empty", "(", "$", "options", "[", "'group'", "]", ")", "?", "''", ":", "static", "::", "buildOptionGroup", "(", "@", "$", "options", "[", "'group'", "]", ")", ";", "$", "result", "[", "'having'", "]", "=", "empty", "(", "$", "options", "[", "'having'", "]", ")", "?", "''", ":", "static", "::", "buildOptionHaving", "(", "@", "$", "options", "[", "'having'", "]", ")", ";", "$", "result", "[", "'order'", "]", "=", "empty", "(", "$", "options", "[", "'order'", "]", ")", "?", "''", ":", "static", "::", "buildOptionOrder", "(", "@", "$", "options", "[", "'order'", "]", ")", ";", "$", "result", "[", "'limit'", "]", "=", "empty", "(", "$", "options", "[", "'limit'", "]", ")", "?", "''", ":", "static", "::", "buildOptionLimit", "(", "@", "$", "options", "[", "'limit'", "]", ")", ";", "return", "$", "result", ";", "}" ]
查询选项解析 @param array $options = <pre>array( 'field' =>'f.a, f.b', // 字段名列表,默认是 * 'table' => 'table_a, table_b AS b', // 查询的表名,可以是多个表,默认是当前模型的表 'join' => [] // [['table_name', 'ON_field_a', 'ON_field_b', 'LEFT|RIGHT|CROSS|INNSER'], ..., "格式2直接写join语法"], // => LEFT JOIN `table_name` ON `field_a` = `field_b` 'where' => [] // 查询条件 array('and|or', array('字段1', '值', '=,+,-,|,&,^,like,in,notin,>,<,<>,>=,<=,!='), array('字段1', '值', '逻辑'), ...) 'group' => '', // 将对其进行SQL注入过滤并且在前面加上GROUP BY 'having' => '', // 数组结构,格式同where,将对其进行SQL注入过滤并且在前面加上 HAVING 'order' => '', // 将对其进行SQL注入过滤并且在前面加上 ORDER BY )</pre> @see \wf\db\DBInterface::whereArr() @throws \wf\db\Exception @return array
[ "查询选项解析" ]
train
https://github.com/windwork/wf-db/blob/b9ee5740a42d572ce728907ea24ba22c158863f5/lib/QueryBuilder.php#L431-L460
windwork/wf-db
lib/QueryBuilder.php
QueryBuilder.buildSqlSet
public static function buildSqlSet(array $data, array $keyInArray, array $keyNotInArray = []) { $set = []; $arg = []; $fields = $keyNotInArray ? array_diff($keyInArray, $keyNotInArray) : $keyInArray; // 取表中存在的字段(MySQL字段名本身不区分大小写,我们全部转成小写) foreach($data as $k => $v) { $k = strtolower($k); if (!in_array($k, $fields)) { continue; } if (is_array($v)) { $v = serialize($v); } // 字段值为null将不做写入属性,如需写入,把值设为空字符 '' if ($v === null) { $set[] = " %c = null "; $arg[] = $k; } else { $set[] = " %c = %s "; $arg[] = $k; $arg[] = $v; } } if (!$set || !$arg) { throw new \wf\db\Exception('请传入正确的数据'); } $sets = join(',', $set); return QueryBuilder::format($sets, $arg); }
php
public static function buildSqlSet(array $data, array $keyInArray, array $keyNotInArray = []) { $set = []; $arg = []; $fields = $keyNotInArray ? array_diff($keyInArray, $keyNotInArray) : $keyInArray; // 取表中存在的字段(MySQL字段名本身不区分大小写,我们全部转成小写) foreach($data as $k => $v) { $k = strtolower($k); if (!in_array($k, $fields)) { continue; } if (is_array($v)) { $v = serialize($v); } // 字段值为null将不做写入属性,如需写入,把值设为空字符 '' if ($v === null) { $set[] = " %c = null "; $arg[] = $k; } else { $set[] = " %c = %s "; $arg[] = $k; $arg[] = $v; } } if (!$set || !$arg) { throw new \wf\db\Exception('请传入正确的数据'); } $sets = join(',', $set); return QueryBuilder::format($sets, $arg); }
[ "public", "static", "function", "buildSqlSet", "(", "array", "$", "data", ",", "array", "$", "keyInArray", ",", "array", "$", "keyNotInArray", "=", "[", "]", ")", "{", "$", "set", "=", "[", "]", ";", "$", "arg", "=", "[", "]", ";", "$", "fields", "=", "$", "keyNotInArray", "?", "array_diff", "(", "$", "keyInArray", ",", "$", "keyNotInArray", ")", ":", "$", "keyInArray", ";", "// 取表中存在的字段(MySQL字段名本身不区分大小写,我们全部转成小写)", "foreach", "(", "$", "data", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "k", "=", "strtolower", "(", "$", "k", ")", ";", "if", "(", "!", "in_array", "(", "$", "k", ",", "$", "fields", ")", ")", "{", "continue", ";", "}", "if", "(", "is_array", "(", "$", "v", ")", ")", "{", "$", "v", "=", "serialize", "(", "$", "v", ")", ";", "}", "// 字段值为null将不做写入属性,如需写入,把值设为空字符 ''", "if", "(", "$", "v", "===", "null", ")", "{", "$", "set", "[", "]", "=", "\" %c = null \"", ";", "$", "arg", "[", "]", "=", "$", "k", ";", "}", "else", "{", "$", "set", "[", "]", "=", "\" %c = %s \"", ";", "$", "arg", "[", "]", "=", "$", "k", ";", "$", "arg", "[", "]", "=", "$", "v", ";", "}", "}", "if", "(", "!", "$", "set", "||", "!", "$", "arg", ")", "{", "throw", "new", "\\", "wf", "\\", "db", "\\", "Exception", "(", "'请传入正确的数据');", "", "", "}", "$", "sets", "=", "join", "(", "','", ",", "$", "set", ")", ";", "return", "QueryBuilder", "::", "format", "(", "$", "sets", ",", "$", "arg", ")", ";", "}" ]
从数组的下标对应的值中获取SQL的"字段1=值1,字段2=值2"的结构 @param array $data 下标 => 值结构 @param array $keyInArray 包含此数组中 的下标则保留,否则去掉 @param array $keyNotInArray = [] 要去掉的下标 @throws \wf\db\Exception @return string 返回 "`f1` = 'xx', `f2` = 'xxx'"
[ "从数组的下标对应的值中获取SQL的", "字段1", "=", "值1", "字段2", "=", "值2", "的结构" ]
train
https://github.com/windwork/wf-db/blob/b9ee5740a42d572ce728907ea24ba22c158863f5/lib/QueryBuilder.php#L644-L679
rattfieldnz/url-validation
src/RattfieldNz/UrlValidation/UrlValidation.php
UrlValidation.getUrlStatusCode
public static function getUrlStatusCode($url) { //Instantiate the EpiCurl class to be used //with checking URL HTTP status code. $epi_curl_checker = EpiCurl::getInstance(); // Add the given URL to the url checker. $url_check = $epi_curl_checker->addURL($url); //Return the HTTP status code. return $url_check->code; }
php
public static function getUrlStatusCode($url) { //Instantiate the EpiCurl class to be used //with checking URL HTTP status code. $epi_curl_checker = EpiCurl::getInstance(); // Add the given URL to the url checker. $url_check = $epi_curl_checker->addURL($url); //Return the HTTP status code. return $url_check->code; }
[ "public", "static", "function", "getUrlStatusCode", "(", "$", "url", ")", "{", "//Instantiate the EpiCurl class to be used\r", "//with checking URL HTTP status code.\r", "$", "epi_curl_checker", "=", "EpiCurl", "::", "getInstance", "(", ")", ";", "// Add the given URL to the url checker.\r", "$", "url_check", "=", "$", "epi_curl_checker", "->", "addURL", "(", "$", "url", ")", ";", "//Return the HTTP status code.\r", "return", "$", "url_check", "->", "code", ";", "}" ]
This function obtains an HTTP status code from a given URL. @param $url @uses EpiCurl::getInstance @return int
[ "This", "function", "obtains", "an", "HTTP", "status", "code", "from", "a", "given", "URL", "." ]
train
https://github.com/rattfieldnz/url-validation/blob/ff44a463a9119fa3bea9bd7fef3d44b7e6f9a44c/src/RattfieldNz/UrlValidation/UrlValidation.php#L53-L64
video-games-records/TeamBundle
Controller/GameController.php
GameController.rankingTeamPointsAction
public function rankingTeamPointsAction($id) { $game = $this->getDoctrine()->getRepository('VideoGamesRecordsCoreBundle:Game')->find($id); $breadcrumbs = $this->getGameBreadcrumbs($game); $breadcrumbs->addItem('game.pointchartranking.full'); return $this->render( 'VideoGamesRecordsTeamBundle:Ranking:points-chart.html.twig', [ 'ranking' => $this->getDoctrine()->getRepository('VideoGamesRecordsTeamBundle:TeamGame')->getRankingPoints($id, 100, null), ] ); }
php
public function rankingTeamPointsAction($id) { $game = $this->getDoctrine()->getRepository('VideoGamesRecordsCoreBundle:Game')->find($id); $breadcrumbs = $this->getGameBreadcrumbs($game); $breadcrumbs->addItem('game.pointchartranking.full'); return $this->render( 'VideoGamesRecordsTeamBundle:Ranking:points-chart.html.twig', [ 'ranking' => $this->getDoctrine()->getRepository('VideoGamesRecordsTeamBundle:TeamGame')->getRankingPoints($id, 100, null), ] ); }
[ "public", "function", "rankingTeamPointsAction", "(", "$", "id", ")", "{", "$", "game", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "'VideoGamesRecordsCoreBundle:Game'", ")", "->", "find", "(", "$", "id", ")", ";", "$", "breadcrumbs", "=", "$", "this", "->", "getGameBreadcrumbs", "(", "$", "game", ")", ";", "$", "breadcrumbs", "->", "addItem", "(", "'game.pointchartranking.full'", ")", ";", "return", "$", "this", "->", "render", "(", "'VideoGamesRecordsTeamBundle:Ranking:points-chart.html.twig'", ",", "[", "'ranking'", "=>", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "'VideoGamesRecordsTeamBundle:TeamGame'", ")", "->", "getRankingPoints", "(", "$", "id", ",", "100", ",", "null", ")", ",", "]", ")", ";", "}" ]
@Route("/ranking-points/id/{id}", requirements={"id": "[1-9]\d*"}, name="vgr_team_game_ranking_points") @Method("GET") @Cache(smaxage="10") @param int $id @return \Symfony\Component\HttpFoundation\Response
[ "@Route", "(", "/", "ranking", "-", "points", "/", "id", "/", "{", "id", "}", "requirements", "=", "{", "id", ":", "[", "1", "-", "9", "]", "\\", "d", "*", "}", "name", "=", "vgr_team_game_ranking_points", ")", "@Method", "(", "GET", ")", "@Cache", "(", "smaxage", "=", "10", ")" ]
train
https://github.com/video-games-records/TeamBundle/blob/4e5b73874bacb96f70ab16e74d54a1b6efc8e62f/Controller/GameController.php#L25-L38
video-games-records/TeamBundle
Controller/GameController.php
GameController.rankingTeamMedalsAction
public function rankingTeamMedalsAction($id) { $game = $this->getDoctrine()->getRepository('VideoGamesRecordsCoreBundle:Game')->find($id); $breadcrumbs = $this->getGameBreadcrumbs($game); $breadcrumbs->addItem('game.medalranking.full'); return $this->render( 'VideoGamesRecordsTeamBundle:Ranking:medals.html.twig', [ 'ranking' => $this->getDoctrine()->getRepository('VideoGamesRecordsTeamBundle:TeamGame')->getRankingMedals($id, 100, null), ] ); }
php
public function rankingTeamMedalsAction($id) { $game = $this->getDoctrine()->getRepository('VideoGamesRecordsCoreBundle:Game')->find($id); $breadcrumbs = $this->getGameBreadcrumbs($game); $breadcrumbs->addItem('game.medalranking.full'); return $this->render( 'VideoGamesRecordsTeamBundle:Ranking:medals.html.twig', [ 'ranking' => $this->getDoctrine()->getRepository('VideoGamesRecordsTeamBundle:TeamGame')->getRankingMedals($id, 100, null), ] ); }
[ "public", "function", "rankingTeamMedalsAction", "(", "$", "id", ")", "{", "$", "game", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "'VideoGamesRecordsCoreBundle:Game'", ")", "->", "find", "(", "$", "id", ")", ";", "$", "breadcrumbs", "=", "$", "this", "->", "getGameBreadcrumbs", "(", "$", "game", ")", ";", "$", "breadcrumbs", "->", "addItem", "(", "'game.medalranking.full'", ")", ";", "return", "$", "this", "->", "render", "(", "'VideoGamesRecordsTeamBundle:Ranking:medals.html.twig'", ",", "[", "'ranking'", "=>", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "'VideoGamesRecordsTeamBundle:TeamGame'", ")", "->", "getRankingMedals", "(", "$", "id", ",", "100", ",", "null", ")", ",", "]", ")", ";", "}" ]
@Route("/ranking-medals/id/{id}", requirements={"id": "[1-9]\d*"}, name="vgr_team_game_ranking_medals") @Method("GET") @Cache(smaxage="10") @param int $id @return \Symfony\Component\HttpFoundation\Response
[ "@Route", "(", "/", "ranking", "-", "medals", "/", "id", "/", "{", "id", "}", "requirements", "=", "{", "id", ":", "[", "1", "-", "9", "]", "\\", "d", "*", "}", "name", "=", "vgr_team_game_ranking_medals", ")", "@Method", "(", "GET", ")", "@Cache", "(", "smaxage", "=", "10", ")" ]
train
https://github.com/video-games-records/TeamBundle/blob/4e5b73874bacb96f70ab16e74d54a1b6efc8e62f/Controller/GameController.php#L49-L62
interactivesolutions/honeycomb-core
src/http/controllers/HCFormManagerController.php
HCFormManagerController.getForm
private function getForm(string $key) { if (!Cache::has('hc-forms')) Artisan::call('hc:forms'); $list = Cache::get('hc-forms'); $new = substr($key, 0, -4); $edit = substr($key, 0, -5); if (isset($list[$new])) { $form = new $list[$new](); return $form->createForm(); } if (isset($list[$edit])) { $form = new $list[$edit](); return $form->createForm(true); } return HCLog::error('CORE-0010', 'Form not found: ' . $key); }
php
private function getForm(string $key) { if (!Cache::has('hc-forms')) Artisan::call('hc:forms'); $list = Cache::get('hc-forms'); $new = substr($key, 0, -4); $edit = substr($key, 0, -5); if (isset($list[$new])) { $form = new $list[$new](); return $form->createForm(); } if (isset($list[$edit])) { $form = new $list[$edit](); return $form->createForm(true); } return HCLog::error('CORE-0010', 'Form not found: ' . $key); }
[ "private", "function", "getForm", "(", "string", "$", "key", ")", "{", "if", "(", "!", "Cache", "::", "has", "(", "'hc-forms'", ")", ")", "Artisan", "::", "call", "(", "'hc:forms'", ")", ";", "$", "list", "=", "Cache", "::", "get", "(", "'hc-forms'", ")", ";", "$", "new", "=", "substr", "(", "$", "key", ",", "0", ",", "-", "4", ")", ";", "$", "edit", "=", "substr", "(", "$", "key", ",", "0", ",", "-", "5", ")", ";", "if", "(", "isset", "(", "$", "list", "[", "$", "new", "]", ")", ")", "{", "$", "form", "=", "new", "$", "list", "[", "$", "new", "]", "(", ")", ";", "return", "$", "form", "->", "createForm", "(", ")", ";", "}", "if", "(", "isset", "(", "$", "list", "[", "$", "edit", "]", ")", ")", "{", "$", "form", "=", "new", "$", "list", "[", "$", "edit", "]", "(", ")", ";", "return", "$", "form", "->", "createForm", "(", "true", ")", ";", "}", "return", "HCLog", "::", "error", "(", "'CORE-0010'", ",", "'Form not found: '", ".", "$", "key", ")", ";", "}" ]
Get form from cache or get it from class and than store it to cache @param string $key @return mixed
[ "Get", "form", "from", "cache", "or", "get", "it", "from", "class", "and", "than", "store", "it", "to", "cache" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/http/controllers/HCFormManagerController.php#L40-L61
webcreate/util
src/Webcreate/Util/Cli.php
Cli.prepare
public function prepare($command, array $arguments = array()) { $commandline = $command; foreach ($arguments as $option => $value) { if (is_bool($value)) { if ($value === true) { $commandline .= ' ' . $option; } } else { $seperator = ' '; if (!is_integer($option)) { $commandline .= ' ' . $option; if (substr($option, -1, 1) == '=') { $seperator = ''; } } $commandline .= $seperator . ProcessUtils::escapeArgument($value); } } return $commandline; }
php
public function prepare($command, array $arguments = array()) { $commandline = $command; foreach ($arguments as $option => $value) { if (is_bool($value)) { if ($value === true) { $commandline .= ' ' . $option; } } else { $seperator = ' '; if (!is_integer($option)) { $commandline .= ' ' . $option; if (substr($option, -1, 1) == '=') { $seperator = ''; } } $commandline .= $seperator . ProcessUtils::escapeArgument($value); } } return $commandline; }
[ "public", "function", "prepare", "(", "$", "command", ",", "array", "$", "arguments", "=", "array", "(", ")", ")", "{", "$", "commandline", "=", "$", "command", ";", "foreach", "(", "$", "arguments", "as", "$", "option", "=>", "$", "value", ")", "{", "if", "(", "is_bool", "(", "$", "value", ")", ")", "{", "if", "(", "$", "value", "===", "true", ")", "{", "$", "commandline", ".=", "' '", ".", "$", "option", ";", "}", "}", "else", "{", "$", "seperator", "=", "' '", ";", "if", "(", "!", "is_integer", "(", "$", "option", ")", ")", "{", "$", "commandline", ".=", "' '", ".", "$", "option", ";", "if", "(", "substr", "(", "$", "option", ",", "-", "1", ",", "1", ")", "==", "'='", ")", "{", "$", "seperator", "=", "''", ";", "}", "}", "$", "commandline", ".=", "$", "seperator", ".", "ProcessUtils", "::", "escapeArgument", "(", "$", "value", ")", ";", "}", "}", "return", "$", "commandline", ";", "}" ]
Prepares a commandline @param string $command @param array $arguments @return string
[ "Prepares", "a", "commandline" ]
train
https://github.com/webcreate/util/blob/16c53697a3d96431d0afd57f8ab9f1df6c21e976/src/Webcreate/Util/Cli.php#L53-L75
webcreate/util
src/Webcreate/Util/Cli.php
Cli.execute
public function execute($commandline, $callback = null, $cwd = null) { $this->process = new Process($commandline, $cwd, null, null, $this->timeout); return $this->process->run($callback); }
php
public function execute($commandline, $callback = null, $cwd = null) { $this->process = new Process($commandline, $cwd, null, null, $this->timeout); return $this->process->run($callback); }
[ "public", "function", "execute", "(", "$", "commandline", ",", "$", "callback", "=", "null", ",", "$", "cwd", "=", "null", ")", "{", "$", "this", "->", "process", "=", "new", "Process", "(", "$", "commandline", ",", "$", "cwd", ",", "null", ",", "null", ",", "$", "this", "->", "timeout", ")", ";", "return", "$", "this", "->", "process", "->", "run", "(", "$", "callback", ")", ";", "}" ]
Runs the process. The callback receives the type of output (out or err) and some bytes from the output in real-time. It allows to have feedback from the independent process during execution. The STDOUT and STDERR are also available after the process is finished via the getOutput() and getErrorOutput() methods. @param string $commandline The command line to run @param Closure|string|array $callback A PHP callback to run whenever there is some output available on STDOUT or STDERR @param string $cwd The working directory @return integer The exit status code @throws \RuntimeException When process can't be launch or is stopped
[ "Runs", "the", "process", "." ]
train
https://github.com/webcreate/util/blob/16c53697a3d96431d0afd57f8ab9f1df6c21e976/src/Webcreate/Util/Cli.php#L96-L101
WScore/Validation
src/Utils/ValueTO.php
ValueTO.message
public function message() { if (!$this->error) { return ''; } if (isset($this->message)) { return $this->message; } if ($this->messenger) { $type = $this->getType(); $method = $this->getErrorMethod(); $parameter = $this->getParameter(); $this->message = $this->messenger->find($type, $method, $parameter); return $this->message; } throw new \BadMethodCallException('cannot return a message. '); }
php
public function message() { if (!$this->error) { return ''; } if (isset($this->message)) { return $this->message; } if ($this->messenger) { $type = $this->getType(); $method = $this->getErrorMethod(); $parameter = $this->getParameter(); $this->message = $this->messenger->find($type, $method, $parameter); return $this->message; } throw new \BadMethodCallException('cannot return a message. '); }
[ "public", "function", "message", "(", ")", "{", "if", "(", "!", "$", "this", "->", "error", ")", "{", "return", "''", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "message", ")", ")", "{", "return", "$", "this", "->", "message", ";", "}", "if", "(", "$", "this", "->", "messenger", ")", "{", "$", "type", "=", "$", "this", "->", "getType", "(", ")", ";", "$", "method", "=", "$", "this", "->", "getErrorMethod", "(", ")", ";", "$", "parameter", "=", "$", "this", "->", "getParameter", "(", ")", ";", "$", "this", "->", "message", "=", "$", "this", "->", "messenger", "->", "find", "(", "$", "type", ",", "$", "method", ",", "$", "parameter", ")", ";", "return", "$", "this", "->", "message", ";", "}", "throw", "new", "\\", "BadMethodCallException", "(", "'cannot return a message. '", ")", ";", "}" ]
gets message regardless of the error state of this ValueTO. use this message ONLY WHEN valueTO is error. @return string|array
[ "gets", "message", "regardless", "of", "the", "error", "state", "of", "this", "ValueTO", ".", "use", "this", "message", "ONLY", "WHEN", "valueTO", "is", "error", "." ]
train
https://github.com/WScore/Validation/blob/25c0dca37d624bb0bb22f8e79ba54db2f69e0950/src/Utils/ValueTO.php#L185-L203
fccn/oai-pmh-core
src/schemas/ands_oai.php
ANDS_OAI.addChild
protected function addChild($mom_node, $name, $value='') { return $this->oai_pmh->addChild($mom_node, $name, $value); }
php
protected function addChild($mom_node, $name, $value='') { return $this->oai_pmh->addChild($mom_node, $name, $value); }
[ "protected", "function", "addChild", "(", "$", "mom_node", ",", "$", "name", ",", "$", "value", "=", "''", ")", "{", "return", "$", "this", "->", "oai_pmh", "->", "addChild", "(", "$", "mom_node", ",", "$", "name", ",", "$", "value", ")", ";", "}" ]
A worker function for easily adding a newly created node to current XML Doc. @param $mom_node Type: DOMElement. Node the new child will be attached to. @param $name Type: sting. The name of the child node is being added. @param $value Type: sting. The text content of the child node is being added. The default is ''. @return DOMElement. The added child node
[ "A", "worker", "function", "for", "easily", "adding", "a", "newly", "created", "node", "to", "current", "XML", "Doc", "." ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_oai.php#L83-L86
fccn/oai-pmh-core
src/schemas/ands_oai.php
ANDS_OAI.create_regObject
protected function create_regObject($group, $key, $originatingSource) { $regObj_node = $this->addChild($this->working_node, 'registryObject'); $regObj_node->setAttribute('group', $group); $this->addChild($regObj_node, 'key', $key); $this->addChild($regObj_node, 'originatingSource', $originatingSource); $this->working_node = $regObj_node; }
php
protected function create_regObject($group, $key, $originatingSource) { $regObj_node = $this->addChild($this->working_node, 'registryObject'); $regObj_node->setAttribute('group', $group); $this->addChild($regObj_node, 'key', $key); $this->addChild($regObj_node, 'originatingSource', $originatingSource); $this->working_node = $regObj_node; }
[ "protected", "function", "create_regObject", "(", "$", "group", ",", "$", "key", ",", "$", "originatingSource", ")", "{", "$", "regObj_node", "=", "$", "this", "->", "addChild", "(", "$", "this", "->", "working_node", ",", "'registryObject'", ")", ";", "$", "regObj_node", "->", "setAttribute", "(", "'group'", ",", "$", "group", ")", ";", "$", "this", "->", "addChild", "(", "$", "regObj_node", ",", "'key'", ",", "$", "key", ")", ";", "$", "this", "->", "addChild", "(", "$", "regObj_node", ",", "'originatingSource'", ",", "$", "originatingSource", ")", ";", "$", "this", "->", "working_node", "=", "$", "regObj_node", ";", "}" ]
Create a single registryObject node. Each set has its own structure but they all have an attribute of group, a key node and an originatingSource node. The newly created node will be used as the working node. \param $group string, group attribute of the new registryObject node . \param $key string, key node, used as an identifier. \param $originatingSource string, an url of the data provider.
[ "Create", "a", "single", "registryObject", "node", ".", "Each", "set", "has", "its", "own", "structure", "but", "they", "all", "have", "an", "attribute", "of", "group", "a", "key", "node", "and", "an", "originatingSource", "node", ".", "The", "newly", "created", "node", "will", "be", "used", "as", "the", "working", "node", "." ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_oai.php#L106-L113
fccn/oai-pmh-core
src/schemas/ands_oai.php
ANDS_OAI.create_dcs_node
protected function create_dcs_node($set_name, $set_type) { $this->working_node = $this->addChild($this->working_node, $set_name); $this->working_node->setAttribute('type', $set_type); }
php
protected function create_dcs_node($set_name, $set_type) { $this->working_node = $this->addChild($this->working_node, $set_name); $this->working_node->setAttribute('type', $set_type); }
[ "protected", "function", "create_dcs_node", "(", "$", "set_name", ",", "$", "set_type", ")", "{", "$", "this", "->", "working_node", "=", "$", "this", "->", "addChild", "(", "$", "this", "->", "working_node", ",", "$", "set_name", ")", ";", "$", "this", "->", "working_node", "->", "setAttribute", "(", "'type'", ",", "$", "set_type", ")", ";", "}" ]
RIF-CS node is the content node of RIF-CS metadata node which starts from regObjects. Each set supportted in RIF-CS has its own content model. The created node will be used as the root node of this record for following nodes will be created. \param $set_name string, the name of set. For ANDS, they are Activity, Party and Collection \param $set_type string, the type of set. For example, Activity can have project as a type.
[ "RIF", "-", "CS", "node", "is", "the", "content", "node", "of", "RIF", "-", "CS", "metadata", "node", "which", "starts", "from", "regObjects", ".", "Each", "set", "supportted", "in", "RIF", "-", "CS", "has", "its", "own", "content", "model", ".", "The", "created", "node", "will", "be", "used", "as", "the", "root", "node", "of", "this", "record", "for", "following", "nodes", "will", "be", "created", "." ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_oai.php#L122-L126
fccn/oai-pmh-core
src/schemas/ands_oai.php
ANDS_OAI.create_name_node
protected function create_name_node($name_type = 'primary') { $c = $this->addChild($this->working_node, 'name'); $c->setAttribute('type', $name_type); return $c; }
php
protected function create_name_node($name_type = 'primary') { $c = $this->addChild($this->working_node, 'name'); $c->setAttribute('type', $name_type); return $c; }
[ "protected", "function", "create_name_node", "(", "$", "name_type", "=", "'primary'", ")", "{", "$", "c", "=", "$", "this", "->", "addChild", "(", "$", "this", "->", "working_node", ",", "'name'", ")", ";", "$", "c", "->", "setAttribute", "(", "'type'", ",", "$", "name_type", ")", ";", "return", "$", "c", ";", "}" ]
Create a top level name node. @param $name_type string. Text for the types, can be either primary or abbreviated. Default: primary @return DOMElement $added_name_node. The newly created node, it will be used for further expansion by adding namePart.
[ "Create", "a", "top", "level", "name", "node", ".", "@param", "$name_type", "string", ".", "Text", "for", "the", "types", "can", "be", "either", "primary", "or", "abbreviated", ".", "Default", ":", "primary" ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_oai.php#L135-L140
fccn/oai-pmh-core
src/schemas/ands_oai.php
ANDS_OAI.create_namePart
protected function create_namePart($name_node, $value, $part_type = '') { $c = $this->addChild($name_node, 'namePart', $value); if (!empty($part_type)) { $c->setAttribute('type', $part_type); } }
php
protected function create_namePart($name_node, $value, $part_type = '') { $c = $this->addChild($name_node, 'namePart', $value); if (!empty($part_type)) { $c->setAttribute('type', $part_type); } }
[ "protected", "function", "create_namePart", "(", "$", "name_node", ",", "$", "value", ",", "$", "part_type", "=", "''", ")", "{", "$", "c", "=", "$", "this", "->", "addChild", "(", "$", "name_node", ",", "'namePart'", ",", "$", "value", ")", ";", "if", "(", "!", "empty", "(", "$", "part_type", ")", ")", "{", "$", "c", "->", "setAttribute", "(", "'type'", ",", "$", "part_type", ")", ";", "}", "}" ]
Create a namePart of a name node. @param $name_node Type: DOMElement. Node of name_node created previously @param $value Type: string. Text fror this namePart @param $part_type Type: string, used for group:person record. Types can be: titile, given, family
[ "Create", "a", "namePart", "of", "a", "name", "node", ".", "@param", "$name_node", "Type", ":", "DOMElement", ".", "Node", "of", "name_node", "created", "previously" ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_oai.php#L153-L159
fccn/oai-pmh-core
src/schemas/ands_oai.php
ANDS_OAI.create_relatedObject
protected function create_relatedObject($key, $relation_type) { $c = $this->addChild($this->working_node, 'relatedObject'); $this->addChild($c, 'key', $key); $c = $this->addChild($c, 'relation'); // Mimick ANDS with enpty value to get both tags for relation. Only for better display // $c = $this->addChild($c, 'relation',' '); $c->setAttribute('type', $relation_type); }
php
protected function create_relatedObject($key, $relation_type) { $c = $this->addChild($this->working_node, 'relatedObject'); $this->addChild($c, 'key', $key); $c = $this->addChild($c, 'relation'); // Mimick ANDS with enpty value to get both tags for relation. Only for better display // $c = $this->addChild($c, 'relation',' '); $c->setAttribute('type', $relation_type); }
[ "protected", "function", "create_relatedObject", "(", "$", "key", ",", "$", "relation_type", ")", "{", "$", "c", "=", "$", "this", "->", "addChild", "(", "$", "this", "->", "working_node", ",", "'relatedObject'", ")", ";", "$", "this", "->", "addChild", "(", "$", "c", ",", "'key'", ",", "$", "key", ")", ";", "$", "c", "=", "$", "this", "->", "addChild", "(", "$", "c", ",", "'relation'", ")", ";", "// Mimick ANDS with enpty value to get both tags for relation. Only for better display", "// $c = $this->addChild($c, 'relation',' ');", "$", "c", "->", "setAttribute", "(", "'type'", ",", "$", "relation_type", ")", ";", "}" ]
Create related object. One RIF-CS can have more than one related object nodes, each object is described by one node. \param $key Type: string. The identifier of the related object. \param $relation_type Type: string. Type of relationship.
[ "Create", "related", "object", ".", "One", "RIF", "-", "CS", "can", "have", "more", "than", "one", "related", "object", "nodes", "each", "object", "is", "described", "by", "one", "node", ".", "\\", "param", "$key", "Type", ":", "string", ".", "The", "identifier", "of", "the", "related", "object", ".", "\\", "param", "$relation_type", "Type", ":", "string", ".", "Type", "of", "relationship", "." ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_oai.php#L169-L177
fccn/oai-pmh-core
src/schemas/ands_oai.php
ANDS_OAI.create_description_node
protected function create_description_node($value, $des_type='brief') { $c = $this->addChild($this->working_node, 'description', $value); $c->setAttribute('type', $des_type); }
php
protected function create_description_node($value, $des_type='brief') { $c = $this->addChild($this->working_node, 'description', $value); $c->setAttribute('type', $des_type); }
[ "protected", "function", "create_description_node", "(", "$", "value", ",", "$", "des_type", "=", "'brief'", ")", "{", "$", "c", "=", "$", "this", "->", "addChild", "(", "$", "this", "->", "working_node", ",", "'description'", ",", "$", "value", ")", ";", "$", "c", "->", "setAttribute", "(", "'type'", ",", "$", "des_type", ")", ";", "}" ]
Create description node. One RIF-CS can have more than one description nodes. Each description node has only one description. \param $value Type: string. The content of the description. \param $des_type Type: string. Type of the description. Types can be brief, full, acessRights and note. Default is 'brief'.
[ "Create", "description", "node", ".", "One", "RIF", "-", "CS", "can", "have", "more", "than", "one", "description", "nodes", ".", "Each", "description", "node", "has", "only", "one", "description", ".", "\\", "param", "$value", "Type", ":", "string", ".", "The", "content", "of", "the", "description", ".", "\\", "param", "$des_type", "Type", ":", "string", ".", "Type", "of", "the", "description", ".", "Types", "can", "be", "brief", "full", "acessRights", "and", "note", ".", "Default", "is", "brief", "." ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_oai.php#L184-L188
fccn/oai-pmh-core
src/schemas/ands_oai.php
ANDS_OAI.create_identifier_node
protected function create_identifier_node($key, $i_type='local') { $c = $this->addChild($this->working_node, 'identifier', $key); $c->setAttribute('type', $i_type); }
php
protected function create_identifier_node($key, $i_type='local') { $c = $this->addChild($this->working_node, 'identifier', $key); $c->setAttribute('type', $i_type); }
[ "protected", "function", "create_identifier_node", "(", "$", "key", ",", "$", "i_type", "=", "'local'", ")", "{", "$", "c", "=", "$", "this", "->", "addChild", "(", "$", "this", "->", "working_node", ",", "'identifier'", ",", "$", "key", ")", ";", "$", "c", "->", "setAttribute", "(", "'type'", ",", "$", "i_type", ")", ";", "}" ]
Create local or other type of identifier inside of RIF-CS metadata node \param $key Type string. The indentifier itself. \param $i_type Type string. Type of identifier. Can be abn, uri, local, etc.. Default is local.
[ "Create", "local", "or", "other", "type", "of", "identifier", "inside", "of", "RIF", "-", "CS", "metadata", "node", "\\", "param", "$key", "Type", "string", ".", "The", "indentifier", "itself", ".", "\\", "param", "$i_type", "Type", "string", ".", "Type", "of", "identifier", ".", "Can", "be", "abn", "uri", "local", "etc", "..", "Default", "is", "local", "." ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_oai.php#L196-L200
fccn/oai-pmh-core
src/schemas/ands_oai.php
ANDS_OAI.create_e_node
protected function create_e_node($addr_node, $e_node, $e_type = 'email') { $c = $this->addChild($addr_node, 'electronic'); $c->setAttribute('type', $e_type); $this->addChild($c, 'value', $e_node); }
php
protected function create_e_node($addr_node, $e_node, $e_type = 'email') { $c = $this->addChild($addr_node, 'electronic'); $c->setAttribute('type', $e_type); $this->addChild($c, 'value', $e_node); }
[ "protected", "function", "create_e_node", "(", "$", "addr_node", ",", "$", "e_node", ",", "$", "e_type", "=", "'email'", ")", "{", "$", "c", "=", "$", "this", "->", "addChild", "(", "$", "addr_node", ",", "'electronic'", ")", ";", "$", "c", "->", "setAttribute", "(", "'type'", ",", "$", "e_type", ")", ";", "$", "this", "->", "addChild", "(", "$", "c", ",", "'value'", ",", "$", "e_node", ")", ";", "}" ]
Electrical address node. Used for email, url, etc \param $addr_node Type: DOMElement. Previously created address node. \param $e_node Type: string. The content of the adding node. \param $e_type Type: string. Default is email.
[ "Electrical", "address", "node", ".", "Used", "for", "email", "url", "etc", "\\", "param", "$addr_node", "Type", ":", "DOMElement", ".", "Previously", "created", "address", "node", ".", "\\", "param", "$e_node", "Type", ":", "string", ".", "The", "content", "of", "the", "adding", "node", ".", "\\", "param", "$e_type", "Type", ":", "string", ".", "Default", "is", "email", "." ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_oai.php#L224-L229