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
j-d/draggy
src/Draggy/Autocode/Templates/PHP/Symfony2/Doctrine2/Entity4.php
Entity4.getSingleContainsCodeLinesBodyPart
public function getSingleContainsCodeLinesBodyPart(PHPAttribute $attribute) { $lines = []; $lines[] = 'return ' . $attribute->getThisName() . '->contains($' . $attribute->getSingleName() . ');'; return $lines; }
php
public function getSingleContainsCodeLinesBodyPart(PHPAttribute $attribute) { $lines = []; $lines[] = 'return ' . $attribute->getThisName() . '->contains($' . $attribute->getSingleName() . ');'; return $lines; }
[ "public", "function", "getSingleContainsCodeLinesBodyPart", "(", "PHPAttribute", "$", "attribute", ")", "{", "$", "lines", "=", "[", "]", ";", "$", "lines", "[", "]", "=", "'return '", ".", "$", "attribute", "->", "getThisName", "(", ")", ".", "'->contains($'", ".", "$", "attribute", "->", "getSingleName", "(", ")", ".", "');'", ";", "return", "$", "lines", ";", "}" ]
<editor-fold desc="Contains">
[ "<editor", "-", "fold", "desc", "=", "Contains", ">" ]
train
https://github.com/j-d/draggy/blob/97ffc66e1aacb5f685d7aac5251c4abb8888d4bb/src/Draggy/Autocode/Templates/PHP/Symfony2/Doctrine2/Entity4.php#L439-L446
bariew/yii2-i18n-cms-module
models/MessageSearch.php
MessageSearch.search
public function search($params) { $query = Message::find(); $query->joinWith('source'); $dataProvider = new ActiveDataProvider(['query' => $query]); $dataProvider->getSort()->attributes['sourceMessage'] = [ 'asc' => ['source.message' => SORT_ASC], 'desc' => ['source.message' => SORT_DESC], ]; $dataProvider->getSort()->attributes['sourceCategory'] = [ 'asc' => ['source.category' => SORT_ASC], 'desc' => ['source.category' => SORT_DESC], ]; if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere(['id' => $this->id]); if ($this->translation) { $t = addslashes($this->translation); $query->where("translation like '%{$t}%'"); } if ($this->translationUpdate === 'is null') { $query->where('translation is null'); } if ($this->translationUpdate === 'is not null') { $query->where('translation is not null'); } if ($this->translation) { $query->andWhere(['like', 'translation', '%' . $this->translation .'%', false]); } if ($this->sourceMessage) { $query->andFilterWhere(['like', 'source.message', $this->sourceMessage]); } if ($this->language) { $query->andWhere(['language' => $this->language]); } if ($this->sourceCategory) { $query->andFilterWhere(['like', 'source.category', $this->sourceCategory]); } return $dataProvider; }
php
public function search($params) { $query = Message::find(); $query->joinWith('source'); $dataProvider = new ActiveDataProvider(['query' => $query]); $dataProvider->getSort()->attributes['sourceMessage'] = [ 'asc' => ['source.message' => SORT_ASC], 'desc' => ['source.message' => SORT_DESC], ]; $dataProvider->getSort()->attributes['sourceCategory'] = [ 'asc' => ['source.category' => SORT_ASC], 'desc' => ['source.category' => SORT_DESC], ]; if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere(['id' => $this->id]); if ($this->translation) { $t = addslashes($this->translation); $query->where("translation like '%{$t}%'"); } if ($this->translationUpdate === 'is null') { $query->where('translation is null'); } if ($this->translationUpdate === 'is not null') { $query->where('translation is not null'); } if ($this->translation) { $query->andWhere(['like', 'translation', '%' . $this->translation .'%', false]); } if ($this->sourceMessage) { $query->andFilterWhere(['like', 'source.message', $this->sourceMessage]); } if ($this->language) { $query->andWhere(['language' => $this->language]); } if ($this->sourceCategory) { $query->andFilterWhere(['like', 'source.category', $this->sourceCategory]); } return $dataProvider; }
[ "public", "function", "search", "(", "$", "params", ")", "{", "$", "query", "=", "Message", "::", "find", "(", ")", ";", "$", "query", "->", "joinWith", "(", "'source'", ")", ";", "$", "dataProvider", "=", "new", "ActiveDataProvider", "(", "[", "'query'", "=>", "$", "query", "]", ")", ";", "$", "dataProvider", "->", "getSort", "(", ")", "->", "attributes", "[", "'sourceMessage'", "]", "=", "[", "'asc'", "=>", "[", "'source.message'", "=>", "SORT_ASC", "]", ",", "'desc'", "=>", "[", "'source.message'", "=>", "SORT_DESC", "]", ",", "]", ";", "$", "dataProvider", "->", "getSort", "(", ")", "->", "attributes", "[", "'sourceCategory'", "]", "=", "[", "'asc'", "=>", "[", "'source.category'", "=>", "SORT_ASC", "]", ",", "'desc'", "=>", "[", "'source.category'", "=>", "SORT_DESC", "]", ",", "]", ";", "if", "(", "!", "(", "$", "this", "->", "load", "(", "$", "params", ")", "&&", "$", "this", "->", "validate", "(", ")", ")", ")", "{", "return", "$", "dataProvider", ";", "}", "$", "query", "->", "andFilterWhere", "(", "[", "'id'", "=>", "$", "this", "->", "id", "]", ")", ";", "if", "(", "$", "this", "->", "translation", ")", "{", "$", "t", "=", "addslashes", "(", "$", "this", "->", "translation", ")", ";", "$", "query", "->", "where", "(", "\"translation like '%{$t}%'\"", ")", ";", "}", "if", "(", "$", "this", "->", "translationUpdate", "===", "'is null'", ")", "{", "$", "query", "->", "where", "(", "'translation is null'", ")", ";", "}", "if", "(", "$", "this", "->", "translationUpdate", "===", "'is not null'", ")", "{", "$", "query", "->", "where", "(", "'translation is not null'", ")", ";", "}", "if", "(", "$", "this", "->", "translation", ")", "{", "$", "query", "->", "andWhere", "(", "[", "'like'", ",", "'translation'", ",", "'%'", ".", "$", "this", "->", "translation", ".", "'%'", ",", "false", "]", ")", ";", "}", "if", "(", "$", "this", "->", "sourceMessage", ")", "{", "$", "query", "->", "andFilterWhere", "(", "[", "'like'", ",", "'source.message'", ",", "$", "this", "->", "sourceMessage", "]", ")", ";", "}", "if", "(", "$", "this", "->", "language", ")", "{", "$", "query", "->", "andWhere", "(", "[", "'language'", "=>", "$", "this", "->", "language", "]", ")", ";", "}", "if", "(", "$", "this", "->", "sourceCategory", ")", "{", "$", "query", "->", "andFilterWhere", "(", "[", "'like'", ",", "'source.category'", ",", "$", "this", "->", "sourceCategory", "]", ")", ";", "}", "return", "$", "dataProvider", ";", "}" ]
Default index search method @param $params @return ActiveDataProvider
[ "Default", "index", "search", "method" ]
train
https://github.com/bariew/yii2-i18n-cms-module/blob/18d2394565cdd8b5070a287a739c9007705ef18a/models/MessageSearch.php#L44-L91
heidelpay/PhpDoc
src/phpDocumentor/Compiler/Pass/Debug.php
Debug.execute
public function execute(ProjectDescriptor $project) { $this->analyzer->analyze($project); $this->log->debug((string) $this->analyzer); }
php
public function execute(ProjectDescriptor $project) { $this->analyzer->analyze($project); $this->log->debug((string) $this->analyzer); }
[ "public", "function", "execute", "(", "ProjectDescriptor", "$", "project", ")", "{", "$", "this", "->", "analyzer", "->", "analyze", "(", "$", "project", ")", ";", "$", "this", "->", "log", "->", "debug", "(", "(", "string", ")", "$", "this", "->", "analyzer", ")", ";", "}" ]
Analyzes the given project and returns the results to the logger. @param ProjectDescriptor $project @return void
[ "Analyzes", "the", "given", "project", "and", "returns", "the", "results", "to", "the", "logger", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Compiler/Pass/Debug.php#L62-L66
thienhungho/yii2-product-management
src/modules/ProductManage/controllers/ProductTypeController.php
ProductTypeController.actionDelete
public function actionDelete($id) { $model = $this->findModel($id); if ($model->deleteWithRelated()) { set_flash_success_delete_content(); Seo::deleteAll([ 'obj_type' => $model->name, ]); TermRelationships::deleteAll([ 'obj_type' => $model->name, ]); } else { set_flash_error_delete_content(); } return $this->goBack(request()->referrer); }
php
public function actionDelete($id) { $model = $this->findModel($id); if ($model->deleteWithRelated()) { set_flash_success_delete_content(); Seo::deleteAll([ 'obj_type' => $model->name, ]); TermRelationships::deleteAll([ 'obj_type' => $model->name, ]); } else { set_flash_error_delete_content(); } return $this->goBack(request()->referrer); }
[ "public", "function", "actionDelete", "(", "$", "id", ")", "{", "$", "model", "=", "$", "this", "->", "findModel", "(", "$", "id", ")", ";", "if", "(", "$", "model", "->", "deleteWithRelated", "(", ")", ")", "{", "set_flash_success_delete_content", "(", ")", ";", "Seo", "::", "deleteAll", "(", "[", "'obj_type'", "=>", "$", "model", "->", "name", ",", "]", ")", ";", "TermRelationships", "::", "deleteAll", "(", "[", "'obj_type'", "=>", "$", "model", "->", "name", ",", "]", ")", ";", "}", "else", "{", "set_flash_error_delete_content", "(", ")", ";", "}", "return", "$", "this", "->", "goBack", "(", "request", "(", ")", "->", "referrer", ")", ";", "}" ]
@param $id @return \yii\web\Response @throws NotFoundHttpException @throws \yii\db\Exception
[ "@param", "$id" ]
train
https://github.com/thienhungho/yii2-product-management/blob/72e1237bba123faf671e44491bd93077b50adde9/src/modules/ProductManage/controllers/ProductTypeController.php#L122-L138
thienhungho/yii2-product-management
src/modules/ProductManage/controllers/ProductTypeController.php
ProductTypeController.findModel
protected function findModel($id) { if (($model = ProductType::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } }
php
protected function findModel($id) { if (($model = ProductType::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } }
[ "protected", "function", "findModel", "(", "$", "id", ")", "{", "if", "(", "(", "$", "model", "=", "ProductType", "::", "findOne", "(", "$", "id", ")", ")", "!==", "null", ")", "{", "return", "$", "model", ";", "}", "else", "{", "throw", "new", "NotFoundHttpException", "(", "t", "(", "'app'", ",", "'The requested page does not exist.'", ")", ")", ";", "}", "}" ]
Finds the ProductType model based on its primary key value. If the model is not found, a 404 HTTP exception will be thrown. @param integer $id @return ProductType the loaded model @throws NotFoundHttpException if the model cannot be found
[ "Finds", "the", "ProductType", "model", "based", "on", "its", "primary", "key", "value", ".", "If", "the", "model", "is", "not", "found", "a", "404", "HTTP", "exception", "will", "be", "thrown", "." ]
train
https://github.com/thienhungho/yii2-product-management/blob/72e1237bba123faf671e44491bd93077b50adde9/src/modules/ProductManage/controllers/ProductTypeController.php#L230-L237
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.init_session
private function init_session() { session_set_cookie_params(ini_get('session.cookie_lifetime'), $this->path); session_name('sid'); session_start(); $this->session = &$_SESSION['session']; if (!isset($this->session['msg'])) { $this->session['msg'] = array('error' => array(), 'information' => array()); } $this->user = &$_SESSION['user']; # Обратная совместимость $GLOBALS['session'] = &$_SESSION['session']; $GLOBALS['user'] = &$_SESSION['user']; }
php
private function init_session() { session_set_cookie_params(ini_get('session.cookie_lifetime'), $this->path); session_name('sid'); session_start(); $this->session = &$_SESSION['session']; if (!isset($this->session['msg'])) { $this->session['msg'] = array('error' => array(), 'information' => array()); } $this->user = &$_SESSION['user']; # Обратная совместимость $GLOBALS['session'] = &$_SESSION['session']; $GLOBALS['user'] = &$_SESSION['user']; }
[ "private", "function", "init_session", "(", ")", "{", "session_set_cookie_params", "(", "ini_get", "(", "'session.cookie_lifetime'", ")", ",", "$", "this", "->", "path", ")", ";", "session_name", "(", "'sid'", ")", ";", "session_start", "(", ")", ";", "$", "this", "->", "session", "=", "&", "$", "_SESSION", "[", "'session'", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "session", "[", "'msg'", "]", ")", ")", "{", "$", "this", "->", "session", "[", "'msg'", "]", "=", "array", "(", "'error'", "=>", "array", "(", ")", ",", "'information'", "=>", "array", "(", ")", ")", ";", "}", "$", "this", "->", "user", "=", "&", "$", "_SESSION", "[", "'user'", "]", ";", "# Обратная совместимость", "$", "GLOBALS", "[", "'session'", "]", "=", "&", "$", "_SESSION", "[", "'session'", "]", ";", "$", "GLOBALS", "[", "'user'", "]", "=", "&", "$", "_SESSION", "[", "'user'", "]", ";", "}" ]
Инициирует сессии
[ "Инициирует", "сессии" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1488-L1503
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.init_resolve
protected function init_resolve() { if (is_null($this->froot)) { $this->froot = Eresus_Kernel::app()->getFsRoot() . '/'; } $this->fdata = $this->froot . 'data' . DIRECTORY_SEPARATOR; $this->fstyle = $this->froot . 'style' . DIRECTORY_SEPARATOR; if (is_null($this->path)) { $s = substr(dirname($_SERVER['SCRIPT_FILENAME']), strlen($_SERVER['DOCUMENT_ROOT'])); if (strlen($s) == 0 || substr($s, -1) != '/') { $s .= '/'; } if (substr($s, 0, 1) != '/') { $s = '/' . $s; } $this->path = $s; } }
php
protected function init_resolve() { if (is_null($this->froot)) { $this->froot = Eresus_Kernel::app()->getFsRoot() . '/'; } $this->fdata = $this->froot . 'data' . DIRECTORY_SEPARATOR; $this->fstyle = $this->froot . 'style' . DIRECTORY_SEPARATOR; if (is_null($this->path)) { $s = substr(dirname($_SERVER['SCRIPT_FILENAME']), strlen($_SERVER['DOCUMENT_ROOT'])); if (strlen($s) == 0 || substr($s, -1) != '/') { $s .= '/'; } if (substr($s, 0, 1) != '/') { $s = '/' . $s; } $this->path = $s; } }
[ "protected", "function", "init_resolve", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "froot", ")", ")", "{", "$", "this", "->", "froot", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getFsRoot", "(", ")", ".", "'/'", ";", "}", "$", "this", "->", "fdata", "=", "$", "this", "->", "froot", ".", "'data'", ".", "DIRECTORY_SEPARATOR", ";", "$", "this", "->", "fstyle", "=", "$", "this", "->", "froot", ".", "'style'", ".", "DIRECTORY_SEPARATOR", ";", "if", "(", "is_null", "(", "$", "this", "->", "path", ")", ")", "{", "$", "s", "=", "substr", "(", "dirname", "(", "$", "_SERVER", "[", "'SCRIPT_FILENAME'", "]", ")", ",", "strlen", "(", "$", "_SERVER", "[", "'DOCUMENT_ROOT'", "]", ")", ")", ";", "if", "(", "strlen", "(", "$", "s", ")", "==", "0", "||", "substr", "(", "$", "s", ",", "-", "1", ")", "!=", "'/'", ")", "{", "$", "s", ".=", "'/'", ";", "}", "if", "(", "substr", "(", "$", "s", ",", "0", ",", "1", ")", "!=", "'/'", ")", "{", "$", "s", "=", "'/'", ".", "$", "s", ";", "}", "$", "this", "->", "path", "=", "$", "s", ";", "}", "}" ]
Определяет файловые пути @return void
[ "Определяет", "файловые", "пути" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1510-L1533
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.initSettings
private function initSettings() { $filename = $this->froot . 'cfg/settings.php'; if (is_file($filename)) { /** @noinspection PhpIncludeInspection */ include_once $filename; } else { throw new Eresus_Exception_ComponentCorrupted( sprintf('Settings file "%s" not found!', $filename)); } }
php
private function initSettings() { $filename = $this->froot . 'cfg/settings.php'; if (is_file($filename)) { /** @noinspection PhpIncludeInspection */ include_once $filename; } else { throw new Eresus_Exception_ComponentCorrupted( sprintf('Settings file "%s" not found!', $filename)); } }
[ "private", "function", "initSettings", "(", ")", "{", "$", "filename", "=", "$", "this", "->", "froot", ".", "'cfg/settings.php'", ";", "if", "(", "is_file", "(", "$", "filename", ")", ")", "{", "/** @noinspection PhpIncludeInspection */", "include_once", "$", "filename", ";", "}", "else", "{", "throw", "new", "Eresus_Exception_ComponentCorrupted", "(", "sprintf", "(", "'Settings file \"%s\" not found!'", ",", "$", "filename", ")", ")", ";", "}", "}" ]
Читает настройки @throws Eresus_Exception_ComponentCorrupted
[ "Читает", "настройки" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1540-L1553
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.init_request
private function init_request() { global $request; # Значения по умолчанию $request = array( 'method' => $_SERVER['REQUEST_METHOD'], 'scheme' => isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http', 'host' => strtolower($_SERVER['HTTP_HOST']), 'port' => '', 'user' => isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '', 'pass' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '', 'path' => '', 'query' => '', 'fragment' => '', 'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '', ); $request['url'] = $request['scheme'] . '://' . $request['host'] . $_SERVER['REQUEST_URI']; $request = array_merge($request, parse_url($request['url'])); $request['file'] = substr($request['path'], strrpos($request['path'], '/')+1); if ($request['file']) { $request['path'] = substr($request['path'], 0, -strlen($request['file'])); } # Создаем заготовку URL для GET-запросов с параметрами $request['link'] = $request['url']; if (substr($request['link'], -1) == '/') { $request['link'] .= '?'; } elseif (strpos($request['link'], '?') === false) { $request['link'] .= '?'; } else { $request['link'] .= '&'; } if (is_null($this->path)) { $s = $this->froot; $s = substr($s, strlen(realpath($_SERVER['DOCUMENT_ROOT'])) - (Eresus_Kernel::isWindows() ? 2 : 0)); if (!strlen($s) || substr($s, -1) != '/') { $s .= '/'; } $this->path = (substr($s, 0, 1) != '/' ? '/' : '').$s; } /* * Установка свойств объекта $Eresus * Должна выполняться ДО вызова __clearargs */ $root = $request['scheme'] . '://' . $request['host'] . ($request['port'] ? ':'.$request['port'] : ''); $this->root = $root.$this->path; $this->data = $this->root.'data/'; $this->style = $this->root.'style/'; # Сбор аргументов вызова $request['arg'] = __clearargs(array_merge($_GET, $_POST)); # Разбивка параметров вызова скрипта $s = substr($request['path'], strlen($this->path)); $request['params'] = $s ? explode('/', substr($s, 0, -1)) : array(); $request['path'] = $root.$request['path']; # Обратная совместимость # <= 2.9 $this->request = &$request; /** * @deprecated с 3.01 */ define('httpPath', $this->path); /** * @deprecated с 3.01 */ define('httpHost', $this->request['host']); /** * @deprecated с 3.01 */ define('httpRoot', $this->root); /** * @deprecated с 3.01 */ define('styleRoot', $this->style); /** * @deprecated с 3.01 */ define('dataRoot', $this->data); /** * @deprecated с 3.01 */ define('cookieHost', $this->request['host']); /** * @deprecated с 3.01 */ define('cookiePath', $this->path); }
php
private function init_request() { global $request; # Значения по умолчанию $request = array( 'method' => $_SERVER['REQUEST_METHOD'], 'scheme' => isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http', 'host' => strtolower($_SERVER['HTTP_HOST']), 'port' => '', 'user' => isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '', 'pass' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '', 'path' => '', 'query' => '', 'fragment' => '', 'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '', ); $request['url'] = $request['scheme'] . '://' . $request['host'] . $_SERVER['REQUEST_URI']; $request = array_merge($request, parse_url($request['url'])); $request['file'] = substr($request['path'], strrpos($request['path'], '/')+1); if ($request['file']) { $request['path'] = substr($request['path'], 0, -strlen($request['file'])); } # Создаем заготовку URL для GET-запросов с параметрами $request['link'] = $request['url']; if (substr($request['link'], -1) == '/') { $request['link'] .= '?'; } elseif (strpos($request['link'], '?') === false) { $request['link'] .= '?'; } else { $request['link'] .= '&'; } if (is_null($this->path)) { $s = $this->froot; $s = substr($s, strlen(realpath($_SERVER['DOCUMENT_ROOT'])) - (Eresus_Kernel::isWindows() ? 2 : 0)); if (!strlen($s) || substr($s, -1) != '/') { $s .= '/'; } $this->path = (substr($s, 0, 1) != '/' ? '/' : '').$s; } /* * Установка свойств объекта $Eresus * Должна выполняться ДО вызова __clearargs */ $root = $request['scheme'] . '://' . $request['host'] . ($request['port'] ? ':'.$request['port'] : ''); $this->root = $root.$this->path; $this->data = $this->root.'data/'; $this->style = $this->root.'style/'; # Сбор аргументов вызова $request['arg'] = __clearargs(array_merge($_GET, $_POST)); # Разбивка параметров вызова скрипта $s = substr($request['path'], strlen($this->path)); $request['params'] = $s ? explode('/', substr($s, 0, -1)) : array(); $request['path'] = $root.$request['path']; # Обратная совместимость # <= 2.9 $this->request = &$request; /** * @deprecated с 3.01 */ define('httpPath', $this->path); /** * @deprecated с 3.01 */ define('httpHost', $this->request['host']); /** * @deprecated с 3.01 */ define('httpRoot', $this->root); /** * @deprecated с 3.01 */ define('styleRoot', $this->style); /** * @deprecated с 3.01 */ define('dataRoot', $this->data); /** * @deprecated с 3.01 */ define('cookieHost', $this->request['host']); /** * @deprecated с 3.01 */ define('cookiePath', $this->path); }
[ "private", "function", "init_request", "(", ")", "{", "global", "$", "request", ";", "# Значения по умолчанию", "$", "request", "=", "array", "(", "'method'", "=>", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ",", "'scheme'", "=>", "isset", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "&&", "!", "empty", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "?", "'https'", ":", "'http'", ",", "'host'", "=>", "strtolower", "(", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ")", ",", "'port'", "=>", "''", ",", "'user'", "=>", "isset", "(", "$", "_SERVER", "[", "'PHP_AUTH_USER'", "]", ")", "?", "$", "_SERVER", "[", "'PHP_AUTH_USER'", "]", ":", "''", ",", "'pass'", "=>", "isset", "(", "$", "_SERVER", "[", "'PHP_AUTH_PW'", "]", ")", "?", "$", "_SERVER", "[", "'PHP_AUTH_PW'", "]", ":", "''", ",", "'path'", "=>", "''", ",", "'query'", "=>", "''", ",", "'fragment'", "=>", "''", ",", "'referer'", "=>", "isset", "(", "$", "_SERVER", "[", "'HTTP_REFERER'", "]", ")", "?", "$", "_SERVER", "[", "'HTTP_REFERER'", "]", ":", "''", ",", ")", ";", "$", "request", "[", "'url'", "]", "=", "$", "request", "[", "'scheme'", "]", ".", "'://'", ".", "$", "request", "[", "'host'", "]", ".", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ";", "$", "request", "=", "array_merge", "(", "$", "request", ",", "parse_url", "(", "$", "request", "[", "'url'", "]", ")", ")", ";", "$", "request", "[", "'file'", "]", "=", "substr", "(", "$", "request", "[", "'path'", "]", ",", "strrpos", "(", "$", "request", "[", "'path'", "]", ",", "'/'", ")", "+", "1", ")", ";", "if", "(", "$", "request", "[", "'file'", "]", ")", "{", "$", "request", "[", "'path'", "]", "=", "substr", "(", "$", "request", "[", "'path'", "]", ",", "0", ",", "-", "strlen", "(", "$", "request", "[", "'file'", "]", ")", ")", ";", "}", "# Создаем заготовку URL для GET-запросов с параметрами", "$", "request", "[", "'link'", "]", "=", "$", "request", "[", "'url'", "]", ";", "if", "(", "substr", "(", "$", "request", "[", "'link'", "]", ",", "-", "1", ")", "==", "'/'", ")", "{", "$", "request", "[", "'link'", "]", ".=", "'?'", ";", "}", "elseif", "(", "strpos", "(", "$", "request", "[", "'link'", "]", ",", "'?'", ")", "===", "false", ")", "{", "$", "request", "[", "'link'", "]", ".=", "'?'", ";", "}", "else", "{", "$", "request", "[", "'link'", "]", ".=", "'&'", ";", "}", "if", "(", "is_null", "(", "$", "this", "->", "path", ")", ")", "{", "$", "s", "=", "$", "this", "->", "froot", ";", "$", "s", "=", "substr", "(", "$", "s", ",", "strlen", "(", "realpath", "(", "$", "_SERVER", "[", "'DOCUMENT_ROOT'", "]", ")", ")", "-", "(", "Eresus_Kernel", "::", "isWindows", "(", ")", "?", "2", ":", "0", ")", ")", ";", "if", "(", "!", "strlen", "(", "$", "s", ")", "||", "substr", "(", "$", "s", ",", "-", "1", ")", "!=", "'/'", ")", "{", "$", "s", ".=", "'/'", ";", "}", "$", "this", "->", "path", "=", "(", "substr", "(", "$", "s", ",", "0", ",", "1", ")", "!=", "'/'", "?", "'/'", ":", "''", ")", ".", "$", "s", ";", "}", "/*\n\t\t * Установка свойств объекта $Eresus\n\t\t * Должна выполняться ДО вызова __clearargs\n\t\t */", "$", "root", "=", "$", "request", "[", "'scheme'", "]", ".", "'://'", ".", "$", "request", "[", "'host'", "]", ".", "(", "$", "request", "[", "'port'", "]", "?", "':'", ".", "$", "request", "[", "'port'", "]", ":", "''", ")", ";", "$", "this", "->", "root", "=", "$", "root", ".", "$", "this", "->", "path", ";", "$", "this", "->", "data", "=", "$", "this", "->", "root", ".", "'data/'", ";", "$", "this", "->", "style", "=", "$", "this", "->", "root", ".", "'style/'", ";", "# Сбор аргументов вызова", "$", "request", "[", "'arg'", "]", "=", "__clearargs", "(", "array_merge", "(", "$", "_GET", ",", "$", "_POST", ")", ")", ";", "# Разбивка параметров вызова скрипта", "$", "s", "=", "substr", "(", "$", "request", "[", "'path'", "]", ",", "strlen", "(", "$", "this", "->", "path", ")", ")", ";", "$", "request", "[", "'params'", "]", "=", "$", "s", "?", "explode", "(", "'/'", ",", "substr", "(", "$", "s", ",", "0", ",", "-", "1", ")", ")", ":", "array", "(", ")", ";", "$", "request", "[", "'path'", "]", "=", "$", "root", ".", "$", "request", "[", "'path'", "]", ";", "# Обратная совместимость", "# <= 2.9", "$", "this", "->", "request", "=", "&", "$", "request", ";", "/**\n * @deprecated с 3.01\n */", "define", "(", "'httpPath'", ",", "$", "this", "->", "path", ")", ";", "/**\n * @deprecated с 3.01\n */", "define", "(", "'httpHost'", ",", "$", "this", "->", "request", "[", "'host'", "]", ")", ";", "/**\n * @deprecated с 3.01\n */", "define", "(", "'httpRoot'", ",", "$", "this", "->", "root", ")", ";", "/**\n * @deprecated с 3.01\n */", "define", "(", "'styleRoot'", ",", "$", "this", "->", "style", ")", ";", "/**\n * @deprecated с 3.01\n */", "define", "(", "'dataRoot'", ",", "$", "this", "->", "data", ")", ";", "/**\n * @deprecated с 3.01\n */", "define", "(", "'cookieHost'", ",", "$", "this", "->", "request", "[", "'host'", "]", ")", ";", "/**\n * @deprecated с 3.01\n */", "define", "(", "'cookiePath'", ",", "$", "this", "->", "path", ")", ";", "}" ]
Первичный разбор запроса
[ "Первичный", "разбор", "запроса" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1558-L1662
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.initLocale
private function initLocale() { global $locale; $locale['lang'] = $this->conf['lang']; $locale['prefix'] = ''; # Подключение строковых данных $filename = $this->froot.'lang/'.$locale['lang'].'.php'; if (is_file($filename)) { /** @noinspection PhpIncludeInspection */ include_once $filename; } else { throw new Eresus_Exception_ComponentCorrupted( sprintf('Locale file "%s" not found!', $filename)); } }
php
private function initLocale() { global $locale; $locale['lang'] = $this->conf['lang']; $locale['prefix'] = ''; # Подключение строковых данных $filename = $this->froot.'lang/'.$locale['lang'].'.php'; if (is_file($filename)) { /** @noinspection PhpIncludeInspection */ include_once $filename; } else { throw new Eresus_Exception_ComponentCorrupted( sprintf('Locale file "%s" not found!', $filename)); } }
[ "private", "function", "initLocale", "(", ")", "{", "global", "$", "locale", ";", "$", "locale", "[", "'lang'", "]", "=", "$", "this", "->", "conf", "[", "'lang'", "]", ";", "$", "locale", "[", "'prefix'", "]", "=", "''", ";", "# Подключение строковых данных", "$", "filename", "=", "$", "this", "->", "froot", ".", "'lang/'", ".", "$", "locale", "[", "'lang'", "]", ".", "'.php'", ";", "if", "(", "is_file", "(", "$", "filename", ")", ")", "{", "/** @noinspection PhpIncludeInspection */", "include_once", "$", "filename", ";", "}", "else", "{", "throw", "new", "Eresus_Exception_ComponentCorrupted", "(", "sprintf", "(", "'Locale file \"%s\" not found!'", ",", "$", "filename", ")", ")", ";", "}", "}" ]
Инициализация локали @throws Eresus_Exception_ComponentCorrupted
[ "Инициализация", "локали" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1669-L1688
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.initClasses
private function initClasses() { $filename = $this->froot.'core/classes.php'; if (is_file($filename)) { /** @noinspection PhpIncludeInspection */ include_once $filename; } else { throw new Eresus_Exception_ComponentCorrupted( sprintf('Classes file "%s" not found!', $filename)); } }
php
private function initClasses() { $filename = $this->froot.'core/classes.php'; if (is_file($filename)) { /** @noinspection PhpIncludeInspection */ include_once $filename; } else { throw new Eresus_Exception_ComponentCorrupted( sprintf('Classes file "%s" not found!', $filename)); } }
[ "private", "function", "initClasses", "(", ")", "{", "$", "filename", "=", "$", "this", "->", "froot", ".", "'core/classes.php'", ";", "if", "(", "is_file", "(", "$", "filename", ")", ")", "{", "/** @noinspection PhpIncludeInspection */", "include_once", "$", "filename", ";", "}", "else", "{", "throw", "new", "Eresus_Exception_ComponentCorrupted", "(", "sprintf", "(", "'Classes file \"%s\" not found!'", ",", "$", "filename", ")", ")", ";", "}", "}" ]
Подключение базовых классов @throws Eresus_Exception_ComponentCorrupted
[ "Подключение", "базовых", "классов" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1695-L1708
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.init_extensions
function init_extensions() { $filename = $this->froot.'cfg/extensions.php'; if (is_file($filename)) { include_once($filename); } $this->extensions = new EresusExtensions(); }
php
function init_extensions() { $filename = $this->froot.'cfg/extensions.php'; if (is_file($filename)) { include_once($filename); } $this->extensions = new EresusExtensions(); }
[ "function", "init_extensions", "(", ")", "{", "$", "filename", "=", "$", "this", "->", "froot", ".", "'cfg/extensions.php'", ";", "if", "(", "is_file", "(", "$", "filename", ")", ")", "{", "include_once", "(", "$", "filename", ")", ";", "}", "$", "this", "->", "extensions", "=", "new", "EresusExtensions", "(", ")", ";", "}" ]
Инициализация расширений
[ "Инициализация", "расширений" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1713-L1722
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.initDataSource
private function initDataSource() { $className = $this->conf['db']['engine']; if (class_exists($className)) { $this->db = new $className; $this->db->init($this->conf['db']['host'], $this->conf['db']['user'], $this->conf['db']['password'], $this->conf['db']['name'], $this->conf['db']['prefix']); } else { throw new Eresus_Exception_ComponentCorrupted( sprintf('Library "%s" not found!', $this->conf['db']['engine'])); } }
php
private function initDataSource() { $className = $this->conf['db']['engine']; if (class_exists($className)) { $this->db = new $className; $this->db->init($this->conf['db']['host'], $this->conf['db']['user'], $this->conf['db']['password'], $this->conf['db']['name'], $this->conf['db']['prefix']); } else { throw new Eresus_Exception_ComponentCorrupted( sprintf('Library "%s" not found!', $this->conf['db']['engine'])); } }
[ "private", "function", "initDataSource", "(", ")", "{", "$", "className", "=", "$", "this", "->", "conf", "[", "'db'", "]", "[", "'engine'", "]", ";", "if", "(", "class_exists", "(", "$", "className", ")", ")", "{", "$", "this", "->", "db", "=", "new", "$", "className", ";", "$", "this", "->", "db", "->", "init", "(", "$", "this", "->", "conf", "[", "'db'", "]", "[", "'host'", "]", ",", "$", "this", "->", "conf", "[", "'db'", "]", "[", "'user'", "]", ",", "$", "this", "->", "conf", "[", "'db'", "]", "[", "'password'", "]", ",", "$", "this", "->", "conf", "[", "'db'", "]", "[", "'name'", "]", ",", "$", "this", "->", "conf", "[", "'db'", "]", "[", "'prefix'", "]", ")", ";", "}", "else", "{", "throw", "new", "Eresus_Exception_ComponentCorrupted", "(", "sprintf", "(", "'Library \"%s\" not found!'", ",", "$", "this", "->", "conf", "[", "'db'", "]", "[", "'engine'", "]", ")", ")", ";", "}", "}" ]
Подключение к источнику данных @throws Eresus_Exception_ComponentCorrupted
[ "Подключение", "к", "источнику", "данных" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1729-L1744
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.check_session
private function check_session() { if (isset($this->session['time'])) { if ( (time() - $this->session['time'] > $this->conf['session']['timeout']*3600) && ($this->user['auth']) ) { $this->logout(false); } else { $this->session['time'] = time(); } } }
php
private function check_session() { if (isset($this->session['time'])) { if ( (time() - $this->session['time'] > $this->conf['session']['timeout']*3600) && ($this->user['auth']) ) { $this->logout(false); } else { $this->session['time'] = time(); } } }
[ "private", "function", "check_session", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "session", "[", "'time'", "]", ")", ")", "{", "if", "(", "(", "time", "(", ")", "-", "$", "this", "->", "session", "[", "'time'", "]", ">", "$", "this", "->", "conf", "[", "'session'", "]", "[", "'timeout'", "]", "*", "3600", ")", "&&", "(", "$", "this", "->", "user", "[", "'auth'", "]", ")", ")", "{", "$", "this", "->", "logout", "(", "false", ")", ";", "}", "else", "{", "$", "this", "->", "session", "[", "'time'", "]", "=", "time", "(", ")", ";", "}", "}", "}" ]
Проверка сессии
[ "Проверка", "сессии" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1749-L1765
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.check_loginout
function check_loginout() { switch (arg('action')) { case 'login': $this->login(arg('user'), $this->password_hash(arg('password')), arg('autologin', 'int')); HTTP::redirect($this->request['url']); break; case 'logout': $this->logout(true); HTTP::redirect($this->root.'admin/'); break; } }
php
function check_loginout() { switch (arg('action')) { case 'login': $this->login(arg('user'), $this->password_hash(arg('password')), arg('autologin', 'int')); HTTP::redirect($this->request['url']); break; case 'logout': $this->logout(true); HTTP::redirect($this->root.'admin/'); break; } }
[ "function", "check_loginout", "(", ")", "{", "switch", "(", "arg", "(", "'action'", ")", ")", "{", "case", "'login'", ":", "$", "this", "->", "login", "(", "arg", "(", "'user'", ")", ",", "$", "this", "->", "password_hash", "(", "arg", "(", "'password'", ")", ")", ",", "arg", "(", "'autologin'", ",", "'int'", ")", ")", ";", "HTTP", "::", "redirect", "(", "$", "this", "->", "request", "[", "'url'", "]", ")", ";", "break", ";", "case", "'logout'", ":", "$", "this", "->", "logout", "(", "true", ")", ";", "HTTP", "::", "redirect", "(", "$", "this", "->", "root", ".", "'admin/'", ")", ";", "break", ";", "}", "}" ]
Проверка на логин/логаут
[ "Проверка", "на", "логин", "/", "логаут" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1771-L1784
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.check_cookies
function check_cookies() { if (!$this->user['auth'] && isset($_COOKIE['eresus_login'])) { if (!$this->login($_COOKIE['eresus_login'], $_COOKIE['eresus_key'], true, true)) { $this->clear_login_cookies(); } } }
php
function check_cookies() { if (!$this->user['auth'] && isset($_COOKIE['eresus_login'])) { if (!$this->login($_COOKIE['eresus_login'], $_COOKIE['eresus_key'], true, true)) { $this->clear_login_cookies(); } } }
[ "function", "check_cookies", "(", ")", "{", "if", "(", "!", "$", "this", "->", "user", "[", "'auth'", "]", "&&", "isset", "(", "$", "_COOKIE", "[", "'eresus_login'", "]", ")", ")", "{", "if", "(", "!", "$", "this", "->", "login", "(", "$", "_COOKIE", "[", "'eresus_login'", "]", ",", "$", "_COOKIE", "[", "'eresus_key'", "]", ",", "true", ",", "true", ")", ")", "{", "$", "this", "->", "clear_login_cookies", "(", ")", ";", "}", "}", "}" ]
Попытка cookie-логина
[ "Попытка", "cookie", "-", "логина" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1789-L1798
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.reset_login
function reset_login() { $this->user['auth'] = isset($this->user['auth']) ? $this->user['auth'] : false; if ($this->user['auth']) { $item = $this->db->selectItem('users', "`id`='".$this->user['id']."'"); if (!is_null($item)) { # Если такой пользователь есть... if ($item['active']) { # Если учетная запись активна... $this->user['name'] = $item['name']; $this->user['mail'] = $item['mail']; $this->user['access'] = $item['access']; $this->user['profile'] = decodeOptions($item['profile']); } else { Eresus_Kernel::app()->getPage()->addErrorMessage( sprintf(ERR_ACCOUNT_NOT_ACTIVE, $item['login'])); $this->logout(); } } else { $this->logout(); } } else { $this->user['access'] = GUEST; } }
php
function reset_login() { $this->user['auth'] = isset($this->user['auth']) ? $this->user['auth'] : false; if ($this->user['auth']) { $item = $this->db->selectItem('users', "`id`='".$this->user['id']."'"); if (!is_null($item)) { # Если такой пользователь есть... if ($item['active']) { # Если учетная запись активна... $this->user['name'] = $item['name']; $this->user['mail'] = $item['mail']; $this->user['access'] = $item['access']; $this->user['profile'] = decodeOptions($item['profile']); } else { Eresus_Kernel::app()->getPage()->addErrorMessage( sprintf(ERR_ACCOUNT_NOT_ACTIVE, $item['login'])); $this->logout(); } } else { $this->logout(); } } else { $this->user['access'] = GUEST; } }
[ "function", "reset_login", "(", ")", "{", "$", "this", "->", "user", "[", "'auth'", "]", "=", "isset", "(", "$", "this", "->", "user", "[", "'auth'", "]", ")", "?", "$", "this", "->", "user", "[", "'auth'", "]", ":", "false", ";", "if", "(", "$", "this", "->", "user", "[", "'auth'", "]", ")", "{", "$", "item", "=", "$", "this", "->", "db", "->", "selectItem", "(", "'users'", ",", "\"`id`='\"", ".", "$", "this", "->", "user", "[", "'id'", "]", ".", "\"'\"", ")", ";", "if", "(", "!", "is_null", "(", "$", "item", ")", ")", "{", "# Если такой пользователь есть...", "if", "(", "$", "item", "[", "'active'", "]", ")", "{", "# Если учетная запись активна...", "$", "this", "->", "user", "[", "'name'", "]", "=", "$", "item", "[", "'name'", "]", ";", "$", "this", "->", "user", "[", "'mail'", "]", "=", "$", "item", "[", "'mail'", "]", ";", "$", "this", "->", "user", "[", "'access'", "]", "=", "$", "item", "[", "'access'", "]", ";", "$", "this", "->", "user", "[", "'profile'", "]", "=", "decodeOptions", "(", "$", "item", "[", "'profile'", "]", ")", ";", "}", "else", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "sprintf", "(", "ERR_ACCOUNT_NOT_ACTIVE", ",", "$", "item", "[", "'login'", "]", ")", ")", ";", "$", "this", "->", "logout", "(", ")", ";", "}", "}", "else", "{", "$", "this", "->", "logout", "(", ")", ";", "}", "}", "else", "{", "$", "this", "->", "user", "[", "'access'", "]", "=", "GUEST", ";", "}", "}" ]
Обновление данных о пользователе
[ "Обновление", "данных", "о", "пользователе" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1803-L1836
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.init
public function init() { if ($this->conf['timezone']) { date_default_timezone_set($this->conf['timezone']); } # Определение путей $this->init_resolve(); # Инициализация сессии $this->init_session(); # Изменяем путь поиска подключаемых файлов set_include_path(dirname(__FILE__) . '/lib' . PATH_SEPARATOR . get_include_path()); # Читаем настройки $this->initSettings(); # Первичный разбор запроса $this->init_request(); # Настройка локали $this->initLocale(); # Подключение базовых классов $this->initClasses(); # Инициализация расширений $this->init_extensions(); # Подключение к источнику данных $this->initDataSource(); $this->plugins = Eresus_Plugin_Registry::getInstance(); $this->plugins->init(); # Проверка сессии $this->check_session(); # Проверка логина/логаута $this->check_loginout(); # Попытка cookie-логина $this->check_cookies(); # Обновление данных о пользователе $this->reset_login(); $this->sections = new Sections; $GLOBALS['KERNEL']['loaded'] = true; # Флаг загрузки ядра }
php
public function init() { if ($this->conf['timezone']) { date_default_timezone_set($this->conf['timezone']); } # Определение путей $this->init_resolve(); # Инициализация сессии $this->init_session(); # Изменяем путь поиска подключаемых файлов set_include_path(dirname(__FILE__) . '/lib' . PATH_SEPARATOR . get_include_path()); # Читаем настройки $this->initSettings(); # Первичный разбор запроса $this->init_request(); # Настройка локали $this->initLocale(); # Подключение базовых классов $this->initClasses(); # Инициализация расширений $this->init_extensions(); # Подключение к источнику данных $this->initDataSource(); $this->plugins = Eresus_Plugin_Registry::getInstance(); $this->plugins->init(); # Проверка сессии $this->check_session(); # Проверка логина/логаута $this->check_loginout(); # Попытка cookie-логина $this->check_cookies(); # Обновление данных о пользователе $this->reset_login(); $this->sections = new Sections; $GLOBALS['KERNEL']['loaded'] = true; # Флаг загрузки ядра }
[ "public", "function", "init", "(", ")", "{", "if", "(", "$", "this", "->", "conf", "[", "'timezone'", "]", ")", "{", "date_default_timezone_set", "(", "$", "this", "->", "conf", "[", "'timezone'", "]", ")", ";", "}", "# Определение путей", "$", "this", "->", "init_resolve", "(", ")", ";", "# Инициализация сессии", "$", "this", "->", "init_session", "(", ")", ";", "# Изменяем путь поиска подключаемых файлов", "set_include_path", "(", "dirname", "(", "__FILE__", ")", ".", "'/lib'", ".", "PATH_SEPARATOR", ".", "get_include_path", "(", ")", ")", ";", "# Читаем настройки", "$", "this", "->", "initSettings", "(", ")", ";", "# Первичный разбор запроса", "$", "this", "->", "init_request", "(", ")", ";", "# Настройка локали", "$", "this", "->", "initLocale", "(", ")", ";", "# Подключение базовых классов", "$", "this", "->", "initClasses", "(", ")", ";", "# Инициализация расширений", "$", "this", "->", "init_extensions", "(", ")", ";", "# Подключение к источнику данных", "$", "this", "->", "initDataSource", "(", ")", ";", "$", "this", "->", "plugins", "=", "Eresus_Plugin_Registry", "::", "getInstance", "(", ")", ";", "$", "this", "->", "plugins", "->", "init", "(", ")", ";", "# Проверка сессии", "$", "this", "->", "check_session", "(", ")", ";", "# Проверка логина/логаута", "$", "this", "->", "check_loginout", "(", ")", ";", "# Попытка cookie-логина", "$", "this", "->", "check_cookies", "(", ")", ";", "# Обновление данных о пользователе", "$", "this", "->", "reset_login", "(", ")", ";", "$", "this", "->", "sections", "=", "new", "Sections", ";", "$", "GLOBALS", "[", "'KERNEL'", "]", "[", "'loaded'", "]", "=", "true", ";", "# Флаг загрузки ядра", "}" ]
Инициализация системы
[ "Инициализация", "системы" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1841-L1877
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.password_hash
function password_hash($password) { $result = md5($password); if (!$this->conf['backward']['weak_password']) { $result = md5($result); } return $result; }
php
function password_hash($password) { $result = md5($password); if (!$this->conf['backward']['weak_password']) { $result = md5($result); } return $result; }
[ "function", "password_hash", "(", "$", "password", ")", "{", "$", "result", "=", "md5", "(", "$", "password", ")", ";", "if", "(", "!", "$", "this", "->", "conf", "[", "'backward'", "]", "[", "'weak_password'", "]", ")", "{", "$", "result", "=", "md5", "(", "$", "result", ")", ";", "}", "return", "$", "result", ";", "}" ]
Хеширует пароль @param string $password Пароль @return string Хеш
[ "Хеширует", "пароль" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1885-L1893
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.set_login_cookies
function set_login_cookies($login, $key) { setcookie('eresus_login', $login, time()+2592000, $this->path); setcookie('eresus_key', $key, time()+2592000, $this->path); }
php
function set_login_cookies($login, $key) { setcookie('eresus_login', $login, time()+2592000, $this->path); setcookie('eresus_key', $key, time()+2592000, $this->path); }
[ "function", "set_login_cookies", "(", "$", "login", ",", "$", "key", ")", "{", "setcookie", "(", "'eresus_login'", ",", "$", "login", ",", "time", "(", ")", "+", "2592000", ",", "$", "this", "->", "path", ")", ";", "setcookie", "(", "'eresus_key'", ",", "$", "key", ",", "time", "(", ")", "+", "2592000", ",", "$", "this", "->", "path", ")", ";", "}" ]
Устанавливает авторизационные кукисы @param string $login @param string $key
[ "Устанавливает", "авторизационные", "кукисы" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1901-L1905
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.login
public function login($unsafeLogin, $key, $auto = false, $cookie = false) { $result = false; $login = preg_replace('/[^a-z0-9_\-\.\@]/', '', $unsafeLogin); if ($login != $unsafeLogin) { Eresus_Kernel::app()->getPage()->addErrorMessage(ERR_PASSWORD_INVALID); return false; } $item = $this->db->selectItem('users', "`login`='$login'"); // Если такой пользователь есть... if (!is_null($item)) { // Если учетная запись активна... if ($item['active']) { $noBruteForcing = time() - $item['lastLoginTime'] > $item['loginErrors']; if ($noBruteForcing || $this->conf['debug']['enable']) { // Если пароль верен... if ($key == $item['hash']) { if ($auto) { $this->set_login_cookies($login, $key); } else { $this->clear_login_cookies(); } $setVisitTime = (! isset($this->user['id'])) || (! (bool) $this->user['id']); $this->user = $item; $this->user['profile'] = decodeOptions($this->user['profile']); $this->user['auth'] = true; # Устанавливаем флаг авторизации // Хэш пароля используется для подтверждения аутентификации $this->user['hash'] = $item['hash']; if ($setVisitTime) { $item['lastVisit'] = gettime(); # Записываем время последнего входа } $item['lastLoginTime'] = time(); $item['loginErrors'] = 0; $this->db->updateItem('users', $item,"`id`='".$item['id']."'"); $this->session['time'] = time(); # Инициализируем время последней активности сессии. $result = true; } else { // Если пароль не верен... if (!$cookie) { Eresus_Kernel::app()->getPage()->addErrorMessage(ERR_PASSWORD_INVALID); $item['lastLoginTime'] = time(); $item['loginErrors']++; $this->db->updateItem('users', $item,"`id`='".$item['id']."'"); } } } else { // Если авторизация проведена слишком рано Eresus_Kernel::app()->getPage()->addErrorMessage( sprintf(ERR_LOGIN_FAILED_TOO_EARLY, $item['loginErrors'])); $item['lastLoginTime'] = time(); $this->db->updateItem('users', $item,"`id`='".$item['id']."'"); } } else { Eresus_Kernel::app()->getPage()->addErrorMessage( sprintf(ERR_ACCOUNT_NOT_ACTIVE, $login)); } } else { Eresus_Kernel::app()->getPage()->addErrorMessage( ERR_PASSWORD_INVALID); } return $result; }
php
public function login($unsafeLogin, $key, $auto = false, $cookie = false) { $result = false; $login = preg_replace('/[^a-z0-9_\-\.\@]/', '', $unsafeLogin); if ($login != $unsafeLogin) { Eresus_Kernel::app()->getPage()->addErrorMessage(ERR_PASSWORD_INVALID); return false; } $item = $this->db->selectItem('users', "`login`='$login'"); // Если такой пользователь есть... if (!is_null($item)) { // Если учетная запись активна... if ($item['active']) { $noBruteForcing = time() - $item['lastLoginTime'] > $item['loginErrors']; if ($noBruteForcing || $this->conf['debug']['enable']) { // Если пароль верен... if ($key == $item['hash']) { if ($auto) { $this->set_login_cookies($login, $key); } else { $this->clear_login_cookies(); } $setVisitTime = (! isset($this->user['id'])) || (! (bool) $this->user['id']); $this->user = $item; $this->user['profile'] = decodeOptions($this->user['profile']); $this->user['auth'] = true; # Устанавливаем флаг авторизации // Хэш пароля используется для подтверждения аутентификации $this->user['hash'] = $item['hash']; if ($setVisitTime) { $item['lastVisit'] = gettime(); # Записываем время последнего входа } $item['lastLoginTime'] = time(); $item['loginErrors'] = 0; $this->db->updateItem('users', $item,"`id`='".$item['id']."'"); $this->session['time'] = time(); # Инициализируем время последней активности сессии. $result = true; } else { // Если пароль не верен... if (!$cookie) { Eresus_Kernel::app()->getPage()->addErrorMessage(ERR_PASSWORD_INVALID); $item['lastLoginTime'] = time(); $item['loginErrors']++; $this->db->updateItem('users', $item,"`id`='".$item['id']."'"); } } } else { // Если авторизация проведена слишком рано Eresus_Kernel::app()->getPage()->addErrorMessage( sprintf(ERR_LOGIN_FAILED_TOO_EARLY, $item['loginErrors'])); $item['lastLoginTime'] = time(); $this->db->updateItem('users', $item,"`id`='".$item['id']."'"); } } else { Eresus_Kernel::app()->getPage()->addErrorMessage( sprintf(ERR_ACCOUNT_NOT_ACTIVE, $login)); } } else { Eresus_Kernel::app()->getPage()->addErrorMessage( ERR_PASSWORD_INVALID); } return $result; }
[ "public", "function", "login", "(", "$", "unsafeLogin", ",", "$", "key", ",", "$", "auto", "=", "false", ",", "$", "cookie", "=", "false", ")", "{", "$", "result", "=", "false", ";", "$", "login", "=", "preg_replace", "(", "'/[^a-z0-9_\\-\\.\\@]/'", ",", "''", ",", "$", "unsafeLogin", ")", ";", "if", "(", "$", "login", "!=", "$", "unsafeLogin", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "ERR_PASSWORD_INVALID", ")", ";", "return", "false", ";", "}", "$", "item", "=", "$", "this", "->", "db", "->", "selectItem", "(", "'users'", ",", "\"`login`='$login'\"", ")", ";", "// Если такой пользователь есть...", "if", "(", "!", "is_null", "(", "$", "item", ")", ")", "{", "// Если учетная запись активна...", "if", "(", "$", "item", "[", "'active'", "]", ")", "{", "$", "noBruteForcing", "=", "time", "(", ")", "-", "$", "item", "[", "'lastLoginTime'", "]", ">", "$", "item", "[", "'loginErrors'", "]", ";", "if", "(", "$", "noBruteForcing", "||", "$", "this", "->", "conf", "[", "'debug'", "]", "[", "'enable'", "]", ")", "{", "// Если пароль верен...", "if", "(", "$", "key", "==", "$", "item", "[", "'hash'", "]", ")", "{", "if", "(", "$", "auto", ")", "{", "$", "this", "->", "set_login_cookies", "(", "$", "login", ",", "$", "key", ")", ";", "}", "else", "{", "$", "this", "->", "clear_login_cookies", "(", ")", ";", "}", "$", "setVisitTime", "=", "(", "!", "isset", "(", "$", "this", "->", "user", "[", "'id'", "]", ")", ")", "||", "(", "!", "(", "bool", ")", "$", "this", "->", "user", "[", "'id'", "]", ")", ";", "$", "this", "->", "user", "=", "$", "item", ";", "$", "this", "->", "user", "[", "'profile'", "]", "=", "decodeOptions", "(", "$", "this", "->", "user", "[", "'profile'", "]", ")", ";", "$", "this", "->", "user", "[", "'auth'", "]", "=", "true", ";", "# Устанавливаем флаг авторизации", "// Хэш пароля используется для подтверждения аутентификации", "$", "this", "->", "user", "[", "'hash'", "]", "=", "$", "item", "[", "'hash'", "]", ";", "if", "(", "$", "setVisitTime", ")", "{", "$", "item", "[", "'lastVisit'", "]", "=", "gettime", "(", ")", ";", "# Записываем время последнего входа", "}", "$", "item", "[", "'lastLoginTime'", "]", "=", "time", "(", ")", ";", "$", "item", "[", "'loginErrors'", "]", "=", "0", ";", "$", "this", "->", "db", "->", "updateItem", "(", "'users'", ",", "$", "item", ",", "\"`id`='\"", ".", "$", "item", "[", "'id'", "]", ".", "\"'\"", ")", ";", "$", "this", "->", "session", "[", "'time'", "]", "=", "time", "(", ")", ";", "# Инициализируем время последней активности сессии.", "$", "result", "=", "true", ";", "}", "else", "{", "// Если пароль не верен...", "if", "(", "!", "$", "cookie", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "ERR_PASSWORD_INVALID", ")", ";", "$", "item", "[", "'lastLoginTime'", "]", "=", "time", "(", ")", ";", "$", "item", "[", "'loginErrors'", "]", "++", ";", "$", "this", "->", "db", "->", "updateItem", "(", "'users'", ",", "$", "item", ",", "\"`id`='\"", ".", "$", "item", "[", "'id'", "]", ".", "\"'\"", ")", ";", "}", "}", "}", "else", "{", "// Если авторизация проведена слишком рано", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "sprintf", "(", "ERR_LOGIN_FAILED_TOO_EARLY", ",", "$", "item", "[", "'loginErrors'", "]", ")", ")", ";", "$", "item", "[", "'lastLoginTime'", "]", "=", "time", "(", ")", ";", "$", "this", "->", "db", "->", "updateItem", "(", "'users'", ",", "$", "item", ",", "\"`id`='\"", ".", "$", "item", "[", "'id'", "]", ".", "\"'\"", ")", ";", "}", "}", "else", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "sprintf", "(", "ERR_ACCOUNT_NOT_ACTIVE", ",", "$", "login", ")", ")", ";", "}", "}", "else", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "ERR_PASSWORD_INVALID", ")", ";", "}", "return", "$", "result", ";", "}" ]
Авторизация пользователя @param string $unsafeLogin Имя пользователя @param string $key Ключ учётной записи @param bool $auto Сохранить авторизационные данные на компьютере посетителя @param bool $cookie Авторизация при помощи cookie @return bool Результат
[ "Авторизация", "пользователя" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L1926-L2008
Eresus/EresusCMS
src/core/kernel-legacy.php
Eresus.logout
public function logout($clearCookies=true) { $this->user['id'] = null; $this->user['auth'] = false; $this->user['access'] = GUEST; if ($clearCookies) { $this->clear_login_cookies(); } }
php
public function logout($clearCookies=true) { $this->user['id'] = null; $this->user['auth'] = false; $this->user['access'] = GUEST; if ($clearCookies) { $this->clear_login_cookies(); } }
[ "public", "function", "logout", "(", "$", "clearCookies", "=", "true", ")", "{", "$", "this", "->", "user", "[", "'id'", "]", "=", "null", ";", "$", "this", "->", "user", "[", "'auth'", "]", "=", "false", ";", "$", "this", "->", "user", "[", "'access'", "]", "=", "GUEST", ";", "if", "(", "$", "clearCookies", ")", "{", "$", "this", "->", "clear_login_cookies", "(", ")", ";", "}", "}" ]
Завершение сеанса работы с системой @param bool $clearCookies
[ "Завершение", "сеанса", "работы", "с", "системой" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/kernel-legacy.php#L2015-L2024
artscorestudio/document-bundle
DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('asf_document'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. $rootNode ->children() ->scalarNode('form_theme') ->defaultValue('ASFDocumentBundle:Form:fields.html.twig') ->end() ->append($this->addPageParameterNode()) ->append($this->addPostParameterNode()) ->end(); return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('asf_document'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. $rootNode ->children() ->scalarNode('form_theme') ->defaultValue('ASFDocumentBundle:Form:fields.html.twig') ->end() ->append($this->addPageParameterNode()) ->append($this->addPostParameterNode()) ->end(); return $treeBuilder; }
[ "public", "function", "getConfigTreeBuilder", "(", ")", "{", "$", "treeBuilder", "=", "new", "TreeBuilder", "(", ")", ";", "$", "rootNode", "=", "$", "treeBuilder", "->", "root", "(", "'asf_document'", ")", ";", "// Here you should define the parameters that are allowed to", "// configure your bundle. See the documentation linked above for", "// more information on that topic.", "$", "rootNode", "->", "children", "(", ")", "->", "scalarNode", "(", "'form_theme'", ")", "->", "defaultValue", "(", "'ASFDocumentBundle:Form:fields.html.twig'", ")", "->", "end", "(", ")", "->", "append", "(", "$", "this", "->", "addPageParameterNode", "(", ")", ")", "->", "append", "(", "$", "this", "->", "addPostParameterNode", "(", ")", ")", "->", "end", "(", ")", ";", "return", "$", "treeBuilder", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/artscorestudio/document-bundle/blob/3aceab0f75de8f7dd0fad0d0db83d7940bf565c8/DependencyInjection/Configuration.php#L25-L44
artscorestudio/document-bundle
DependencyInjection/Configuration.php
Configuration.addPageParameterNode
protected function addPageParameterNode() { $builder = new TreeBuilder(); $node = $builder->root('page'); $node ->treatTrueLike(array( 'versionable' => false, 'signable' => false, 'form' => array( 'type' => "ASF\DocumentBundle\Form\Type\PageType", 'name' => 'page_type' ) )) ->treatFalseLike(array( 'versionable' => false, 'signable' => false, 'form' => array( 'type' => "ASF\DocumentBundle\Form\Type\PageType", 'name' => 'page_type' ) )) ->addDefaultsIfNotSet() ->children() ->booleanNode('versionable') ->defaultFalse() ->end() ->booleanNode('signable') ->defaultFalse() ->end() ->arrayNode('form') ->addDefaultsIfNotSet() ->children() ->scalarNode('type') ->defaultValue('ASF\DocumentBundle\Form\Type\PageType') ->end() ->scalarNode('name') ->defaultValue('page_type') ->end() ->arrayNode('validation_groups') ->prototype('scalar')->end() ->defaultValue(array("Default")) ->end() ->end() ->end() ->end() ; return $node; }
php
protected function addPageParameterNode() { $builder = new TreeBuilder(); $node = $builder->root('page'); $node ->treatTrueLike(array( 'versionable' => false, 'signable' => false, 'form' => array( 'type' => "ASF\DocumentBundle\Form\Type\PageType", 'name' => 'page_type' ) )) ->treatFalseLike(array( 'versionable' => false, 'signable' => false, 'form' => array( 'type' => "ASF\DocumentBundle\Form\Type\PageType", 'name' => 'page_type' ) )) ->addDefaultsIfNotSet() ->children() ->booleanNode('versionable') ->defaultFalse() ->end() ->booleanNode('signable') ->defaultFalse() ->end() ->arrayNode('form') ->addDefaultsIfNotSet() ->children() ->scalarNode('type') ->defaultValue('ASF\DocumentBundle\Form\Type\PageType') ->end() ->scalarNode('name') ->defaultValue('page_type') ->end() ->arrayNode('validation_groups') ->prototype('scalar')->end() ->defaultValue(array("Default")) ->end() ->end() ->end() ->end() ; return $node; }
[ "protected", "function", "addPageParameterNode", "(", ")", "{", "$", "builder", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "builder", "->", "root", "(", "'page'", ")", ";", "$", "node", "->", "treatTrueLike", "(", "array", "(", "'versionable'", "=>", "false", ",", "'signable'", "=>", "false", ",", "'form'", "=>", "array", "(", "'type'", "=>", "\"ASF\\DocumentBundle\\Form\\Type\\PageType\"", ",", "'name'", "=>", "'page_type'", ")", ")", ")", "->", "treatFalseLike", "(", "array", "(", "'versionable'", "=>", "false", ",", "'signable'", "=>", "false", ",", "'form'", "=>", "array", "(", "'type'", "=>", "\"ASF\\DocumentBundle\\Form\\Type\\PageType\"", ",", "'name'", "=>", "'page_type'", ")", ")", ")", "->", "addDefaultsIfNotSet", "(", ")", "->", "children", "(", ")", "->", "booleanNode", "(", "'versionable'", ")", "->", "defaultFalse", "(", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "'signable'", ")", "->", "defaultFalse", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'form'", ")", "->", "addDefaultsIfNotSet", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'type'", ")", "->", "defaultValue", "(", "'ASF\\DocumentBundle\\Form\\Type\\PageType'", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'name'", ")", "->", "defaultValue", "(", "'page_type'", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'validation_groups'", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "defaultValue", "(", "array", "(", "\"Default\"", ")", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "node", ";", "}" ]
Add Page Entity Configuration
[ "Add", "Page", "Entity", "Configuration" ]
train
https://github.com/artscorestudio/document-bundle/blob/3aceab0f75de8f7dd0fad0d0db83d7940bf565c8/DependencyInjection/Configuration.php#L49-L98
thelia-modules/CustomerGroup
Model/Base/CustomerCustomerGroupQuery.php
CustomerCustomerGroupQuery.create
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof \CustomerGroup\Model\CustomerCustomerGroupQuery) { return $criteria; } $query = new \CustomerGroup\Model\CustomerCustomerGroupQuery(); if (null !== $modelAlias) { $query->setModelAlias($modelAlias); } if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
php
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof \CustomerGroup\Model\CustomerCustomerGroupQuery) { return $criteria; } $query = new \CustomerGroup\Model\CustomerCustomerGroupQuery(); if (null !== $modelAlias) { $query->setModelAlias($modelAlias); } if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
[ "public", "static", "function", "create", "(", "$", "modelAlias", "=", "null", ",", "$", "criteria", "=", "null", ")", "{", "if", "(", "$", "criteria", "instanceof", "\\", "CustomerGroup", "\\", "Model", "\\", "CustomerCustomerGroupQuery", ")", "{", "return", "$", "criteria", ";", "}", "$", "query", "=", "new", "\\", "CustomerGroup", "\\", "Model", "\\", "CustomerCustomerGroupQuery", "(", ")", ";", "if", "(", "null", "!==", "$", "modelAlias", ")", "{", "$", "query", "->", "setModelAlias", "(", "$", "modelAlias", ")", ";", "}", "if", "(", "$", "criteria", "instanceof", "Criteria", ")", "{", "$", "query", "->", "mergeWith", "(", "$", "criteria", ")", ";", "}", "return", "$", "query", ";", "}" ]
Returns a new ChildCustomerCustomerGroupQuery object. @param string $modelAlias The alias of a model in the query @param Criteria $criteria Optional Criteria to build the query from @return ChildCustomerCustomerGroupQuery
[ "Returns", "a", "new", "ChildCustomerCustomerGroupQuery", "object", "." ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Model/Base/CustomerCustomerGroupQuery.php#L76-L90
thelia-modules/CustomerGroup
Model/Base/CustomerCustomerGroupQuery.php
CustomerCustomerGroupQuery.filterByPrimaryKey
public function filterByPrimaryKey($key) { $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_ID, $key[0], Criteria::EQUAL); $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $key[1], Criteria::EQUAL); return $this; }
php
public function filterByPrimaryKey($key) { $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_ID, $key[0], Criteria::EQUAL); $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $key[1], Criteria::EQUAL); return $this; }
[ "public", "function", "filterByPrimaryKey", "(", "$", "key", ")", "{", "$", "this", "->", "addUsingAlias", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_ID", ",", "$", "key", "[", "0", "]", ",", "Criteria", "::", "EQUAL", ")", ";", "$", "this", "->", "addUsingAlias", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_GROUP_ID", ",", "$", "key", "[", "1", "]", ",", "Criteria", "::", "EQUAL", ")", ";", "return", "$", "this", ";", "}" ]
Filter the query by primary key @param mixed $key Primary key to use for the query @return ChildCustomerCustomerGroupQuery The current query, for fluid interface
[ "Filter", "the", "query", "by", "primary", "key" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Model/Base/CustomerCustomerGroupQuery.php#L210-L216
thelia-modules/CustomerGroup
Model/Base/CustomerCustomerGroupQuery.php
CustomerCustomerGroupQuery.filterByPrimaryKeys
public function filterByPrimaryKeys($keys) { if (empty($keys)) { return $this->add(null, '1<>1', Criteria::CUSTOM); } foreach ($keys as $key) { $cton0 = $this->getNewCriterion(CustomerCustomerGroupTableMap::CUSTOMER_ID, $key[0], Criteria::EQUAL); $cton1 = $this->getNewCriterion(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $key[1], Criteria::EQUAL); $cton0->addAnd($cton1); $this->addOr($cton0); } return $this; }
php
public function filterByPrimaryKeys($keys) { if (empty($keys)) { return $this->add(null, '1<>1', Criteria::CUSTOM); } foreach ($keys as $key) { $cton0 = $this->getNewCriterion(CustomerCustomerGroupTableMap::CUSTOMER_ID, $key[0], Criteria::EQUAL); $cton1 = $this->getNewCriterion(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $key[1], Criteria::EQUAL); $cton0->addAnd($cton1); $this->addOr($cton0); } return $this; }
[ "public", "function", "filterByPrimaryKeys", "(", "$", "keys", ")", "{", "if", "(", "empty", "(", "$", "keys", ")", ")", "{", "return", "$", "this", "->", "add", "(", "null", ",", "'1<>1'", ",", "Criteria", "::", "CUSTOM", ")", ";", "}", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "cton0", "=", "$", "this", "->", "getNewCriterion", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_ID", ",", "$", "key", "[", "0", "]", ",", "Criteria", "::", "EQUAL", ")", ";", "$", "cton1", "=", "$", "this", "->", "getNewCriterion", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_GROUP_ID", ",", "$", "key", "[", "1", "]", ",", "Criteria", "::", "EQUAL", ")", ";", "$", "cton0", "->", "addAnd", "(", "$", "cton1", ")", ";", "$", "this", "->", "addOr", "(", "$", "cton0", ")", ";", "}", "return", "$", "this", ";", "}" ]
Filter the query by a list of primary keys @param array $keys The list of primary key to use for the query @return ChildCustomerCustomerGroupQuery The current query, for fluid interface
[ "Filter", "the", "query", "by", "a", "list", "of", "primary", "keys" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Model/Base/CustomerCustomerGroupQuery.php#L225-L238
thelia-modules/CustomerGroup
Model/Base/CustomerCustomerGroupQuery.php
CustomerCustomerGroupQuery.filterByCustomerGroupId
public function filterByCustomerGroupId($customerGroupId = null, $comparison = null) { if (is_array($customerGroupId)) { $useMinMax = false; if (isset($customerGroupId['min'])) { $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroupId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($customerGroupId['max'])) { $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroupId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroupId, $comparison); }
php
public function filterByCustomerGroupId($customerGroupId = null, $comparison = null) { if (is_array($customerGroupId)) { $useMinMax = false; if (isset($customerGroupId['min'])) { $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroupId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($customerGroupId['max'])) { $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroupId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroupId, $comparison); }
[ "public", "function", "filterByCustomerGroupId", "(", "$", "customerGroupId", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "customerGroupId", ")", ")", "{", "$", "useMinMax", "=", "false", ";", "if", "(", "isset", "(", "$", "customerGroupId", "[", "'min'", "]", ")", ")", "{", "$", "this", "->", "addUsingAlias", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_GROUP_ID", ",", "$", "customerGroupId", "[", "'min'", "]", ",", "Criteria", "::", "GREATER_EQUAL", ")", ";", "$", "useMinMax", "=", "true", ";", "}", "if", "(", "isset", "(", "$", "customerGroupId", "[", "'max'", "]", ")", ")", "{", "$", "this", "->", "addUsingAlias", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_GROUP_ID", ",", "$", "customerGroupId", "[", "'max'", "]", ",", "Criteria", "::", "LESS_EQUAL", ")", ";", "$", "useMinMax", "=", "true", ";", "}", "if", "(", "$", "useMinMax", ")", "{", "return", "$", "this", ";", "}", "if", "(", "null", "===", "$", "comparison", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_GROUP_ID", ",", "$", "customerGroupId", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the customer_group_id column Example usage: <code> $query->filterByCustomerGroupId(1234); // WHERE customer_group_id = 1234 $query->filterByCustomerGroupId(array(12, 34)); // WHERE customer_group_id IN (12, 34) $query->filterByCustomerGroupId(array('min' => 12)); // WHERE customer_group_id > 12 </code> @see filterByCustomerGroup() @param mixed $customerGroupId The value to use as filter. Use scalar values for equality. Use array values for in_array() equivalent. Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return ChildCustomerCustomerGroupQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "customer_group_id", "column" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Model/Base/CustomerCustomerGroupQuery.php#L303-L324
thelia-modules/CustomerGroup
Model/Base/CustomerCustomerGroupQuery.php
CustomerCustomerGroupQuery.filterByCustomer
public function filterByCustomer($customer, $comparison = null) { if ($customer instanceof \Thelia\Model\Customer) { return $this ->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_ID, $customer->getId(), $comparison); } elseif ($customer instanceof ObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_ID, $customer->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByCustomer() only accepts arguments of type \Thelia\Model\Customer or Collection'); } }
php
public function filterByCustomer($customer, $comparison = null) { if ($customer instanceof \Thelia\Model\Customer) { return $this ->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_ID, $customer->getId(), $comparison); } elseif ($customer instanceof ObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_ID, $customer->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByCustomer() only accepts arguments of type \Thelia\Model\Customer or Collection'); } }
[ "public", "function", "filterByCustomer", "(", "$", "customer", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "$", "customer", "instanceof", "\\", "Thelia", "\\", "Model", "\\", "Customer", ")", "{", "return", "$", "this", "->", "addUsingAlias", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_ID", ",", "$", "customer", "->", "getId", "(", ")", ",", "$", "comparison", ")", ";", "}", "elseif", "(", "$", "customer", "instanceof", "ObjectCollection", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "return", "$", "this", "->", "addUsingAlias", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_ID", ",", "$", "customer", "->", "toKeyValue", "(", "'PrimaryKey'", ",", "'Id'", ")", ",", "$", "comparison", ")", ";", "}", "else", "{", "throw", "new", "PropelException", "(", "'filterByCustomer() only accepts arguments of type \\Thelia\\Model\\Customer or Collection'", ")", ";", "}", "}" ]
Filter the query by a related \Thelia\Model\Customer object @param \Thelia\Model\Customer|ObjectCollection $customer The related object(s) to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return ChildCustomerCustomerGroupQuery The current query, for fluid interface
[ "Filter", "the", "query", "by", "a", "related", "\\", "Thelia", "\\", "Model", "\\", "Customer", "object" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Model/Base/CustomerCustomerGroupQuery.php#L334-L349
thelia-modules/CustomerGroup
Model/Base/CustomerCustomerGroupQuery.php
CustomerCustomerGroupQuery.useCustomerQuery
public function useCustomerQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinCustomer($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'Customer', '\Thelia\Model\CustomerQuery'); }
php
public function useCustomerQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinCustomer($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'Customer', '\Thelia\Model\CustomerQuery'); }
[ "public", "function", "useCustomerQuery", "(", "$", "relationAlias", "=", "null", ",", "$", "joinType", "=", "Criteria", "::", "INNER_JOIN", ")", "{", "return", "$", "this", "->", "joinCustomer", "(", "$", "relationAlias", ",", "$", "joinType", ")", "->", "useQuery", "(", "$", "relationAlias", "?", "$", "relationAlias", ":", "'Customer'", ",", "'\\Thelia\\Model\\CustomerQuery'", ")", ";", "}" ]
Use the Customer relation Customer object @see useQuery() @param string $relationAlias optional alias for the relation, to be used as main alias in the secondary query @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' @return \Thelia\Model\CustomerQuery A secondary query class using the current class as primary query
[ "Use", "the", "Customer", "relation", "Customer", "object" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Model/Base/CustomerCustomerGroupQuery.php#L394-L399
thelia-modules/CustomerGroup
Model/Base/CustomerCustomerGroupQuery.php
CustomerCustomerGroupQuery.filterByCustomerGroup
public function filterByCustomerGroup($customerGroup, $comparison = null) { if ($customerGroup instanceof \CustomerGroup\Model\CustomerGroup) { return $this ->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroup->getId(), $comparison); } elseif ($customerGroup instanceof ObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroup->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByCustomerGroup() only accepts arguments of type \CustomerGroup\Model\CustomerGroup or Collection'); } }
php
public function filterByCustomerGroup($customerGroup, $comparison = null) { if ($customerGroup instanceof \CustomerGroup\Model\CustomerGroup) { return $this ->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroup->getId(), $comparison); } elseif ($customerGroup instanceof ObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID, $customerGroup->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByCustomerGroup() only accepts arguments of type \CustomerGroup\Model\CustomerGroup or Collection'); } }
[ "public", "function", "filterByCustomerGroup", "(", "$", "customerGroup", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "$", "customerGroup", "instanceof", "\\", "CustomerGroup", "\\", "Model", "\\", "CustomerGroup", ")", "{", "return", "$", "this", "->", "addUsingAlias", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_GROUP_ID", ",", "$", "customerGroup", "->", "getId", "(", ")", ",", "$", "comparison", ")", ";", "}", "elseif", "(", "$", "customerGroup", "instanceof", "ObjectCollection", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "return", "$", "this", "->", "addUsingAlias", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_GROUP_ID", ",", "$", "customerGroup", "->", "toKeyValue", "(", "'PrimaryKey'", ",", "'Id'", ")", ",", "$", "comparison", ")", ";", "}", "else", "{", "throw", "new", "PropelException", "(", "'filterByCustomerGroup() only accepts arguments of type \\CustomerGroup\\Model\\CustomerGroup or Collection'", ")", ";", "}", "}" ]
Filter the query by a related \CustomerGroup\Model\CustomerGroup object @param \CustomerGroup\Model\CustomerGroup|ObjectCollection $customerGroup The related object(s) to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return ChildCustomerCustomerGroupQuery The current query, for fluid interface
[ "Filter", "the", "query", "by", "a", "related", "\\", "CustomerGroup", "\\", "Model", "\\", "CustomerGroup", "object" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Model/Base/CustomerCustomerGroupQuery.php#L409-L424
thelia-modules/CustomerGroup
Model/Base/CustomerCustomerGroupQuery.php
CustomerCustomerGroupQuery.useCustomerGroupQuery
public function useCustomerGroupQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinCustomerGroup($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'CustomerGroup', '\CustomerGroup\Model\CustomerGroupQuery'); }
php
public function useCustomerGroupQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinCustomerGroup($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'CustomerGroup', '\CustomerGroup\Model\CustomerGroupQuery'); }
[ "public", "function", "useCustomerGroupQuery", "(", "$", "relationAlias", "=", "null", ",", "$", "joinType", "=", "Criteria", "::", "INNER_JOIN", ")", "{", "return", "$", "this", "->", "joinCustomerGroup", "(", "$", "relationAlias", ",", "$", "joinType", ")", "->", "useQuery", "(", "$", "relationAlias", "?", "$", "relationAlias", ":", "'CustomerGroup'", ",", "'\\CustomerGroup\\Model\\CustomerGroupQuery'", ")", ";", "}" ]
Use the CustomerGroup relation CustomerGroup object @see useQuery() @param string $relationAlias optional alias for the relation, to be used as main alias in the secondary query @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' @return \CustomerGroup\Model\CustomerGroupQuery A secondary query class using the current class as primary query
[ "Use", "the", "CustomerGroup", "relation", "CustomerGroup", "object" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Model/Base/CustomerCustomerGroupQuery.php#L469-L474
thelia-modules/CustomerGroup
Model/Base/CustomerCustomerGroupQuery.php
CustomerCustomerGroupQuery.prune
public function prune($customerCustomerGroup = null) { if ($customerCustomerGroup) { $this->addCond('pruneCond0', $this->getAliasedColName(CustomerCustomerGroupTableMap::CUSTOMER_ID), $customerCustomerGroup->getCustomerId(), Criteria::NOT_EQUAL); $this->addCond('pruneCond1', $this->getAliasedColName(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID), $customerCustomerGroup->getCustomerGroupId(), Criteria::NOT_EQUAL); $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); } return $this; }
php
public function prune($customerCustomerGroup = null) { if ($customerCustomerGroup) { $this->addCond('pruneCond0', $this->getAliasedColName(CustomerCustomerGroupTableMap::CUSTOMER_ID), $customerCustomerGroup->getCustomerId(), Criteria::NOT_EQUAL); $this->addCond('pruneCond1', $this->getAliasedColName(CustomerCustomerGroupTableMap::CUSTOMER_GROUP_ID), $customerCustomerGroup->getCustomerGroupId(), Criteria::NOT_EQUAL); $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); } return $this; }
[ "public", "function", "prune", "(", "$", "customerCustomerGroup", "=", "null", ")", "{", "if", "(", "$", "customerCustomerGroup", ")", "{", "$", "this", "->", "addCond", "(", "'pruneCond0'", ",", "$", "this", "->", "getAliasedColName", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_ID", ")", ",", "$", "customerCustomerGroup", "->", "getCustomerId", "(", ")", ",", "Criteria", "::", "NOT_EQUAL", ")", ";", "$", "this", "->", "addCond", "(", "'pruneCond1'", ",", "$", "this", "->", "getAliasedColName", "(", "CustomerCustomerGroupTableMap", "::", "CUSTOMER_GROUP_ID", ")", ",", "$", "customerCustomerGroup", "->", "getCustomerGroupId", "(", ")", ",", "Criteria", "::", "NOT_EQUAL", ")", ";", "$", "this", "->", "combine", "(", "array", "(", "'pruneCond0'", ",", "'pruneCond1'", ")", ",", "Criteria", "::", "LOGICAL_OR", ")", ";", "}", "return", "$", "this", ";", "}" ]
Exclude object from result @param ChildCustomerCustomerGroup $customerCustomerGroup Object to remove from the list of results @return ChildCustomerCustomerGroupQuery The current query, for fluid interface
[ "Exclude", "object", "from", "result" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/Model/Base/CustomerCustomerGroupQuery.php#L483-L492
mustardandrew/muan-laravel-acl
src/Commands/User/ViewCommand.php
ViewCommand.handle
public function handle() { $id = $this->argument('id'); try { $user = $this->prepareUser($id); } catch (Exception $e) { $this->warn($e->getMessage()); return 1; } echo "User name: {$user->name} (ID = {$user->id})", PHP_EOL; echo "Created at: {$user->created_at}", PHP_EOL; echo "Updated at: {$user->updated_at}", PHP_EOL; $this->show($user, 'role'); $this->show($user, 'permission'); return 0; }
php
public function handle() { $id = $this->argument('id'); try { $user = $this->prepareUser($id); } catch (Exception $e) { $this->warn($e->getMessage()); return 1; } echo "User name: {$user->name} (ID = {$user->id})", PHP_EOL; echo "Created at: {$user->created_at}", PHP_EOL; echo "Updated at: {$user->updated_at}", PHP_EOL; $this->show($user, 'role'); $this->show($user, 'permission'); return 0; }
[ "public", "function", "handle", "(", ")", "{", "$", "id", "=", "$", "this", "->", "argument", "(", "'id'", ")", ";", "try", "{", "$", "user", "=", "$", "this", "->", "prepareUser", "(", "$", "id", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "this", "->", "warn", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "return", "1", ";", "}", "echo", "\"User name: {$user->name} (ID = {$user->id})\"", ",", "PHP_EOL", ";", "echo", "\"Created at: {$user->created_at}\"", ",", "PHP_EOL", ";", "echo", "\"Updated at: {$user->updated_at}\"", ",", "PHP_EOL", ";", "$", "this", "->", "show", "(", "$", "user", ",", "'role'", ")", ";", "$", "this", "->", "show", "(", "$", "user", ",", "'permission'", ")", ";", "return", "0", ";", "}" ]
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/mustardandrew/muan-laravel-acl/blob/b5f23340b5536babb98d9fd0d727a7a3371c97d5/src/Commands/User/ViewCommand.php#L38-L57
mustardandrew/muan-laravel-acl
src/Commands/User/ViewCommand.php
ViewCommand.show
protected function show($user, string $modelName) { $method = "{$modelName}s"; $methodTitle = ucfirst($method); if (! $user->$method) { $this->warn("User not use Has{$methodTitle}Trait!"); return; } echo "{$methodTitle}:", PHP_EOL; $data = $this->prepareData($user->$method->toArray()); if ($user->$method->count()) { $this->table(['ID', ucfirst($modelName), 'Created At', 'Updated At'], $data); } else { $this->warn("Not found any {$method}!"); } }
php
protected function show($user, string $modelName) { $method = "{$modelName}s"; $methodTitle = ucfirst($method); if (! $user->$method) { $this->warn("User not use Has{$methodTitle}Trait!"); return; } echo "{$methodTitle}:", PHP_EOL; $data = $this->prepareData($user->$method->toArray()); if ($user->$method->count()) { $this->table(['ID', ucfirst($modelName), 'Created At', 'Updated At'], $data); } else { $this->warn("Not found any {$method}!"); } }
[ "protected", "function", "show", "(", "$", "user", ",", "string", "$", "modelName", ")", "{", "$", "method", "=", "\"{$modelName}s\"", ";", "$", "methodTitle", "=", "ucfirst", "(", "$", "method", ")", ";", "if", "(", "!", "$", "user", "->", "$", "method", ")", "{", "$", "this", "->", "warn", "(", "\"User not use Has{$methodTitle}Trait!\"", ")", ";", "return", ";", "}", "echo", "\"{$methodTitle}:\"", ",", "PHP_EOL", ";", "$", "data", "=", "$", "this", "->", "prepareData", "(", "$", "user", "->", "$", "method", "->", "toArray", "(", ")", ")", ";", "if", "(", "$", "user", "->", "$", "method", "->", "count", "(", ")", ")", "{", "$", "this", "->", "table", "(", "[", "'ID'", ",", "ucfirst", "(", "$", "modelName", ")", ",", "'Created At'", ",", "'Updated At'", "]", ",", "$", "data", ")", ";", "}", "else", "{", "$", "this", "->", "warn", "(", "\"Not found any {$method}!\"", ")", ";", "}", "}" ]
Show roles or permissions @param $user @param string $modelName
[ "Show", "roles", "or", "permissions" ]
train
https://github.com/mustardandrew/muan-laravel-acl/blob/b5f23340b5536babb98d9fd0d727a7a3371c97d5/src/Commands/User/ViewCommand.php#L65-L84
pixxet/flysystem-webdav
src/WebDAVAdapter.php
WebDAVAdapter.rename
function rename($path, $newpath) { $location = $this->applyPathPrefix($this->encodePath($path)); $newLocation = $this->applyPathPrefix($this->encodePath($newpath)); try { $response = $this->client->request('MOVE', '/' . ltrim($location, '/'), null, [ 'Destination' => '/' . ltrim($newLocation, '/'), ]); if ($response['statusCode'] >= 200 && $response['statusCode'] < 300) { return true; } } catch (NotFound $e) { // Would have returned false here, but would be redundant } return false; }
php
function rename($path, $newpath) { $location = $this->applyPathPrefix($this->encodePath($path)); $newLocation = $this->applyPathPrefix($this->encodePath($newpath)); try { $response = $this->client->request('MOVE', '/' . ltrim($location, '/'), null, [ 'Destination' => '/' . ltrim($newLocation, '/'), ]); if ($response['statusCode'] >= 200 && $response['statusCode'] < 300) { return true; } } catch (NotFound $e) { // Would have returned false here, but would be redundant } return false; }
[ "function", "rename", "(", "$", "path", ",", "$", "newpath", ")", "{", "$", "location", "=", "$", "this", "->", "applyPathPrefix", "(", "$", "this", "->", "encodePath", "(", "$", "path", ")", ")", ";", "$", "newLocation", "=", "$", "this", "->", "applyPathPrefix", "(", "$", "this", "->", "encodePath", "(", "$", "newpath", ")", ")", ";", "try", "{", "$", "response", "=", "$", "this", "->", "client", "->", "request", "(", "'MOVE'", ",", "'/'", ".", "ltrim", "(", "$", "location", ",", "'/'", ")", ",", "null", ",", "[", "'Destination'", "=>", "'/'", ".", "ltrim", "(", "$", "newLocation", ",", "'/'", ")", ",", "]", ")", ";", "if", "(", "$", "response", "[", "'statusCode'", "]", ">=", "200", "&&", "$", "response", "[", "'statusCode'", "]", "<", "300", ")", "{", "return", "true", ";", "}", "}", "catch", "(", "NotFound", "$", "e", ")", "{", "// Would have returned false here, but would be redundant", "}", "return", "false", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/pixxet/flysystem-webdav/blob/1ce6d63f9565171ccb5f4741d43906e50441516a/src/WebDAVAdapter.php#L170-L188
pixxet/flysystem-webdav
src/WebDAVAdapter.php
WebDAVAdapter.nativeCopy
function nativeCopy($path, $newPath) { if (!$this->createDir(Util::dirname($newPath), new Config())) { return false; } $location = $this->applyPathPrefix($this->encodePath($path)); $newLocation = $this->applyPathPrefix($this->encodePath($newPath)); try { $destination = $this->client->getAbsoluteUrl($newLocation); $response = $this->client->request('COPY', '/' . ltrim($location, '/'), null, [ 'Destination' => $destination, ]); if ($response['statusCode'] >= 200 && $response['statusCode'] < 300) { return true; } } catch (NotFound $e) { // Would have returned false here, but would be redundant } return false; }
php
function nativeCopy($path, $newPath) { if (!$this->createDir(Util::dirname($newPath), new Config())) { return false; } $location = $this->applyPathPrefix($this->encodePath($path)); $newLocation = $this->applyPathPrefix($this->encodePath($newPath)); try { $destination = $this->client->getAbsoluteUrl($newLocation); $response = $this->client->request('COPY', '/' . ltrim($location, '/'), null, [ 'Destination' => $destination, ]); if ($response['statusCode'] >= 200 && $response['statusCode'] < 300) { return true; } } catch (NotFound $e) { // Would have returned false here, but would be redundant } return false; }
[ "function", "nativeCopy", "(", "$", "path", ",", "$", "newPath", ")", "{", "if", "(", "!", "$", "this", "->", "createDir", "(", "Util", "::", "dirname", "(", "$", "newPath", ")", ",", "new", "Config", "(", ")", ")", ")", "{", "return", "false", ";", "}", "$", "location", "=", "$", "this", "->", "applyPathPrefix", "(", "$", "this", "->", "encodePath", "(", "$", "path", ")", ")", ";", "$", "newLocation", "=", "$", "this", "->", "applyPathPrefix", "(", "$", "this", "->", "encodePath", "(", "$", "newPath", ")", ")", ";", "try", "{", "$", "destination", "=", "$", "this", "->", "client", "->", "getAbsoluteUrl", "(", "$", "newLocation", ")", ";", "$", "response", "=", "$", "this", "->", "client", "->", "request", "(", "'COPY'", ",", "'/'", ".", "ltrim", "(", "$", "location", ",", "'/'", ")", ",", "null", ",", "[", "'Destination'", "=>", "$", "destination", ",", "]", ")", ";", "if", "(", "$", "response", "[", "'statusCode'", "]", ">=", "200", "&&", "$", "response", "[", "'statusCode'", "]", "<", "300", ")", "{", "return", "true", ";", "}", "}", "catch", "(", "NotFound", "$", "e", ")", "{", "// Would have returned false here, but would be redundant", "}", "return", "false", ";", "}" ]
Copy a file through WebDav COPY method. @param string $path @param string $newPath @return bool
[ "Copy", "a", "file", "through", "WebDav", "COPY", "method", "." ]
train
https://github.com/pixxet/flysystem-webdav/blob/1ce6d63f9565171ccb5f4741d43906e50441516a/src/WebDAVAdapter.php#L338-L361
pixxet/flysystem-webdav
src/WebDAVAdapter.php
WebDAVAdapter.normalizeObject
function normalizeObject(array $object, $path) { if (!isset($object['{DAV:}getcontentlength']) or $object['{DAV:}getcontentlength'] == "") { return ['type' => 'dir', 'path' => trim($path, '/')]; } $result = Util::map($object, static::$resultMap); if (isset($object['{DAV:}getlastmodified'])) { $result['timestamp'] = strtotime($object['{DAV:}getlastmodified']); } $result['type'] = 'file'; $result['path'] = trim($path, '/'); return $result; }
php
function normalizeObject(array $object, $path) { if (!isset($object['{DAV:}getcontentlength']) or $object['{DAV:}getcontentlength'] == "") { return ['type' => 'dir', 'path' => trim($path, '/')]; } $result = Util::map($object, static::$resultMap); if (isset($object['{DAV:}getlastmodified'])) { $result['timestamp'] = strtotime($object['{DAV:}getlastmodified']); } $result['type'] = 'file'; $result['path'] = trim($path, '/'); return $result; }
[ "function", "normalizeObject", "(", "array", "$", "object", ",", "$", "path", ")", "{", "if", "(", "!", "isset", "(", "$", "object", "[", "'{DAV:}getcontentlength'", "]", ")", "or", "$", "object", "[", "'{DAV:}getcontentlength'", "]", "==", "\"\"", ")", "{", "return", "[", "'type'", "=>", "'dir'", ",", "'path'", "=>", "trim", "(", "$", "path", ",", "'/'", ")", "]", ";", "}", "$", "result", "=", "Util", "::", "map", "(", "$", "object", ",", "static", "::", "$", "resultMap", ")", ";", "if", "(", "isset", "(", "$", "object", "[", "'{DAV:}getlastmodified'", "]", ")", ")", "{", "$", "result", "[", "'timestamp'", "]", "=", "strtotime", "(", "$", "object", "[", "'{DAV:}getlastmodified'", "]", ")", ";", "}", "$", "result", "[", "'type'", "]", "=", "'file'", ";", "$", "result", "[", "'path'", "]", "=", "trim", "(", "$", "path", ",", "'/'", ")", ";", "return", "$", "result", ";", "}" ]
Normalise a WebDAV repsonse object. @param array $object @param string $path @return array
[ "Normalise", "a", "WebDAV", "repsonse", "object", "." ]
train
https://github.com/pixxet/flysystem-webdav/blob/1ce6d63f9565171ccb5f4741d43906e50441516a/src/WebDAVAdapter.php#L371-L387
pixxet/flysystem-webdav
src/WebDAVAdapter.php
WebDAVAdapter.removePathPrefix
function removePathPrefix($path) { if (strpos($path, $this->getPathPrefix()) === false) { return basename($path); } return parent::removePathPrefix($path); }
php
function removePathPrefix($path) { if (strpos($path, $this->getPathPrefix()) === false) { return basename($path); } return parent::removePathPrefix($path); }
[ "function", "removePathPrefix", "(", "$", "path", ")", "{", "if", "(", "strpos", "(", "$", "path", ",", "$", "this", "->", "getPathPrefix", "(", ")", ")", "===", "false", ")", "{", "return", "basename", "(", "$", "path", ")", ";", "}", "return", "parent", "::", "removePathPrefix", "(", "$", "path", ")", ";", "}" ]
Remove a path prefix. @param string $path @return string path without the prefix
[ "Remove", "a", "path", "prefix", "." ]
train
https://github.com/pixxet/flysystem-webdav/blob/1ce6d63f9565171ccb5f4741d43906e50441516a/src/WebDAVAdapter.php#L396-L403
thienhungho/yii2-product-management
src/modules/ProductManage/controllers/TermOfProductTypeController.php
TermOfProductTypeController.actionIndex
public function actionIndex($type = 'product') { if (!is_product_type_name($type)) { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } $searchModel = new TermOfProductTypeSearch(); $queryParams = request()->queryParams; $queryParams['TermOfProductTypeSearch']['product_type'] = $type; $dataProvider = $searchModel->search($queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); }
php
public function actionIndex($type = 'product') { if (!is_product_type_name($type)) { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } $searchModel = new TermOfProductTypeSearch(); $queryParams = request()->queryParams; $queryParams['TermOfProductTypeSearch']['product_type'] = $type; $dataProvider = $searchModel->search($queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); }
[ "public", "function", "actionIndex", "(", "$", "type", "=", "'product'", ")", "{", "if", "(", "!", "is_product_type_name", "(", "$", "type", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", "t", "(", "'app'", ",", "'The requested page does not exist.'", ")", ")", ";", "}", "$", "searchModel", "=", "new", "TermOfProductTypeSearch", "(", ")", ";", "$", "queryParams", "=", "request", "(", ")", "->", "queryParams", ";", "$", "queryParams", "[", "'TermOfProductTypeSearch'", "]", "[", "'product_type'", "]", "=", "$", "type", ";", "$", "dataProvider", "=", "$", "searchModel", "->", "search", "(", "$", "queryParams", ")", ";", "return", "$", "this", "->", "render", "(", "'index'", ",", "[", "'searchModel'", "=>", "$", "searchModel", ",", "'dataProvider'", "=>", "$", "dataProvider", ",", "]", ")", ";", "}" ]
@param string $type @return string @throws NotFoundHttpException
[ "@param", "string", "$type" ]
train
https://github.com/thienhungho/yii2-product-management/blob/72e1237bba123faf671e44491bd93077b50adde9/src/modules/ProductManage/controllers/TermOfProductTypeController.php#L34-L48
thienhungho/yii2-product-management
src/modules/ProductManage/controllers/TermOfProductTypeController.php
TermOfProductTypeController.actionCreate
public function actionCreate($type = 'product') { if (!is_product_type_name($type)) { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } $model = new TermOfProductType(); $model->product_type = $type; if ($model->loadAll(request()->post())) { if (!TermOfProductType::find() ->where(['product_type' => $model->product_type]) ->andWhere(['name' => $model->name]) ->exists()) { if ($model->saveAll()) { return $this->redirect([ 'update', 'id' => $model->id, ]); } } else { $model->addError('name', t('app', 'This name has already been set.')); } } return $this->render('create', [ 'model' => $model, ]); }
php
public function actionCreate($type = 'product') { if (!is_product_type_name($type)) { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } $model = new TermOfProductType(); $model->product_type = $type; if ($model->loadAll(request()->post())) { if (!TermOfProductType::find() ->where(['product_type' => $model->product_type]) ->andWhere(['name' => $model->name]) ->exists()) { if ($model->saveAll()) { return $this->redirect([ 'update', 'id' => $model->id, ]); } } else { $model->addError('name', t('app', 'This name has already been set.')); } } return $this->render('create', [ 'model' => $model, ]); }
[ "public", "function", "actionCreate", "(", "$", "type", "=", "'product'", ")", "{", "if", "(", "!", "is_product_type_name", "(", "$", "type", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", "t", "(", "'app'", ",", "'The requested page does not exist.'", ")", ")", ";", "}", "$", "model", "=", "new", "TermOfProductType", "(", ")", ";", "$", "model", "->", "product_type", "=", "$", "type", ";", "if", "(", "$", "model", "->", "loadAll", "(", "request", "(", ")", "->", "post", "(", ")", ")", ")", "{", "if", "(", "!", "TermOfProductType", "::", "find", "(", ")", "->", "where", "(", "[", "'product_type'", "=>", "$", "model", "->", "product_type", "]", ")", "->", "andWhere", "(", "[", "'name'", "=>", "$", "model", "->", "name", "]", ")", "->", "exists", "(", ")", ")", "{", "if", "(", "$", "model", "->", "saveAll", "(", ")", ")", "{", "return", "$", "this", "->", "redirect", "(", "[", "'update'", ",", "'id'", "=>", "$", "model", "->", "id", ",", "]", ")", ";", "}", "}", "else", "{", "$", "model", "->", "addError", "(", "'name'", ",", "t", "(", "'app'", ",", "'This name has already been set.'", ")", ")", ";", "}", "}", "return", "$", "this", "->", "render", "(", "'create'", ",", "[", "'model'", "=>", "$", "model", ",", "]", ")", ";", "}" ]
@param string $type @return string|\yii\web\Response @throws NotFoundHttpException @throws \yii\db\Exception
[ "@param", "string", "$type" ]
train
https://github.com/thienhungho/yii2-product-management/blob/72e1237bba123faf671e44491bd93077b50adde9/src/modules/ProductManage/controllers/TermOfProductTypeController.php#L70-L96
thienhungho/yii2-product-management
src/modules/ProductManage/controllers/TermOfProductTypeController.php
TermOfProductTypeController.findModel
protected function findModel($id) { if (($model = TermOfProductType::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } }
php
protected function findModel($id) { if (($model = TermOfProductType::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } }
[ "protected", "function", "findModel", "(", "$", "id", ")", "{", "if", "(", "(", "$", "model", "=", "TermOfProductType", "::", "findOne", "(", "$", "id", ")", ")", "!==", "null", ")", "{", "return", "$", "model", ";", "}", "else", "{", "throw", "new", "NotFoundHttpException", "(", "t", "(", "'app'", ",", "'The requested page does not exist.'", ")", ")", ";", "}", "}" ]
Finds the TermOfProductType model based on its primary key value. If the model is not found, a 404 HTTP exception will be thrown. @param integer $id @return TermOfProductType the loaded model @throws NotFoundHttpException if the model cannot be found
[ "Finds", "the", "TermOfProductType", "model", "based", "on", "its", "primary", "key", "value", ".", "If", "the", "model", "is", "not", "found", "a", "404", "HTTP", "exception", "will", "be", "thrown", "." ]
train
https://github.com/thienhungho/yii2-product-management/blob/72e1237bba123faf671e44491bd93077b50adde9/src/modules/ProductManage/controllers/TermOfProductTypeController.php#L207-L214
giftcards/Encryption
Key/SourceBuilder.php
SourceBuilder.add
public function add( $source, array $options = array(), $prefix = null, $addCircularGuard = false ) { if (!$source instanceof SourceInterface) { if (!$prefix && $prefix !== false) { $prefix = $source; } $source = $this->factory->create($source, $options); } if ($prefix) { $source = new PrefixKeyNameSource($prefix, $source); } if ($addCircularGuard) { $source = new CircularGuardSource($source); } $this->sources[] = $source; return $this; }
php
public function add( $source, array $options = array(), $prefix = null, $addCircularGuard = false ) { if (!$source instanceof SourceInterface) { if (!$prefix && $prefix !== false) { $prefix = $source; } $source = $this->factory->create($source, $options); } if ($prefix) { $source = new PrefixKeyNameSource($prefix, $source); } if ($addCircularGuard) { $source = new CircularGuardSource($source); } $this->sources[] = $source; return $this; }
[ "public", "function", "add", "(", "$", "source", ",", "array", "$", "options", "=", "array", "(", ")", ",", "$", "prefix", "=", "null", ",", "$", "addCircularGuard", "=", "false", ")", "{", "if", "(", "!", "$", "source", "instanceof", "SourceInterface", ")", "{", "if", "(", "!", "$", "prefix", "&&", "$", "prefix", "!==", "false", ")", "{", "$", "prefix", "=", "$", "source", ";", "}", "$", "source", "=", "$", "this", "->", "factory", "->", "create", "(", "$", "source", ",", "$", "options", ")", ";", "}", "if", "(", "$", "prefix", ")", "{", "$", "source", "=", "new", "PrefixKeyNameSource", "(", "$", "prefix", ",", "$", "source", ")", ";", "}", "if", "(", "$", "addCircularGuard", ")", "{", "$", "source", "=", "new", "CircularGuardSource", "(", "$", "source", ")", ";", "}", "$", "this", "->", "sources", "[", "]", "=", "$", "source", ";", "return", "$", "this", ";", "}" ]
@param $source @param array $options @param null $prefix @param bool|false $addCircularGuard @return $this Add a new key source either an instance of the interface or a name and options. i nal cases a prefix can be given and a boollean stating if they hsould be wrapped in a circular guard
[ "@param", "$source", "@param", "array", "$options", "@param", "null", "$prefix", "@param", "bool|false", "$addCircularGuard", "@return", "$this" ]
train
https://github.com/giftcards/Encryption/blob/a48f92408538e2ffe1c8603f168d57803aad7100/Key/SourceBuilder.php#L88-L112
giftcards/Encryption
Key/SourceBuilder.php
SourceBuilder.addFallback
public function addFallback($name, $fallbackName) { if (!isset($this->fallbacks[$name])) { $this->fallbacks[$name] = array(); } $this->fallbacks[$name][] = $fallbackName; return $this; }
php
public function addFallback($name, $fallbackName) { if (!isset($this->fallbacks[$name])) { $this->fallbacks[$name] = array(); } $this->fallbacks[$name][] = $fallbackName; return $this; }
[ "public", "function", "addFallback", "(", "$", "name", ",", "$", "fallbackName", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "fallbacks", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "fallbacks", "[", "$", "name", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "fallbacks", "[", "$", "name", "]", "[", "]", "=", "$", "fallbackName", ";", "return", "$", "this", ";", "}" ]
@param $name @param $fallbackName @return $this add a fallback for a certain key name if it doesnt exist
[ "@param", "$name", "@param", "$fallbackName", "@return", "$this" ]
train
https://github.com/giftcards/Encryption/blob/a48f92408538e2ffe1c8603f168d57803aad7100/Key/SourceBuilder.php#L121-L128
giftcards/Encryption
Key/SourceBuilder.php
SourceBuilder.combine
public function combine($left, $right, $name) { $this->combined[$name] = array( CombiningSource::LEFT => $left, CombiningSource::RIGHT => $right ); return $this; }
php
public function combine($left, $right, $name) { $this->combined[$name] = array( CombiningSource::LEFT => $left, CombiningSource::RIGHT => $right ); return $this; }
[ "public", "function", "combine", "(", "$", "left", ",", "$", "right", ",", "$", "name", ")", "{", "$", "this", "->", "combined", "[", "$", "name", "]", "=", "array", "(", "CombiningSource", "::", "LEFT", "=>", "$", "left", ",", "CombiningSource", "::", "RIGHT", "=>", "$", "right", ")", ";", "return", "$", "this", ";", "}" ]
@param string $left the name of the ey to use for the left side of the combined key @param string $right the name of the ey to use for the right side of the combined key @param string $name @return $this add a new combined key made up of 3 other keys named by $left and $right
[ "@param", "string", "$left", "the", "name", "of", "the", "ey", "to", "use", "for", "the", "left", "side", "of", "the", "combined", "key", "@param", "string", "$right", "the", "name", "of", "the", "ey", "to", "use", "for", "the", "right", "side", "of", "the", "combined", "key", "@param", "string", "$name", "@return", "$this" ]
train
https://github.com/giftcards/Encryption/blob/a48f92408538e2ffe1c8603f168d57803aad7100/Key/SourceBuilder.php#L151-L158
surebert/surebert-framework
src/sb/CURL/Client.php
Client.load
public function load($url, $data = null, $headers = null, $curl_opts = []) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 2); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookies); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookies); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); if($headers){ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } if ($data) { curl_setopt($ch, CURLOPT_POST, true); if(is_array($data)){ $data = http_build_query($data); } curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } if ($this->verbose) { curl_setopt($ch, CURLOPT_VERBOSE, 2); } foreach ($curl_opts as $opt => $val) { curl_setopt($ch, $opt, $val); } $response = curl_exec($ch); $i = curl_getinfo($ch); if ($i['http_code'] != 200) { throw(new \Exception("ERROR READING URL:\n" . curl_error($ch) . print_r($i, 1))); } return $response; }
php
public function load($url, $data = null, $headers = null, $curl_opts = []) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 2); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookies); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookies); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); if($headers){ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } if ($data) { curl_setopt($ch, CURLOPT_POST, true); if(is_array($data)){ $data = http_build_query($data); } curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } if ($this->verbose) { curl_setopt($ch, CURLOPT_VERBOSE, 2); } foreach ($curl_opts as $opt => $val) { curl_setopt($ch, $opt, $val); } $response = curl_exec($ch); $i = curl_getinfo($ch); if ($i['http_code'] != 200) { throw(new \Exception("ERROR READING URL:\n" . curl_error($ch) . print_r($i, 1))); } return $response; }
[ "public", "function", "load", "(", "$", "url", ",", "$", "data", "=", "null", ",", "$", "headers", "=", "null", ",", "$", "curl_opts", "=", "[", "]", ")", "{", "$", "ch", "=", "curl_init", "(", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "2", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYHOST", ",", "2", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_COOKIEJAR", ",", "$", "this", "->", "cookies", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_COOKIEFILE", ",", "$", "this", "->", "cookies", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_FOLLOWLOCATION", ",", "true", ")", ";", "if", "(", "$", "headers", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "$", "headers", ")", ";", "}", "if", "(", "$", "data", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "true", ")", ";", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "$", "data", "=", "http_build_query", "(", "$", "data", ")", ";", "}", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "data", ")", ";", "}", "if", "(", "$", "this", "->", "verbose", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_VERBOSE", ",", "2", ")", ";", "}", "foreach", "(", "$", "curl_opts", "as", "$", "opt", "=>", "$", "val", ")", "{", "curl_setopt", "(", "$", "ch", ",", "$", "opt", ",", "$", "val", ")", ";", "}", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "$", "i", "=", "curl_getinfo", "(", "$", "ch", ")", ";", "if", "(", "$", "i", "[", "'http_code'", "]", "!=", "200", ")", "{", "throw", "(", "new", "\\", "Exception", "(", "\"ERROR READING URL:\\n\"", ".", "curl_error", "(", "$", "ch", ")", ".", "print_r", "(", "$", "i", ",", "1", ")", ")", ")", ";", "}", "return", "$", "response", ";", "}" ]
Loads a response from an NTLM service @param string $url The url to visit @param string/array $post The post data to send @param array $headers The headers to send @param array $curl_opts Any additional curl_opts to send @return string the response text @throws \Exception
[ "Loads", "a", "response", "from", "an", "NTLM", "service" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/CURL/Client.php#L57-L96
surebert/surebert-framework
src/sb/CURL/Client.php
Client.post
public function post($url, $data = [], $headers = [], $curl_opts = []) { return $this->load($url, $data, $headers, $curl_opts); }
php
public function post($url, $data = [], $headers = [], $curl_opts = []) { return $this->load($url, $data, $headers, $curl_opts); }
[ "public", "function", "post", "(", "$", "url", ",", "$", "data", "=", "[", "]", ",", "$", "headers", "=", "[", "]", ",", "$", "curl_opts", "=", "[", "]", ")", "{", "return", "$", "this", "->", "load", "(", "$", "url", ",", "$", "data", ",", "$", "headers", ",", "$", "curl_opts", ")", ";", "}" ]
GETs data from the server @param string $url The URL to grab @param array $data The data to pass @param array $headers additional HTTP options @param array $curl_opts additional CURL options @return string @throws \Exception
[ "GETs", "data", "from", "the", "server" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/CURL/Client.php#L119-L121
surebert/surebert-framework
src/sb/CURL/Client.php
Client.put
public function put($url, $data = [], $headers = [], $curl_opts = []) { $curl_opts[CURLOPT_CUSTOMREQUEST] = 'PUT'; return $this->load($url, $data, $headers, $curl_opts); }
php
public function put($url, $data = [], $headers = [], $curl_opts = []) { $curl_opts[CURLOPT_CUSTOMREQUEST] = 'PUT'; return $this->load($url, $data, $headers, $curl_opts); }
[ "public", "function", "put", "(", "$", "url", ",", "$", "data", "=", "[", "]", ",", "$", "headers", "=", "[", "]", ",", "$", "curl_opts", "=", "[", "]", ")", "{", "$", "curl_opts", "[", "CURLOPT_CUSTOMREQUEST", "]", "=", "'PUT'", ";", "return", "$", "this", "->", "load", "(", "$", "url", ",", "$", "data", ",", "$", "headers", ",", "$", "curl_opts", ")", ";", "}" ]
PUTs data to the server @param string $url The URL to grab @param array $data The data to pass @param array $headers additional HTTP options @param array $curl_opts additional CURL options @return string @throws \Exception
[ "PUTs", "data", "to", "the", "server" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/CURL/Client.php#L132-L135
surebert/surebert-framework
src/sb/CURL/Client.php
Client.delete
public function delete($url, $data = [], $headers = [], $curl_opts = []) { $curl_opts[CURLOPT_CUSTOMREQUEST] = 'DELETE'; return $this->load($url, $data, $headers, $curl_opts); }
php
public function delete($url, $data = [], $headers = [], $curl_opts = []) { $curl_opts[CURLOPT_CUSTOMREQUEST] = 'DELETE'; return $this->load($url, $data, $headers, $curl_opts); }
[ "public", "function", "delete", "(", "$", "url", ",", "$", "data", "=", "[", "]", ",", "$", "headers", "=", "[", "]", ",", "$", "curl_opts", "=", "[", "]", ")", "{", "$", "curl_opts", "[", "CURLOPT_CUSTOMREQUEST", "]", "=", "'DELETE'", ";", "return", "$", "this", "->", "load", "(", "$", "url", ",", "$", "data", ",", "$", "headers", ",", "$", "curl_opts", ")", ";", "}" ]
DELETEs data from the server @param string $url The URL to grab @param array $data The data to pass @param array $headers additional HTTP options @param array $curl_opts additional CURL options @return string @throws \Exception
[ "DELETEs", "data", "from", "the", "server" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/CURL/Client.php#L146-L149
FriendsOfApi/phraseapp
src/Model/Translation/Index.php
Index.createFromArray
public static function createFromArray(array $data) { $self = new self(); foreach ($data as $translation) { $self->addTranslation(Translation::createFromArray($translation)); } return $self; }
php
public static function createFromArray(array $data) { $self = new self(); foreach ($data as $translation) { $self->addTranslation(Translation::createFromArray($translation)); } return $self; }
[ "public", "static", "function", "createFromArray", "(", "array", "$", "data", ")", "{", "$", "self", "=", "new", "self", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "translation", ")", "{", "$", "self", "->", "addTranslation", "(", "Translation", "::", "createFromArray", "(", "$", "translation", ")", ")", ";", "}", "return", "$", "self", ";", "}" ]
@param array $data @return Index
[ "@param", "array", "$data" ]
train
https://github.com/FriendsOfApi/phraseapp/blob/1553bf857eb0858f9a7eb905b085864d24f80886/src/Model/Translation/Index.php#L29-L38
blast-project/BaseEntitiesBundle
src/DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('blast_base_entities'); $rootNode ->append($this->getVendorNode('orm')) ->append($this->getVendorNode('odm')) // not tested yet ->children() ->arrayNode('entity_search_indexes') ->useAttributeAsKey('class') ->prototype('array') ->children() ->scalarNode('class')->end() ->variableNode('fields')->end() ->end() ->end() ->defaultValue([]) ->end() ->end() ; return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('blast_base_entities'); $rootNode ->append($this->getVendorNode('orm')) ->append($this->getVendorNode('odm')) // not tested yet ->children() ->arrayNode('entity_search_indexes') ->useAttributeAsKey('class') ->prototype('array') ->children() ->scalarNode('class')->end() ->variableNode('fields')->end() ->end() ->end() ->defaultValue([]) ->end() ->end() ; return $treeBuilder; }
[ "public", "function", "getConfigTreeBuilder", "(", ")", "{", "$", "treeBuilder", "=", "new", "TreeBuilder", "(", ")", ";", "$", "rootNode", "=", "$", "treeBuilder", "->", "root", "(", "'blast_base_entities'", ")", ";", "$", "rootNode", "->", "append", "(", "$", "this", "->", "getVendorNode", "(", "'orm'", ")", ")", "->", "append", "(", "$", "this", "->", "getVendorNode", "(", "'odm'", ")", ")", "// not tested yet", "->", "children", "(", ")", "->", "arrayNode", "(", "'entity_search_indexes'", ")", "->", "useAttributeAsKey", "(", "'class'", ")", "->", "prototype", "(", "'array'", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'class'", ")", "->", "end", "(", ")", "->", "variableNode", "(", "'fields'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "defaultValue", "(", "[", "]", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "treeBuilder", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/blast-project/BaseEntitiesBundle/blob/abd06891fc38922225ab7e4fcb437a286ba2c0c4/src/DependencyInjection/Configuration.php#L28-L51
madkom/regex
src/Splitter.php
Splitter.split
public function split(string $subject, int $limit = -1, int $flags = 0) : array { $result = preg_split($this->pattern->getPattern() . $this->modifier, $subject, $limit, $flags); if (($errno = preg_last_error()) !== PREG_NO_ERROR) { $message = array_flip(get_defined_constants(true)['pcre'])[$errno]; switch ($errno) { case PREG_INTERNAL_ERROR: throw new InternalException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_BACKTRACK_LIMIT_ERROR: throw new BacktrackLimitException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_RECURSION_LIMIT_ERROR: throw new RecursionLimitException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_BAD_UTF8_ERROR: throw new BadUtf8Exception("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_BAD_UTF8_OFFSET_ERROR: throw new BadUtf8OffsetException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_JIT_STACKLIMIT_ERROR: throw new JitStackLimitException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); } } return $result; }
php
public function split(string $subject, int $limit = -1, int $flags = 0) : array { $result = preg_split($this->pattern->getPattern() . $this->modifier, $subject, $limit, $flags); if (($errno = preg_last_error()) !== PREG_NO_ERROR) { $message = array_flip(get_defined_constants(true)['pcre'])[$errno]; switch ($errno) { case PREG_INTERNAL_ERROR: throw new InternalException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_BACKTRACK_LIMIT_ERROR: throw new BacktrackLimitException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_RECURSION_LIMIT_ERROR: throw new RecursionLimitException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_BAD_UTF8_ERROR: throw new BadUtf8Exception("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_BAD_UTF8_OFFSET_ERROR: throw new BadUtf8OffsetException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); case PREG_JIT_STACKLIMIT_ERROR: throw new JitStackLimitException("{$message} using pattern: {$this->pattern->getPattern()}", $errno); } } return $result; }
[ "public", "function", "split", "(", "string", "$", "subject", ",", "int", "$", "limit", "=", "-", "1", ",", "int", "$", "flags", "=", "0", ")", ":", "array", "{", "$", "result", "=", "preg_split", "(", "$", "this", "->", "pattern", "->", "getPattern", "(", ")", ".", "$", "this", "->", "modifier", ",", "$", "subject", ",", "$", "limit", ",", "$", "flags", ")", ";", "if", "(", "(", "$", "errno", "=", "preg_last_error", "(", ")", ")", "!==", "PREG_NO_ERROR", ")", "{", "$", "message", "=", "array_flip", "(", "get_defined_constants", "(", "true", ")", "[", "'pcre'", "]", ")", "[", "$", "errno", "]", ";", "switch", "(", "$", "errno", ")", "{", "case", "PREG_INTERNAL_ERROR", ":", "throw", "new", "InternalException", "(", "\"{$message} using pattern: {$this->pattern->getPattern()}\"", ",", "$", "errno", ")", ";", "case", "PREG_BACKTRACK_LIMIT_ERROR", ":", "throw", "new", "BacktrackLimitException", "(", "\"{$message} using pattern: {$this->pattern->getPattern()}\"", ",", "$", "errno", ")", ";", "case", "PREG_RECURSION_LIMIT_ERROR", ":", "throw", "new", "RecursionLimitException", "(", "\"{$message} using pattern: {$this->pattern->getPattern()}\"", ",", "$", "errno", ")", ";", "case", "PREG_BAD_UTF8_ERROR", ":", "throw", "new", "BadUtf8Exception", "(", "\"{$message} using pattern: {$this->pattern->getPattern()}\"", ",", "$", "errno", ")", ";", "case", "PREG_BAD_UTF8_OFFSET_ERROR", ":", "throw", "new", "BadUtf8OffsetException", "(", "\"{$message} using pattern: {$this->pattern->getPattern()}\"", ",", "$", "errno", ")", ";", "case", "PREG_JIT_STACKLIMIT_ERROR", ":", "throw", "new", "JitStackLimitException", "(", "\"{$message} using pattern: {$this->pattern->getPattern()}\"", ",", "$", "errno", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Retrieves subject split with Pattern @param string $subject @param int $limit @param int $flags @return array @throws BacktrackLimitException @throws BadUtf8Exception @throws BadUtf8OffsetException @throws InternalException @throws JitStackLimitException @throws RecursionLimitException
[ "Retrieves", "subject", "split", "with", "Pattern" ]
train
https://github.com/madkom/regex/blob/798c1124805b130b1110ee6e8dcc9a88d8aaffa8/src/Splitter.php#L57-L80
highday/glitter
src/Console/Commands/OrderCommand.php
OrderCommand.handle
public function handle() { $this->app = $this->getLaravel(); $flows = [ \Glitter\Commerce\Order\Flow\CartConvert::class, \Glitter\Commerce\Order\Flow\Shipping::class, \Glitter\Commerce\Order\Flow\Discount::class, ]; $order = $this->app->make(OrderContext::class); $order = (new Pipeline($this->app)) ->send($order) ->through($flows)->via('process') ->then(function (OrderContext $order) { return $order; }); $table = new Table($this->getOutput()); $table->setHeaders([ [new TableCell('Order Details', ['colspan' => 3])], ['Item', 'Quantity', 'Price'], ]); $rows = []; foreach ($order->getBoxes() as $box) { foreach ($box as $item) { $rows[] = [ $item->getName(), $item->getQuantity(), $item->getUnitPrice(), ]; } $rows[] = new TableSeparator(); } $rows[] = [ new TableCell('Shipping', ['colspan' => 2]), $order->getShippingFee(), ]; $rows[] = new TableSeparator(); $rows[] = [ new TableCell('Discount', ['colspan' => 2]), $order->getDiscountPirce(), ]; $rows[] = new TableSeparator(); $rows[] = [ new TableCell('Total', ['colspan' => 2]), $order->getTotalPirce(), ]; $table->setRows($rows); $table->render(); }
php
public function handle() { $this->app = $this->getLaravel(); $flows = [ \Glitter\Commerce\Order\Flow\CartConvert::class, \Glitter\Commerce\Order\Flow\Shipping::class, \Glitter\Commerce\Order\Flow\Discount::class, ]; $order = $this->app->make(OrderContext::class); $order = (new Pipeline($this->app)) ->send($order) ->through($flows)->via('process') ->then(function (OrderContext $order) { return $order; }); $table = new Table($this->getOutput()); $table->setHeaders([ [new TableCell('Order Details', ['colspan' => 3])], ['Item', 'Quantity', 'Price'], ]); $rows = []; foreach ($order->getBoxes() as $box) { foreach ($box as $item) { $rows[] = [ $item->getName(), $item->getQuantity(), $item->getUnitPrice(), ]; } $rows[] = new TableSeparator(); } $rows[] = [ new TableCell('Shipping', ['colspan' => 2]), $order->getShippingFee(), ]; $rows[] = new TableSeparator(); $rows[] = [ new TableCell('Discount', ['colspan' => 2]), $order->getDiscountPirce(), ]; $rows[] = new TableSeparator(); $rows[] = [ new TableCell('Total', ['colspan' => 2]), $order->getTotalPirce(), ]; $table->setRows($rows); $table->render(); }
[ "public", "function", "handle", "(", ")", "{", "$", "this", "->", "app", "=", "$", "this", "->", "getLaravel", "(", ")", ";", "$", "flows", "=", "[", "\\", "Glitter", "\\", "Commerce", "\\", "Order", "\\", "Flow", "\\", "CartConvert", "::", "class", ",", "\\", "Glitter", "\\", "Commerce", "\\", "Order", "\\", "Flow", "\\", "Shipping", "::", "class", ",", "\\", "Glitter", "\\", "Commerce", "\\", "Order", "\\", "Flow", "\\", "Discount", "::", "class", ",", "]", ";", "$", "order", "=", "$", "this", "->", "app", "->", "make", "(", "OrderContext", "::", "class", ")", ";", "$", "order", "=", "(", "new", "Pipeline", "(", "$", "this", "->", "app", ")", ")", "->", "send", "(", "$", "order", ")", "->", "through", "(", "$", "flows", ")", "->", "via", "(", "'process'", ")", "->", "then", "(", "function", "(", "OrderContext", "$", "order", ")", "{", "return", "$", "order", ";", "}", ")", ";", "$", "table", "=", "new", "Table", "(", "$", "this", "->", "getOutput", "(", ")", ")", ";", "$", "table", "->", "setHeaders", "(", "[", "[", "new", "TableCell", "(", "'Order Details'", ",", "[", "'colspan'", "=>", "3", "]", ")", "]", ",", "[", "'Item'", ",", "'Quantity'", ",", "'Price'", "]", ",", "]", ")", ";", "$", "rows", "=", "[", "]", ";", "foreach", "(", "$", "order", "->", "getBoxes", "(", ")", "as", "$", "box", ")", "{", "foreach", "(", "$", "box", "as", "$", "item", ")", "{", "$", "rows", "[", "]", "=", "[", "$", "item", "->", "getName", "(", ")", ",", "$", "item", "->", "getQuantity", "(", ")", ",", "$", "item", "->", "getUnitPrice", "(", ")", ",", "]", ";", "}", "$", "rows", "[", "]", "=", "new", "TableSeparator", "(", ")", ";", "}", "$", "rows", "[", "]", "=", "[", "new", "TableCell", "(", "'Shipping'", ",", "[", "'colspan'", "=>", "2", "]", ")", ",", "$", "order", "->", "getShippingFee", "(", ")", ",", "]", ";", "$", "rows", "[", "]", "=", "new", "TableSeparator", "(", ")", ";", "$", "rows", "[", "]", "=", "[", "new", "TableCell", "(", "'Discount'", ",", "[", "'colspan'", "=>", "2", "]", ")", ",", "$", "order", "->", "getDiscountPirce", "(", ")", ",", "]", ";", "$", "rows", "[", "]", "=", "new", "TableSeparator", "(", ")", ";", "$", "rows", "[", "]", "=", "[", "new", "TableCell", "(", "'Total'", ",", "[", "'colspan'", "=>", "2", "]", ")", ",", "$", "order", "->", "getTotalPirce", "(", ")", ",", "]", ";", "$", "table", "->", "setRows", "(", "$", "rows", ")", ";", "$", "table", "->", "render", "(", ")", ";", "}" ]
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/highday/glitter/blob/d1c7a227fd2343806bd3ec0314e621ced57dfe66/src/Console/Commands/OrderCommand.php#L33-L88
namics/twig-nitro-library
src/Twig/TokenParser/ComponentTokenParser.php
ComponentTokenParser.parse
public function parse(Twig_Token $token) { $component = $this->parser->getExpressionParser()->parseExpression(); list($data, $only) = $this->parseArguments(); return new ComponentNode($component, $this->ctxProvider, $data, $only, $token->getLine(), $this->getTag()); }
php
public function parse(Twig_Token $token) { $component = $this->parser->getExpressionParser()->parseExpression(); list($data, $only) = $this->parseArguments(); return new ComponentNode($component, $this->ctxProvider, $data, $only, $token->getLine(), $this->getTag()); }
[ "public", "function", "parse", "(", "Twig_Token", "$", "token", ")", "{", "$", "component", "=", "$", "this", "->", "parser", "->", "getExpressionParser", "(", ")", "->", "parseExpression", "(", ")", ";", "list", "(", "$", "data", ",", "$", "only", ")", "=", "$", "this", "->", "parseArguments", "(", ")", ";", "return", "new", "ComponentNode", "(", "$", "component", ",", "$", "this", "->", "ctxProvider", ",", "$", "data", ",", "$", "only", ",", "$", "token", "->", "getLine", "(", ")", ",", "$", "this", "->", "getTag", "(", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/namics/twig-nitro-library/blob/f4631b50876b7cdc79f3cca4d3465c8c9a2e87de/src/Twig/TokenParser/ComponentTokenParser.php#L44-L50
namics/twig-nitro-library
src/Twig/TokenParser/ComponentTokenParser.php
ComponentTokenParser.parseArguments
protected function parseArguments() { $stream = $this->parser->getStream(); $data = null; $only = false; if ($stream->test(Twig_Token::BLOCK_END_TYPE)) { $stream->expect(Twig_Token::BLOCK_END_TYPE); return [$data, $only]; } if ($stream->test(Twig_Token::NAME_TYPE, 'only')) { $only = true; $stream->next(); $stream->expect(Twig_Token::BLOCK_END_TYPE); return [$data, $only]; } $data = $this->parser->getExpressionParser()->parseExpression(); if ($stream->test(Twig_Token::NAME_TYPE, 'only')) { $only = true; $stream->next(); } $stream->expect(Twig_Token::BLOCK_END_TYPE); return [$data, $only]; }
php
protected function parseArguments() { $stream = $this->parser->getStream(); $data = null; $only = false; if ($stream->test(Twig_Token::BLOCK_END_TYPE)) { $stream->expect(Twig_Token::BLOCK_END_TYPE); return [$data, $only]; } if ($stream->test(Twig_Token::NAME_TYPE, 'only')) { $only = true; $stream->next(); $stream->expect(Twig_Token::BLOCK_END_TYPE); return [$data, $only]; } $data = $this->parser->getExpressionParser()->parseExpression(); if ($stream->test(Twig_Token::NAME_TYPE, 'only')) { $only = true; $stream->next(); } $stream->expect(Twig_Token::BLOCK_END_TYPE); return [$data, $only]; }
[ "protected", "function", "parseArguments", "(", ")", "{", "$", "stream", "=", "$", "this", "->", "parser", "->", "getStream", "(", ")", ";", "$", "data", "=", "null", ";", "$", "only", "=", "false", ";", "if", "(", "$", "stream", "->", "test", "(", "Twig_Token", "::", "BLOCK_END_TYPE", ")", ")", "{", "$", "stream", "->", "expect", "(", "Twig_Token", "::", "BLOCK_END_TYPE", ")", ";", "return", "[", "$", "data", ",", "$", "only", "]", ";", "}", "if", "(", "$", "stream", "->", "test", "(", "Twig_Token", "::", "NAME_TYPE", ",", "'only'", ")", ")", "{", "$", "only", "=", "true", ";", "$", "stream", "->", "next", "(", ")", ";", "$", "stream", "->", "expect", "(", "Twig_Token", "::", "BLOCK_END_TYPE", ")", ";", "return", "[", "$", "data", ",", "$", "only", "]", ";", "}", "$", "data", "=", "$", "this", "->", "parser", "->", "getExpressionParser", "(", ")", "->", "parseExpression", "(", ")", ";", "if", "(", "$", "stream", "->", "test", "(", "Twig_Token", "::", "NAME_TYPE", ",", "'only'", ")", ")", "{", "$", "only", "=", "true", ";", "$", "stream", "->", "next", "(", ")", ";", "}", "$", "stream", "->", "expect", "(", "Twig_Token", "::", "BLOCK_END_TYPE", ")", ";", "return", "[", "$", "data", ",", "$", "only", "]", ";", "}" ]
Tokenizes the component stream. @return array
[ "Tokenizes", "the", "component", "stream", "." ]
train
https://github.com/namics/twig-nitro-library/blob/f4631b50876b7cdc79f3cca4d3465c8c9a2e87de/src/Twig/TokenParser/ComponentTokenParser.php#L56-L87
chrismou/phergie-irc-plugin-react-google
src/Plugin.php
Plugin.getSubscribedEvents
public function getSubscribedEvents() { $events = []; foreach ($this->providers as $command => $provider) { $events['command.' . $command] = 'handleCommand'; $events['command.' . $command . '.help'] = 'handleCommandHelp'; } return $events; }
php
public function getSubscribedEvents() { $events = []; foreach ($this->providers as $command => $provider) { $events['command.' . $command] = 'handleCommand'; $events['command.' . $command . '.help'] = 'handleCommandHelp'; } return $events; }
[ "public", "function", "getSubscribedEvents", "(", ")", "{", "$", "events", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "providers", "as", "$", "command", "=>", "$", "provider", ")", "{", "$", "events", "[", "'command.'", ".", "$", "command", "]", "=", "'handleCommand'", ";", "$", "events", "[", "'command.'", ".", "$", "command", ".", "'.help'", "]", "=", "'handleCommandHelp'", ";", "}", "return", "$", "events", ";", "}" ]
Return an array of commands and associated methods @return array
[ "Return", "an", "array", "of", "commands", "and", "associated", "methods" ]
train
https://github.com/chrismou/phergie-irc-plugin-react-google/blob/4492bf1e25826a9cf7187afee0ec35deddefaf6f/src/Plugin.php#L62-L71
chrismou/phergie-irc-plugin-react-google
src/Plugin.php
Plugin.handleCommandHelp
public function handleCommandHelp(Event $event, Queue $queue) { $params = $event->getCustomParams(); $provider = $this->getProvider( ($event->getCustomCommand() === "help") ? $params[0] : $event->getCustomCommand() ); if ($provider) { $this->sendIrcResponse($event, $queue, $provider->getHelpLines()); } }
php
public function handleCommandHelp(Event $event, Queue $queue) { $params = $event->getCustomParams(); $provider = $this->getProvider( ($event->getCustomCommand() === "help") ? $params[0] : $event->getCustomCommand() ); if ($provider) { $this->sendIrcResponse($event, $queue, $provider->getHelpLines()); } }
[ "public", "function", "handleCommandHelp", "(", "Event", "$", "event", ",", "Queue", "$", "queue", ")", "{", "$", "params", "=", "$", "event", "->", "getCustomParams", "(", ")", ";", "$", "provider", "=", "$", "this", "->", "getProvider", "(", "(", "$", "event", "->", "getCustomCommand", "(", ")", "===", "\"help\"", ")", "?", "$", "params", "[", "0", "]", ":", "$", "event", "->", "getCustomCommand", "(", ")", ")", ";", "if", "(", "$", "provider", ")", "{", "$", "this", "->", "sendIrcResponse", "(", "$", "event", ",", "$", "queue", ",", "$", "provider", "->", "getHelpLines", "(", ")", ")", ";", "}", "}" ]
Main plugin handler for help requests @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event @param \Phergie\Irc\Bot\React\EventQueueInterface $queue
[ "Main", "plugin", "handler", "for", "help", "requests" ]
train
https://github.com/chrismou/phergie-irc-plugin-react-google/blob/4492bf1e25826a9cf7187afee0ec35deddefaf6f/src/Plugin.php#L98-L109
chrismou/phergie-irc-plugin-react-google
src/Plugin.php
Plugin.getProvider
public function getProvider($command) { $providerExists = (isset($this->providers[$command]) && class_exists($this->providers[$command])); return ($providerExists) ? new $this->providers[$command] : false; }
php
public function getProvider($command) { $providerExists = (isset($this->providers[$command]) && class_exists($this->providers[$command])); return ($providerExists) ? new $this->providers[$command] : false; }
[ "public", "function", "getProvider", "(", "$", "command", ")", "{", "$", "providerExists", "=", "(", "isset", "(", "$", "this", "->", "providers", "[", "$", "command", "]", ")", "&&", "class_exists", "(", "$", "this", "->", "providers", "[", "$", "command", "]", ")", ")", ";", "return", "(", "$", "providerExists", ")", "?", "new", "$", "this", "->", "providers", "[", "$", "command", "]", ":", "false", ";", "}" ]
Get a single provider class by command @param string $command @return mixed
[ "Get", "a", "single", "provider", "class", "by", "command" ]
train
https://github.com/chrismou/phergie-irc-plugin-react-google/blob/4492bf1e25826a9cf7187afee0ec35deddefaf6f/src/Plugin.php#L118-L122
chrismou/phergie-irc-plugin-react-google
src/Plugin.php
Plugin.getApiRequest
protected function getApiRequest(Event $event, Queue $queue, GoogleProviderInterface $provider) { $self = $this; return new HttpRequest([ 'url' => $provider->getApiRequestUrl($event), 'resolveCallback' => function (Response $response) use ($self, $event, $queue, $provider) { $self->sendIrcResponse($event, $queue, $provider->getSuccessLines($event, $response->getBody())); }, 'rejectCallback' => function ($error) use ($self, $event, $queue, $provider) { $self->sendIrcResponse($event, $queue, $provider->getRejectLines($event, $error)); } ]); }
php
protected function getApiRequest(Event $event, Queue $queue, GoogleProviderInterface $provider) { $self = $this; return new HttpRequest([ 'url' => $provider->getApiRequestUrl($event), 'resolveCallback' => function (Response $response) use ($self, $event, $queue, $provider) { $self->sendIrcResponse($event, $queue, $provider->getSuccessLines($event, $response->getBody())); }, 'rejectCallback' => function ($error) use ($self, $event, $queue, $provider) { $self->sendIrcResponse($event, $queue, $provider->getRejectLines($event, $error)); } ]); }
[ "protected", "function", "getApiRequest", "(", "Event", "$", "event", ",", "Queue", "$", "queue", ",", "GoogleProviderInterface", "$", "provider", ")", "{", "$", "self", "=", "$", "this", ";", "return", "new", "HttpRequest", "(", "[", "'url'", "=>", "$", "provider", "->", "getApiRequestUrl", "(", "$", "event", ")", ",", "'resolveCallback'", "=>", "function", "(", "Response", "$", "response", ")", "use", "(", "$", "self", ",", "$", "event", ",", "$", "queue", ",", "$", "provider", ")", "{", "$", "self", "->", "sendIrcResponse", "(", "$", "event", ",", "$", "queue", ",", "$", "provider", "->", "getSuccessLines", "(", "$", "event", ",", "$", "response", "->", "getBody", "(", ")", ")", ")", ";", "}", ",", "'rejectCallback'", "=>", "function", "(", "$", "error", ")", "use", "(", "$", "self", ",", "$", "event", ",", "$", "queue", ",", "$", "provider", ")", "{", "$", "self", "->", "sendIrcResponse", "(", "$", "event", ",", "$", "queue", ",", "$", "provider", "->", "getRejectLines", "(", "$", "event", ",", "$", "error", ")", ")", ";", "}", "]", ")", ";", "}" ]
Set up the API request and set the callbacks @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event @param \Phergie\Irc\Bot\React\EventQueueInterface $queue @param \Chrismou\Phergie\Plugin\Google\Provider\GoogleProviderInterface $provider @return \Phergie\Plugin\Http\Request
[ "Set", "up", "the", "API", "request", "and", "set", "the", "callbacks" ]
train
https://github.com/chrismou/phergie-irc-plugin-react-google/blob/4492bf1e25826a9cf7187afee0ec35deddefaf6f/src/Plugin.php#L133-L146
chrismou/phergie-irc-plugin-react-google
src/Plugin.php
Plugin.sendIrcResponse
protected function sendIrcResponse(Event $event, Queue $queue, array $ircResponse) { foreach ($ircResponse as $ircResponseLine) { $this->sendIrcResponseLine($event, $queue, $ircResponseLine); } }
php
protected function sendIrcResponse(Event $event, Queue $queue, array $ircResponse) { foreach ($ircResponse as $ircResponseLine) { $this->sendIrcResponseLine($event, $queue, $ircResponseLine); } }
[ "protected", "function", "sendIrcResponse", "(", "Event", "$", "event", ",", "Queue", "$", "queue", ",", "array", "$", "ircResponse", ")", "{", "foreach", "(", "$", "ircResponse", "as", "$", "ircResponseLine", ")", "{", "$", "this", "->", "sendIrcResponseLine", "(", "$", "event", ",", "$", "queue", ",", "$", "ircResponseLine", ")", ";", "}", "}" ]
Send an array of response lines back to IRC @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event @param \Phergie\Irc\Bot\React\EventQueueInterface $queue @param array $ircResponse
[ "Send", "an", "array", "of", "response", "lines", "back", "to", "IRC" ]
train
https://github.com/chrismou/phergie-irc-plugin-react-google/blob/4492bf1e25826a9cf7187afee0ec35deddefaf6f/src/Plugin.php#L156-L161
chrismou/phergie-irc-plugin-react-google
src/Plugin.php
Plugin.sendIrcResponseLine
protected function sendIrcResponseLine(Event $event, Queue $queue, $ircResponseLine) { $queue->ircPrivmsg($event->getSource(), $ircResponseLine); }
php
protected function sendIrcResponseLine(Event $event, Queue $queue, $ircResponseLine) { $queue->ircPrivmsg($event->getSource(), $ircResponseLine); }
[ "protected", "function", "sendIrcResponseLine", "(", "Event", "$", "event", ",", "Queue", "$", "queue", ",", "$", "ircResponseLine", ")", "{", "$", "queue", "->", "ircPrivmsg", "(", "$", "event", "->", "getSource", "(", ")", ",", "$", "ircResponseLine", ")", ";", "}" ]
Send a single response line back to IRC @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event @param \Phergie\Irc\Bot\React\EventQueueInterface $queue @param string $ircResponseLine
[ "Send", "a", "single", "response", "line", "back", "to", "IRC" ]
train
https://github.com/chrismou/phergie-irc-plugin-react-google/blob/4492bf1e25826a9cf7187afee0ec35deddefaf6f/src/Plugin.php#L171-L174
mothership-ec/composer
src/Composer/Config/JsonConfigSource.php
JsonConfigSource.addRepository
public function addRepository($name, $config) { $this->manipulateJson('addRepository', $name, $config, function (&$config, $repo, $repoConfig) { $config['repositories'][$repo] = $repoConfig; }); }
php
public function addRepository($name, $config) { $this->manipulateJson('addRepository', $name, $config, function (&$config, $repo, $repoConfig) { $config['repositories'][$repo] = $repoConfig; }); }
[ "public", "function", "addRepository", "(", "$", "name", ",", "$", "config", ")", "{", "$", "this", "->", "manipulateJson", "(", "'addRepository'", ",", "$", "name", ",", "$", "config", ",", "function", "(", "&", "$", "config", ",", "$", "repo", ",", "$", "repoConfig", ")", "{", "$", "config", "[", "'repositories'", "]", "[", "$", "repo", "]", "=", "$", "repoConfig", ";", "}", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Config/JsonConfigSource.php#L59-L64
codezero-be/curl
src/ResponseInfo.php
ResponseInfo.fetchInfo
private function fetchInfo($key) { return array_key_exists($key, $this->info) ? $this->info[$key] : null; }
php
private function fetchInfo($key) { return array_key_exists($key, $this->info) ? $this->info[$key] : null; }
[ "private", "function", "fetchInfo", "(", "$", "key", ")", "{", "return", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "info", ")", "?", "$", "this", "->", "info", "[", "$", "key", "]", ":", "null", ";", "}" ]
Search the information array for the specified key and return the value @param string $key @return mixed
[ "Search", "the", "information", "array", "for", "the", "specified", "key", "and", "return", "the", "value" ]
train
https://github.com/codezero-be/curl/blob/c1385479886662b6276c18dd9140df529959d95c/src/ResponseInfo.php#L144-L149
alevilar/ristorantino-vendor
Printers/Lib/NONOReceiptPrint.php
ReceiptPrint.comanda
public static function comanda ( $comanda_id ) { debug( $comanda_id );die("asas"); $Comanda = ClassRegistry::init('Comanda.Comanda'); $productos_x_comanda = array(); // se supone que en una comanda yo no voy a tener productos que se impriman en comanderas distitas // (esto es separado desde el mismo controlador y se manda aimprimir a comandas diferentes) // pero , por las dudas que ésto suceda, cuando yo listo los productos de una comanda, me los separa para ser impreso en Comanderas distintas // Entonces, por lo genral (SIEMPRE) se imprimiria x 1 sola Comandera en este método del Componente $comanderas_involucradas = $Comanda->comanderas_involucradas($comanda_id); $entradas = $Comanda->listado_de_productos_con_sabores($comanda_id, DETALLE_COMANDA_TRAER_ENTRADAS); $platos_principales = $Comanda->listado_de_productos_con_sabores($comanda_id, DETALLE_COMANDA_TRAER_PLATOS_PRINCIPALES); $productos = array_merge($entradas, $platos_principales); // genero el array lindo paraimprimir por cada comanda // o sea, genero un renglón de la comanda // por ejmeplo me queraria algo asi: // "1) Milanesa de pollo\n" foreach($comanderas_involucradas as $printer_id): Printaitor::send(array( 'productos' => $productos, 'entradas' => $entradas, ), $printer_id, 'comandas' // user vista comandas.ctp ); endforeach; }
php
public static function comanda ( $comanda_id ) { debug( $comanda_id );die("asas"); $Comanda = ClassRegistry::init('Comanda.Comanda'); $productos_x_comanda = array(); // se supone que en una comanda yo no voy a tener productos que se impriman en comanderas distitas // (esto es separado desde el mismo controlador y se manda aimprimir a comandas diferentes) // pero , por las dudas que ésto suceda, cuando yo listo los productos de una comanda, me los separa para ser impreso en Comanderas distintas // Entonces, por lo genral (SIEMPRE) se imprimiria x 1 sola Comandera en este método del Componente $comanderas_involucradas = $Comanda->comanderas_involucradas($comanda_id); $entradas = $Comanda->listado_de_productos_con_sabores($comanda_id, DETALLE_COMANDA_TRAER_ENTRADAS); $platos_principales = $Comanda->listado_de_productos_con_sabores($comanda_id, DETALLE_COMANDA_TRAER_PLATOS_PRINCIPALES); $productos = array_merge($entradas, $platos_principales); // genero el array lindo paraimprimir por cada comanda // o sea, genero un renglón de la comanda // por ejmeplo me queraria algo asi: // "1) Milanesa de pollo\n" foreach($comanderas_involucradas as $printer_id): Printaitor::send(array( 'productos' => $productos, 'entradas' => $entradas, ), $printer_id, 'comandas' // user vista comandas.ctp ); endforeach; }
[ "public", "static", "function", "comanda", "(", "$", "comanda_id", ")", "{", "debug", "(", "$", "comanda_id", ")", ";", "die", "(", "\"asas\"", ")", ";", "$", "Comanda", "=", "ClassRegistry", "::", "init", "(", "'Comanda.Comanda'", ")", ";", "$", "productos_x_comanda", "=", "array", "(", ")", ";", "// se supone que en una comanda yo no voy a tener productos que se impriman en comanderas distitas", "// (esto es separado desde el mismo controlador y se manda aimprimir a comandas diferentes)", "// pero , por las dudas que ésto suceda, cuando yo listo los productos de una comanda, me los separa para ser impreso en Comanderas distintas", "// Entonces, por lo genral (SIEMPRE) se imprimiria x 1 sola Comandera en este método del Componente", "$", "comanderas_involucradas", "=", "$", "Comanda", "->", "comanderas_involucradas", "(", "$", "comanda_id", ")", ";", "$", "entradas", "=", "$", "Comanda", "->", "listado_de_productos_con_sabores", "(", "$", "comanda_id", ",", "DETALLE_COMANDA_TRAER_ENTRADAS", ")", ";", "$", "platos_principales", "=", "$", "Comanda", "->", "listado_de_productos_con_sabores", "(", "$", "comanda_id", ",", "DETALLE_COMANDA_TRAER_PLATOS_PRINCIPALES", ")", ";", "$", "productos", "=", "array_merge", "(", "$", "entradas", ",", "$", "platos_principales", ")", ";", "// genero el array lindo paraimprimir por cada comanda", "// o sea, genero un renglón de la comanda", "// por ejmeplo me queraria algo asi:", "// \"1) Milanesa de pollo\\n\"", "foreach", "(", "$", "comanderas_involucradas", "as", "$", "printer_id", ")", ":", "Printaitor", "::", "send", "(", "array", "(", "'productos'", "=>", "$", "productos", ",", "'entradas'", "=>", "$", "entradas", ",", ")", ",", "$", "printer_id", ",", "'comandas'", "// user vista comandas.ctp", ")", ";", "endforeach", ";", "}" ]
Imprime una comanda en particular @param id $comanda_id @return null
[ "Imprime", "una", "comanda", "en", "particular" ]
train
https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Printers/Lib/NONOReceiptPrint.php#L14-L45
RhubarbPHP/Module.RestApi
src/UrlHandlers/RestResourceHandler.php
RestResourceHandler.getRestResource
protected function getRestResource() { $parentResource = $this->getParentResource(); if ($parentResource !== null) { $childResource = $parentResource->getChildResource($this->matchingUrl); if ($childResource) { $childResource->setUrlHandler($this); return $childResource; } } $className = $this->apiResourceClassName; /** @var RestResource $resource */ $resource = new $className($this->getParentResource()); $resource->setUrlHandler($this); return $resource; }
php
protected function getRestResource() { $parentResource = $this->getParentResource(); if ($parentResource !== null) { $childResource = $parentResource->getChildResource($this->matchingUrl); if ($childResource) { $childResource->setUrlHandler($this); return $childResource; } } $className = $this->apiResourceClassName; /** @var RestResource $resource */ $resource = new $className($this->getParentResource()); $resource->setUrlHandler($this); return $resource; }
[ "protected", "function", "getRestResource", "(", ")", "{", "$", "parentResource", "=", "$", "this", "->", "getParentResource", "(", ")", ";", "if", "(", "$", "parentResource", "!==", "null", ")", "{", "$", "childResource", "=", "$", "parentResource", "->", "getChildResource", "(", "$", "this", "->", "matchingUrl", ")", ";", "if", "(", "$", "childResource", ")", "{", "$", "childResource", "->", "setUrlHandler", "(", "$", "this", ")", ";", "return", "$", "childResource", ";", "}", "}", "$", "className", "=", "$", "this", "->", "apiResourceClassName", ";", "/** @var RestResource $resource */", "$", "resource", "=", "new", "$", "className", "(", "$", "this", "->", "getParentResource", "(", ")", ")", ";", "$", "resource", "->", "setUrlHandler", "(", "$", "this", ")", ";", "return", "$", "resource", ";", "}" ]
Gets the RestResource object @return RestResource
[ "Gets", "the", "RestResource", "object" ]
train
https://github.com/RhubarbPHP/Module.RestApi/blob/825d2b920caed13811971c5eb2784a94417787bd/src/UrlHandlers/RestResourceHandler.php#L71-L89
NuclearCMS/Hierarchy
src/Bags/NodeTypeBag.php
NodeTypeBag.addNodeType
public function addNodeType(NodeTypeContract $nodeType) { if ( ! $this->hasNodeType($nodeType->getKey())) { $this->put($nodeType->getKey(), $nodeType); } }
php
public function addNodeType(NodeTypeContract $nodeType) { if ( ! $this->hasNodeType($nodeType->getKey())) { $this->put($nodeType->getKey(), $nodeType); } }
[ "public", "function", "addNodeType", "(", "NodeTypeContract", "$", "nodeType", ")", "{", "if", "(", "!", "$", "this", "->", "hasNodeType", "(", "$", "nodeType", "->", "getKey", "(", ")", ")", ")", "{", "$", "this", "->", "put", "(", "$", "nodeType", "->", "getKey", "(", ")", ",", "$", "nodeType", ")", ";", "}", "}" ]
Adds a node type to the bag @param NodeTypeContract $nodeType
[ "Adds", "a", "node", "type", "to", "the", "bag" ]
train
https://github.com/NuclearCMS/Hierarchy/blob/535171c5e2db72265313fd2110aec8456e46f459/src/Bags/NodeTypeBag.php#L17-L23
nabab/bbn
src/bbn/appui/cron.php
cron._run
private function _run(): void { // The DB and the controller exist if ( $this->check() && isset($this->data['type'])){ if ( !defined('BBN_EXTERNAL_USER_ID') && defined('BBN_EXTERNAL_USER_EMAIL') ){ define('BBN_EXTERNAL_USER_ID', $this->db->select_one('bbn_users', 'id', ['email' => BBN_EXTERNAL_USER_EMAIL])); } if ( defined('BBN_EXTERNAL_USER_ID') && class_exists('\\bbn\\appui\\history') ){ \bbn\appui\history::set_user(BBN_EXTERNAL_USER_ID); } $type = $this->data['type']; // Removing file cache clearstatcache(); // only 2 types: poll or cron if ( $type !== 'poll' ){ $type = 'cron'; } $pid = $this->get_pid_path($this->data); // Checking for the presence of the manual files if ( !$this->is_active() || (($type === 'cron') && !$this->is_cron_active()) || (($type === 'poll') && !$this->is_poll_active()) ){ // Exiting the script if one is missing if ( is_file($pid) ){ @unlink($pid); } exit("GETTING OUT of $type BECAUSE one of the manual files is missing"); } // Loooking for a running PID if ( is_file($pid) && ($file_content = @file_get_contents($pid)) ){ $pid_content = explode('|', $file_content); if ( $pid_content[1] && file_exists('/proc/'.$pid_content[0]) ){ // If it's currently running we exit exit("There is already a process running with PID ".file_get_contents($pid)." in $pid"); } else{ // Otherwise we delete the PID file echo "DELETING FILEPID AS THE PROCESS IS DEAD ".implode(PHP_EOL, $pid_content).PHP_EOL; @unlink($pid); } } // We create the PID file corresponding to the current process file_put_contents($pid, getmypid().'|'.time()); $cron =& $this; // Shutdown function, will be always executed, except if the server is stopped register_shutdown_function(function() use($cron){ $data = $cron->get_data(); $pid = $this->get_pid_path($data); $file_content = @file_get_contents($pid); // Write the error log if an error is present if ( $error = error_get_last() ){ @file_put_contents($cron->get_error_log_path($data), \bbn\x::get_dump($error)); if ( defined('BBN_DATA_PATH') && is_dir(BBN_DATA_PATH.'logs') ){ bbn\x::log([$data, $error], 'cron'); } } $ok = true; // We check if there is a problem with the PID file (it's only debug it shouldn't be necessary) if ( $file_content ){ echo $file_content.PHP_EOL; $pid_content = explode('|', $file_content); if ( $pid_content[1] && ($pid_content[0] != getmypid()) ){ echo 'Different processes: '.$pid_content[0].'/'.getmypid().PHP_EOL; $ok = false; } } if ( $ok && isset($data['type']) ){ // We output the ending time (as all output will be logged in the output file echo 'SHUTDOWN '.date('H:i:s'); // Removing PID file if ( is_file($pid) ){ @unlink($pid); } // And relaunching the continuous tasks if we are in the poller... if ( ($data['type'] === 'poll') && $cron->is_poll_active() ){ $cron->launch_poll(); } else if ( !array_key_exists('id', $data) && ($data['type'] === 'cron') && $cron->is_cron_active() ){ $cron->launch_task_system(); } } }); // And here we really do what we have to do // Poll case if ( $type === 'poll' ){ $this->poll(); } else if ( $type === 'cron' ){ if ( array_key_exists('id', $this->data) ){ echo 'Launching task...'; $this->run_task($this->data); } else{ $this->run_task_system(); } } } }
php
private function _run(): void { // The DB and the controller exist if ( $this->check() && isset($this->data['type'])){ if ( !defined('BBN_EXTERNAL_USER_ID') && defined('BBN_EXTERNAL_USER_EMAIL') ){ define('BBN_EXTERNAL_USER_ID', $this->db->select_one('bbn_users', 'id', ['email' => BBN_EXTERNAL_USER_EMAIL])); } if ( defined('BBN_EXTERNAL_USER_ID') && class_exists('\\bbn\\appui\\history') ){ \bbn\appui\history::set_user(BBN_EXTERNAL_USER_ID); } $type = $this->data['type']; // Removing file cache clearstatcache(); // only 2 types: poll or cron if ( $type !== 'poll' ){ $type = 'cron'; } $pid = $this->get_pid_path($this->data); // Checking for the presence of the manual files if ( !$this->is_active() || (($type === 'cron') && !$this->is_cron_active()) || (($type === 'poll') && !$this->is_poll_active()) ){ // Exiting the script if one is missing if ( is_file($pid) ){ @unlink($pid); } exit("GETTING OUT of $type BECAUSE one of the manual files is missing"); } // Loooking for a running PID if ( is_file($pid) && ($file_content = @file_get_contents($pid)) ){ $pid_content = explode('|', $file_content); if ( $pid_content[1] && file_exists('/proc/'.$pid_content[0]) ){ // If it's currently running we exit exit("There is already a process running with PID ".file_get_contents($pid)." in $pid"); } else{ // Otherwise we delete the PID file echo "DELETING FILEPID AS THE PROCESS IS DEAD ".implode(PHP_EOL, $pid_content).PHP_EOL; @unlink($pid); } } // We create the PID file corresponding to the current process file_put_contents($pid, getmypid().'|'.time()); $cron =& $this; // Shutdown function, will be always executed, except if the server is stopped register_shutdown_function(function() use($cron){ $data = $cron->get_data(); $pid = $this->get_pid_path($data); $file_content = @file_get_contents($pid); // Write the error log if an error is present if ( $error = error_get_last() ){ @file_put_contents($cron->get_error_log_path($data), \bbn\x::get_dump($error)); if ( defined('BBN_DATA_PATH') && is_dir(BBN_DATA_PATH.'logs') ){ bbn\x::log([$data, $error], 'cron'); } } $ok = true; // We check if there is a problem with the PID file (it's only debug it shouldn't be necessary) if ( $file_content ){ echo $file_content.PHP_EOL; $pid_content = explode('|', $file_content); if ( $pid_content[1] && ($pid_content[0] != getmypid()) ){ echo 'Different processes: '.$pid_content[0].'/'.getmypid().PHP_EOL; $ok = false; } } if ( $ok && isset($data['type']) ){ // We output the ending time (as all output will be logged in the output file echo 'SHUTDOWN '.date('H:i:s'); // Removing PID file if ( is_file($pid) ){ @unlink($pid); } // And relaunching the continuous tasks if we are in the poller... if ( ($data['type'] === 'poll') && $cron->is_poll_active() ){ $cron->launch_poll(); } else if ( !array_key_exists('id', $data) && ($data['type'] === 'cron') && $cron->is_cron_active() ){ $cron->launch_task_system(); } } }); // And here we really do what we have to do // Poll case if ( $type === 'poll' ){ $this->poll(); } else if ( $type === 'cron' ){ if ( array_key_exists('id', $this->data) ){ echo 'Launching task...'; $this->run_task($this->data); } else{ $this->run_task_system(); } } } }
[ "private", "function", "_run", "(", ")", ":", "void", "{", "// The DB and the controller exist", "if", "(", "$", "this", "->", "check", "(", ")", "&&", "isset", "(", "$", "this", "->", "data", "[", "'type'", "]", ")", ")", "{", "if", "(", "!", "defined", "(", "'BBN_EXTERNAL_USER_ID'", ")", "&&", "defined", "(", "'BBN_EXTERNAL_USER_EMAIL'", ")", ")", "{", "define", "(", "'BBN_EXTERNAL_USER_ID'", ",", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_users'", ",", "'id'", ",", "[", "'email'", "=>", "BBN_EXTERNAL_USER_EMAIL", "]", ")", ")", ";", "}", "if", "(", "defined", "(", "'BBN_EXTERNAL_USER_ID'", ")", "&&", "class_exists", "(", "'\\\\bbn\\\\appui\\\\history'", ")", ")", "{", "\\", "bbn", "\\", "appui", "\\", "history", "::", "set_user", "(", "BBN_EXTERNAL_USER_ID", ")", ";", "}", "$", "type", "=", "$", "this", "->", "data", "[", "'type'", "]", ";", "// Removing file cache", "clearstatcache", "(", ")", ";", "// only 2 types: poll or cron", "if", "(", "$", "type", "!==", "'poll'", ")", "{", "$", "type", "=", "'cron'", ";", "}", "$", "pid", "=", "$", "this", "->", "get_pid_path", "(", "$", "this", "->", "data", ")", ";", "// Checking for the presence of the manual files", "if", "(", "!", "$", "this", "->", "is_active", "(", ")", "||", "(", "(", "$", "type", "===", "'cron'", ")", "&&", "!", "$", "this", "->", "is_cron_active", "(", ")", ")", "||", "(", "(", "$", "type", "===", "'poll'", ")", "&&", "!", "$", "this", "->", "is_poll_active", "(", ")", ")", ")", "{", "// Exiting the script if one is missing", "if", "(", "is_file", "(", "$", "pid", ")", ")", "{", "@", "unlink", "(", "$", "pid", ")", ";", "}", "exit", "(", "\"GETTING OUT of $type BECAUSE one of the manual files is missing\"", ")", ";", "}", "// Loooking for a running PID", "if", "(", "is_file", "(", "$", "pid", ")", "&&", "(", "$", "file_content", "=", "@", "file_get_contents", "(", "$", "pid", ")", ")", ")", "{", "$", "pid_content", "=", "explode", "(", "'|'", ",", "$", "file_content", ")", ";", "if", "(", "$", "pid_content", "[", "1", "]", "&&", "file_exists", "(", "'/proc/'", ".", "$", "pid_content", "[", "0", "]", ")", ")", "{", "// If it's currently running we exit", "exit", "(", "\"There is already a process running with PID \"", ".", "file_get_contents", "(", "$", "pid", ")", ".", "\" in $pid\"", ")", ";", "}", "else", "{", "// Otherwise we delete the PID file", "echo", "\"DELETING FILEPID AS THE PROCESS IS DEAD \"", ".", "implode", "(", "PHP_EOL", ",", "$", "pid_content", ")", ".", "PHP_EOL", ";", "@", "unlink", "(", "$", "pid", ")", ";", "}", "}", "// We create the PID file corresponding to the current process", "file_put_contents", "(", "$", "pid", ",", "getmypid", "(", ")", ".", "'|'", ".", "time", "(", ")", ")", ";", "$", "cron", "=", "&", "$", "this", ";", "// Shutdown function, will be always executed, except if the server is stopped", "register_shutdown_function", "(", "function", "(", ")", "use", "(", "$", "cron", ")", "{", "$", "data", "=", "$", "cron", "->", "get_data", "(", ")", ";", "$", "pid", "=", "$", "this", "->", "get_pid_path", "(", "$", "data", ")", ";", "$", "file_content", "=", "@", "file_get_contents", "(", "$", "pid", ")", ";", "// Write the error log if an error is present", "if", "(", "$", "error", "=", "error_get_last", "(", ")", ")", "{", "@", "file_put_contents", "(", "$", "cron", "->", "get_error_log_path", "(", "$", "data", ")", ",", "\\", "bbn", "\\", "x", "::", "get_dump", "(", "$", "error", ")", ")", ";", "if", "(", "defined", "(", "'BBN_DATA_PATH'", ")", "&&", "is_dir", "(", "BBN_DATA_PATH", ".", "'logs'", ")", ")", "{", "bbn", "\\", "x", "::", "log", "(", "[", "$", "data", ",", "$", "error", "]", ",", "'cron'", ")", ";", "}", "}", "$", "ok", "=", "true", ";", "// We check if there is a problem with the PID file (it's only debug it shouldn't be necessary)", "if", "(", "$", "file_content", ")", "{", "echo", "$", "file_content", ".", "PHP_EOL", ";", "$", "pid_content", "=", "explode", "(", "'|'", ",", "$", "file_content", ")", ";", "if", "(", "$", "pid_content", "[", "1", "]", "&&", "(", "$", "pid_content", "[", "0", "]", "!=", "getmypid", "(", ")", ")", ")", "{", "echo", "'Different processes: '", ".", "$", "pid_content", "[", "0", "]", ".", "'/'", ".", "getmypid", "(", ")", ".", "PHP_EOL", ";", "$", "ok", "=", "false", ";", "}", "}", "if", "(", "$", "ok", "&&", "isset", "(", "$", "data", "[", "'type'", "]", ")", ")", "{", "// We output the ending time (as all output will be logged in the output file", "echo", "'SHUTDOWN '", ".", "date", "(", "'H:i:s'", ")", ";", "// Removing PID file", "if", "(", "is_file", "(", "$", "pid", ")", ")", "{", "@", "unlink", "(", "$", "pid", ")", ";", "}", "// And relaunching the continuous tasks if we are in the poller...", "if", "(", "(", "$", "data", "[", "'type'", "]", "===", "'poll'", ")", "&&", "$", "cron", "->", "is_poll_active", "(", ")", ")", "{", "$", "cron", "->", "launch_poll", "(", ")", ";", "}", "else", "if", "(", "!", "array_key_exists", "(", "'id'", ",", "$", "data", ")", "&&", "(", "$", "data", "[", "'type'", "]", "===", "'cron'", ")", "&&", "$", "cron", "->", "is_cron_active", "(", ")", ")", "{", "$", "cron", "->", "launch_task_system", "(", ")", ";", "}", "}", "}", ")", ";", "// And here we really do what we have to do", "// Poll case", "if", "(", "$", "type", "===", "'poll'", ")", "{", "$", "this", "->", "poll", "(", ")", ";", "}", "else", "if", "(", "$", "type", "===", "'cron'", ")", "{", "if", "(", "array_key_exists", "(", "'id'", ",", "$", "this", "->", "data", ")", ")", "{", "echo", "'Launching task...'", ";", "$", "this", "->", "run_task", "(", "$", "this", "->", "data", ")", ";", "}", "else", "{", "$", "this", "->", "run_task_system", "(", ")", ";", "}", "}", "}", "}" ]
The script as executed by the CLI in which the real task will come executed. @param string $type
[ "The", "script", "as", "executed", "by", "the", "CLI", "in", "which", "the", "real", "task", "will", "come", "executed", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/cron.php#L126-L226
nabab/bbn
src/bbn/appui/cron.php
cron.execute
public static function execute($path, string $output = null){ if ( $output ){ exec(sprintf('php -f router.php %s > %s 2>&1 &', $path, $output)); } else{ exec(sprintf('php -f router.php %s > /dev/null 2>&1 &', $path)); } }
php
public static function execute($path, string $output = null){ if ( $output ){ exec(sprintf('php -f router.php %s > %s 2>&1 &', $path, $output)); } else{ exec(sprintf('php -f router.php %s > /dev/null 2>&1 &', $path)); } }
[ "public", "static", "function", "execute", "(", "$", "path", ",", "string", "$", "output", "=", "null", ")", "{", "if", "(", "$", "output", ")", "{", "exec", "(", "sprintf", "(", "'php -f router.php %s > %s 2>&1 &'", ",", "$", "path", ",", "$", "output", ")", ")", ";", "}", "else", "{", "exec", "(", "sprintf", "(", "'php -f router.php %s > /dev/null 2>&1 &'", ",", "$", "path", ")", ")", ";", "}", "}" ]
Executes the cli/run file in order to run another script from within the CRON process @param $path @param string|null $output
[ "Executes", "the", "cli", "/", "run", "file", "in", "order", "to", "run", "another", "script", "from", "within", "the", "CRON", "process" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/cron.php#L234-L241
nabab/bbn
src/bbn/appui/cron.php
cron.get_cron
public function get_cron($id): ?array { if ( $this->check() && ($data = $this->db->rselect($this->table, [], ['id' => $id])) ){ $data['cfg'] = json_decode($data['cfg'], 1); return $data; } return null; }
php
public function get_cron($id): ?array { if ( $this->check() && ($data = $this->db->rselect($this->table, [], ['id' => $id])) ){ $data['cfg'] = json_decode($data['cfg'], 1); return $data; } return null; }
[ "public", "function", "get_cron", "(", "$", "id", ")", ":", "?", "array", "{", "if", "(", "$", "this", "->", "check", "(", ")", "&&", "(", "$", "data", "=", "$", "this", "->", "db", "->", "rselect", "(", "$", "this", "->", "table", ",", "[", "]", ",", "[", "'id'", "=>", "$", "id", "]", ")", ")", ")", "{", "$", "data", "[", "'cfg'", "]", "=", "json_decode", "(", "$", "data", "[", "'cfg'", "]", ",", "1", ")", ";", "return", "$", "data", ";", "}", "return", "null", ";", "}" ]
Returns the full row as an indexed array for the given CRON ID. @param $id @return null|array
[ "Returns", "the", "full", "row", "as", "an", "indexed", "array", "for", "the", "given", "CRON", "ID", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/cron.php#L498-L505
nabab/bbn
src/bbn/appui/cron.php
cron.start
public function start($id_cron): bool { $res = false; if ( $this->check() && ($cron = $this->get_cron($id_cron)) ){ bbn\appui\history::disable(); $start = date('Y-m-d H:i:s'); if ( $this->db->update($this->table, [ 'prev' => $start, 'next' => date('Y-m-d H:i:s', $this->get_next_date($cron['cfg']['frequency'])) ], [ 'id' => $id_cron ]) ){ $res = true; } bbn\appui\history::enable(); } return $res; }
php
public function start($id_cron): bool { $res = false; if ( $this->check() && ($cron = $this->get_cron($id_cron)) ){ bbn\appui\history::disable(); $start = date('Y-m-d H:i:s'); if ( $this->db->update($this->table, [ 'prev' => $start, 'next' => date('Y-m-d H:i:s', $this->get_next_date($cron['cfg']['frequency'])) ], [ 'id' => $id_cron ]) ){ $res = true; } bbn\appui\history::enable(); } return $res; }
[ "public", "function", "start", "(", "$", "id_cron", ")", ":", "bool", "{", "$", "res", "=", "false", ";", "if", "(", "$", "this", "->", "check", "(", ")", "&&", "(", "$", "cron", "=", "$", "this", "->", "get_cron", "(", "$", "id_cron", ")", ")", ")", "{", "bbn", "\\", "appui", "\\", "history", "::", "disable", "(", ")", ";", "$", "start", "=", "date", "(", "'Y-m-d H:i:s'", ")", ";", "if", "(", "$", "this", "->", "db", "->", "update", "(", "$", "this", "->", "table", ",", "[", "'prev'", "=>", "$", "start", ",", "'next'", "=>", "date", "(", "'Y-m-d H:i:s'", ",", "$", "this", "->", "get_next_date", "(", "$", "cron", "[", "'cfg'", "]", "[", "'frequency'", "]", ")", ")", "]", ",", "[", "'id'", "=>", "$", "id_cron", "]", ")", ")", "{", "$", "res", "=", "true", ";", "}", "bbn", "\\", "appui", "\\", "history", "::", "enable", "(", ")", ";", "}", "return", "$", "res", ";", "}" ]
Writes in the given CRON row the next start time, the current as previous, and the new running status. @param $id_cron @return bool
[ "Writes", "in", "the", "given", "CRON", "row", "the", "next", "start", "time", "the", "current", "as", "previous", "and", "the", "new", "running", "status", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/cron.php#L512-L529
nabab/bbn
src/bbn/appui/cron.php
cron.finish
public function finish($id, $res = ''){ if ( ($article = $this->get_article($id)) && ($cron = $this->get_cron($article['id_cron'])) ){ bbn\appui\history::disable(); $time = $this->timer->has_started('cron_'.$article['id_cron']) ? $this->timer->stop('cron_'.$article['id_cron']): 0; if ( !empty($res) ){ bbn\x::hdump($id, $res); $this->db->update($this->jtable, [ 'finish' => date('Y-m-d H:i:s'), 'duration' => $time, 'res' => $res ], [ 'id' => $id ]); } else{ $this->db->delete($this->jtable, ['id' => $id]); $prev = $this->db->rselect($this->jtable, ['res', 'id'], ['id_cron' => $article['id_cron']], ['finish' => 'DESC']); if ( $prev['res'] === 'error' ){ $this->db->update($this->jtable, ['res' => 'Restarted after error'], ['id' => $prev['id']]); } } bbn\appui\history::enable(); return $time; } return false; }
php
public function finish($id, $res = ''){ if ( ($article = $this->get_article($id)) && ($cron = $this->get_cron($article['id_cron'])) ){ bbn\appui\history::disable(); $time = $this->timer->has_started('cron_'.$article['id_cron']) ? $this->timer->stop('cron_'.$article['id_cron']): 0; if ( !empty($res) ){ bbn\x::hdump($id, $res); $this->db->update($this->jtable, [ 'finish' => date('Y-m-d H:i:s'), 'duration' => $time, 'res' => $res ], [ 'id' => $id ]); } else{ $this->db->delete($this->jtable, ['id' => $id]); $prev = $this->db->rselect($this->jtable, ['res', 'id'], ['id_cron' => $article['id_cron']], ['finish' => 'DESC']); if ( $prev['res'] === 'error' ){ $this->db->update($this->jtable, ['res' => 'Restarted after error'], ['id' => $prev['id']]); } } bbn\appui\history::enable(); return $time; } return false; }
[ "public", "function", "finish", "(", "$", "id", ",", "$", "res", "=", "''", ")", "{", "if", "(", "(", "$", "article", "=", "$", "this", "->", "get_article", "(", "$", "id", ")", ")", "&&", "(", "$", "cron", "=", "$", "this", "->", "get_cron", "(", "$", "article", "[", "'id_cron'", "]", ")", ")", ")", "{", "bbn", "\\", "appui", "\\", "history", "::", "disable", "(", ")", ";", "$", "time", "=", "$", "this", "->", "timer", "->", "has_started", "(", "'cron_'", ".", "$", "article", "[", "'id_cron'", "]", ")", "?", "$", "this", "->", "timer", "->", "stop", "(", "'cron_'", ".", "$", "article", "[", "'id_cron'", "]", ")", ":", "0", ";", "if", "(", "!", "empty", "(", "$", "res", ")", ")", "{", "bbn", "\\", "x", "::", "hdump", "(", "$", "id", ",", "$", "res", ")", ";", "$", "this", "->", "db", "->", "update", "(", "$", "this", "->", "jtable", ",", "[", "'finish'", "=>", "date", "(", "'Y-m-d H:i:s'", ")", ",", "'duration'", "=>", "$", "time", ",", "'res'", "=>", "$", "res", "]", ",", "[", "'id'", "=>", "$", "id", "]", ")", ";", "}", "else", "{", "$", "this", "->", "db", "->", "delete", "(", "$", "this", "->", "jtable", ",", "[", "'id'", "=>", "$", "id", "]", ")", ";", "$", "prev", "=", "$", "this", "->", "db", "->", "rselect", "(", "$", "this", "->", "jtable", ",", "[", "'res'", ",", "'id'", "]", ",", "[", "'id_cron'", "=>", "$", "article", "[", "'id_cron'", "]", "]", ",", "[", "'finish'", "=>", "'DESC'", "]", ")", ";", "if", "(", "$", "prev", "[", "'res'", "]", "===", "'error'", ")", "{", "$", "this", "->", "db", "->", "update", "(", "$", "this", "->", "jtable", ",", "[", "'res'", "=>", "'Restarted after error'", "]", ",", "[", "'id'", "=>", "$", "prev", "[", "'id'", "]", "]", ")", ";", "}", "}", "bbn", "\\", "appui", "\\", "history", "::", "enable", "(", ")", ";", "return", "$", "time", ";", "}", "return", "false", ";", "}" ]
Writes in the given CRON row the duration and the new finished status. @param $id @param string $res @return bool|int
[ "Writes", "in", "the", "given", "CRON", "row", "the", "duration", "and", "the", "new", "finished", "status", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/cron.php#L537-L563
nabab/bbn
src/bbn/appui/cron.php
cron.get_next_date
public function get_next_date(string $frequency, int $from_time = 0): ?string { if ( \is_string($frequency) && (\strlen($frequency) >= 2) ){ if ( !$from_time ){ $from_time = time(); } $letter = bbn\str::change_case(substr($frequency, 0, 1), 'lower'); $number = (int)substr($frequency, 1); $unit = null; if ( $number > 0 ){ switch ( $letter ){ case 'i': $unit = 60; break; case 'h': $unit = 3600; break; case 'd': $unit = 86400; break; case 'w': $unit = 604800; break; } $r = null; if ( null !== $unit ){ $r = $from_time + ($unit * $number); } if ( $letter === 'm' ){ $r = mktime(date('H', $from_time), date('i', $from_time), date('s', $from_time), date('n', $from_time)+$number, date('j', $from_time), date('Y', $from_time)); } if ( $letter === 'y' ){ $r = mktime(date('H', $from_time), date('i', $from_time), date('s', $from_time), date('n', $from_time)+$number, date('j', $from_time), date('Y', $from_time)); } if ( null !== $r ){ if ( $r < time() ){ return $this->get_next_date($frequency); } return $r; } } } return null; }
php
public function get_next_date(string $frequency, int $from_time = 0): ?string { if ( \is_string($frequency) && (\strlen($frequency) >= 2) ){ if ( !$from_time ){ $from_time = time(); } $letter = bbn\str::change_case(substr($frequency, 0, 1), 'lower'); $number = (int)substr($frequency, 1); $unit = null; if ( $number > 0 ){ switch ( $letter ){ case 'i': $unit = 60; break; case 'h': $unit = 3600; break; case 'd': $unit = 86400; break; case 'w': $unit = 604800; break; } $r = null; if ( null !== $unit ){ $r = $from_time + ($unit * $number); } if ( $letter === 'm' ){ $r = mktime(date('H', $from_time), date('i', $from_time), date('s', $from_time), date('n', $from_time)+$number, date('j', $from_time), date('Y', $from_time)); } if ( $letter === 'y' ){ $r = mktime(date('H', $from_time), date('i', $from_time), date('s', $from_time), date('n', $from_time)+$number, date('j', $from_time), date('Y', $from_time)); } if ( null !== $r ){ if ( $r < time() ){ return $this->get_next_date($frequency); } return $r; } } } return null; }
[ "public", "function", "get_next_date", "(", "string", "$", "frequency", ",", "int", "$", "from_time", "=", "0", ")", ":", "?", "string", "{", "if", "(", "\\", "is_string", "(", "$", "frequency", ")", "&&", "(", "\\", "strlen", "(", "$", "frequency", ")", ">=", "2", ")", ")", "{", "if", "(", "!", "$", "from_time", ")", "{", "$", "from_time", "=", "time", "(", ")", ";", "}", "$", "letter", "=", "bbn", "\\", "str", "::", "change_case", "(", "substr", "(", "$", "frequency", ",", "0", ",", "1", ")", ",", "'lower'", ")", ";", "$", "number", "=", "(", "int", ")", "substr", "(", "$", "frequency", ",", "1", ")", ";", "$", "unit", "=", "null", ";", "if", "(", "$", "number", ">", "0", ")", "{", "switch", "(", "$", "letter", ")", "{", "case", "'i'", ":", "$", "unit", "=", "60", ";", "break", ";", "case", "'h'", ":", "$", "unit", "=", "3600", ";", "break", ";", "case", "'d'", ":", "$", "unit", "=", "86400", ";", "break", ";", "case", "'w'", ":", "$", "unit", "=", "604800", ";", "break", ";", "}", "$", "r", "=", "null", ";", "if", "(", "null", "!==", "$", "unit", ")", "{", "$", "r", "=", "$", "from_time", "+", "(", "$", "unit", "*", "$", "number", ")", ";", "}", "if", "(", "$", "letter", "===", "'m'", ")", "{", "$", "r", "=", "mktime", "(", "date", "(", "'H'", ",", "$", "from_time", ")", ",", "date", "(", "'i'", ",", "$", "from_time", ")", ",", "date", "(", "'s'", ",", "$", "from_time", ")", ",", "date", "(", "'n'", ",", "$", "from_time", ")", "+", "$", "number", ",", "date", "(", "'j'", ",", "$", "from_time", ")", ",", "date", "(", "'Y'", ",", "$", "from_time", ")", ")", ";", "}", "if", "(", "$", "letter", "===", "'y'", ")", "{", "$", "r", "=", "mktime", "(", "date", "(", "'H'", ",", "$", "from_time", ")", ",", "date", "(", "'i'", ",", "$", "from_time", ")", ",", "date", "(", "'s'", ",", "$", "from_time", ")", ",", "date", "(", "'n'", ",", "$", "from_time", ")", "+", "$", "number", ",", "date", "(", "'j'", ",", "$", "from_time", ")", ",", "date", "(", "'Y'", ",", "$", "from_time", ")", ")", ";", "}", "if", "(", "null", "!==", "$", "r", ")", "{", "if", "(", "$", "r", "<", "time", "(", ")", ")", "{", "return", "$", "this", "->", "get_next_date", "(", "$", "frequency", ")", ";", "}", "return", "$", "r", ";", "}", "}", "}", "return", "null", ";", "}" ]
Returns a SQL date for the next event given a frequency and a time to count from (now if 0). @param $frequency @param int $from_time @return null|string
[ "Returns", "a", "SQL", "date", "for", "the", "next", "event", "given", "a", "frequency", "and", "a", "time", "to", "count", "from", "(", "now", "if", "0", ")", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/cron.php#L571-L614
nabab/bbn
src/bbn/appui/cron.php
cron.get_next
public function get_next($id_cron = null): ?array { if ( $this->check() && ($data = $this->db->get_row(" SELECT * FROM {$this->table} WHERE `active` = 1 AND `next` < NOW()". ( bbn\str::is_uid($id_cron) ? " AND `id` = '$id_cron'" : '' )." ORDER BY `priority` ASC, `next` ASC LIMIT 1")) ){ // Dans cfg: timeout, et soit: latency, minute, hour, day of month, day of week, date $data['cfg'] = json_decode($data['cfg'], 1); return $data; } }
php
public function get_next($id_cron = null): ?array { if ( $this->check() && ($data = $this->db->get_row(" SELECT * FROM {$this->table} WHERE `active` = 1 AND `next` < NOW()". ( bbn\str::is_uid($id_cron) ? " AND `id` = '$id_cron'" : '' )." ORDER BY `priority` ASC, `next` ASC LIMIT 1")) ){ // Dans cfg: timeout, et soit: latency, minute, hour, day of month, day of week, date $data['cfg'] = json_decode($data['cfg'], 1); return $data; } }
[ "public", "function", "get_next", "(", "$", "id_cron", "=", "null", ")", ":", "?", "array", "{", "if", "(", "$", "this", "->", "check", "(", ")", "&&", "(", "$", "data", "=", "$", "this", "->", "db", "->", "get_row", "(", "\"\n SELECT *\n FROM {$this->table}\n WHERE `active` = 1\n AND `next` < NOW()\"", ".", "(", "bbn", "\\", "str", "::", "is_uid", "(", "$", "id_cron", ")", "?", "\" AND `id` = '$id_cron'\"", ":", "''", ")", ".", "\"\n ORDER BY `priority` ASC, `next` ASC\n LIMIT 1\"", ")", ")", ")", "{", "// Dans cfg: timeout, et soit: latency, minute, hour, day of month, day of week, date", "$", "data", "[", "'cfg'", "]", "=", "json_decode", "(", "$", "data", "[", "'cfg'", "]", ",", "1", ")", ";", "return", "$", "data", ";", "}", "}" ]
Returns the whole row for the next CRON to be executed from now if there is any. @param null $id_cron @return null|array
[ "Returns", "the", "whole", "row", "for", "the", "next", "CRON", "to", "be", "executed", "from", "now", "if", "there", "is", "any", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/cron.php#L621-L635
maxmirazh33/yii2-uploadable-file
src/Behavior.php
Behavior.beforeValidate
public function beforeValidate() { /* @var $model ActiveRecord */ $model = $this->owner; foreach ($this->attributes as $attr => $options) { $this->ensureAttributes($attr, $options); if ($file = UploadedFile::getInstance($model, $attr)) { $model->{$attr} = $file; } } }
php
public function beforeValidate() { /* @var $model ActiveRecord */ $model = $this->owner; foreach ($this->attributes as $attr => $options) { $this->ensureAttributes($attr, $options); if ($file = UploadedFile::getInstance($model, $attr)) { $model->{$attr} = $file; } } }
[ "public", "function", "beforeValidate", "(", ")", "{", "/* @var $model ActiveRecord */", "$", "model", "=", "$", "this", "->", "owner", ";", "foreach", "(", "$", "this", "->", "attributes", "as", "$", "attr", "=>", "$", "options", ")", "{", "$", "this", "->", "ensureAttributes", "(", "$", "attr", ",", "$", "options", ")", ";", "if", "(", "$", "file", "=", "UploadedFile", "::", "getInstance", "(", "$", "model", ",", "$", "attr", ")", ")", "{", "$", "model", "->", "{", "$", "attr", "}", "=", "$", "file", ";", "}", "}", "}" ]
function for EVENT_BEFORE_VALIDATE
[ "function", "for", "EVENT_BEFORE_VALIDATE" ]
train
https://github.com/maxmirazh33/yii2-uploadable-file/blob/7993d091b2969cb8ac9ff95254dc311967bd90ce/src/Behavior.php#L70-L80
maxmirazh33/yii2-uploadable-file
src/Behavior.php
Behavior.beforeSave
public function beforeSave() { /* @var $model ActiveRecord */ $model = $this->owner; foreach ($this->attributes as $attr => $options) { $this->ensureAttributes($attr, $options); if ($file = UploadedFile::getInstance($model, $attr)) { $this->createDirIfNotExists($attr); if (!$model->isNewRecord) { $this->deleteFiles($attr); } $fileName = uniqid() . '.' . $file->extension; $model->{$attr} = $fileName; $file->saveAs($this->getSavePath($attr) . $fileName); } elseif (isset($model->oldAttributes[$attr])) { $model->{$attr} = $model->oldAttributes[$attr]; } } }
php
public function beforeSave() { /* @var $model ActiveRecord */ $model = $this->owner; foreach ($this->attributes as $attr => $options) { $this->ensureAttributes($attr, $options); if ($file = UploadedFile::getInstance($model, $attr)) { $this->createDirIfNotExists($attr); if (!$model->isNewRecord) { $this->deleteFiles($attr); } $fileName = uniqid() . '.' . $file->extension; $model->{$attr} = $fileName; $file->saveAs($this->getSavePath($attr) . $fileName); } elseif (isset($model->oldAttributes[$attr])) { $model->{$attr} = $model->oldAttributes[$attr]; } } }
[ "public", "function", "beforeSave", "(", ")", "{", "/* @var $model ActiveRecord */", "$", "model", "=", "$", "this", "->", "owner", ";", "foreach", "(", "$", "this", "->", "attributes", "as", "$", "attr", "=>", "$", "options", ")", "{", "$", "this", "->", "ensureAttributes", "(", "$", "attr", ",", "$", "options", ")", ";", "if", "(", "$", "file", "=", "UploadedFile", "::", "getInstance", "(", "$", "model", ",", "$", "attr", ")", ")", "{", "$", "this", "->", "createDirIfNotExists", "(", "$", "attr", ")", ";", "if", "(", "!", "$", "model", "->", "isNewRecord", ")", "{", "$", "this", "->", "deleteFiles", "(", "$", "attr", ")", ";", "}", "$", "fileName", "=", "uniqid", "(", ")", ".", "'.'", ".", "$", "file", "->", "extension", ";", "$", "model", "->", "{", "$", "attr", "}", "=", "$", "fileName", ";", "$", "file", "->", "saveAs", "(", "$", "this", "->", "getSavePath", "(", "$", "attr", ")", ".", "$", "fileName", ")", ";", "}", "elseif", "(", "isset", "(", "$", "model", "->", "oldAttributes", "[", "$", "attr", "]", ")", ")", "{", "$", "model", "->", "{", "$", "attr", "}", "=", "$", "model", "->", "oldAttributes", "[", "$", "attr", "]", ";", "}", "}", "}" ]
function for EVENT_BEFORE_INSERT and EVENT_BEFORE_UPDATE
[ "function", "for", "EVENT_BEFORE_INSERT", "and", "EVENT_BEFORE_UPDATE" ]
train
https://github.com/maxmirazh33/yii2-uploadable-file/blob/7993d091b2969cb8ac9ff95254dc311967bd90ce/src/Behavior.php#L85-L103
maxmirazh33/yii2-uploadable-file
src/Behavior.php
Behavior.beforeDelete
public function beforeDelete() { foreach ($this->attributes as $attr => $options) { $this->ensureAttributes($attr, $options); $this->deleteFiles($attr); } }
php
public function beforeDelete() { foreach ($this->attributes as $attr => $options) { $this->ensureAttributes($attr, $options); $this->deleteFiles($attr); } }
[ "public", "function", "beforeDelete", "(", ")", "{", "foreach", "(", "$", "this", "->", "attributes", "as", "$", "attr", "=>", "$", "options", ")", "{", "$", "this", "->", "ensureAttributes", "(", "$", "attr", ",", "$", "options", ")", ";", "$", "this", "->", "deleteFiles", "(", "$", "attr", ")", ";", "}", "}" ]
function for EVENT_BEFORE_DELETE
[ "function", "for", "EVENT_BEFORE_DELETE" ]
train
https://github.com/maxmirazh33/yii2-uploadable-file/blob/7993d091b2969cb8ac9ff95254dc311967bd90ce/src/Behavior.php#L118-L124
maxmirazh33/yii2-uploadable-file
src/Behavior.php
Behavior.deleteFiles
private function deleteFiles($attr) { $base = $this->getSavePath($attr); /* @var $model ActiveRecord */ $model = $this->owner; if ($model->isNewRecord) { $value = $model->{$attr}; } else { $value = $model->oldAttributes[$attr]; } $file = $base . $value; if (is_file($file)) { unlink($file); } }
php
private function deleteFiles($attr) { $base = $this->getSavePath($attr); /* @var $model ActiveRecord */ $model = $this->owner; if ($model->isNewRecord) { $value = $model->{$attr}; } else { $value = $model->oldAttributes[$attr]; } $file = $base . $value; if (is_file($file)) { unlink($file); } }
[ "private", "function", "deleteFiles", "(", "$", "attr", ")", "{", "$", "base", "=", "$", "this", "->", "getSavePath", "(", "$", "attr", ")", ";", "/* @var $model ActiveRecord */", "$", "model", "=", "$", "this", "->", "owner", ";", "if", "(", "$", "model", "->", "isNewRecord", ")", "{", "$", "value", "=", "$", "model", "->", "{", "$", "attr", "}", ";", "}", "else", "{", "$", "value", "=", "$", "model", "->", "oldAttributes", "[", "$", "attr", "]", ";", "}", "$", "file", "=", "$", "base", ".", "$", "value", ";", "if", "(", "is_file", "(", "$", "file", ")", ")", "{", "unlink", "(", "$", "file", ")", ";", "}", "}" ]
Delete images @param string $attr name of attribute
[ "Delete", "images" ]
train
https://github.com/maxmirazh33/yii2-uploadable-file/blob/7993d091b2969cb8ac9ff95254dc311967bd90ce/src/Behavior.php#L192-L207
maxmirazh33/yii2-uploadable-file
src/Behavior.php
Behavior.checkAttrExists
private function checkAttrExists($attribute) { foreach ($this->attributes as $attr => $options) { $this->ensureAttributes($attr, $options); if ($attr == $attribute) { return; } } throw new InvalidParamException(); }
php
private function checkAttrExists($attribute) { foreach ($this->attributes as $attr => $options) { $this->ensureAttributes($attr, $options); if ($attr == $attribute) { return; } } throw new InvalidParamException(); }
[ "private", "function", "checkAttrExists", "(", "$", "attribute", ")", "{", "foreach", "(", "$", "this", "->", "attributes", "as", "$", "attr", "=>", "$", "options", ")", "{", "$", "this", "->", "ensureAttributes", "(", "$", "attr", ",", "$", "options", ")", ";", "if", "(", "$", "attr", "==", "$", "attribute", ")", "{", "return", ";", "}", "}", "throw", "new", "InvalidParamException", "(", ")", ";", "}" ]
Check isset attribute or not @param string $attribute name of attribute @throws InvalidParamException
[ "Check", "isset", "attribute", "or", "not" ]
train
https://github.com/maxmirazh33/yii2-uploadable-file/blob/7993d091b2969cb8ac9ff95254dc311967bd90ce/src/Behavior.php#L214-L223
KodiComponents/Support
src/Http/QueryFilters.php
QueryFilters.apply
public function apply(Builder $builder) { $this->builder = $builder; foreach ($this->filters() as $name => $value) { if (! method_exists($this, $name)) { continue; } if (is_array($value) or trim($value)) { $this->$name($value); } else { $this->$name(); } } return $this->builder; }
php
public function apply(Builder $builder) { $this->builder = $builder; foreach ($this->filters() as $name => $value) { if (! method_exists($this, $name)) { continue; } if (is_array($value) or trim($value)) { $this->$name($value); } else { $this->$name(); } } return $this->builder; }
[ "public", "function", "apply", "(", "Builder", "$", "builder", ")", "{", "$", "this", "->", "builder", "=", "$", "builder", ";", "foreach", "(", "$", "this", "->", "filters", "(", ")", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "!", "method_exists", "(", "$", "this", ",", "$", "name", ")", ")", "{", "continue", ";", "}", "if", "(", "is_array", "(", "$", "value", ")", "or", "trim", "(", "$", "value", ")", ")", "{", "$", "this", "->", "$", "name", "(", "$", "value", ")", ";", "}", "else", "{", "$", "this", "->", "$", "name", "(", ")", ";", "}", "}", "return", "$", "this", "->", "builder", ";", "}" ]
Apply the filters to the builder. @param Builder $builder @return Builder
[ "Apply", "the", "filters", "to", "the", "builder", "." ]
train
https://github.com/KodiComponents/Support/blob/9090543605a2354c7454d707650a0abdb815b60a/src/Http/QueryFilters.php#L42-L59
phpcurl/curlhttp
src/HttpClient.php
HttpClient.head
public function head($url, array $headers = []) { return $this->executor->execute( $url, [ CURLOPT_NOBODY => true, CURLOPT_HTTPHEADER => $headers, ] ); }
php
public function head($url, array $headers = []) { return $this->executor->execute( $url, [ CURLOPT_NOBODY => true, CURLOPT_HTTPHEADER => $headers, ] ); }
[ "public", "function", "head", "(", "$", "url", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "return", "$", "this", "->", "executor", "->", "execute", "(", "$", "url", ",", "[", "CURLOPT_NOBODY", "=>", "true", ",", "CURLOPT_HTTPHEADER", "=>", "$", "headers", ",", "]", ")", ";", "}" ]
HTTP HEAD (implemented using CURLOPT_NOBODY) @param string $url Goes to curl_init() @param array $headers Same as CURLOPT_HEADER @return HttpResponse
[ "HTTP", "HEAD", "(", "implemented", "using", "CURLOPT_NOBODY", ")" ]
train
https://github.com/phpcurl/curlhttp/blob/e29c0b9c59f9028699d573c35e97d2ba66862c2c/src/HttpClient.php#L45-L54
phpcurl/curlhttp
src/HttpClient.php
HttpClient.post
public function post($url, $data = '', array $headers = []) { return $this->executor->execute( $url, [ CURLOPT_POST => true, CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $data, ] ); }
php
public function post($url, $data = '', array $headers = []) { return $this->executor->execute( $url, [ CURLOPT_POST => true, CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $data, ] ); }
[ "public", "function", "post", "(", "$", "url", ",", "$", "data", "=", "''", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "return", "$", "this", "->", "executor", "->", "execute", "(", "$", "url", ",", "[", "CURLOPT_POST", "=>", "true", ",", "CURLOPT_HTTPHEADER", "=>", "$", "headers", ",", "CURLOPT_POSTFIELDS", "=>", "$", "data", ",", "]", ")", ";", "}" ]
HTTP POST @param string $url Goes to curl_init() @param string|array $data Same as CURLOPT_POSTFIELDS @param array $headers Same as CURLOPT_HEADER @return HttpResponse
[ "HTTP", "POST" ]
train
https://github.com/phpcurl/curlhttp/blob/e29c0b9c59f9028699d573c35e97d2ba66862c2c/src/HttpClient.php#L63-L73
phpcurl/curlhttp
src/HttpClient.php
HttpClient.put
public function put($url, $data = '', array $headers = []) { return $this->executor->execute( $url, [ CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $data, ] ); }
php
public function put($url, $data = '', array $headers = []) { return $this->executor->execute( $url, [ CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $data, ] ); }
[ "public", "function", "put", "(", "$", "url", ",", "$", "data", "=", "''", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "return", "$", "this", "->", "executor", "->", "execute", "(", "$", "url", ",", "[", "CURLOPT_CUSTOMREQUEST", "=>", "'PUT'", ",", "CURLOPT_HTTPHEADER", "=>", "$", "headers", ",", "CURLOPT_POSTFIELDS", "=>", "$", "data", ",", "]", ")", ";", "}" ]
HTTP PUT @param string $url Goes to curl_init() @param string|array $data Same as CURLOPT_POSTFIELDS @param array $headers Same as CURLOPT_HEADER @return HttpResponse
[ "HTTP", "PUT" ]
train
https://github.com/phpcurl/curlhttp/blob/e29c0b9c59f9028699d573c35e97d2ba66862c2c/src/HttpClient.php#L82-L92
phpcurl/curlhttp
src/HttpClient.php
HttpClient.delete
public function delete($url, array $headers = []) { return $this->executor->execute( $url, [ CURLOPT_CUSTOMREQUEST => 'DELETE', CURLOPT_HTTPHEADER => $headers, ] ); }
php
public function delete($url, array $headers = []) { return $this->executor->execute( $url, [ CURLOPT_CUSTOMREQUEST => 'DELETE', CURLOPT_HTTPHEADER => $headers, ] ); }
[ "public", "function", "delete", "(", "$", "url", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "return", "$", "this", "->", "executor", "->", "execute", "(", "$", "url", ",", "[", "CURLOPT_CUSTOMREQUEST", "=>", "'DELETE'", ",", "CURLOPT_HTTPHEADER", "=>", "$", "headers", ",", "]", ")", ";", "}" ]
HTTP DELETE @param string $url Goes to curl_init() @param array $headers Same as CURLOPT_HEADER @return HttpResponse
[ "HTTP", "DELETE" ]
train
https://github.com/phpcurl/curlhttp/blob/e29c0b9c59f9028699d573c35e97d2ba66862c2c/src/HttpClient.php#L100-L109
ezsystems/ezcomments-ls-extension
classes/ezcomcomment.php
ezcomComment.definition
public static function definition() { static $def = array( 'fields' => array( 'id' => array( 'name' => 'ID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'language_id' => array( 'name' => 'LanguageID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'created' => array( 'name' => 'Created', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'modified' => array( 'name' => 'Modified', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'user_id' => array( 'name' => 'UserID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'session_key' => array( 'name' => 'SessionKey', 'datatype' => 'string', 'default' => '', 'required' => true ), 'ip' => array( 'name' => 'IPAddress', 'datatype' => 'string', 'default' => '', 'required' => true ), 'contentobject_id' => array( 'name' => 'ContentObjectID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'parent_comment_id' => array( 'name' => 'ParentCommentID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'name' => array( 'name' => 'Name', 'datatype' => 'string', 'default' => '', 'required' => true ), 'email' => array( 'name' => 'EMail', 'datatype' => 'string', 'default' => '', 'required' => true ), 'url' => array( 'name' => 'URL', 'datatype' => 'string', 'default' => '', 'required' => true ), 'text' => array( 'name' => 'Text', 'datatype' => 'string', 'default' => '', 'required' => true ), 'status' => array( 'name' => 'Status', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'title' => array( 'name' => 'Title', 'datatype' => 'string', 'default' => '', 'required' => true ) ), 'keys' => array( 'id' ), 'function_attributes' => array( 'contentobject' => 'contentObject' ), 'increment_key' => 'id', 'class_name' => 'ezcomComment', 'name' => 'ezcomment' ); return $def; }
php
public static function definition() { static $def = array( 'fields' => array( 'id' => array( 'name' => 'ID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'language_id' => array( 'name' => 'LanguageID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'created' => array( 'name' => 'Created', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'modified' => array( 'name' => 'Modified', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'user_id' => array( 'name' => 'UserID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'session_key' => array( 'name' => 'SessionKey', 'datatype' => 'string', 'default' => '', 'required' => true ), 'ip' => array( 'name' => 'IPAddress', 'datatype' => 'string', 'default' => '', 'required' => true ), 'contentobject_id' => array( 'name' => 'ContentObjectID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'parent_comment_id' => array( 'name' => 'ParentCommentID', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'name' => array( 'name' => 'Name', 'datatype' => 'string', 'default' => '', 'required' => true ), 'email' => array( 'name' => 'EMail', 'datatype' => 'string', 'default' => '', 'required' => true ), 'url' => array( 'name' => 'URL', 'datatype' => 'string', 'default' => '', 'required' => true ), 'text' => array( 'name' => 'Text', 'datatype' => 'string', 'default' => '', 'required' => true ), 'status' => array( 'name' => 'Status', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'title' => array( 'name' => 'Title', 'datatype' => 'string', 'default' => '', 'required' => true ) ), 'keys' => array( 'id' ), 'function_attributes' => array( 'contentobject' => 'contentObject' ), 'increment_key' => 'id', 'class_name' => 'ezcomComment', 'name' => 'ezcomment' ); return $def; }
[ "public", "static", "function", "definition", "(", ")", "{", "static", "$", "def", "=", "array", "(", "'fields'", "=>", "array", "(", "'id'", "=>", "array", "(", "'name'", "=>", "'ID'", ",", "'datatype'", "=>", "'integer'", ",", "'default'", "=>", "0", ",", "'required'", "=>", "true", ")", ",", "'language_id'", "=>", "array", "(", "'name'", "=>", "'LanguageID'", ",", "'datatype'", "=>", "'integer'", ",", "'default'", "=>", "0", ",", "'required'", "=>", "true", ")", ",", "'created'", "=>", "array", "(", "'name'", "=>", "'Created'", ",", "'datatype'", "=>", "'integer'", ",", "'default'", "=>", "0", ",", "'required'", "=>", "true", ")", ",", "'modified'", "=>", "array", "(", "'name'", "=>", "'Modified'", ",", "'datatype'", "=>", "'integer'", ",", "'default'", "=>", "0", ",", "'required'", "=>", "true", ")", ",", "'user_id'", "=>", "array", "(", "'name'", "=>", "'UserID'", ",", "'datatype'", "=>", "'integer'", ",", "'default'", "=>", "0", ",", "'required'", "=>", "true", ")", ",", "'session_key'", "=>", "array", "(", "'name'", "=>", "'SessionKey'", ",", "'datatype'", "=>", "'string'", ",", "'default'", "=>", "''", ",", "'required'", "=>", "true", ")", ",", "'ip'", "=>", "array", "(", "'name'", "=>", "'IPAddress'", ",", "'datatype'", "=>", "'string'", ",", "'default'", "=>", "''", ",", "'required'", "=>", "true", ")", ",", "'contentobject_id'", "=>", "array", "(", "'name'", "=>", "'ContentObjectID'", ",", "'datatype'", "=>", "'integer'", ",", "'default'", "=>", "0", ",", "'required'", "=>", "true", ")", ",", "'parent_comment_id'", "=>", "array", "(", "'name'", "=>", "'ParentCommentID'", ",", "'datatype'", "=>", "'integer'", ",", "'default'", "=>", "0", ",", "'required'", "=>", "true", ")", ",", "'name'", "=>", "array", "(", "'name'", "=>", "'Name'", ",", "'datatype'", "=>", "'string'", ",", "'default'", "=>", "''", ",", "'required'", "=>", "true", ")", ",", "'email'", "=>", "array", "(", "'name'", "=>", "'EMail'", ",", "'datatype'", "=>", "'string'", ",", "'default'", "=>", "''", ",", "'required'", "=>", "true", ")", ",", "'url'", "=>", "array", "(", "'name'", "=>", "'URL'", ",", "'datatype'", "=>", "'string'", ",", "'default'", "=>", "''", ",", "'required'", "=>", "true", ")", ",", "'text'", "=>", "array", "(", "'name'", "=>", "'Text'", ",", "'datatype'", "=>", "'string'", ",", "'default'", "=>", "''", ",", "'required'", "=>", "true", ")", ",", "'status'", "=>", "array", "(", "'name'", "=>", "'Status'", ",", "'datatype'", "=>", "'integer'", ",", "'default'", "=>", "0", ",", "'required'", "=>", "true", ")", ",", "'title'", "=>", "array", "(", "'name'", "=>", "'Title'", ",", "'datatype'", "=>", "'string'", ",", "'default'", "=>", "''", ",", "'required'", "=>", "true", ")", ")", ",", "'keys'", "=>", "array", "(", "'id'", ")", ",", "'function_attributes'", "=>", "array", "(", "'contentobject'", "=>", "'contentObject'", ")", ",", "'increment_key'", "=>", "'id'", ",", "'class_name'", "=>", "'ezcomComment'", ",", "'name'", "=>", "'ezcomment'", ")", ";", "return", "$", "def", ";", "}" ]
Fields definition. @static @return array
[ "Fields", "definition", "." ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomcomment.php#L32-L101
ezsystems/ezcomments-ls-extension
classes/ezcomcomment.php
ezcomComment.fetchByEmail
static function fetchByEmail( $email, $sorts = null, $offset = null, $length = null, $status = false ) { $cond = array(); $cond['email'] = $email; if ( $status !== false ) { $cond['status'] = $status; } $limit = null; if ( !is_null( $offset ) ) { $limit = array(); $limit = array( 'offset' => $offset, 'length' => $length ); } $return = eZPersistentObject::fetchObjectList( self::definition(), null, $cond, $sorts, $limit ); return $return; }
php
static function fetchByEmail( $email, $sorts = null, $offset = null, $length = null, $status = false ) { $cond = array(); $cond['email'] = $email; if ( $status !== false ) { $cond['status'] = $status; } $limit = null; if ( !is_null( $offset ) ) { $limit = array(); $limit = array( 'offset' => $offset, 'length' => $length ); } $return = eZPersistentObject::fetchObjectList( self::definition(), null, $cond, $sorts, $limit ); return $return; }
[ "static", "function", "fetchByEmail", "(", "$", "email", ",", "$", "sorts", "=", "null", ",", "$", "offset", "=", "null", ",", "$", "length", "=", "null", ",", "$", "status", "=", "false", ")", "{", "$", "cond", "=", "array", "(", ")", ";", "$", "cond", "[", "'email'", "]", "=", "$", "email", ";", "if", "(", "$", "status", "!==", "false", ")", "{", "$", "cond", "[", "'status'", "]", "=", "$", "status", ";", "}", "$", "limit", "=", "null", ";", "if", "(", "!", "is_null", "(", "$", "offset", ")", ")", "{", "$", "limit", "=", "array", "(", ")", ";", "$", "limit", "=", "array", "(", "'offset'", "=>", "$", "offset", ",", "'length'", "=>", "$", "length", ")", ";", "}", "$", "return", "=", "eZPersistentObject", "::", "fetchObjectList", "(", "self", "::", "definition", "(", ")", ",", "null", ",", "$", "cond", ",", "$", "sorts", ",", "$", "limit", ")", ";", "return", "$", "return", ";", "}" ]
fetch comment by email @param string $email email address @param array $sorts sort array @param integer $offset offset @param integer $length length @param integer $status status of comment @return ezcomComment|null
[ "fetch", "comment", "by", "email" ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomcomment.php#L150-L166
ezsystems/ezcomments-ls-extension
classes/ezcomcomment.php
ezcomComment.fetchByContentObjectID
static function fetchByContentObjectID( $contentObjectID, $languageID, $status = null, $sorts = null, $offset = null, $length = null ) { $cond = array(); $cond['contentobject_id'] = $contentObjectID; if ( $languageID !== false ) { $cond['language_id'] = $languageID; } if( !is_null( $status ) ) { $cond['status'] = $status; } if ( is_null( $offset ) || is_null( $length ) ) { return null; } else { $limit = array( 'offset' => $offset, 'length' => $length); $return = eZPersistentObject::fetchObjectList( self::definition(), null, $cond, $sorts, $limit ); return $return; } }
php
static function fetchByContentObjectID( $contentObjectID, $languageID, $status = null, $sorts = null, $offset = null, $length = null ) { $cond = array(); $cond['contentobject_id'] = $contentObjectID; if ( $languageID !== false ) { $cond['language_id'] = $languageID; } if( !is_null( $status ) ) { $cond['status'] = $status; } if ( is_null( $offset ) || is_null( $length ) ) { return null; } else { $limit = array( 'offset' => $offset, 'length' => $length); $return = eZPersistentObject::fetchObjectList( self::definition(), null, $cond, $sorts, $limit ); return $return; } }
[ "static", "function", "fetchByContentObjectID", "(", "$", "contentObjectID", ",", "$", "languageID", ",", "$", "status", "=", "null", ",", "$", "sorts", "=", "null", ",", "$", "offset", "=", "null", ",", "$", "length", "=", "null", ")", "{", "$", "cond", "=", "array", "(", ")", ";", "$", "cond", "[", "'contentobject_id'", "]", "=", "$", "contentObjectID", ";", "if", "(", "$", "languageID", "!==", "false", ")", "{", "$", "cond", "[", "'language_id'", "]", "=", "$", "languageID", ";", "}", "if", "(", "!", "is_null", "(", "$", "status", ")", ")", "{", "$", "cond", "[", "'status'", "]", "=", "$", "status", ";", "}", "if", "(", "is_null", "(", "$", "offset", ")", "||", "is_null", "(", "$", "length", ")", ")", "{", "return", "null", ";", "}", "else", "{", "$", "limit", "=", "array", "(", "'offset'", "=>", "$", "offset", ",", "'length'", "=>", "$", "length", ")", ";", "$", "return", "=", "eZPersistentObject", "::", "fetchObjectList", "(", "self", "::", "definition", "(", ")", ",", "null", ",", "$", "cond", ",", "$", "sorts", ",", "$", "limit", ")", ";", "return", "$", "return", ";", "}", "}" ]
fetch comment list by contentobject id @param string $contentObjectID @param string $languageID @param integer $status @param array $sorts @param integer $offset @param integer $length @return array comment list
[ "fetch", "comment", "list", "by", "contentobject", "id" ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomcomment.php#L178-L200
ezsystems/ezcomments-ls-extension
classes/ezcomcomment.php
ezcomComment.fetchByContentObjectIDList
public static function fetchByContentObjectIDList( $objectIDList = null, $userID = null, $languageCode = null, $status = null, $sorts = null, $offset = null, $length = null, $extraCondition = array() ) { $cond = array(); // object id list if( $objectIDList !== null && !is_array( $objectIDList ) ) { return null; } if( is_array( $objectIDList ) ) { $cond['contentobject_id'] = array( $objectIDList ); } // user id if( $userID !== null ) { $cond['user_id'] = $userID; } // language id if( $languageCode === null ) { $ini = eZINI::instance(); $languageCode = $ini->variable( 'RegionalSettings' , 'ContentObjectLocale' ); } $languageID = eZContentLanguage::fetchByLocale( $languageCode )->attribute( 'id' ); $cond['language_id'] = $languageID; // status if( $status !== null ) { $cond['status'] = $status; } $cond = array_merge( $cond, $extraCondition ); $limit = array( 'offset' => $offset, 'length' => $length ); $result = eZPersistentObject::fetchObjectList( self::definition(), null, $cond, $sorts, $limit ); return $result; }
php
public static function fetchByContentObjectIDList( $objectIDList = null, $userID = null, $languageCode = null, $status = null, $sorts = null, $offset = null, $length = null, $extraCondition = array() ) { $cond = array(); // object id list if( $objectIDList !== null && !is_array( $objectIDList ) ) { return null; } if( is_array( $objectIDList ) ) { $cond['contentobject_id'] = array( $objectIDList ); } // user id if( $userID !== null ) { $cond['user_id'] = $userID; } // language id if( $languageCode === null ) { $ini = eZINI::instance(); $languageCode = $ini->variable( 'RegionalSettings' , 'ContentObjectLocale' ); } $languageID = eZContentLanguage::fetchByLocale( $languageCode )->attribute( 'id' ); $cond['language_id'] = $languageID; // status if( $status !== null ) { $cond['status'] = $status; } $cond = array_merge( $cond, $extraCondition ); $limit = array( 'offset' => $offset, 'length' => $length ); $result = eZPersistentObject::fetchObjectList( self::definition(), null, $cond, $sorts, $limit ); return $result; }
[ "public", "static", "function", "fetchByContentObjectIDList", "(", "$", "objectIDList", "=", "null", ",", "$", "userID", "=", "null", ",", "$", "languageCode", "=", "null", ",", "$", "status", "=", "null", ",", "$", "sorts", "=", "null", ",", "$", "offset", "=", "null", ",", "$", "length", "=", "null", ",", "$", "extraCondition", "=", "array", "(", ")", ")", "{", "$", "cond", "=", "array", "(", ")", ";", "// object id list", "if", "(", "$", "objectIDList", "!==", "null", "&&", "!", "is_array", "(", "$", "objectIDList", ")", ")", "{", "return", "null", ";", "}", "if", "(", "is_array", "(", "$", "objectIDList", ")", ")", "{", "$", "cond", "[", "'contentobject_id'", "]", "=", "array", "(", "$", "objectIDList", ")", ";", "}", "// user id", "if", "(", "$", "userID", "!==", "null", ")", "{", "$", "cond", "[", "'user_id'", "]", "=", "$", "userID", ";", "}", "// language id", "if", "(", "$", "languageCode", "===", "null", ")", "{", "$", "ini", "=", "eZINI", "::", "instance", "(", ")", ";", "$", "languageCode", "=", "$", "ini", "->", "variable", "(", "'RegionalSettings'", ",", "'ContentObjectLocale'", ")", ";", "}", "$", "languageID", "=", "eZContentLanguage", "::", "fetchByLocale", "(", "$", "languageCode", ")", "->", "attribute", "(", "'id'", ")", ";", "$", "cond", "[", "'language_id'", "]", "=", "$", "languageID", ";", "// status", "if", "(", "$", "status", "!==", "null", ")", "{", "$", "cond", "[", "'status'", "]", "=", "$", "status", ";", "}", "$", "cond", "=", "array_merge", "(", "$", "cond", ",", "$", "extraCondition", ")", ";", "$", "limit", "=", "array", "(", "'offset'", "=>", "$", "offset", ",", "'length'", "=>", "$", "length", ")", ";", "$", "result", "=", "eZPersistentObject", "::", "fetchObjectList", "(", "self", "::", "definition", "(", ")", ",", "null", ",", "$", "cond", ",", "$", "sorts", ",", "$", "limit", ")", ";", "return", "$", "result", ";", "}" ]
Fetch object by object id list. available since 1.1 If $objectIDList is null, it will fetch all comments regardless of content id If $userID is null, it will fetch all user's comments If $languageCode is null, it will fetch comments on currrent site access language code If $status is null, it will fetch comment regardless of status @param array|null $objectIDList @param integer|null $userID @param string|null $languageCode @param integer|null $status @param array|null $sorts @param integer|null $offset @param integer|null $length @param array $extraCondition extra condition according to condition standard in eZPersistentObject::fetchObjectList @return array<ezcomComment>|null|array()
[ "Fetch", "object", "by", "object", "id", "list", ".", "available", "since", "1", ".", "1", "If", "$objectIDList", "is", "null", "it", "will", "fetch", "all", "comments", "regardless", "of", "content", "id", "If", "$userID", "is", "null", "it", "will", "fetch", "all", "user", "s", "comments", "If", "$languageCode", "is", "null", "it", "will", "fetch", "comments", "on", "currrent", "site", "access", "language", "code", "If", "$status", "is", "null", "it", "will", "fetch", "comment", "regardless", "of", "status" ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomcomment.php#L219-L259
ezsystems/ezcomments-ls-extension
classes/ezcomcomment.php
ezcomComment.countByContent
static function countByContent( $contentObjectID = false, $languageID = false, $status = null ) { $cond = array(); if ( $contentObjectID !== false ) { $cond['contentobject_id'] = $contentObjectID; } if ( $languageID !== false ) { $cond['language_id'] = $languageID; } if ( !is_null( $status ) ) { $cond['status'] = $status; } return eZPersistentObject::count( self::definition(), $cond ); }
php
static function countByContent( $contentObjectID = false, $languageID = false, $status = null ) { $cond = array(); if ( $contentObjectID !== false ) { $cond['contentobject_id'] = $contentObjectID; } if ( $languageID !== false ) { $cond['language_id'] = $languageID; } if ( !is_null( $status ) ) { $cond['status'] = $status; } return eZPersistentObject::count( self::definition(), $cond ); }
[ "static", "function", "countByContent", "(", "$", "contentObjectID", "=", "false", ",", "$", "languageID", "=", "false", ",", "$", "status", "=", "null", ")", "{", "$", "cond", "=", "array", "(", ")", ";", "if", "(", "$", "contentObjectID", "!==", "false", ")", "{", "$", "cond", "[", "'contentobject_id'", "]", "=", "$", "contentObjectID", ";", "}", "if", "(", "$", "languageID", "!==", "false", ")", "{", "$", "cond", "[", "'language_id'", "]", "=", "$", "languageID", ";", "}", "if", "(", "!", "is_null", "(", "$", "status", ")", ")", "{", "$", "cond", "[", "'status'", "]", "=", "$", "status", ";", "}", "return", "eZPersistentObject", "::", "count", "(", "self", "::", "definition", "(", ")", ",", "$", "cond", ")", ";", "}" ]
Count the comments by content object id @param integer $contentObjectID @param integer $languageID @param integer $status @return count of comments
[ "Count", "the", "comments", "by", "content", "object", "id" ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomcomment.php#L268-L284
ezsystems/ezcomments-ls-extension
classes/ezcomcomment.php
ezcomComment.countContentObjectByEmail
static function countContentObjectByEmail( $email, $status = false ) { $statusString = ""; if ( $status !== false ) { $statusString = " AND status = $status"; } $sql = "SELECT COUNT(*) as row_count FROM " . "( SELECT DISTINCT contentobject_id, language_id ". " FROM ezcomment " . " WHERE email='$email'" . "$statusString" . ") as contentobject"; $db = eZDB::instance(); $result = $db->arrayQuery( $sql ); return $result[0]['row_count']; }
php
static function countContentObjectByEmail( $email, $status = false ) { $statusString = ""; if ( $status !== false ) { $statusString = " AND status = $status"; } $sql = "SELECT COUNT(*) as row_count FROM " . "( SELECT DISTINCT contentobject_id, language_id ". " FROM ezcomment " . " WHERE email='$email'" . "$statusString" . ") as contentobject"; $db = eZDB::instance(); $result = $db->arrayQuery( $sql ); return $result[0]['row_count']; }
[ "static", "function", "countContentObjectByEmail", "(", "$", "email", ",", "$", "status", "=", "false", ")", "{", "$", "statusString", "=", "\"\"", ";", "if", "(", "$", "status", "!==", "false", ")", "{", "$", "statusString", "=", "\" AND status = $status\"", ";", "}", "$", "sql", "=", "\"SELECT COUNT(*) as row_count FROM \"", ".", "\"( SELECT DISTINCT contentobject_id, language_id \"", ".", "\" FROM ezcomment \"", ".", "\" WHERE email='$email'\"", ".", "\"$statusString\"", ".", "\") as contentobject\"", ";", "$", "db", "=", "eZDB", "::", "instance", "(", ")", ";", "$", "result", "=", "$", "db", "->", "arrayQuery", "(", "$", "sql", ")", ";", "return", "$", "result", "[", "0", "]", "[", "'row_count'", "]", ";", "}" ]
Fetch the count of contentobject the user commented on @param $email user's email @param $status status of comment @return count of contentobject with id.
[ "Fetch", "the", "count", "of", "contentobject", "the", "user", "commented", "on" ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomcomment.php#L292-L308
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/ArgumentConverter.php
ArgumentConverter.convert
public function convert(\DOMElement $parent, ArgumentDescriptor $argument) { $child = new \DOMElement('argument'); $parent->appendChild($child); $child->setAttribute('line', $argument->getLine()); $child->setAttribute('by_reference', var_export($argument->isByReference(), true)); $child->appendChild(new \DOMElement('name', $argument->getName())); $child->appendChild(new \DOMElement('default')) ->appendChild(new \DOMText($argument->getDefault())); $types = $argument->getTypes(); $typeStrings = array(); foreach ($types as $type) { $typeStrings[] = $type instanceof DescriptorAbstract ? $type->getFullyQualifiedStructuralElementName() : $type; } $child->appendChild(new \DOMElement('type', implode('|', $typeStrings))); return $child; }
php
public function convert(\DOMElement $parent, ArgumentDescriptor $argument) { $child = new \DOMElement('argument'); $parent->appendChild($child); $child->setAttribute('line', $argument->getLine()); $child->setAttribute('by_reference', var_export($argument->isByReference(), true)); $child->appendChild(new \DOMElement('name', $argument->getName())); $child->appendChild(new \DOMElement('default')) ->appendChild(new \DOMText($argument->getDefault())); $types = $argument->getTypes(); $typeStrings = array(); foreach ($types as $type) { $typeStrings[] = $type instanceof DescriptorAbstract ? $type->getFullyQualifiedStructuralElementName() : $type; } $child->appendChild(new \DOMElement('type', implode('|', $typeStrings))); return $child; }
[ "public", "function", "convert", "(", "\\", "DOMElement", "$", "parent", ",", "ArgumentDescriptor", "$", "argument", ")", "{", "$", "child", "=", "new", "\\", "DOMElement", "(", "'argument'", ")", ";", "$", "parent", "->", "appendChild", "(", "$", "child", ")", ";", "$", "child", "->", "setAttribute", "(", "'line'", ",", "$", "argument", "->", "getLine", "(", ")", ")", ";", "$", "child", "->", "setAttribute", "(", "'by_reference'", ",", "var_export", "(", "$", "argument", "->", "isByReference", "(", ")", ",", "true", ")", ")", ";", "$", "child", "->", "appendChild", "(", "new", "\\", "DOMElement", "(", "'name'", ",", "$", "argument", "->", "getName", "(", ")", ")", ")", ";", "$", "child", "->", "appendChild", "(", "new", "\\", "DOMElement", "(", "'default'", ")", ")", "->", "appendChild", "(", "new", "\\", "DOMText", "(", "$", "argument", "->", "getDefault", "(", ")", ")", ")", ";", "$", "types", "=", "$", "argument", "->", "getTypes", "(", ")", ";", "$", "typeStrings", "=", "array", "(", ")", ";", "foreach", "(", "$", "types", "as", "$", "type", ")", "{", "$", "typeStrings", "[", "]", "=", "$", "type", "instanceof", "DescriptorAbstract", "?", "$", "type", "->", "getFullyQualifiedStructuralElementName", "(", ")", ":", "$", "type", ";", "}", "$", "child", "->", "appendChild", "(", "new", "\\", "DOMElement", "(", "'type'", ",", "implode", "(", "'|'", ",", "$", "typeStrings", ")", ")", ")", ";", "return", "$", "child", ";", "}" ]
Exports the given reflection object to the parent XML element. This method creates a new child element on the given parent XML element and takes the properties of the Reflection argument and sets the elements and attributes on the child. @param \DOMElement $parent The parent element to augment. @param ArgumentDescriptor $argument The data source. @return \DOMElement
[ "Exports", "the", "given", "reflection", "object", "to", "the", "parent", "XML", "element", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/ArgumentConverter.php#L34-L56
oroinc/OroLayoutComponent
LayoutFactoryBuilder.php
LayoutFactoryBuilder.getLayoutFactory
public function getLayoutFactory() { // initialize extension manager $registry = new LayoutRegistry(); foreach ($this->extensions as $extension) { $registry->addExtension($extension); } if (!empty($this->types) || !empty($this->typeExtensions) || !empty($this->layoutUpdates)) { $registry->addExtension( new PreloadedExtension( $this->types, $this->typeExtensions, $this->layoutUpdates ) ); } // initialize renderer registry $rendererRegistry = new LayoutRendererRegistry(); $defaultRenderer = $this->defaultRenderer; foreach ($this->renderers as $name => $renderer) { $rendererRegistry->addRenderer($name, $renderer); if (!$defaultRenderer) { $defaultRenderer = $name; } } if ($defaultRenderer) { $rendererRegistry->setDefaultRenderer($defaultRenderer); } return new LayoutFactory($registry, $rendererRegistry, $this->expressionProcessor, $this->getBlockViewCache()); }
php
public function getLayoutFactory() { // initialize extension manager $registry = new LayoutRegistry(); foreach ($this->extensions as $extension) { $registry->addExtension($extension); } if (!empty($this->types) || !empty($this->typeExtensions) || !empty($this->layoutUpdates)) { $registry->addExtension( new PreloadedExtension( $this->types, $this->typeExtensions, $this->layoutUpdates ) ); } // initialize renderer registry $rendererRegistry = new LayoutRendererRegistry(); $defaultRenderer = $this->defaultRenderer; foreach ($this->renderers as $name => $renderer) { $rendererRegistry->addRenderer($name, $renderer); if (!$defaultRenderer) { $defaultRenderer = $name; } } if ($defaultRenderer) { $rendererRegistry->setDefaultRenderer($defaultRenderer); } return new LayoutFactory($registry, $rendererRegistry, $this->expressionProcessor, $this->getBlockViewCache()); }
[ "public", "function", "getLayoutFactory", "(", ")", "{", "// initialize extension manager", "$", "registry", "=", "new", "LayoutRegistry", "(", ")", ";", "foreach", "(", "$", "this", "->", "extensions", "as", "$", "extension", ")", "{", "$", "registry", "->", "addExtension", "(", "$", "extension", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "types", ")", "||", "!", "empty", "(", "$", "this", "->", "typeExtensions", ")", "||", "!", "empty", "(", "$", "this", "->", "layoutUpdates", ")", ")", "{", "$", "registry", "->", "addExtension", "(", "new", "PreloadedExtension", "(", "$", "this", "->", "types", ",", "$", "this", "->", "typeExtensions", ",", "$", "this", "->", "layoutUpdates", ")", ")", ";", "}", "// initialize renderer registry", "$", "rendererRegistry", "=", "new", "LayoutRendererRegistry", "(", ")", ";", "$", "defaultRenderer", "=", "$", "this", "->", "defaultRenderer", ";", "foreach", "(", "$", "this", "->", "renderers", "as", "$", "name", "=>", "$", "renderer", ")", "{", "$", "rendererRegistry", "->", "addRenderer", "(", "$", "name", ",", "$", "renderer", ")", ";", "if", "(", "!", "$", "defaultRenderer", ")", "{", "$", "defaultRenderer", "=", "$", "name", ";", "}", "}", "if", "(", "$", "defaultRenderer", ")", "{", "$", "rendererRegistry", "->", "setDefaultRenderer", "(", "$", "defaultRenderer", ")", ";", "}", "return", "new", "LayoutFactory", "(", "$", "registry", ",", "$", "rendererRegistry", ",", "$", "this", "->", "expressionProcessor", ",", "$", "this", "->", "getBlockViewCache", "(", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/LayoutFactoryBuilder.php#L165-L196
zhouyl/mellivora
Mellivora/Config/Accessor.php
Accessor.setup
public function setup(array $options) { foreach ($options as $method => $value) { $method = 'set' . ucfirst($method); if (method_exists($this, $method)) { $this->{$method}($value); } } }
php
public function setup(array $options) { foreach ($options as $method => $value) { $method = 'set' . ucfirst($method); if (method_exists($this, $method)) { $this->{$method}($value); } } }
[ "public", "function", "setup", "(", "array", "$", "options", ")", "{", "foreach", "(", "$", "options", "as", "$", "method", "=>", "$", "value", ")", "{", "$", "method", "=", "'set'", ".", "ucfirst", "(", "$", "method", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "$", "this", "->", "{", "$", "method", "}", "(", "$", "value", ")", ";", "}", "}", "}" ]
配置文件自动加载参数配置 可支持的配置选项包括 paths/parsers @param array $options
[ "配置文件自动加载参数配置" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Config/Accessor.php#L85-L93
zhouyl/mellivora
Mellivora/Config/Accessor.php
Accessor.load
public function load($name) { if (!array_key_exists($name, $this->cached)) { foreach (array_reverse($this->paths) as $path) { foreach ($this->parsers as $ext => $parser) { $file = "$path/$name.$ext"; if (is_file($file)) { $this->cached[$name] = new $parser($file); break 2; } } } } if (!isset($this->cached[$name])) { $this->cached[$name] = new NativeArray; } return $this->cached[$name]; }
php
public function load($name) { if (!array_key_exists($name, $this->cached)) { foreach (array_reverse($this->paths) as $path) { foreach ($this->parsers as $ext => $parser) { $file = "$path/$name.$ext"; if (is_file($file)) { $this->cached[$name] = new $parser($file); break 2; } } } } if (!isset($this->cached[$name])) { $this->cached[$name] = new NativeArray; } return $this->cached[$name]; }
[ "public", "function", "load", "(", "$", "name", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "cached", ")", ")", "{", "foreach", "(", "array_reverse", "(", "$", "this", "->", "paths", ")", "as", "$", "path", ")", "{", "foreach", "(", "$", "this", "->", "parsers", "as", "$", "ext", "=>", "$", "parser", ")", "{", "$", "file", "=", "\"$path/$name.$ext\"", ";", "if", "(", "is_file", "(", "$", "file", ")", ")", "{", "$", "this", "->", "cached", "[", "$", "name", "]", "=", "new", "$", "parser", "(", "$", "file", ")", ";", "break", "2", ";", "}", "}", "}", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "cached", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "cached", "[", "$", "name", "]", "=", "new", "NativeArray", ";", "}", "return", "$", "this", "->", "cached", "[", "$", "name", "]", ";", "}" ]
根据名称,自动查找并载入配置 <code> $config->load('db'); </code> @param string $name @return false|object
[ "根据名称,自动查找并载入配置" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Config/Accessor.php#L162-L182
zhouyl/mellivora
Mellivora/Config/Accessor.php
Accessor.get
public function get($path, $default = null) { list($name, $path) = $this->splitPath($path); $config = $this->load($name); return empty($path) ? $config : $config->get($path, $default); }
php
public function get($path, $default = null) { list($name, $path) = $this->splitPath($path); $config = $this->load($name); return empty($path) ? $config : $config->get($path, $default); }
[ "public", "function", "get", "(", "$", "path", ",", "$", "default", "=", "null", ")", "{", "list", "(", "$", "name", ",", "$", "path", ")", "=", "$", "this", "->", "splitPath", "(", "$", "path", ")", ";", "$", "config", "=", "$", "this", "->", "load", "(", "$", "name", ")", ";", "return", "empty", "(", "$", "path", ")", "?", "$", "config", ":", "$", "config", "->", "get", "(", "$", "path", ",", "$", "default", ")", ";", "}" ]
根据配置名称及路径,加载配置数据 <code> $config->get('db.default.host'); </code> @param string $path @param mixed $default @return mixed
[ "根据配置名称及路径,加载配置数据" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Config/Accessor.php#L196-L203
zhouyl/mellivora
Mellivora/Config/Accessor.php
Accessor.set
public function set($path, $value) { list($name, $path) = $this->splitPath($path); if (empty($path)) { throw new RuntimeException('The root node of config is not writable'); } return $this->load($name)->set($path, $value); }
php
public function set($path, $value) { list($name, $path) = $this->splitPath($path); if (empty($path)) { throw new RuntimeException('The root node of config is not writable'); } return $this->load($name)->set($path, $value); }
[ "public", "function", "set", "(", "$", "path", ",", "$", "value", ")", "{", "list", "(", "$", "name", ",", "$", "path", ")", "=", "$", "this", "->", "splitPath", "(", "$", "path", ")", ";", "if", "(", "empty", "(", "$", "path", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'The root node of config is not writable'", ")", ";", "}", "return", "$", "this", "->", "load", "(", "$", "name", ")", "->", "set", "(", "$", "path", ",", "$", "value", ")", ";", "}" ]
根据配置名称及路径,对配置数据进行设置 @param string $key @param mixed $value @param mixed $path @throws \RuntimeException @return \Mellivora\Config\NativeArray
[ "根据配置名称及路径,对配置数据进行设置" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Config/Accessor.php#L216-L225
zhouyl/mellivora
Mellivora/Config/Accessor.php
Accessor.remove
public function remove($path) { list($name, $path) = $this->splitPath($path); if (empty($path)) { throw new RuntimeException('The root node of config is not writable'); } return $this->load($name)->remove($path); }
php
public function remove($path) { list($name, $path) = $this->splitPath($path); if (empty($path)) { throw new RuntimeException('The root node of config is not writable'); } return $this->load($name)->remove($path); }
[ "public", "function", "remove", "(", "$", "path", ")", "{", "list", "(", "$", "name", ",", "$", "path", ")", "=", "$", "this", "->", "splitPath", "(", "$", "path", ")", ";", "if", "(", "empty", "(", "$", "path", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'The root node of config is not writable'", ")", ";", "}", "return", "$", "this", "->", "load", "(", "$", "name", ")", "->", "remove", "(", "$", "path", ")", ";", "}" ]
根据配置名称及路径,删除配置数据 @param string $path @return \Mellivora\Config\NativeArray
[ "根据配置名称及路径,删除配置数据" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Config/Accessor.php#L234-L243
zhouyl/mellivora
Mellivora/Config/Accessor.php
Accessor.exists
public function exists($path) { list($name, $path) = $this->splitPath($path); return $this->load($name)->exists($path); }
php
public function exists($path) { list($name, $path) = $this->splitPath($path); return $this->load($name)->exists($path); }
[ "public", "function", "exists", "(", "$", "path", ")", "{", "list", "(", "$", "name", ",", "$", "path", ")", "=", "$", "this", "->", "splitPath", "(", "$", "path", ")", ";", "return", "$", "this", "->", "load", "(", "$", "name", ")", "->", "exists", "(", "$", "path", ")", ";", "}" ]
根据配置名称及路径,判断是否存在 @param string $path @return bool
[ "根据配置名称及路径,判断是否存在" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Config/Accessor.php#L264-L269
inhere/php-librarys
src/Helpers/ProcessHelper.php
ProcessHelper.runAsDaemon
public static function runAsDaemon(\Closure $beforeQuit = null) { // umask(0); $pid = pcntl_fork(); switch ($pid) { case 0: // at new process $pid = getmypid(); // can also use: posix_getpid() if (posix_setsid() < 0) { Cli::stderr('posix_setsid() execute failed! exiting'); } // chdir('/'); // umask(0); break; case -1: // fork failed. Cli::stderr('Fork new process is failed! exiting'); break; default: // at parent if ($beforeQuit) { $beforeQuit($pid); } exit; } return $pid; }
php
public static function runAsDaemon(\Closure $beforeQuit = null) { // umask(0); $pid = pcntl_fork(); switch ($pid) { case 0: // at new process $pid = getmypid(); // can also use: posix_getpid() if (posix_setsid() < 0) { Cli::stderr('posix_setsid() execute failed! exiting'); } // chdir('/'); // umask(0); break; case -1: // fork failed. Cli::stderr('Fork new process is failed! exiting'); break; default: // at parent if ($beforeQuit) { $beforeQuit($pid); } exit; } return $pid; }
[ "public", "static", "function", "runAsDaemon", "(", "\\", "Closure", "$", "beforeQuit", "=", "null", ")", "{", "// umask(0);", "$", "pid", "=", "pcntl_fork", "(", ")", ";", "switch", "(", "$", "pid", ")", "{", "case", "0", ":", "// at new process", "$", "pid", "=", "getmypid", "(", ")", ";", "// can also use: posix_getpid()", "if", "(", "posix_setsid", "(", ")", "<", "0", ")", "{", "Cli", "::", "stderr", "(", "'posix_setsid() execute failed! exiting'", ")", ";", "}", "// chdir('/');", "// umask(0);", "break", ";", "case", "-", "1", ":", "// fork failed.", "Cli", "::", "stderr", "(", "'Fork new process is failed! exiting'", ")", ";", "break", ";", "default", ":", "// at parent", "if", "(", "$", "beforeQuit", ")", "{", "$", "beforeQuit", "(", "$", "pid", ")", ";", "}", "exit", ";", "}", "return", "$", "pid", ";", "}" ]
Daemon, detach and run in the background @param \Closure|null $beforeQuit @return int Return new process PID
[ "Daemon", "detach", "and", "run", "in", "the", "background" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/ProcessHelper.php#L22-L52
inhere/php-librarys
src/Helpers/ProcessHelper.php
ProcessHelper.forks
public static function forks($number, callable $childHandler = null) { $num = (int)$number > 0 ? (int)$number : 0; if ($num <= 0) { return false; } $pidAry = []; for ($id = 0; $id < $num; $id++) { $child = self::fork($id, $childHandler); $pidAry[$child['pid']] = $child; } return $pidAry; }
php
public static function forks($number, callable $childHandler = null) { $num = (int)$number > 0 ? (int)$number : 0; if ($num <= 0) { return false; } $pidAry = []; for ($id = 0; $id < $num; $id++) { $child = self::fork($id, $childHandler); $pidAry[$child['pid']] = $child; } return $pidAry; }
[ "public", "static", "function", "forks", "(", "$", "number", ",", "callable", "$", "childHandler", "=", "null", ")", "{", "$", "num", "=", "(", "int", ")", "$", "number", ">", "0", "?", "(", "int", ")", "$", "number", ":", "0", ";", "if", "(", "$", "num", "<=", "0", ")", "{", "return", "false", ";", "}", "$", "pidAry", "=", "[", "]", ";", "for", "(", "$", "id", "=", "0", ";", "$", "id", "<", "$", "num", ";", "$", "id", "++", ")", "{", "$", "child", "=", "self", "::", "fork", "(", "$", "id", ",", "$", "childHandler", ")", ";", "$", "pidAry", "[", "$", "child", "[", "'pid'", "]", "]", "=", "$", "child", ";", "}", "return", "$", "pidAry", ";", "}" ]
fork multi child processes. @param int $number @param callable|null $childHandler @return array|int
[ "fork", "multi", "child", "processes", "." ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/ProcessHelper.php#L60-L76
inhere/php-librarys
src/Helpers/ProcessHelper.php
ProcessHelper.fork
public static function fork($id = 0, callable $childHandler = null) { $info = []; $pid = pcntl_fork(); if ($pid > 0) {// at parent, get forked child info $info = [ 'id' => $id, 'pid' => $pid, 'startTime' => time(), ]; } elseif ($pid === 0) { // at child $pid = getmypid(); if ($childHandler) { $childHandler($id, $pid); } } else { Cli::stderr("Fork child process failed! exiting.\n"); } return $info; }
php
public static function fork($id = 0, callable $childHandler = null) { $info = []; $pid = pcntl_fork(); if ($pid > 0) {// at parent, get forked child info $info = [ 'id' => $id, 'pid' => $pid, 'startTime' => time(), ]; } elseif ($pid === 0) { // at child $pid = getmypid(); if ($childHandler) { $childHandler($id, $pid); } } else { Cli::stderr("Fork child process failed! exiting.\n"); } return $info; }
[ "public", "static", "function", "fork", "(", "$", "id", "=", "0", ",", "callable", "$", "childHandler", "=", "null", ")", "{", "$", "info", "=", "[", "]", ";", "$", "pid", "=", "pcntl_fork", "(", ")", ";", "if", "(", "$", "pid", ">", "0", ")", "{", "// at parent, get forked child info", "$", "info", "=", "[", "'id'", "=>", "$", "id", ",", "'pid'", "=>", "$", "pid", ",", "'startTime'", "=>", "time", "(", ")", ",", "]", ";", "}", "elseif", "(", "$", "pid", "===", "0", ")", "{", "// at child", "$", "pid", "=", "getmypid", "(", ")", ";", "if", "(", "$", "childHandler", ")", "{", "$", "childHandler", "(", "$", "id", ",", "$", "pid", ")", ";", "}", "}", "else", "{", "Cli", "::", "stderr", "(", "\"Fork child process failed! exiting.\\n\"", ")", ";", "}", "return", "$", "info", ";", "}" ]
fork a child process. @param int $id @param callable|null $childHandler param bool $first @return array
[ "fork", "a", "child", "process", "." ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/ProcessHelper.php#L85-L108