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
codeages/beanstalk-client
src/Client.php
Client._statsRead
protected function _statsRead($decode = true) { $status = strtok($this->_read(), ' '); switch ($status) { case 'OK': $data = $this->_read((integer) strtok(' ')); return $decode ? $this->_decode($data) : $data; default: throw new ServerException('Stats error: '.$status); } }
php
protected function _statsRead($decode = true) { $status = strtok($this->_read(), ' '); switch ($status) { case 'OK': $data = $this->_read((integer) strtok(' ')); return $decode ? $this->_decode($data) : $data; default: throw new ServerException('Stats error: '.$status); } }
[ "protected", "function", "_statsRead", "(", "$", "decode", "=", "true", ")", "{", "$", "status", "=", "strtok", "(", "$", "this", "->", "_read", "(", ")", ",", "' '", ")", ";", "switch", "(", "$", "status", ")", "{", "case", "'OK'", ":", "$", "data", "=", "$", "this", "->", "_read", "(", "(", "integer", ")", "strtok", "(", "' '", ")", ")", ";", "return", "$", "decode", "?", "$", "this", "->", "_decode", "(", "$", "data", ")", ":", "$", "data", ";", "default", ":", "throw", "new", "ServerException", "(", "'Stats error: '", ".", "$", "status", ")", ";", "}", "}" ]
Handles responses for all stat methods. @param bool $decode Whether to decode data before returning it or not. Default is `true`. @return array|string|bool `false` on error otherwise statistical data.
[ "Handles", "responses", "for", "all", "stat", "methods", "." ]
train
https://github.com/codeages/beanstalk-client/blob/097acad3cd9489413863f6cad86791216bc972e1/src/Client.php#L724-L736
antaresproject/notifications
src/Http/Datatables/Logs.php
Logs.ajax
public function ajax() { return $this->prepare() ->editColumn('lang_code', function ($row = null) { $code = $row->lang_code; $codeIcon = (($code == 'en') ? 'us' : $code); return '<i data-tooltip-inline="' . $row->lang_name . '" class="flag-icon flag-icon-' . $codeIcon . '"></i>'; }) ->editColumn('area', function ($row = null) { $area = !is_null($recipients = array_get($row->variables, 'recipients')) ? user($recipients[0]['id'])->getArea() : $row->area; return config('areas.areas.' . $area); }) ->editColumn('fullname', function ($row = null) { $recipients = !is_null($recipients = array_get($row->variables, 'recipients')) ? $recipients[0] : []; $id = !empty($recipients) ? array_get($recipients, 'id') : $row->author_id; $title = '#' . $id . ' ' . array_get($recipients, 'fullname', $row->fullname); return app('html')->link(handles('antares/foundation::users/' . $id), $title)->get(); }) ->addColumn('action', $this->getActionsColumn()) ->make(true); }
php
public function ajax() { return $this->prepare() ->editColumn('lang_code', function ($row = null) { $code = $row->lang_code; $codeIcon = (($code == 'en') ? 'us' : $code); return '<i data-tooltip-inline="' . $row->lang_name . '" class="flag-icon flag-icon-' . $codeIcon . '"></i>'; }) ->editColumn('area', function ($row = null) { $area = !is_null($recipients = array_get($row->variables, 'recipients')) ? user($recipients[0]['id'])->getArea() : $row->area; return config('areas.areas.' . $area); }) ->editColumn('fullname', function ($row = null) { $recipients = !is_null($recipients = array_get($row->variables, 'recipients')) ? $recipients[0] : []; $id = !empty($recipients) ? array_get($recipients, 'id') : $row->author_id; $title = '#' . $id . ' ' . array_get($recipients, 'fullname', $row->fullname); return app('html')->link(handles('antares/foundation::users/' . $id), $title)->get(); }) ->addColumn('action', $this->getActionsColumn()) ->make(true); }
[ "public", "function", "ajax", "(", ")", "{", "return", "$", "this", "->", "prepare", "(", ")", "->", "editColumn", "(", "'lang_code'", ",", "function", "(", "$", "row", "=", "null", ")", "{", "$", "code", "=", "$", "row", "->", "lang_code", ";", "$", "codeIcon", "=", "(", "(", "$", "code", "==", "'en'", ")", "?", "'us'", ":", "$", "code", ")", ";", "return", "'<i data-tooltip-inline=\"'", ".", "$", "row", "->", "lang_name", ".", "'\" class=\"flag-icon flag-icon-'", ".", "$", "codeIcon", ".", "'\"></i>'", ";", "}", ")", "->", "editColumn", "(", "'area'", ",", "function", "(", "$", "row", "=", "null", ")", "{", "$", "area", "=", "!", "is_null", "(", "$", "recipients", "=", "array_get", "(", "$", "row", "->", "variables", ",", "'recipients'", ")", ")", "?", "user", "(", "$", "recipients", "[", "0", "]", "[", "'id'", "]", ")", "->", "getArea", "(", ")", ":", "$", "row", "->", "area", ";", "return", "config", "(", "'areas.areas.'", ".", "$", "area", ")", ";", "}", ")", "->", "editColumn", "(", "'fullname'", ",", "function", "(", "$", "row", "=", "null", ")", "{", "$", "recipients", "=", "!", "is_null", "(", "$", "recipients", "=", "array_get", "(", "$", "row", "->", "variables", ",", "'recipients'", ")", ")", "?", "$", "recipients", "[", "0", "]", ":", "[", "]", ";", "$", "id", "=", "!", "empty", "(", "$", "recipients", ")", "?", "array_get", "(", "$", "recipients", ",", "'id'", ")", ":", "$", "row", "->", "author_id", ";", "$", "title", "=", "'#'", ".", "$", "id", ".", "' '", ".", "array_get", "(", "$", "recipients", ",", "'fullname'", ",", "$", "row", "->", "fullname", ")", ";", "return", "app", "(", "'html'", ")", "->", "link", "(", "handles", "(", "'antares/foundation::users/'", ".", "$", "id", ")", ",", "$", "title", ")", "->", "get", "(", ")", ";", "}", ")", "->", "addColumn", "(", "'action'", ",", "$", "this", "->", "getActionsColumn", "(", ")", ")", "->", "make", "(", "true", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Http/Datatables/Logs.php#L67-L88
antaresproject/notifications
src/Http/Datatables/Logs.php
Logs.html
public function html() { publish('notifications', ['js/notification-logs.js']); $html = app('html'); return $this->setName('Notifications List') ->addColumn(['data' => 'tbl_notifications_stack.id', 'name' => 'tbl_notifications_stack.id', 'data' => 'id', 'title' => 'Id']) ->addColumn(['data' => 'created_at', 'name' => 'tbl_notifications_stack.created_at', 'title' => trans('antares/notifications::logs.headers.date'), 'className' => 'bolded']) ->addColumn(['data' => 'name', 'name' => 'tbl_notifications.event', 'title' => trans('antares/notifications::logs.headers.name')]) ->addColumn(['data' => 'lang_code', 'name' => 'tbl_languages.code', 'title' => trans('antares/notifications::logs.headers.lang')]) ->addColumn(['data' => 'title', 'name' => 'tbl_notification_contents.title', 'title' => trans('antares/notifications::logs.headers.title')]) ->addColumn(['data' => 'type', 'name' => 'tbl_notification_types.title', 'title' => trans('antares/notifications::logs.headers.type')]) ->addColumn(['data' => 'area', 'name' => 'area', 'title' => trans('antares/notifications::logs.headers.level')]) ->addColumn(['data' => 'fullname', 'name' => 'tbl_users.firstname', 'title' => trans('antares/notifications::logs.headers.user')]) ->addAction(['name' => 'edit', 'title' => '', 'class' => 'mass-actions dt-actions', 'orderable' => false, 'searchable' => false]) ->addGroupSelect($this->types(), 5, null, ['data-prefix' => trans('antares/notifications::messages.datatables.select_type')]) ->addMassAction('delete', $html->link(handles('antares::notifications/logs/delete', ['csrf' => true]), $html->raw('<i class="zmdi zmdi-delete"></i><span>' . trans('antares/notifications::logs.actions.delete') . '</span>'), [ 'class' => "triggerable confirm mass-action", 'data-title' => trans("antares/notifications::logs.are_you_sure"), 'data-description' => trans("antares/notifications::logs.mass_deleteing_notification_logs_desc"), ]))->parameters([ 'order' => [[1, 'desc']], 'aoColumnDefs' => [ ['width' => '1%', 'targets' => 0], ['width' => '7%', 'targets' => 1], ['width' => '14%', 'targets' => 2], ['width' => '2%', 'targets' => 3], ['width' => '7%', 'targets' => 5], ['width' => '5%', 'targets' => 6], ['width' => '10%', 'targets' => 7], ['width' => '1%', 'targets' => 8], ]]); }
php
public function html() { publish('notifications', ['js/notification-logs.js']); $html = app('html'); return $this->setName('Notifications List') ->addColumn(['data' => 'tbl_notifications_stack.id', 'name' => 'tbl_notifications_stack.id', 'data' => 'id', 'title' => 'Id']) ->addColumn(['data' => 'created_at', 'name' => 'tbl_notifications_stack.created_at', 'title' => trans('antares/notifications::logs.headers.date'), 'className' => 'bolded']) ->addColumn(['data' => 'name', 'name' => 'tbl_notifications.event', 'title' => trans('antares/notifications::logs.headers.name')]) ->addColumn(['data' => 'lang_code', 'name' => 'tbl_languages.code', 'title' => trans('antares/notifications::logs.headers.lang')]) ->addColumn(['data' => 'title', 'name' => 'tbl_notification_contents.title', 'title' => trans('antares/notifications::logs.headers.title')]) ->addColumn(['data' => 'type', 'name' => 'tbl_notification_types.title', 'title' => trans('antares/notifications::logs.headers.type')]) ->addColumn(['data' => 'area', 'name' => 'area', 'title' => trans('antares/notifications::logs.headers.level')]) ->addColumn(['data' => 'fullname', 'name' => 'tbl_users.firstname', 'title' => trans('antares/notifications::logs.headers.user')]) ->addAction(['name' => 'edit', 'title' => '', 'class' => 'mass-actions dt-actions', 'orderable' => false, 'searchable' => false]) ->addGroupSelect($this->types(), 5, null, ['data-prefix' => trans('antares/notifications::messages.datatables.select_type')]) ->addMassAction('delete', $html->link(handles('antares::notifications/logs/delete', ['csrf' => true]), $html->raw('<i class="zmdi zmdi-delete"></i><span>' . trans('antares/notifications::logs.actions.delete') . '</span>'), [ 'class' => "triggerable confirm mass-action", 'data-title' => trans("antares/notifications::logs.are_you_sure"), 'data-description' => trans("antares/notifications::logs.mass_deleteing_notification_logs_desc"), ]))->parameters([ 'order' => [[1, 'desc']], 'aoColumnDefs' => [ ['width' => '1%', 'targets' => 0], ['width' => '7%', 'targets' => 1], ['width' => '14%', 'targets' => 2], ['width' => '2%', 'targets' => 3], ['width' => '7%', 'targets' => 5], ['width' => '5%', 'targets' => 6], ['width' => '10%', 'targets' => 7], ['width' => '1%', 'targets' => 8], ]]); }
[ "public", "function", "html", "(", ")", "{", "publish", "(", "'notifications'", ",", "[", "'js/notification-logs.js'", "]", ")", ";", "$", "html", "=", "app", "(", "'html'", ")", ";", "return", "$", "this", "->", "setName", "(", "'Notifications List'", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'tbl_notifications_stack.id'", ",", "'name'", "=>", "'tbl_notifications_stack.id'", ",", "'data'", "=>", "'id'", ",", "'title'", "=>", "'Id'", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'created_at'", ",", "'name'", "=>", "'tbl_notifications_stack.created_at'", ",", "'title'", "=>", "trans", "(", "'antares/notifications::logs.headers.date'", ")", ",", "'className'", "=>", "'bolded'", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'name'", ",", "'name'", "=>", "'tbl_notifications.event'", ",", "'title'", "=>", "trans", "(", "'antares/notifications::logs.headers.name'", ")", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'lang_code'", ",", "'name'", "=>", "'tbl_languages.code'", ",", "'title'", "=>", "trans", "(", "'antares/notifications::logs.headers.lang'", ")", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'title'", ",", "'name'", "=>", "'tbl_notification_contents.title'", ",", "'title'", "=>", "trans", "(", "'antares/notifications::logs.headers.title'", ")", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'type'", ",", "'name'", "=>", "'tbl_notification_types.title'", ",", "'title'", "=>", "trans", "(", "'antares/notifications::logs.headers.type'", ")", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'area'", ",", "'name'", "=>", "'area'", ",", "'title'", "=>", "trans", "(", "'antares/notifications::logs.headers.level'", ")", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'fullname'", ",", "'name'", "=>", "'tbl_users.firstname'", ",", "'title'", "=>", "trans", "(", "'antares/notifications::logs.headers.user'", ")", "]", ")", "->", "addAction", "(", "[", "'name'", "=>", "'edit'", ",", "'title'", "=>", "''", ",", "'class'", "=>", "'mass-actions dt-actions'", ",", "'orderable'", "=>", "false", ",", "'searchable'", "=>", "false", "]", ")", "->", "addGroupSelect", "(", "$", "this", "->", "types", "(", ")", ",", "5", ",", "null", ",", "[", "'data-prefix'", "=>", "trans", "(", "'antares/notifications::messages.datatables.select_type'", ")", "]", ")", "->", "addMassAction", "(", "'delete'", ",", "$", "html", "->", "link", "(", "handles", "(", "'antares::notifications/logs/delete'", ",", "[", "'csrf'", "=>", "true", "]", ")", ",", "$", "html", "->", "raw", "(", "'<i class=\"zmdi zmdi-delete\"></i><span>'", ".", "trans", "(", "'antares/notifications::logs.actions.delete'", ")", ".", "'</span>'", ")", ",", "[", "'class'", "=>", "\"triggerable confirm mass-action\"", ",", "'data-title'", "=>", "trans", "(", "\"antares/notifications::logs.are_you_sure\"", ")", ",", "'data-description'", "=>", "trans", "(", "\"antares/notifications::logs.mass_deleteing_notification_logs_desc\"", ")", ",", "]", ")", ")", "->", "parameters", "(", "[", "'order'", "=>", "[", "[", "1", ",", "'desc'", "]", "]", ",", "'aoColumnDefs'", "=>", "[", "[", "'width'", "=>", "'1%'", ",", "'targets'", "=>", "0", "]", ",", "[", "'width'", "=>", "'7%'", ",", "'targets'", "=>", "1", "]", ",", "[", "'width'", "=>", "'14%'", ",", "'targets'", "=>", "2", "]", ",", "[", "'width'", "=>", "'2%'", ",", "'targets'", "=>", "3", "]", ",", "[", "'width'", "=>", "'7%'", ",", "'targets'", "=>", "5", "]", ",", "[", "'width'", "=>", "'5%'", ",", "'targets'", "=>", "6", "]", ",", "[", "'width'", "=>", "'10%'", ",", "'targets'", "=>", "7", "]", ",", "[", "'width'", "=>", "'1%'", ",", "'targets'", "=>", "8", "]", ",", "]", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Http/Datatables/Logs.php#L93-L124
antaresproject/notifications
src/Http/Datatables/Logs.php
Logs.getActionsColumn
protected function getActionsColumn() { return function ($row) { $html = app('html'); $btns = [ $html->create('li', $html->link(handles("antares::notifications/logs/preview/" . $row->id), trans('antares/notifications::logs.actions.preview'), ['data-notification' => !in_array($row->type, ['Email', 'Sms']), 'data-icon' => 'desktop-windows', 'class' => "triggerable preview-notification-log"])), $html->create('li', $html->link(handles("antares::notifications/logs/" . $row->id . "/delete"), trans('antares/notifications::logs.actions.delete'), ['class' => "triggerable confirm", 'data-icon' => 'delete', 'data-title' => trans("antares/notifications::logs.are_you_sure"), 'data-description' => trans('antares/notifications::logs.delete_notification_log_desc', ['id' => $row->id])])) ]; $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu', 'data-id' => $row->id])->get(); return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get(); }; }
php
protected function getActionsColumn() { return function ($row) { $html = app('html'); $btns = [ $html->create('li', $html->link(handles("antares::notifications/logs/preview/" . $row->id), trans('antares/notifications::logs.actions.preview'), ['data-notification' => !in_array($row->type, ['Email', 'Sms']), 'data-icon' => 'desktop-windows', 'class' => "triggerable preview-notification-log"])), $html->create('li', $html->link(handles("antares::notifications/logs/" . $row->id . "/delete"), trans('antares/notifications::logs.actions.delete'), ['class' => "triggerable confirm", 'data-icon' => 'delete', 'data-title' => trans("antares/notifications::logs.are_you_sure"), 'data-description' => trans('antares/notifications::logs.delete_notification_log_desc', ['id' => $row->id])])) ]; $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu', 'data-id' => $row->id])->get(); return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get(); }; }
[ "protected", "function", "getActionsColumn", "(", ")", "{", "return", "function", "(", "$", "row", ")", "{", "$", "html", "=", "app", "(", "'html'", ")", ";", "$", "btns", "=", "[", "$", "html", "->", "create", "(", "'li'", ",", "$", "html", "->", "link", "(", "handles", "(", "\"antares::notifications/logs/preview/\"", ".", "$", "row", "->", "id", ")", ",", "trans", "(", "'antares/notifications::logs.actions.preview'", ")", ",", "[", "'data-notification'", "=>", "!", "in_array", "(", "$", "row", "->", "type", ",", "[", "'Email'", ",", "'Sms'", "]", ")", ",", "'data-icon'", "=>", "'desktop-windows'", ",", "'class'", "=>", "\"triggerable preview-notification-log\"", "]", ")", ")", ",", "$", "html", "->", "create", "(", "'li'", ",", "$", "html", "->", "link", "(", "handles", "(", "\"antares::notifications/logs/\"", ".", "$", "row", "->", "id", ".", "\"/delete\"", ")", ",", "trans", "(", "'antares/notifications::logs.actions.delete'", ")", ",", "[", "'class'", "=>", "\"triggerable confirm\"", ",", "'data-icon'", "=>", "'delete'", ",", "'data-title'", "=>", "trans", "(", "\"antares/notifications::logs.are_you_sure\"", ")", ",", "'data-description'", "=>", "trans", "(", "'antares/notifications::logs.delete_notification_log_desc'", ",", "[", "'id'", "=>", "$", "row", "->", "id", "]", ")", "]", ")", ")", "]", ";", "$", "section", "=", "$", "html", "->", "create", "(", "'div'", ",", "$", "html", "->", "create", "(", "'section'", ",", "$", "html", "->", "create", "(", "'ul'", ",", "$", "html", "->", "raw", "(", "implode", "(", "''", ",", "$", "btns", ")", ")", ")", ")", ",", "[", "'class'", "=>", "'mass-actions-menu'", ",", "'data-id'", "=>", "$", "row", "->", "id", "]", ")", "->", "get", "(", ")", ";", "return", "'<i class=\"zmdi zmdi-more\"></i>'", ".", "$", "html", "->", "raw", "(", "$", "section", ")", "->", "get", "(", ")", ";", "}", ";", "}" ]
Get actions column for table builder. @return callable
[ "Get", "actions", "column", "for", "table", "builder", "." ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Http/Datatables/Logs.php#L141-L153
jim-moser/zf2-validators-empty-or
src/EmptyValidator.php
EmptyValidator.setType
public function setType($type = null) { $type = $this->calculateTypeValue($type); if (!is_int($type) || ($type < 0) || ($type > self::ALL)) { throw new Exception\InvalidArgumentException('Unknown type'); } $this->options['type'] = $type; return $this; }
php
public function setType($type = null) { $type = $this->calculateTypeValue($type); if (!is_int($type) || ($type < 0) || ($type > self::ALL)) { throw new Exception\InvalidArgumentException('Unknown type'); } $this->options['type'] = $type; return $this; }
[ "public", "function", "setType", "(", "$", "type", "=", "null", ")", "{", "$", "type", "=", "$", "this", "->", "calculateTypeValue", "(", "$", "type", ")", ";", "if", "(", "!", "is_int", "(", "$", "type", ")", "||", "(", "$", "type", "<", "0", ")", "||", "(", "$", "type", ">", "self", "::", "ALL", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "'Unknown type'", ")", ";", "}", "$", "this", "->", "options", "[", "'type'", "]", "=", "$", "type", ";", "return", "$", "this", ";", "}" ]
Sets types of values that are to be considered empty. @param int|array|null $type @throws Exception\InvalidArgumentException @return NotEmpty
[ "Sets", "types", "of", "values", "that", "are", "to", "be", "considered", "empty", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/EmptyValidator.php#L182-L193
jim-moser/zf2-validators-empty-or
src/EmptyValidator.php
EmptyValidator.isValid
public function isValid($value) { if ($value !== null && !is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value) && !is_array($value) && !is_object($value) ) { $this->error(self::INVALID); return false; } $type = $this->getType(); $this->setValue($value); $object = false; // OBJECT_COUNT (countable object) if ($type & self::OBJECT_COUNT) { $object = true; if (is_object($value) && ($value instanceof \Countable) && (count($value) === 0)) { return true; } } // OBJECT_STRING (object's toString) if ($type & self::OBJECT_STRING) { $object = true; if ((is_object($value) && (!method_exists($value, '__toString'))) || (is_object($value) && (method_exists($value, '__toString')) && (((string) $value) === ""))) { return true; } } // OBJECT (object) if ($type & self::OBJECT) { // Fall through. Objects are always considered not empty. } elseif ($object === false) { // If object not allowed but object given then return false. if (is_object($value)) { $this->error(self::INVALID); return false; } } // SPACE (' ') if ($type & self::SPACE) { if (is_string($value) && (preg_match('/^\s+$/s', $value))) { return true; } } // NULL (null) if ($type & self::NULL) { if ($value === null) { return true; } } // EMPTY_ARRAY (array()) if ($type & self::EMPTY_ARRAY) { if (is_array($value) && ($value == array())) { return true; } } // ZERO ('0') if ($type & self::ZERO) { if (is_string($value) && ($value == '0')) { return true; } } // STRING ('') if ($type & self::STRING) { if (is_string($value) && ($value == '')) { return true; } } // FLOAT (0.0) if ($type & self::FLOAT) { if (is_float($value) && ($value == 0.0)) { return true; } } // INTEGER (0) if ($type & self::INTEGER) { if (is_int($value) && ($value == 0)) { return true; } } // BOOLEAN (false) if ($type & self::BOOLEAN) { if (is_bool($value) && ($value == false)) { return true; } } $this->error(self::IS_NOT_EMPTY); return false; }
php
public function isValid($value) { if ($value !== null && !is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value) && !is_array($value) && !is_object($value) ) { $this->error(self::INVALID); return false; } $type = $this->getType(); $this->setValue($value); $object = false; // OBJECT_COUNT (countable object) if ($type & self::OBJECT_COUNT) { $object = true; if (is_object($value) && ($value instanceof \Countable) && (count($value) === 0)) { return true; } } // OBJECT_STRING (object's toString) if ($type & self::OBJECT_STRING) { $object = true; if ((is_object($value) && (!method_exists($value, '__toString'))) || (is_object($value) && (method_exists($value, '__toString')) && (((string) $value) === ""))) { return true; } } // OBJECT (object) if ($type & self::OBJECT) { // Fall through. Objects are always considered not empty. } elseif ($object === false) { // If object not allowed but object given then return false. if (is_object($value)) { $this->error(self::INVALID); return false; } } // SPACE (' ') if ($type & self::SPACE) { if (is_string($value) && (preg_match('/^\s+$/s', $value))) { return true; } } // NULL (null) if ($type & self::NULL) { if ($value === null) { return true; } } // EMPTY_ARRAY (array()) if ($type & self::EMPTY_ARRAY) { if (is_array($value) && ($value == array())) { return true; } } // ZERO ('0') if ($type & self::ZERO) { if (is_string($value) && ($value == '0')) { return true; } } // STRING ('') if ($type & self::STRING) { if (is_string($value) && ($value == '')) { return true; } } // FLOAT (0.0) if ($type & self::FLOAT) { if (is_float($value) && ($value == 0.0)) { return true; } } // INTEGER (0) if ($type & self::INTEGER) { if (is_int($value) && ($value == 0)) { return true; } } // BOOLEAN (false) if ($type & self::BOOLEAN) { if (is_bool($value) && ($value == false)) { return true; } } $this->error(self::IS_NOT_EMPTY); return false; }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "if", "(", "$", "value", "!==", "null", "&&", "!", "is_string", "(", "$", "value", ")", "&&", "!", "is_int", "(", "$", "value", ")", "&&", "!", "is_float", "(", "$", "value", ")", "&&", "!", "is_bool", "(", "$", "value", ")", "&&", "!", "is_array", "(", "$", "value", ")", "&&", "!", "is_object", "(", "$", "value", ")", ")", "{", "$", "this", "->", "error", "(", "self", "::", "INVALID", ")", ";", "return", "false", ";", "}", "$", "type", "=", "$", "this", "->", "getType", "(", ")", ";", "$", "this", "->", "setValue", "(", "$", "value", ")", ";", "$", "object", "=", "false", ";", "// OBJECT_COUNT (countable object)", "if", "(", "$", "type", "&", "self", "::", "OBJECT_COUNT", ")", "{", "$", "object", "=", "true", ";", "if", "(", "is_object", "(", "$", "value", ")", "&&", "(", "$", "value", "instanceof", "\\", "Countable", ")", "&&", "(", "count", "(", "$", "value", ")", "===", "0", ")", ")", "{", "return", "true", ";", "}", "}", "// OBJECT_STRING (object's toString)", "if", "(", "$", "type", "&", "self", "::", "OBJECT_STRING", ")", "{", "$", "object", "=", "true", ";", "if", "(", "(", "is_object", "(", "$", "value", ")", "&&", "(", "!", "method_exists", "(", "$", "value", ",", "'__toString'", ")", ")", ")", "||", "(", "is_object", "(", "$", "value", ")", "&&", "(", "method_exists", "(", "$", "value", ",", "'__toString'", ")", ")", "&&", "(", "(", "(", "string", ")", "$", "value", ")", "===", "\"\"", ")", ")", ")", "{", "return", "true", ";", "}", "}", "// OBJECT (object)", "if", "(", "$", "type", "&", "self", "::", "OBJECT", ")", "{", "// Fall through. Objects are always considered not empty.", "}", "elseif", "(", "$", "object", "===", "false", ")", "{", "// If object not allowed but object given then return false.", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "$", "this", "->", "error", "(", "self", "::", "INVALID", ")", ";", "return", "false", ";", "}", "}", "// SPACE (' ')", "if", "(", "$", "type", "&", "self", "::", "SPACE", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", "&&", "(", "preg_match", "(", "'/^\\s+$/s'", ",", "$", "value", ")", ")", ")", "{", "return", "true", ";", "}", "}", "// NULL (null)", "if", "(", "$", "type", "&", "self", "::", "NULL", ")", "{", "if", "(", "$", "value", "===", "null", ")", "{", "return", "true", ";", "}", "}", "// EMPTY_ARRAY (array())", "if", "(", "$", "type", "&", "self", "::", "EMPTY_ARRAY", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "(", "$", "value", "==", "array", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "// ZERO ('0')", "if", "(", "$", "type", "&", "self", "::", "ZERO", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", "&&", "(", "$", "value", "==", "'0'", ")", ")", "{", "return", "true", ";", "}", "}", "// STRING ('')", "if", "(", "$", "type", "&", "self", "::", "STRING", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", "&&", "(", "$", "value", "==", "''", ")", ")", "{", "return", "true", ";", "}", "}", "// FLOAT (0.0)", "if", "(", "$", "type", "&", "self", "::", "FLOAT", ")", "{", "if", "(", "is_float", "(", "$", "value", ")", "&&", "(", "$", "value", "==", "0.0", ")", ")", "{", "return", "true", ";", "}", "}", "// INTEGER (0)", "if", "(", "$", "type", "&", "self", "::", "INTEGER", ")", "{", "if", "(", "is_int", "(", "$", "value", ")", "&&", "(", "$", "value", "==", "0", ")", ")", "{", "return", "true", ";", "}", "}", "// BOOLEAN (false)", "if", "(", "$", "type", "&", "self", "::", "BOOLEAN", ")", "{", "if", "(", "is_bool", "(", "$", "value", ")", "&&", "(", "$", "value", "==", "false", ")", ")", "{", "return", "true", ";", "}", "}", "$", "this", "->", "error", "(", "self", "::", "IS_NOT_EMPTY", ")", ";", "return", "false", ";", "}" ]
Returns true only if $value is empty value. @param mixed $value @return bool
[ "Returns", "true", "only", "if", "$value", "is", "empty", "value", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/EmptyValidator.php#L201-L305
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.month
function month($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('n', $time); }
php
function month($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('n', $time); }
[ "function", "month", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "date", "(", "'n'", ",", "$", "time", ")", ";", "}" ]
eof jahr
[ "eof", "jahr" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L51-L55
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.month0
function month0($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('m', $time); }
php
function month0($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('m', $time); }
[ "function", "month0", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "date", "(", "'m'", ",", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L59-L63
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.monthS
function monthS($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('M', $time); }
php
function monthS($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('M', $time); }
[ "function", "monthS", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "date", "(", "'M'", ",", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L66-L70
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.day
function day($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('j', $time); }
php
function day($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('j', $time); }
[ "function", "day", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "date", "(", "'j'", ",", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L73-L77
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.weekday
function weekday($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('D', $time); }
php
function weekday($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('D', $time); }
[ "function", "weekday", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "date", "(", "'D'", ",", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L80-L84
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.week
function week($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('W', $time); }
php
function week($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('W', $time); }
[ "function", "week", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "date", "(", "'W'", ",", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L87-L91
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.hour
function hour($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('H', $time); }
php
function hour($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('H', $time); }
[ "function", "hour", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "date", "(", "'H'", ",", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L96-L100
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.minute
function minute($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('i', $time); }
php
function minute($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('i', $time); }
[ "function", "minute", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "date", "(", "'i'", ",", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L104-L108
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.sec
function sec($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('s', $time); }
php
function sec($time = NULL) { if( !is_numeric($time) )$time = $this->n; return date('s', $time); }
[ "function", "sec", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "date", "(", "'s'", ",", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L112-L116
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.now
function now($time = NULL) { if( !is_numeric($time) )$time = $this->n; return $this->hour($time).':'.$this->minute($time).' '.$this->sec($time); }
php
function now($time = NULL) { if( !is_numeric($time) )$time = $this->n; return $this->hour($time).':'.$this->minute($time).' '.$this->sec($time); }
[ "function", "now", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "$", "this", "->", "hour", "(", "$", "time", ")", ".", "':'", ".", "$", "this", "->", "minute", "(", "$", "time", ")", ".", "' '", ".", "$", "this", "->", "sec", "(", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L120-L124
frdl/webfan
.ApplicationComposer/lib/webdof/wDate.php
wDate.date
function date($time = NULL) { if( !is_numeric($time) )$time = $this->n; return $this->day($time).'.'.$this->month($time).'.'.$this->year($time); }
php
function date($time = NULL) { if( !is_numeric($time) )$time = $this->n; return $this->day($time).'.'.$this->month($time).'.'.$this->year($time); }
[ "function", "date", "(", "$", "time", "=", "NULL", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "time", ")", ")", "$", "time", "=", "$", "this", "->", "n", ";", "return", "$", "this", "->", "day", "(", "$", "time", ")", ".", "'.'", ".", "$", "this", "->", "month", "(", "$", "time", ")", ".", "'.'", ".", "$", "this", "->", "year", "(", "$", "time", ")", ";", "}" ]
eof
[ "eof" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wDate.php#L128-L132
dotkernel/dot-rbac
src/Rbac.php
Rbac.isGranted
public function isGranted(string $permission, array $roles): bool { foreach ($this->flattenRoles($roles) as $role) { if ($role->hasPermission($permission)) { return true; } } return false; }
php
public function isGranted(string $permission, array $roles): bool { foreach ($this->flattenRoles($roles) as $role) { if ($role->hasPermission($permission)) { return true; } } return false; }
[ "public", "function", "isGranted", "(", "string", "$", "permission", ",", "array", "$", "roles", ")", ":", "bool", "{", "foreach", "(", "$", "this", "->", "flattenRoles", "(", "$", "roles", ")", "as", "$", "role", ")", "{", "if", "(", "$", "role", "->", "hasPermission", "(", "$", "permission", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
@param RoleInterface|RoleInterface[]|\Traversable $roles @param string $permission @return bool
[ "@param", "RoleInterface|RoleInterface", "[]", "|", "\\", "Traversable", "$roles", "@param", "string", "$permission" ]
train
https://github.com/dotkernel/dot-rbac/blob/747ffadf3cf28750bb7cf81be60eb4c93b830446/src/Rbac.php#L27-L36
bolt/codingstyle
src/Config.php
Config.addRules
public function addRules($rules) { if ($rules instanceof RiskyRulesAwareInterface && $rules->isRisky()) { $this->setRiskyAllowed(true); } if ($rules instanceof \Traversable) { $rules = iterator_to_array($rules); } if (!is_array($rules)) { throw new \InvalidArgumentException('Expected rules to be an iterable.'); } $rules = array_replace($this->getRules(), $rules); $this->setRules($rules); return $this; }
php
public function addRules($rules) { if ($rules instanceof RiskyRulesAwareInterface && $rules->isRisky()) { $this->setRiskyAllowed(true); } if ($rules instanceof \Traversable) { $rules = iterator_to_array($rules); } if (!is_array($rules)) { throw new \InvalidArgumentException('Expected rules to be an iterable.'); } $rules = array_replace($this->getRules(), $rules); $this->setRules($rules); return $this; }
[ "public", "function", "addRules", "(", "$", "rules", ")", "{", "if", "(", "$", "rules", "instanceof", "RiskyRulesAwareInterface", "&&", "$", "rules", "->", "isRisky", "(", ")", ")", "{", "$", "this", "->", "setRiskyAllowed", "(", "true", ")", ";", "}", "if", "(", "$", "rules", "instanceof", "\\", "Traversable", ")", "{", "$", "rules", "=", "iterator_to_array", "(", "$", "rules", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "rules", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Expected rules to be an iterable.'", ")", ";", "}", "$", "rules", "=", "array_replace", "(", "$", "this", "->", "getRules", "(", ")", ",", "$", "rules", ")", ";", "$", "this", "->", "setRules", "(", "$", "rules", ")", ";", "return", "$", "this", ";", "}" ]
Add to the current rules. Overrides existing rules. See {@see setRules} for the format of these rules. @param iterable $rules @return $this
[ "Add", "to", "the", "current", "rules", ".", "Overrides", "existing", "rules", "." ]
train
https://github.com/bolt/codingstyle/blob/df4d149430c66ce4d0ddca4d2469ca0da62a8cce/src/Config.php#L37-L56
Isset/pushnotification
src/PushNotification/Type/Apple/StreamSocket.php
StreamSocket.read
public function read() { if (!$this->connected()) { throw new LogicException('No connection'); } $streams = [$this->connection]; $write = $except = null; $streamsReadyToRead = stream_select($streams, $write, $except, 0, self::READ_TIMEOUT); if ($streamsReadyToRead > 0) { return stream_get_contents($this->connection); } }
php
public function read() { if (!$this->connected()) { throw new LogicException('No connection'); } $streams = [$this->connection]; $write = $except = null; $streamsReadyToRead = stream_select($streams, $write, $except, 0, self::READ_TIMEOUT); if ($streamsReadyToRead > 0) { return stream_get_contents($this->connection); } }
[ "public", "function", "read", "(", ")", "{", "if", "(", "!", "$", "this", "->", "connected", "(", ")", ")", "{", "throw", "new", "LogicException", "(", "'No connection'", ")", ";", "}", "$", "streams", "=", "[", "$", "this", "->", "connection", "]", ";", "$", "write", "=", "$", "except", "=", "null", ";", "$", "streamsReadyToRead", "=", "stream_select", "(", "$", "streams", ",", "$", "write", ",", "$", "except", ",", "0", ",", "self", "::", "READ_TIMEOUT", ")", ";", "if", "(", "$", "streamsReadyToRead", ">", "0", ")", "{", "return", "stream_get_contents", "(", "$", "this", "->", "connection", ")", ";", "}", "}" ]
@throws LogicException @return string|null
[ "@throws", "LogicException" ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Type/Apple/StreamSocket.php#L108-L120
Isset/pushnotification
src/PushNotification/Type/Apple/StreamSocket.php
StreamSocket.write
public function write(string $data): int { if (!$this->connected()) { throw new LogicException('Not connected'); } return (int) fwrite($this->connection, $data, strlen($data)); }
php
public function write(string $data): int { if (!$this->connected()) { throw new LogicException('Not connected'); } return (int) fwrite($this->connection, $data, strlen($data)); }
[ "public", "function", "write", "(", "string", "$", "data", ")", ":", "int", "{", "if", "(", "!", "$", "this", "->", "connected", "(", ")", ")", "{", "throw", "new", "LogicException", "(", "'Not connected'", ")", ";", "}", "return", "(", "int", ")", "fwrite", "(", "$", "this", "->", "connection", ",", "$", "data", ",", "strlen", "(", "$", "data", ")", ")", ";", "}" ]
@param string $data @return int
[ "@param", "string", "$data" ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Type/Apple/StreamSocket.php#L135-L142
josegonzalez/cakephp-sanction
Controller/Component/PermitComponent.php
PermitComponent.initialize
public function initialize(Controller $controller) { if ($this->settings['isTest']) { return; } $this->user = $this->Session->read("{$this->settings['path']}"); $this->routes = Permit::$routes; Permit::$user = $this->user; $this->request = $controller->request; foreach (array('controller', 'plugin') as $inflected) { if (isset($this->request->params[$inflected])) { $this->request->params[$inflected] = strtolower(Inflector::underscore($this->request->params[$inflected])); } } }
php
public function initialize(Controller $controller) { if ($this->settings['isTest']) { return; } $this->user = $this->Session->read("{$this->settings['path']}"); $this->routes = Permit::$routes; Permit::$user = $this->user; $this->request = $controller->request; foreach (array('controller', 'plugin') as $inflected) { if (isset($this->request->params[$inflected])) { $this->request->params[$inflected] = strtolower(Inflector::underscore($this->request->params[$inflected])); } } }
[ "public", "function", "initialize", "(", "Controller", "$", "controller", ")", "{", "if", "(", "$", "this", "->", "settings", "[", "'isTest'", "]", ")", "{", "return", ";", "}", "$", "this", "->", "user", "=", "$", "this", "->", "Session", "->", "read", "(", "\"{$this->settings['path']}\"", ")", ";", "$", "this", "->", "routes", "=", "Permit", "::", "$", "routes", ";", "Permit", "::", "$", "user", "=", "$", "this", "->", "user", ";", "$", "this", "->", "request", "=", "$", "controller", "->", "request", ";", "foreach", "(", "array", "(", "'controller'", ",", "'plugin'", ")", "as", "$", "inflected", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "request", "->", "params", "[", "$", "inflected", "]", ")", ")", "{", "$", "this", "->", "request", "->", "params", "[", "$", "inflected", "]", "=", "strtolower", "(", "Inflector", "::", "underscore", "(", "$", "this", "->", "request", "->", "params", "[", "$", "inflected", "]", ")", ")", ";", "}", "}", "}" ]
Initializes SanctionComponent for use in the controller @param object $controller A reference to the instantiating controller object @return void
[ "Initializes", "SanctionComponent", "for", "use", "in", "the", "controller" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Controller/Component/PermitComponent.php#L99-L116
josegonzalez/cakephp-sanction
Controller/Component/PermitComponent.php
PermitComponent.startup
public function startup(Controller $controller) { if ($this->settings['isTest']) { return; } foreach ($this->routes as $route) { if (!$this->_parse($route['route'])) { continue; } if (!$this->_execute($route)) { break; } $this->Session->write('Sanction.referer', $this->request->here()); return $this->redirect($controller, $route); } }
php
public function startup(Controller $controller) { if ($this->settings['isTest']) { return; } foreach ($this->routes as $route) { if (!$this->_parse($route['route'])) { continue; } if (!$this->_execute($route)) { break; } $this->Session->write('Sanction.referer', $this->request->here()); return $this->redirect($controller, $route); } }
[ "public", "function", "startup", "(", "Controller", "$", "controller", ")", "{", "if", "(", "$", "this", "->", "settings", "[", "'isTest'", "]", ")", "{", "return", ";", "}", "foreach", "(", "$", "this", "->", "routes", "as", "$", "route", ")", "{", "if", "(", "!", "$", "this", "->", "_parse", "(", "$", "route", "[", "'route'", "]", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "$", "this", "->", "_execute", "(", "$", "route", ")", ")", "{", "break", ";", "}", "$", "this", "->", "Session", "->", "write", "(", "'Sanction.referer'", ",", "$", "this", "->", "request", "->", "here", "(", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "controller", ",", "$", "route", ")", ";", "}", "}" ]
Main execution method. Handles redirecting of invalid users, and saving of request url as Sanction.referer @param object $controller A reference to the instantiating controller object @return bool
[ "Main", "execution", "method", ".", "Handles", "redirecting", "of", "invalid", "users", "and", "saving", "of", "request", "url", "as", "Sanction", ".", "referer" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Controller/Component/PermitComponent.php#L125-L142
josegonzalez/cakephp-sanction
Controller/Component/PermitComponent.php
PermitComponent._ensureHere
protected function _ensureHere() { if (empty($this->_here) || empty($this->_hereQuery)) { $this->_here = rtrim(preg_replace( '/^' . preg_quote($this->request->base, '/') . '/', '', $this->request->here, 1 ), '/'); $this->_hereQuery = rtrim($this->request->here(false), '/'); } }
php
protected function _ensureHere() { if (empty($this->_here) || empty($this->_hereQuery)) { $this->_here = rtrim(preg_replace( '/^' . preg_quote($this->request->base, '/') . '/', '', $this->request->here, 1 ), '/'); $this->_hereQuery = rtrim($this->request->here(false), '/'); } }
[ "protected", "function", "_ensureHere", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "_here", ")", "||", "empty", "(", "$", "this", "->", "_hereQuery", ")", ")", "{", "$", "this", "->", "_here", "=", "rtrim", "(", "preg_replace", "(", "'/^'", ".", "preg_quote", "(", "$", "this", "->", "request", "->", "base", ",", "'/'", ")", ".", "'/'", ",", "''", ",", "$", "this", "->", "request", "->", "here", ",", "1", ")", ",", "'/'", ")", ";", "$", "this", "->", "_hereQuery", "=", "rtrim", "(", "$", "this", "->", "request", "->", "here", "(", "false", ")", ",", "'/'", ")", ";", "}", "}" ]
Ensure both $this->_here and $this->_hereQuery are set @return void
[ "Ensure", "both", "$this", "-", ">", "_here", "and", "$this", "-", ">", "_hereQuery", "are", "set" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Controller/Component/PermitComponent.php#L149-L159
josegonzalez/cakephp-sanction
Controller/Component/PermitComponent.php
PermitComponent._parse
protected function _parse($route) { if (is_string($route)) { $this->_ensureHere(); $url = parse_url($route); $_path = rtrim($url['path'], '/'); if ($_path . '?' . Hash::get($url, 'query') === $this->_hereQuery) { return true; } if ($_path === $this->_here) { return true; } return false; } $count = count($route); if ($count == 0) { return false; } foreach ($route as $key => $value) { if (array_key_exists($key, $this->request->params)) { $values = (array)$value; $check = (array)$this->request->params[$key]; $hasNullValues = (count($values) != count(array_filter($values)) || count($values) == 0); $currentValueIsNullish = (in_array(null, $check) || in_array('', $check) || count($check) == 0); if ($hasNullValues && $currentValueIsNullish) { $count--; continue; } if (in_array($key, array('controller', 'plugin'))) { foreach ($check as $k => $_check) { $check[$k] = Inflector::underscore(strtolower($_check)); } } else { foreach ($check as $k => $_check) { $check[$k] = strtolower($_check); } } if (count($values) > 0) { foreach ($values as $k => $v) { if (in_array(strtolower($v), $check)) { $count--; break; } } } elseif (count($check) === 0) { $count--; } } elseif (is_numeric($key) && isset($this->request->params['pass'])) { if (is_array($this->request->params['pass'])) { if (Hash::contains($this->request->params['pass'], $value)) { $count--; } } } } return ($count == 0); }
php
protected function _parse($route) { if (is_string($route)) { $this->_ensureHere(); $url = parse_url($route); $_path = rtrim($url['path'], '/'); if ($_path . '?' . Hash::get($url, 'query') === $this->_hereQuery) { return true; } if ($_path === $this->_here) { return true; } return false; } $count = count($route); if ($count == 0) { return false; } foreach ($route as $key => $value) { if (array_key_exists($key, $this->request->params)) { $values = (array)$value; $check = (array)$this->request->params[$key]; $hasNullValues = (count($values) != count(array_filter($values)) || count($values) == 0); $currentValueIsNullish = (in_array(null, $check) || in_array('', $check) || count($check) == 0); if ($hasNullValues && $currentValueIsNullish) { $count--; continue; } if (in_array($key, array('controller', 'plugin'))) { foreach ($check as $k => $_check) { $check[$k] = Inflector::underscore(strtolower($_check)); } } else { foreach ($check as $k => $_check) { $check[$k] = strtolower($_check); } } if (count($values) > 0) { foreach ($values as $k => $v) { if (in_array(strtolower($v), $check)) { $count--; break; } } } elseif (count($check) === 0) { $count--; } } elseif (is_numeric($key) && isset($this->request->params['pass'])) { if (is_array($this->request->params['pass'])) { if (Hash::contains($this->request->params['pass'], $value)) { $count--; } } } } return ($count == 0); }
[ "protected", "function", "_parse", "(", "$", "route", ")", "{", "if", "(", "is_string", "(", "$", "route", ")", ")", "{", "$", "this", "->", "_ensureHere", "(", ")", ";", "$", "url", "=", "parse_url", "(", "$", "route", ")", ";", "$", "_path", "=", "rtrim", "(", "$", "url", "[", "'path'", "]", ",", "'/'", ")", ";", "if", "(", "$", "_path", ".", "'?'", ".", "Hash", "::", "get", "(", "$", "url", ",", "'query'", ")", "===", "$", "this", "->", "_hereQuery", ")", "{", "return", "true", ";", "}", "if", "(", "$", "_path", "===", "$", "this", "->", "_here", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "$", "count", "=", "count", "(", "$", "route", ")", ";", "if", "(", "$", "count", "==", "0", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "route", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "request", "->", "params", ")", ")", "{", "$", "values", "=", "(", "array", ")", "$", "value", ";", "$", "check", "=", "(", "array", ")", "$", "this", "->", "request", "->", "params", "[", "$", "key", "]", ";", "$", "hasNullValues", "=", "(", "count", "(", "$", "values", ")", "!=", "count", "(", "array_filter", "(", "$", "values", ")", ")", "||", "count", "(", "$", "values", ")", "==", "0", ")", ";", "$", "currentValueIsNullish", "=", "(", "in_array", "(", "null", ",", "$", "check", ")", "||", "in_array", "(", "''", ",", "$", "check", ")", "||", "count", "(", "$", "check", ")", "==", "0", ")", ";", "if", "(", "$", "hasNullValues", "&&", "$", "currentValueIsNullish", ")", "{", "$", "count", "--", ";", "continue", ";", "}", "if", "(", "in_array", "(", "$", "key", ",", "array", "(", "'controller'", ",", "'plugin'", ")", ")", ")", "{", "foreach", "(", "$", "check", "as", "$", "k", "=>", "$", "_check", ")", "{", "$", "check", "[", "$", "k", "]", "=", "Inflector", "::", "underscore", "(", "strtolower", "(", "$", "_check", ")", ")", ";", "}", "}", "else", "{", "foreach", "(", "$", "check", "as", "$", "k", "=>", "$", "_check", ")", "{", "$", "check", "[", "$", "k", "]", "=", "strtolower", "(", "$", "_check", ")", ";", "}", "}", "if", "(", "count", "(", "$", "values", ")", ">", "0", ")", "{", "foreach", "(", "$", "values", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "in_array", "(", "strtolower", "(", "$", "v", ")", ",", "$", "check", ")", ")", "{", "$", "count", "--", ";", "break", ";", "}", "}", "}", "elseif", "(", "count", "(", "$", "check", ")", "===", "0", ")", "{", "$", "count", "--", ";", "}", "}", "elseif", "(", "is_numeric", "(", "$", "key", ")", "&&", "isset", "(", "$", "this", "->", "request", "->", "params", "[", "'pass'", "]", ")", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "request", "->", "params", "[", "'pass'", "]", ")", ")", "{", "if", "(", "Hash", "::", "contains", "(", "$", "this", "->", "request", "->", "params", "[", "'pass'", "]", ",", "$", "value", ")", ")", "{", "$", "count", "--", ";", "}", "}", "}", "}", "return", "(", "$", "count", "==", "0", ")", ";", "}" ]
Parses a given Permit route to see if it matches the current request @param array $route A Permit Route @return bool true if current request matches Permit route, false otherwise
[ "Parses", "a", "given", "Permit", "route", "to", "see", "if", "it", "matches", "the", "current", "request" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Controller/Component/PermitComponent.php#L167-L231
josegonzalez/cakephp-sanction
Controller/Component/PermitComponent.php
PermitComponent._execute
protected function _execute($route) { Permit::$executed = $this->executed = $route; if (empty($route['rules'])) { return false; } if (isset($route['rules']['deny'])) { return $route['rules']['deny'] == true; } if (!isset($route['rules']['auth'])) { return false; } if (is_bool($route['rules']['auth'])) { $isAuthed = $this->Session->read("{$this->settings['path']}.{$this->settings['check']}"); if ($route['rules']['auth'] == true && !$isAuthed) { return true; } if ($route['rules']['auth'] == false && $isAuthed) { return true; } return false; } elseif (!is_array($route['rules']['auth'])) { return false; } if ($this->user == false) { return true; } $fieldsBehavior = 'and'; if (!empty($route['rules']['fields_behavior'])) { $fieldsBehavior = strtolower($route['rules']['fields_behavior']); } if (!in_array($fieldsBehavior, array('and', 'or'))) { $fieldsBehavior = 'and'; } $count = count(Set::flatten($route['rules']['auth'])); foreach ($route['rules']['auth'] as $path => $condition) { $path = '/' . str_replace('.', '/', $path); $path = preg_replace('/^([\/]+)/', '/', $path); $check = $condition; $continue = false; $decrement = 1; $values = Set::extract($path, $this->user); // Support for OR Model-syntax foreach (array('or', 'OR') as $anOr) { if (is_array($condition) && array_key_exists($anOr, $condition)) { $check = $condition[$anOr]; $continue = true; $decrement = count($check); } } if ($fieldsBehavior == 'or') { $check = $condition; $continue = true; $decrement = count($check); } foreach ((array)$check as $cond) { if (in_array($cond, (array)$values)) { $count -= $decrement; if ($continue) { continue 2; } } } } return $count !== 0; }
php
protected function _execute($route) { Permit::$executed = $this->executed = $route; if (empty($route['rules'])) { return false; } if (isset($route['rules']['deny'])) { return $route['rules']['deny'] == true; } if (!isset($route['rules']['auth'])) { return false; } if (is_bool($route['rules']['auth'])) { $isAuthed = $this->Session->read("{$this->settings['path']}.{$this->settings['check']}"); if ($route['rules']['auth'] == true && !$isAuthed) { return true; } if ($route['rules']['auth'] == false && $isAuthed) { return true; } return false; } elseif (!is_array($route['rules']['auth'])) { return false; } if ($this->user == false) { return true; } $fieldsBehavior = 'and'; if (!empty($route['rules']['fields_behavior'])) { $fieldsBehavior = strtolower($route['rules']['fields_behavior']); } if (!in_array($fieldsBehavior, array('and', 'or'))) { $fieldsBehavior = 'and'; } $count = count(Set::flatten($route['rules']['auth'])); foreach ($route['rules']['auth'] as $path => $condition) { $path = '/' . str_replace('.', '/', $path); $path = preg_replace('/^([\/]+)/', '/', $path); $check = $condition; $continue = false; $decrement = 1; $values = Set::extract($path, $this->user); // Support for OR Model-syntax foreach (array('or', 'OR') as $anOr) { if (is_array($condition) && array_key_exists($anOr, $condition)) { $check = $condition[$anOr]; $continue = true; $decrement = count($check); } } if ($fieldsBehavior == 'or') { $check = $condition; $continue = true; $decrement = count($check); } foreach ((array)$check as $cond) { if (in_array($cond, (array)$values)) { $count -= $decrement; if ($continue) { continue 2; } } } } return $count !== 0; }
[ "protected", "function", "_execute", "(", "$", "route", ")", "{", "Permit", "::", "$", "executed", "=", "$", "this", "->", "executed", "=", "$", "route", ";", "if", "(", "empty", "(", "$", "route", "[", "'rules'", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "isset", "(", "$", "route", "[", "'rules'", "]", "[", "'deny'", "]", ")", ")", "{", "return", "$", "route", "[", "'rules'", "]", "[", "'deny'", "]", "==", "true", ";", "}", "if", "(", "!", "isset", "(", "$", "route", "[", "'rules'", "]", "[", "'auth'", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "is_bool", "(", "$", "route", "[", "'rules'", "]", "[", "'auth'", "]", ")", ")", "{", "$", "isAuthed", "=", "$", "this", "->", "Session", "->", "read", "(", "\"{$this->settings['path']}.{$this->settings['check']}\"", ")", ";", "if", "(", "$", "route", "[", "'rules'", "]", "[", "'auth'", "]", "==", "true", "&&", "!", "$", "isAuthed", ")", "{", "return", "true", ";", "}", "if", "(", "$", "route", "[", "'rules'", "]", "[", "'auth'", "]", "==", "false", "&&", "$", "isAuthed", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "elseif", "(", "!", "is_array", "(", "$", "route", "[", "'rules'", "]", "[", "'auth'", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "user", "==", "false", ")", "{", "return", "true", ";", "}", "$", "fieldsBehavior", "=", "'and'", ";", "if", "(", "!", "empty", "(", "$", "route", "[", "'rules'", "]", "[", "'fields_behavior'", "]", ")", ")", "{", "$", "fieldsBehavior", "=", "strtolower", "(", "$", "route", "[", "'rules'", "]", "[", "'fields_behavior'", "]", ")", ";", "}", "if", "(", "!", "in_array", "(", "$", "fieldsBehavior", ",", "array", "(", "'and'", ",", "'or'", ")", ")", ")", "{", "$", "fieldsBehavior", "=", "'and'", ";", "}", "$", "count", "=", "count", "(", "Set", "::", "flatten", "(", "$", "route", "[", "'rules'", "]", "[", "'auth'", "]", ")", ")", ";", "foreach", "(", "$", "route", "[", "'rules'", "]", "[", "'auth'", "]", "as", "$", "path", "=>", "$", "condition", ")", "{", "$", "path", "=", "'/'", ".", "str_replace", "(", "'.'", ",", "'/'", ",", "$", "path", ")", ";", "$", "path", "=", "preg_replace", "(", "'/^([\\/]+)/'", ",", "'/'", ",", "$", "path", ")", ";", "$", "check", "=", "$", "condition", ";", "$", "continue", "=", "false", ";", "$", "decrement", "=", "1", ";", "$", "values", "=", "Set", "::", "extract", "(", "$", "path", ",", "$", "this", "->", "user", ")", ";", "// Support for OR Model-syntax", "foreach", "(", "array", "(", "'or'", ",", "'OR'", ")", "as", "$", "anOr", ")", "{", "if", "(", "is_array", "(", "$", "condition", ")", "&&", "array_key_exists", "(", "$", "anOr", ",", "$", "condition", ")", ")", "{", "$", "check", "=", "$", "condition", "[", "$", "anOr", "]", ";", "$", "continue", "=", "true", ";", "$", "decrement", "=", "count", "(", "$", "check", ")", ";", "}", "}", "if", "(", "$", "fieldsBehavior", "==", "'or'", ")", "{", "$", "check", "=", "$", "condition", ";", "$", "continue", "=", "true", ";", "$", "decrement", "=", "count", "(", "$", "check", ")", ";", "}", "foreach", "(", "(", "array", ")", "$", "check", "as", "$", "cond", ")", "{", "if", "(", "in_array", "(", "$", "cond", ",", "(", "array", ")", "$", "values", ")", ")", "{", "$", "count", "-=", "$", "decrement", ";", "if", "(", "$", "continue", ")", "{", "continue", "2", ";", "}", "}", "}", "}", "return", "$", "count", "!==", "0", ";", "}" ]
Determines whether the given user is authorized to perform an action. The result of a failed request depends upon the options for the route @param array $route A Permit Route @return bool True if redirect should be executed, false otherwise
[ "Determines", "whether", "the", "given", "user", "is", "authorized", "to", "perform", "an", "action", ".", "The", "result", "of", "a", "failed", "request", "depends", "upon", "the", "options", "for", "the", "route" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Controller/Component/PermitComponent.php#L240-L320
josegonzalez/cakephp-sanction
Controller/Component/PermitComponent.php
PermitComponent.redirect
public function redirect(Controller $Controller, $route) { if ($route['message'] != null) { $message = $route['message']; $element = $route['element']; $params = $route['params']; $this->Session->write("Message.{$route['key']}", compact('message', 'element', 'params')); } $Controller->redirect($route['redirect']); }
php
public function redirect(Controller $Controller, $route) { if ($route['message'] != null) { $message = $route['message']; $element = $route['element']; $params = $route['params']; $this->Session->write("Message.{$route['key']}", compact('message', 'element', 'params')); } $Controller->redirect($route['redirect']); }
[ "public", "function", "redirect", "(", "Controller", "$", "Controller", ",", "$", "route", ")", "{", "if", "(", "$", "route", "[", "'message'", "]", "!=", "null", ")", "{", "$", "message", "=", "$", "route", "[", "'message'", "]", ";", "$", "element", "=", "$", "route", "[", "'element'", "]", ";", "$", "params", "=", "$", "route", "[", "'params'", "]", ";", "$", "this", "->", "Session", "->", "write", "(", "\"Message.{$route['key']}\"", ",", "compact", "(", "'message'", ",", "'element'", ",", "'params'", ")", ")", ";", "}", "$", "Controller", "->", "redirect", "(", "$", "route", "[", "'redirect'", "]", ")", ";", "}" ]
Performs a redirect based upon a given route @param Controller|object $Controller A reference to the instantiating controller object @param array $route A Permit Route @return void
[ "Performs", "a", "redirect", "based", "upon", "a", "given", "route" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Controller/Component/PermitComponent.php#L329-L338
josegonzalez/cakephp-sanction
Controller/Component/PermitComponent.php
PermitComponent.access
public function access($route, $rules = array(), $redirect = array()) { $this->routes[] = Permit::access($route, $rules, $redirect); }
php
public function access($route, $rules = array(), $redirect = array()) { $this->routes[] = Permit::access($route, $rules, $redirect); }
[ "public", "function", "access", "(", "$", "route", ",", "$", "rules", "=", "array", "(", ")", ",", "$", "redirect", "=", "array", "(", ")", ")", "{", "$", "this", "->", "routes", "[", "]", "=", "Permit", "::", "access", "(", "$", "route", ",", "$", "rules", ",", "$", "redirect", ")", ";", "}" ]
Connects a route to a given ruleset @param array $route array describing a route @param array $rules array of rules regarding the route @param array $redirect Array containing the url to redirect to on route fail @return array Array of connected routes
[ "Connects", "a", "route", "to", "a", "given", "ruleset" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Controller/Component/PermitComponent.php#L348-L350
josegonzalez/cakephp-sanction
Controller/Component/PermitComponent.php
PermitComponent.referer
public function referer($referer = null) { if ($this->Session->check('Sanction.referer')) { $referer = $this->Session->read('Sanction.referer'); $this->Session->delete('Sanction.referer'); } if ($referer === null) { return false; } return Router::normalize($referer); }
php
public function referer($referer = null) { if ($this->Session->check('Sanction.referer')) { $referer = $this->Session->read('Sanction.referer'); $this->Session->delete('Sanction.referer'); } if ($referer === null) { return false; } return Router::normalize($referer); }
[ "public", "function", "referer", "(", "$", "referer", "=", "null", ")", "{", "if", "(", "$", "this", "->", "Session", "->", "check", "(", "'Sanction.referer'", ")", ")", "{", "$", "referer", "=", "$", "this", "->", "Session", "->", "read", "(", "'Sanction.referer'", ")", ";", "$", "this", "->", "Session", "->", "delete", "(", "'Sanction.referer'", ")", ";", "}", "if", "(", "$", "referer", "===", "null", ")", "{", "return", "false", ";", "}", "return", "Router", "::", "normalize", "(", "$", "referer", ")", ";", "}" ]
Returns the referring URL for this request. @param mixed $referer Default URL to use if Session cannot be read @return string Referring URL
[ "Returns", "the", "referring", "URL", "for", "this", "request", "." ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Controller/Component/PermitComponent.php#L358-L369
josegonzalez/cakephp-sanction
Controller/Component/PermitComponent.php
Permit.access
public static function access($route, $rules = array(), $redirect = array()) { $redirect = array_merge(array( 'redirect' => '/', 'message' => __('Access denied', true), 'element' => 'default', 'params' => array(), 'key' => 'flash' ), $redirect ); if (is_array($route)) { foreach (array('controller', 'plugin') as $inflected) { if (isset($route[$inflected])) { if (is_array($route[$inflected])) { foreach ($route[$inflected] as $i => $controllerName) { $route[$inflected][$i] = Inflector::underscore($controllerName); } } else { $route[$inflected] = Inflector::underscore($route[$inflected]); } } } foreach ($route as $k => $value) { if (is_array($value)) { foreach ($value as $i => $_value) { $route[$k][$i] = strtolower($_value); } } else { $route[$k] = strtolower($value); } } } $newRoute = array( 'route' => $route, 'rules' => $rules, 'redirect' => $redirect['redirect'], 'message' => $redirect['message'], 'element' => $redirect['element'], 'params' => $redirect['params'], 'key' => $redirect['key'], ); self::$routes[] = $newRoute; return $newRoute; }
php
public static function access($route, $rules = array(), $redirect = array()) { $redirect = array_merge(array( 'redirect' => '/', 'message' => __('Access denied', true), 'element' => 'default', 'params' => array(), 'key' => 'flash' ), $redirect ); if (is_array($route)) { foreach (array('controller', 'plugin') as $inflected) { if (isset($route[$inflected])) { if (is_array($route[$inflected])) { foreach ($route[$inflected] as $i => $controllerName) { $route[$inflected][$i] = Inflector::underscore($controllerName); } } else { $route[$inflected] = Inflector::underscore($route[$inflected]); } } } foreach ($route as $k => $value) { if (is_array($value)) { foreach ($value as $i => $_value) { $route[$k][$i] = strtolower($_value); } } else { $route[$k] = strtolower($value); } } } $newRoute = array( 'route' => $route, 'rules' => $rules, 'redirect' => $redirect['redirect'], 'message' => $redirect['message'], 'element' => $redirect['element'], 'params' => $redirect['params'], 'key' => $redirect['key'], ); self::$routes[] = $newRoute; return $newRoute; }
[ "public", "static", "function", "access", "(", "$", "route", ",", "$", "rules", "=", "array", "(", ")", ",", "$", "redirect", "=", "array", "(", ")", ")", "{", "$", "redirect", "=", "array_merge", "(", "array", "(", "'redirect'", "=>", "'/'", ",", "'message'", "=>", "__", "(", "'Access denied'", ",", "true", ")", ",", "'element'", "=>", "'default'", ",", "'params'", "=>", "array", "(", ")", ",", "'key'", "=>", "'flash'", ")", ",", "$", "redirect", ")", ";", "if", "(", "is_array", "(", "$", "route", ")", ")", "{", "foreach", "(", "array", "(", "'controller'", ",", "'plugin'", ")", "as", "$", "inflected", ")", "{", "if", "(", "isset", "(", "$", "route", "[", "$", "inflected", "]", ")", ")", "{", "if", "(", "is_array", "(", "$", "route", "[", "$", "inflected", "]", ")", ")", "{", "foreach", "(", "$", "route", "[", "$", "inflected", "]", "as", "$", "i", "=>", "$", "controllerName", ")", "{", "$", "route", "[", "$", "inflected", "]", "[", "$", "i", "]", "=", "Inflector", "::", "underscore", "(", "$", "controllerName", ")", ";", "}", "}", "else", "{", "$", "route", "[", "$", "inflected", "]", "=", "Inflector", "::", "underscore", "(", "$", "route", "[", "$", "inflected", "]", ")", ";", "}", "}", "}", "foreach", "(", "$", "route", "as", "$", "k", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "foreach", "(", "$", "value", "as", "$", "i", "=>", "$", "_value", ")", "{", "$", "route", "[", "$", "k", "]", "[", "$", "i", "]", "=", "strtolower", "(", "$", "_value", ")", ";", "}", "}", "else", "{", "$", "route", "[", "$", "k", "]", "=", "strtolower", "(", "$", "value", ")", ";", "}", "}", "}", "$", "newRoute", "=", "array", "(", "'route'", "=>", "$", "route", ",", "'rules'", "=>", "$", "rules", ",", "'redirect'", "=>", "$", "redirect", "[", "'redirect'", "]", ",", "'message'", "=>", "$", "redirect", "[", "'message'", "]", ",", "'element'", "=>", "$", "redirect", "[", "'element'", "]", ",", "'params'", "=>", "$", "redirect", "[", "'params'", "]", ",", "'key'", "=>", "$", "redirect", "[", "'key'", "]", ",", ")", ";", "self", "::", "$", "routes", "[", "]", "=", "$", "newRoute", ";", "return", "$", "newRoute", ";", "}" ]
Connects a route to a given ruleset Also converts underscored names to camelCase as additional way of accessing a controller @param array $route array describing a route @param array $rules array of rules regarding the route @param array $redirect Array containing the url to redirect to on route fail @return array Array of connected routes
[ "Connects", "a", "route", "to", "a", "given", "ruleset" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Controller/Component/PermitComponent.php#L402-L449
php-comp/lite-database
example/feat/Builder/PdoBuilder.php
PdoBuilder.quote
public function quote($value) { // If a PDO database connection is set, use it to quote the value using // the underlying database. Otherwise, quote it manually. if ($pdo = $this->getPdo()) { return $pdo->quote($value); } if (\is_numeric($value)) { return $value; } if (null === $value) { return 'NULL'; } return "'" . \addslashes($value) . "'"; }
php
public function quote($value) { // If a PDO database connection is set, use it to quote the value using // the underlying database. Otherwise, quote it manually. if ($pdo = $this->getPdo()) { return $pdo->quote($value); } if (\is_numeric($value)) { return $value; } if (null === $value) { return 'NULL'; } return "'" . \addslashes($value) . "'"; }
[ "public", "function", "quote", "(", "$", "value", ")", "{", "// If a PDO database connection is set, use it to quote the value using", "// the underlying database. Otherwise, quote it manually.", "if", "(", "$", "pdo", "=", "$", "this", "->", "getPdo", "(", ")", ")", "{", "return", "$", "pdo", "->", "quote", "(", "$", "value", ")", ";", "}", "if", "(", "\\", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "if", "(", "null", "===", "$", "value", ")", "{", "return", "'NULL'", ";", "}", "return", "\"'\"", ".", "\\", "addslashes", "(", "$", "value", ")", ".", "\"'\"", ";", "}" ]
Safely escape a value for use in a statement. @param mixed $value value to escape @return mixed|false escaped value or false if failed
[ "Safely", "escape", "a", "value", "for", "use", "in", "a", "statement", "." ]
train
https://github.com/php-comp/lite-database/blob/af5f73cb89e0e6cd24dd464f7a48fb5088eaafca/example/feat/Builder/PdoBuilder.php#L179-L196
php-comp/lite-database
example/feat/Builder/PdoBuilder.php
PdoBuilder.select
public function select($column, string $alias = null): self { if (\is_string($column)) { if (\strpos($column, ',')) { $this->select = \array_merge($this->select, \array_filter(\explode(',', $column))); } else { $this->select[$column] = $alias; } } elseif (\is_array($column)) { foreach ($column as $col => $ali) { if (\is_numeric($col)) { $this->select[$ali] = null; } else { $this->select[$col] = $ali; } } } return $this; }
php
public function select($column, string $alias = null): self { if (\is_string($column)) { if (\strpos($column, ',')) { $this->select = \array_merge($this->select, \array_filter(\explode(',', $column))); } else { $this->select[$column] = $alias; } } elseif (\is_array($column)) { foreach ($column as $col => $ali) { if (\is_numeric($col)) { $this->select[$ali] = null; } else { $this->select[$col] = $ali; } } } return $this; }
[ "public", "function", "select", "(", "$", "column", ",", "string", "$", "alias", "=", "null", ")", ":", "self", "{", "if", "(", "\\", "is_string", "(", "$", "column", ")", ")", "{", "if", "(", "\\", "strpos", "(", "$", "column", ",", "','", ")", ")", "{", "$", "this", "->", "select", "=", "\\", "array_merge", "(", "$", "this", "->", "select", ",", "\\", "array_filter", "(", "\\", "explode", "(", "','", ",", "$", "column", ")", ")", ")", ";", "}", "else", "{", "$", "this", "->", "select", "[", "$", "column", "]", "=", "$", "alias", ";", "}", "}", "elseif", "(", "\\", "is_array", "(", "$", "column", ")", ")", "{", "foreach", "(", "$", "column", "as", "$", "col", "=>", "$", "ali", ")", "{", "if", "(", "\\", "is_numeric", "(", "$", "col", ")", ")", "{", "$", "this", "->", "select", "[", "$", "ali", "]", "=", "null", ";", "}", "else", "{", "$", "this", "->", "select", "[", "$", "col", "]", "=", "$", "ali", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Add a SELECT column, table, or expression with optional alias. @param string|array $column column name, table name, or expression @param string $alias optional alias @return Miner
[ "Add", "a", "SELECT", "column", "table", "or", "expression", "with", "optional", "alias", "." ]
train
https://github.com/php-comp/lite-database/blob/af5f73cb89e0e6cd24dd464f7a48fb5088eaafca/example/feat/Builder/PdoBuilder.php#L208-L227
old-town/workflow-designer-server
Module.php
Module.onBootstrap
public function onBootstrap(EventInterface $e) { /** @var MvcEvent $e */ $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'onRoute'), -1 * PHP_INT_MAX); $eventManager->attach(MvcEvent::EVENT_RENDER, array($this, 'onRender'), PHP_INT_MAX); $serviceManager = $e->getApplication()->getServiceManager(); /** @var SendResponseListener $sendResponseListener */ $sendResponseListener = $serviceManager->get('SendResponseListener'); $sendApiProblemResponseListener = $serviceManager->get(SendApiProblemResponseListener::class); $sendResponseEventManager = $sendResponseListener->getEventManager(); $sendResponseEventManager->attach(SendResponseEvent::EVENT_SEND_RESPONSE, $sendApiProblemResponseListener, -400); }
php
public function onBootstrap(EventInterface $e) { /** @var MvcEvent $e */ $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'onRoute'), -1 * PHP_INT_MAX); $eventManager->attach(MvcEvent::EVENT_RENDER, array($this, 'onRender'), PHP_INT_MAX); $serviceManager = $e->getApplication()->getServiceManager(); /** @var SendResponseListener $sendResponseListener */ $sendResponseListener = $serviceManager->get('SendResponseListener'); $sendApiProblemResponseListener = $serviceManager->get(SendApiProblemResponseListener::class); $sendResponseEventManager = $sendResponseListener->getEventManager(); $sendResponseEventManager->attach(SendResponseEvent::EVENT_SEND_RESPONSE, $sendApiProblemResponseListener, -400); }
[ "public", "function", "onBootstrap", "(", "EventInterface", "$", "e", ")", "{", "/** @var MvcEvent $e */", "$", "eventManager", "=", "$", "e", "->", "getApplication", "(", ")", "->", "getEventManager", "(", ")", ";", "$", "moduleRouteListener", "=", "new", "ModuleRouteListener", "(", ")", ";", "$", "moduleRouteListener", "->", "attach", "(", "$", "eventManager", ")", ";", "$", "eventManager", "->", "attach", "(", "MvcEvent", "::", "EVENT_ROUTE", ",", "array", "(", "$", "this", ",", "'onRoute'", ")", ",", "-", "1", "*", "PHP_INT_MAX", ")", ";", "$", "eventManager", "->", "attach", "(", "MvcEvent", "::", "EVENT_RENDER", ",", "array", "(", "$", "this", ",", "'onRender'", ")", ",", "PHP_INT_MAX", ")", ";", "$", "serviceManager", "=", "$", "e", "->", "getApplication", "(", ")", "->", "getServiceManager", "(", ")", ";", "/** @var SendResponseListener $sendResponseListener */", "$", "sendResponseListener", "=", "$", "serviceManager", "->", "get", "(", "'SendResponseListener'", ")", ";", "$", "sendApiProblemResponseListener", "=", "$", "serviceManager", "->", "get", "(", "SendApiProblemResponseListener", "::", "class", ")", ";", "$", "sendResponseEventManager", "=", "$", "sendResponseListener", "->", "getEventManager", "(", ")", ";", "$", "sendResponseEventManager", "->", "attach", "(", "SendResponseEvent", "::", "EVENT_SEND_RESPONSE", ",", "$", "sendApiProblemResponseListener", ",", "-", "400", ")", ";", "}" ]
@param EventInterface $e @return array|void @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
[ "@param", "EventInterface", "$e" ]
train
https://github.com/old-town/workflow-designer-server/blob/6389c5a515861cc8e0b769f1ca7be12c6b78c611/Module.php#L38-L60
surebert/surebert-framework
src/sb/REST/Client.php
Client.setDefaultArguments
public function setDefaultArguments($default_settings) { foreach ($default_settings as $setting => $val) { if (property_exists(get_class(), $setting)) { $this->$setting = $val; } } }
php
public function setDefaultArguments($default_settings) { foreach ($default_settings as $setting => $val) { if (property_exists(get_class(), $setting)) { $this->$setting = $val; } } }
[ "public", "function", "setDefaultArguments", "(", "$", "default_settings", ")", "{", "foreach", "(", "$", "default_settings", "as", "$", "setting", "=>", "$", "val", ")", "{", "if", "(", "property_exists", "(", "get_class", "(", ")", ",", "$", "setting", ")", ")", "{", "$", "this", "->", "$", "setting", "=", "$", "val", ";", "}", "}", "}" ]
Overrides the default settings for all requests @param array $default_settings settings to override the default properties of follow_location, verify_ssl, return_transfer, debug, cookie_file, user_agent, timeout, on_http_error, on_headers, on_body
[ "Overrides", "the", "default", "settings", "for", "all", "requests" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/REST/Client.php#L177-L184
surebert/surebert-framework
src/sb/REST/Client.php
Client.setAuthentication
public function setAuthentication($uname = '', $pass = '', $type = 'basic') { $this->authentication['uname'] = $uname; $this->authentication['pass'] = $pass; $this->authentication['type'] = $type; }
php
public function setAuthentication($uname = '', $pass = '', $type = 'basic') { $this->authentication['uname'] = $uname; $this->authentication['pass'] = $pass; $this->authentication['type'] = $type; }
[ "public", "function", "setAuthentication", "(", "$", "uname", "=", "''", ",", "$", "pass", "=", "''", ",", "$", "type", "=", "'basic'", ")", "{", "$", "this", "->", "authentication", "[", "'uname'", "]", "=", "$", "uname", ";", "$", "this", "->", "authentication", "[", "'pass'", "]", "=", "$", "pass", ";", "$", "this", "->", "authentication", "[", "'type'", "]", "=", "$", "type", ";", "}" ]
Sets the authentication type used @param string $uname The username @param string $pass The password @param string $type The auth type basic, ntlm, digest
[ "Sets", "the", "authentication", "type", "used" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/REST/Client.php#L192-L197
surebert/surebert-framework
src/sb/REST/Client.php
Client.processCurl
protected function processCurl($method, $data, $override_settings = Array()) { $settings = get_object_vars($this); foreach ($override_settings as $setting => $val) { $settings[$setting] = $val; } $url = $settings['url']; if ($method == 'GET' && is_array($data)) { $url .='?' . http_build_query($data); } $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, $settings['return_transfer'] ? TRUE : FALSE); curl_setopt($ch, CURLOPT_USERAGENT, $settings['user_agent']); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $settings['follow_location'] ? TRUE : FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $settings['verify_ssl'] ? TRUE : FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $settings['verify_ssl'] ? TRUE : FALSE); curl_setopt($ch, CURLOPT_TIMEOUT, is_int($settings['debug']) ? $settings['debug'] : 30); if (is_array($settings['authentication']) && count($settings['authentication'])) { $auth_type = isset($settings['authentication']['type']) ? $settings['authentication']['type'] : 'basic'; switch ($auth_type) { case 'ntlm': $auth_type = CURLAUTH_NTLM; break; case 'digest': curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); $auth_type = CURLAUTH_DIGEST; break; case 'any': $auth_type = CURLAUTH_ANY; case 'basic': default: $auth_type = CURLAUTH_BASIC; break; } curl_setopt($ch, CURLOPT_HTTPAUTH, $auth_type); $uname = isset($settings['authentication']['uname']) ? $settings['authentication']['uname'] : ''; $pass = isset($settings['authentication']['pass']) ? $settings['authentication']['pass'] : ''; curl_setopt($ch, CURLOPT_USERPWD, $uname . ':' . $pass); } if (is_array($settings['headers'])) { foreach ($settings['headers'] as $key => $val) { curl_setopt($ch, CURLOPT_HTTPHEADER, array($key . ": " . $val)); } } if ($settings['debug']) { curl_setopt($ch, CURLOPT_VERBOSE, $settings['debug'] ? TRUE : FALSE); } if (!empty($settings['cookie_file'])) { curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie_file); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie_file); } if ($method != 'GET') { if ($method == 'POST') { curl_setopt($ch, CURLOPT_POST, 1); } else { $data = is_array($data) ? http_build_query($data) : $data; curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($data))); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); } curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $data) use ($settings) { if (!is_null($data)) { if (is_callable($settings['on_headers'])) { $settings['on_headers']($data); } if (preg_match("~^HTTP/\d+\.\d+\s(\d+)\s(.*?)[\r\n]~", $data, $match) && !in_array($match[1], Array(100, 200))) { if (is_callable($settings['on_http_error'])) { $settings['on_http_error']($match[1], $match[2]); } } } return strlen($data); }); curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use($settings) { if (is_callable($settings['on_body'])) { $settings['on_body']($data); } return strlen($data); }); $response = curl_exec($ch); if ($response === false) { $error = curl_error($ch); $error_no = curl_errno($ch); if (is_callable($settings['on_error'])) { return $settings['on_error']($error_no, $error); } return $error_no . ' ' . $error; } return $response; }
php
protected function processCurl($method, $data, $override_settings = Array()) { $settings = get_object_vars($this); foreach ($override_settings as $setting => $val) { $settings[$setting] = $val; } $url = $settings['url']; if ($method == 'GET' && is_array($data)) { $url .='?' . http_build_query($data); } $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, $settings['return_transfer'] ? TRUE : FALSE); curl_setopt($ch, CURLOPT_USERAGENT, $settings['user_agent']); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $settings['follow_location'] ? TRUE : FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $settings['verify_ssl'] ? TRUE : FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $settings['verify_ssl'] ? TRUE : FALSE); curl_setopt($ch, CURLOPT_TIMEOUT, is_int($settings['debug']) ? $settings['debug'] : 30); if (is_array($settings['authentication']) && count($settings['authentication'])) { $auth_type = isset($settings['authentication']['type']) ? $settings['authentication']['type'] : 'basic'; switch ($auth_type) { case 'ntlm': $auth_type = CURLAUTH_NTLM; break; case 'digest': curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); $auth_type = CURLAUTH_DIGEST; break; case 'any': $auth_type = CURLAUTH_ANY; case 'basic': default: $auth_type = CURLAUTH_BASIC; break; } curl_setopt($ch, CURLOPT_HTTPAUTH, $auth_type); $uname = isset($settings['authentication']['uname']) ? $settings['authentication']['uname'] : ''; $pass = isset($settings['authentication']['pass']) ? $settings['authentication']['pass'] : ''; curl_setopt($ch, CURLOPT_USERPWD, $uname . ':' . $pass); } if (is_array($settings['headers'])) { foreach ($settings['headers'] as $key => $val) { curl_setopt($ch, CURLOPT_HTTPHEADER, array($key . ": " . $val)); } } if ($settings['debug']) { curl_setopt($ch, CURLOPT_VERBOSE, $settings['debug'] ? TRUE : FALSE); } if (!empty($settings['cookie_file'])) { curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie_file); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie_file); } if ($method != 'GET') { if ($method == 'POST') { curl_setopt($ch, CURLOPT_POST, 1); } else { $data = is_array($data) ? http_build_query($data) : $data; curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($data))); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); } curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $data) use ($settings) { if (!is_null($data)) { if (is_callable($settings['on_headers'])) { $settings['on_headers']($data); } if (preg_match("~^HTTP/\d+\.\d+\s(\d+)\s(.*?)[\r\n]~", $data, $match) && !in_array($match[1], Array(100, 200))) { if (is_callable($settings['on_http_error'])) { $settings['on_http_error']($match[1], $match[2]); } } } return strlen($data); }); curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use($settings) { if (is_callable($settings['on_body'])) { $settings['on_body']($data); } return strlen($data); }); $response = curl_exec($ch); if ($response === false) { $error = curl_error($ch); $error_no = curl_errno($ch); if (is_callable($settings['on_error'])) { return $settings['on_error']($error_no, $error); } return $error_no . ' ' . $error; } return $response; }
[ "protected", "function", "processCurl", "(", "$", "method", ",", "$", "data", ",", "$", "override_settings", "=", "Array", "(", ")", ")", "{", "$", "settings", "=", "get_object_vars", "(", "$", "this", ")", ";", "foreach", "(", "$", "override_settings", "as", "$", "setting", "=>", "$", "val", ")", "{", "$", "settings", "[", "$", "setting", "]", "=", "$", "val", ";", "}", "$", "url", "=", "$", "settings", "[", "'url'", "]", ";", "if", "(", "$", "method", "==", "'GET'", "&&", "is_array", "(", "$", "data", ")", ")", "{", "$", "url", ".=", "'?'", ".", "http_build_query", "(", "$", "data", ")", ";", "}", "$", "ch", "=", "curl_init", "(", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "$", "settings", "[", "'return_transfer'", "]", "?", "TRUE", ":", "FALSE", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "$", "settings", "[", "'user_agent'", "]", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_FOLLOWLOCATION", ",", "$", "settings", "[", "'follow_location'", "]", "?", "TRUE", ":", "FALSE", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "$", "settings", "[", "'verify_ssl'", "]", "?", "TRUE", ":", "FALSE", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYHOST", ",", "$", "settings", "[", "'verify_ssl'", "]", "?", "TRUE", ":", "FALSE", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_TIMEOUT", ",", "is_int", "(", "$", "settings", "[", "'debug'", "]", ")", "?", "$", "settings", "[", "'debug'", "]", ":", "30", ")", ";", "if", "(", "is_array", "(", "$", "settings", "[", "'authentication'", "]", ")", "&&", "count", "(", "$", "settings", "[", "'authentication'", "]", ")", ")", "{", "$", "auth_type", "=", "isset", "(", "$", "settings", "[", "'authentication'", "]", "[", "'type'", "]", ")", "?", "$", "settings", "[", "'authentication'", "]", "[", "'type'", "]", ":", "'basic'", ";", "switch", "(", "$", "auth_type", ")", "{", "case", "'ntlm'", ":", "$", "auth_type", "=", "CURLAUTH_NTLM", ";", "break", ";", "case", "'digest'", ":", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPAUTH", ",", "CURLAUTH_NTLM", ")", ";", "$", "auth_type", "=", "CURLAUTH_DIGEST", ";", "break", ";", "case", "'any'", ":", "$", "auth_type", "=", "CURLAUTH_ANY", ";", "case", "'basic'", ":", "default", ":", "$", "auth_type", "=", "CURLAUTH_BASIC", ";", "break", ";", "}", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPAUTH", ",", "$", "auth_type", ")", ";", "$", "uname", "=", "isset", "(", "$", "settings", "[", "'authentication'", "]", "[", "'uname'", "]", ")", "?", "$", "settings", "[", "'authentication'", "]", "[", "'uname'", "]", ":", "''", ";", "$", "pass", "=", "isset", "(", "$", "settings", "[", "'authentication'", "]", "[", "'pass'", "]", ")", "?", "$", "settings", "[", "'authentication'", "]", "[", "'pass'", "]", ":", "''", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERPWD", ",", "$", "uname", ".", "':'", ".", "$", "pass", ")", ";", "}", "if", "(", "is_array", "(", "$", "settings", "[", "'headers'", "]", ")", ")", "{", "foreach", "(", "$", "settings", "[", "'headers'", "]", "as", "$", "key", "=>", "$", "val", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "array", "(", "$", "key", ".", "\": \"", ".", "$", "val", ")", ")", ";", "}", "}", "if", "(", "$", "settings", "[", "'debug'", "]", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_VERBOSE", ",", "$", "settings", "[", "'debug'", "]", "?", "TRUE", ":", "FALSE", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "settings", "[", "'cookie_file'", "]", ")", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_COOKIEJAR", ",", "$", "this", "->", "cookie_file", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_COOKIEFILE", ",", "$", "this", "->", "cookie_file", ")", ";", "}", "if", "(", "$", "method", "!=", "'GET'", ")", "{", "if", "(", "$", "method", "==", "'POST'", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "1", ")", ";", "}", "else", "{", "$", "data", "=", "is_array", "(", "$", "data", ")", "?", "http_build_query", "(", "$", "data", ")", ":", "$", "data", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "array", "(", "'Content-Length: '", ".", "strlen", "(", "$", "data", ")", ")", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "$", "method", ")", ";", "}", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "data", ")", ";", "}", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADERFUNCTION", ",", "function", "(", "$", "ch", ",", "$", "data", ")", "use", "(", "$", "settings", ")", "{", "if", "(", "!", "is_null", "(", "$", "data", ")", ")", "{", "if", "(", "is_callable", "(", "$", "settings", "[", "'on_headers'", "]", ")", ")", "{", "$", "settings", "[", "'on_headers'", "]", "(", "$", "data", ")", ";", "}", "if", "(", "preg_match", "(", "\"~^HTTP/\\d+\\.\\d+\\s(\\d+)\\s(.*?)[\\r\\n]~\"", ",", "$", "data", ",", "$", "match", ")", "&&", "!", "in_array", "(", "$", "match", "[", "1", "]", ",", "Array", "(", "100", ",", "200", ")", ")", ")", "{", "if", "(", "is_callable", "(", "$", "settings", "[", "'on_http_error'", "]", ")", ")", "{", "$", "settings", "[", "'on_http_error'", "]", "(", "$", "match", "[", "1", "]", ",", "$", "match", "[", "2", "]", ")", ";", "}", "}", "}", "return", "strlen", "(", "$", "data", ")", ";", "}", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_WRITEFUNCTION", ",", "function", "(", "$", "ch", ",", "$", "data", ")", "use", "(", "$", "settings", ")", "{", "if", "(", "is_callable", "(", "$", "settings", "[", "'on_body'", "]", ")", ")", "{", "$", "settings", "[", "'on_body'", "]", "(", "$", "data", ")", ";", "}", "return", "strlen", "(", "$", "data", ")", ";", "}", ")", ";", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "if", "(", "$", "response", "===", "false", ")", "{", "$", "error", "=", "curl_error", "(", "$", "ch", ")", ";", "$", "error_no", "=", "curl_errno", "(", "$", "ch", ")", ";", "if", "(", "is_callable", "(", "$", "settings", "[", "'on_error'", "]", ")", ")", "{", "return", "$", "settings", "[", "'on_error'", "]", "(", "$", "error_no", ",", "$", "error", ")", ";", "}", "return", "$", "error_no", ".", "' '", ".", "$", "error", ";", "}", "return", "$", "response", ";", "}" ]
Passes the request of to CURL for processing @param string $method The type of method to send it with, POST, GET, PUT, DELETE @param array $data The data to send @param array $override_settings settings to override the default properties of follow_location, verify_ssl, return_transfer, debug, cookie_file, user_agent, timeout, on_http_error, on_headers, on_body
[ "Passes", "the", "request", "of", "to", "CURL", "for", "processing" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/REST/Client.php#L271-L384
Smile-SA/CronBundle
Service/CronService.php
CronService.runQueued
public function runQueued(InputInterface $input, OutputInterface $output) { /** @var SmileCron[] $smileCrons */ $smileCrons = $this->listQueued(); /** @var CronInterface[] $crons */ $crons = $this->getCrons(); /** @var CronInterface[] $cronAlias */ $cronAlias = array(); foreach ($crons as $cron) { $cronAlias[$cron->getAlias()] = $cron; } if ($smileCrons) { foreach ($smileCrons as $smileCron) { if (isset($cronAlias[$smileCron->getAlias()])) { $this->run($smileCron); $status = $cronAlias[$smileCron->getAlias()]->run($input, $output); $this->end($smileCron, $status); } } } }
php
public function runQueued(InputInterface $input, OutputInterface $output) { /** @var SmileCron[] $smileCrons */ $smileCrons = $this->listQueued(); /** @var CronInterface[] $crons */ $crons = $this->getCrons(); /** @var CronInterface[] $cronAlias */ $cronAlias = array(); foreach ($crons as $cron) { $cronAlias[$cron->getAlias()] = $cron; } if ($smileCrons) { foreach ($smileCrons as $smileCron) { if (isset($cronAlias[$smileCron->getAlias()])) { $this->run($smileCron); $status = $cronAlias[$smileCron->getAlias()]->run($input, $output); $this->end($smileCron, $status); } } } }
[ "public", "function", "runQueued", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "/** @var SmileCron[] $smileCrons */", "$", "smileCrons", "=", "$", "this", "->", "listQueued", "(", ")", ";", "/** @var CronInterface[] $crons */", "$", "crons", "=", "$", "this", "->", "getCrons", "(", ")", ";", "/** @var CronInterface[] $cronAlias */", "$", "cronAlias", "=", "array", "(", ")", ";", "foreach", "(", "$", "crons", "as", "$", "cron", ")", "{", "$", "cronAlias", "[", "$", "cron", "->", "getAlias", "(", ")", "]", "=", "$", "cron", ";", "}", "if", "(", "$", "smileCrons", ")", "{", "foreach", "(", "$", "smileCrons", "as", "$", "smileCron", ")", "{", "if", "(", "isset", "(", "$", "cronAlias", "[", "$", "smileCron", "->", "getAlias", "(", ")", "]", ")", ")", "{", "$", "this", "->", "run", "(", "$", "smileCron", ")", ";", "$", "status", "=", "$", "cronAlias", "[", "$", "smileCron", "->", "getAlias", "(", ")", "]", "->", "run", "(", "$", "input", ",", "$", "output", ")", ";", "$", "this", "->", "end", "(", "$", "smileCron", ",", "$", "status", ")", ";", "}", "}", "}", "}" ]
List cron commands identified as queued @param InputInterface $input input interface @param OutputInterface $output output interface
[ "List", "cron", "commands", "identified", "as", "queued" ]
train
https://github.com/Smile-SA/CronBundle/blob/3e6d29112915fa957cc04386ba9c6d1fc134d31f/Service/CronService.php#L107-L130
Smile-SA/CronBundle
Service/CronService.php
CronService.listCronsStatus
public function listCronsStatus() { /** @var SmileCron[] $smileCrons */ $smileCrons = $this->repository->listCrons(); /** @var CronInterface[] $crons */ $crons = $this->getCrons(); $cronAlias = array(); foreach ($crons as $cron) { $cronAlias[$cron->getAlias()] = $cron; } if ($smileCrons) { foreach ($smileCrons as $smileCron) { if (isset($cronAlias[$smileCron->getAlias()])) { $cronAlias[$smileCron->getAlias()] = $smileCron; } } } return $cronAlias; }
php
public function listCronsStatus() { /** @var SmileCron[] $smileCrons */ $smileCrons = $this->repository->listCrons(); /** @var CronInterface[] $crons */ $crons = $this->getCrons(); $cronAlias = array(); foreach ($crons as $cron) { $cronAlias[$cron->getAlias()] = $cron; } if ($smileCrons) { foreach ($smileCrons as $smileCron) { if (isset($cronAlias[$smileCron->getAlias()])) { $cronAlias[$smileCron->getAlias()] = $smileCron; } } } return $cronAlias; }
[ "public", "function", "listCronsStatus", "(", ")", "{", "/** @var SmileCron[] $smileCrons */", "$", "smileCrons", "=", "$", "this", "->", "repository", "->", "listCrons", "(", ")", ";", "/** @var CronInterface[] $crons */", "$", "crons", "=", "$", "this", "->", "getCrons", "(", ")", ";", "$", "cronAlias", "=", "array", "(", ")", ";", "foreach", "(", "$", "crons", "as", "$", "cron", ")", "{", "$", "cronAlias", "[", "$", "cron", "->", "getAlias", "(", ")", "]", "=", "$", "cron", ";", "}", "if", "(", "$", "smileCrons", ")", "{", "foreach", "(", "$", "smileCrons", "as", "$", "smileCron", ")", "{", "if", "(", "isset", "(", "$", "cronAlias", "[", "$", "smileCron", "->", "getAlias", "(", ")", "]", ")", ")", "{", "$", "cronAlias", "[", "$", "smileCron", "->", "getAlias", "(", ")", "]", "=", "$", "smileCron", ";", "}", "}", "}", "return", "$", "cronAlias", ";", "}" ]
Return cron list and status @return SmileCron[] cron list with status
[ "Return", "cron", "list", "and", "status" ]
train
https://github.com/Smile-SA/CronBundle/blob/3e6d29112915fa957cc04386ba9c6d1fc134d31f/Service/CronService.php#L137-L159
nabab/bbn
src/bbn/appui/i18n.php
i18n.analyze_php
public function analyze_php(string $file): array { $res = []; $php = file_get_contents($file); if ( $tmp = \Gettext\Translations::fromPhpCodeString($php, [ 'functions' => ['_' => 'gettext'], 'file' => $file ]) ){ foreach ( $tmp->getIterator() as $r => $tr ){ $res[] = $tr->getOriginal(); } $this->parser->mergeWith($tmp); } return array_unique($res); }
php
public function analyze_php(string $file): array { $res = []; $php = file_get_contents($file); if ( $tmp = \Gettext\Translations::fromPhpCodeString($php, [ 'functions' => ['_' => 'gettext'], 'file' => $file ]) ){ foreach ( $tmp->getIterator() as $r => $tr ){ $res[] = $tr->getOriginal(); } $this->parser->mergeWith($tmp); } return array_unique($res); }
[ "public", "function", "analyze_php", "(", "string", "$", "file", ")", ":", "array", "{", "$", "res", "=", "[", "]", ";", "$", "php", "=", "file_get_contents", "(", "$", "file", ")", ";", "if", "(", "$", "tmp", "=", "\\", "Gettext", "\\", "Translations", "::", "fromPhpCodeString", "(", "$", "php", ",", "[", "'functions'", "=>", "[", "'_'", "=>", "'gettext'", "]", ",", "'file'", "=>", "$", "file", "]", ")", ")", "{", "foreach", "(", "$", "tmp", "->", "getIterator", "(", ")", "as", "$", "r", "=>", "$", "tr", ")", "{", "$", "res", "[", "]", "=", "$", "tr", "->", "getOriginal", "(", ")", ";", "}", "$", "this", "->", "parser", "->", "mergeWith", "(", "$", "tmp", ")", ";", "}", "return", "array_unique", "(", "$", "res", ")", ";", "}" ]
Returns the strings contained in the given php file @param string $file @return array
[ "Returns", "the", "strings", "contained", "in", "the", "given", "php", "file" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L41-L55
nabab/bbn
src/bbn/appui/i18n.php
i18n.analyze_js
public function analyze_js(string $file): array { $res = []; $js = file_get_contents($file); if ( $tmp = \Gettext\Translations::fromJsCodeString($js, [ 'functions' => [ '_' => 'gettext', 'bbn._' => 'gettext' ], 'file' => $file ]) ){ foreach ( $tmp->getIterator() as $r => $tr ){ $res[] = $tr->getOriginal(); } $this->parser->mergeWith($tmp); } return array_unique($res); }
php
public function analyze_js(string $file): array { $res = []; $js = file_get_contents($file); if ( $tmp = \Gettext\Translations::fromJsCodeString($js, [ 'functions' => [ '_' => 'gettext', 'bbn._' => 'gettext' ], 'file' => $file ]) ){ foreach ( $tmp->getIterator() as $r => $tr ){ $res[] = $tr->getOriginal(); } $this->parser->mergeWith($tmp); } return array_unique($res); }
[ "public", "function", "analyze_js", "(", "string", "$", "file", ")", ":", "array", "{", "$", "res", "=", "[", "]", ";", "$", "js", "=", "file_get_contents", "(", "$", "file", ")", ";", "if", "(", "$", "tmp", "=", "\\", "Gettext", "\\", "Translations", "::", "fromJsCodeString", "(", "$", "js", ",", "[", "'functions'", "=>", "[", "'_'", "=>", "'gettext'", ",", "'bbn._'", "=>", "'gettext'", "]", ",", "'file'", "=>", "$", "file", "]", ")", ")", "{", "foreach", "(", "$", "tmp", "->", "getIterator", "(", ")", "as", "$", "r", "=>", "$", "tr", ")", "{", "$", "res", "[", "]", "=", "$", "tr", "->", "getOriginal", "(", ")", ";", "}", "$", "this", "->", "parser", "->", "mergeWith", "(", "$", "tmp", ")", ";", "}", "return", "array_unique", "(", "$", "res", ")", ";", "}" ]
Returns the strings contained in the given js file @param string $file @return array
[ "Returns", "the", "strings", "contained", "in", "the", "given", "js", "file" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L63-L80
nabab/bbn
src/bbn/appui/i18n.php
i18n.analyze_file
public function analyze_file(string $file): array { $res = []; $ext = bbn\str::file_ext($file); if ( \in_array($ext, self::$extensions, true) && is_file($file) ){ switch ( $ext ){ case 'html': $res = $this->analyze_php($file); break; case 'php': $res = $this->analyze_php($file); break; case 'js': $res = $this->analyze_js($file); break; /*case 'json': $res = $this->analyze_json($file); break;*/ } } return $res; }
php
public function analyze_file(string $file): array { $res = []; $ext = bbn\str::file_ext($file); if ( \in_array($ext, self::$extensions, true) && is_file($file) ){ switch ( $ext ){ case 'html': $res = $this->analyze_php($file); break; case 'php': $res = $this->analyze_php($file); break; case 'js': $res = $this->analyze_js($file); break; /*case 'json': $res = $this->analyze_json($file); break;*/ } } return $res; }
[ "public", "function", "analyze_file", "(", "string", "$", "file", ")", ":", "array", "{", "$", "res", "=", "[", "]", ";", "$", "ext", "=", "bbn", "\\", "str", "::", "file_ext", "(", "$", "file", ")", ";", "if", "(", "\\", "in_array", "(", "$", "ext", ",", "self", "::", "$", "extensions", ",", "true", ")", "&&", "is_file", "(", "$", "file", ")", ")", "{", "switch", "(", "$", "ext", ")", "{", "case", "'html'", ":", "$", "res", "=", "$", "this", "->", "analyze_php", "(", "$", "file", ")", ";", "break", ";", "case", "'php'", ":", "$", "res", "=", "$", "this", "->", "analyze_php", "(", "$", "file", ")", ";", "break", ";", "case", "'js'", ":", "$", "res", "=", "$", "this", "->", "analyze_js", "(", "$", "file", ")", ";", "break", ";", "/*case 'json':\n $res = $this->analyze_json($file);\n break;*/", "}", "}", "return", "$", "res", ";", "}" ]
Returns the strings contained in the given file @param string $file @return array
[ "Returns", "the", "strings", "contained", "in", "the", "given", "file" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L129-L150
nabab/bbn
src/bbn/appui/i18n.php
i18n.analyze_folder
public function analyze_folder(string $folder = '.', bool $deep = false): array { $res = []; if ( \is_dir($folder) ){ $files = $deep ? bbn\file\dir::scan($folder, 'file') : bbn\file\dir::get_files($folder); foreach ( $files as $f ){ $words = $this->analyze_file($f); foreach ( $words as $word ){ if ( !isset($res[$word]) ){ $res[$word] = []; } if ( !in_array($f, $res[$word]) ){ $res[$word][] = $f; } } } } return $res; }
php
public function analyze_folder(string $folder = '.', bool $deep = false): array { $res = []; if ( \is_dir($folder) ){ $files = $deep ? bbn\file\dir::scan($folder, 'file') : bbn\file\dir::get_files($folder); foreach ( $files as $f ){ $words = $this->analyze_file($f); foreach ( $words as $word ){ if ( !isset($res[$word]) ){ $res[$word] = []; } if ( !in_array($f, $res[$word]) ){ $res[$word][] = $f; } } } } return $res; }
[ "public", "function", "analyze_folder", "(", "string", "$", "folder", "=", "'.'", ",", "bool", "$", "deep", "=", "false", ")", ":", "array", "{", "$", "res", "=", "[", "]", ";", "if", "(", "\\", "is_dir", "(", "$", "folder", ")", ")", "{", "$", "files", "=", "$", "deep", "?", "bbn", "\\", "file", "\\", "dir", "::", "scan", "(", "$", "folder", ",", "'file'", ")", ":", "bbn", "\\", "file", "\\", "dir", "::", "get_files", "(", "$", "folder", ")", ";", "foreach", "(", "$", "files", "as", "$", "f", ")", "{", "$", "words", "=", "$", "this", "->", "analyze_file", "(", "$", "f", ")", ";", "foreach", "(", "$", "words", "as", "$", "word", ")", "{", "if", "(", "!", "isset", "(", "$", "res", "[", "$", "word", "]", ")", ")", "{", "$", "res", "[", "$", "word", "]", "=", "[", "]", ";", "}", "if", "(", "!", "in_array", "(", "$", "f", ",", "$", "res", "[", "$", "word", "]", ")", ")", "{", "$", "res", "[", "$", "word", "]", "[", "]", "=", "$", "f", ";", "}", "}", "}", "}", "return", "$", "res", ";", "}" ]
Returns an array containing the strings found in the given folder @param string $folder @param boolean $deep @return array
[ "Returns", "an", "array", "containing", "the", "strings", "found", "in", "the", "given", "folder" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L159-L179
nabab/bbn
src/bbn/appui/i18n.php
i18n.get_id_project
public function get_id_project($id_option, $projects){ foreach( $projects as $i => $p ){ foreach ( $projects[$i]['path'] as $idx => $pa ){ if ( $projects[$i]['path'][$idx]['id_option'] === $id_option ){ return $projects[$i]['id']; } } } }
php
public function get_id_project($id_option, $projects){ foreach( $projects as $i => $p ){ foreach ( $projects[$i]['path'] as $idx => $pa ){ if ( $projects[$i]['path'][$idx]['id_option'] === $id_option ){ return $projects[$i]['id']; } } } }
[ "public", "function", "get_id_project", "(", "$", "id_option", ",", "$", "projects", ")", "{", "foreach", "(", "$", "projects", "as", "$", "i", "=>", "$", "p", ")", "{", "foreach", "(", "$", "projects", "[", "$", "i", "]", "[", "'path'", "]", "as", "$", "idx", "=>", "$", "pa", ")", "{", "if", "(", "$", "projects", "[", "$", "i", "]", "[", "'path'", "]", "[", "$", "idx", "]", "[", "'id_option'", "]", "===", "$", "id_option", ")", "{", "return", "$", "projects", "[", "$", "i", "]", "[", "'id'", "]", ";", "}", "}", "}", "}" ]
get the id of the project from the id_option of a path @param $id_option @param $projects @return void
[ "get", "the", "id", "of", "the", "project", "from", "the", "id_option", "of", "a", "path" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L204-L212
nabab/bbn
src/bbn/appui/i18n.php
i18n.get_primaries_langs
public function get_primaries_langs(){ $uid_languages = self::get_appui_option_id('languages'); $languages = options::get_instance()->full_tree($uid_languages); $primaries = array_values(array_filter($languages['items'], function($v) { return !empty($v['primary']); })); return $primaries; }
php
public function get_primaries_langs(){ $uid_languages = self::get_appui_option_id('languages'); $languages = options::get_instance()->full_tree($uid_languages); $primaries = array_values(array_filter($languages['items'], function($v) { return !empty($v['primary']); })); return $primaries; }
[ "public", "function", "get_primaries_langs", "(", ")", "{", "$", "uid_languages", "=", "self", "::", "get_appui_option_id", "(", "'languages'", ")", ";", "$", "languages", "=", "options", "::", "get_instance", "(", ")", "->", "full_tree", "(", "$", "uid_languages", ")", ";", "$", "primaries", "=", "array_values", "(", "array_filter", "(", "$", "languages", "[", "'items'", "]", ",", "function", "(", "$", "v", ")", "{", "return", "!", "empty", "(", "$", "v", "[", "'primary'", "]", ")", ";", "}", ")", ")", ";", "return", "$", "primaries", ";", "}" ]
Gets primaries langs from option @return void
[ "Gets", "primaries", "langs", "from", "option" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L231-L238
nabab/bbn
src/bbn/appui/i18n.php
i18n.get_num_options
public function get_num_options(){ /** @var $paths takes all options with i18n property setted*/ $paths = options::get_instance()->find_i18n(); $data = []; /** * creates the property data_widget that will have just num of items found for the option + 1 (the text of the option parent), the * * number of strings translated and the source language indexed to the language */ $primaries = $this->get_primaries_langs(); foreach ($primaries as $p ){ $configured_langs[] = $p['code']; } foreach ( $paths as $p => $val){ $parent = options::get_instance()->get_id_parent($paths[$p]['id']); foreach ( $configured_langs as $lang ) { $count = 0; $items = $paths[$p]['items']; /** push the text of the option into the array of strings */ $items[] = [ 'id' => $paths[$p]['id'], 'text' => $paths[$p]['text'], 'id_parent' => $parent ]; foreach ( $items as $idx => $item ){ if ( $id = $this->db->select_one('bbn_i18n', 'id', [ 'exp'=> $item['text'], 'lang' => $paths[$p]['language'] ])){ if ( $this->db->select_one('bbn_i18n_exp', 'id_exp', [ 'id_exp' => $id, 'lang' => $lang ]) ){ $count ++; } } } $paths[$p]['data_widget']['result'][$lang] = [ 'num' => count($items), 'num_translations' => $count, 'lang' => $lang ]; } $paths[$p]['data_widget']['locale_dirs'] = []; unset($paths[$p]['items']); $data[] = $paths[$p]; } return [ 'data'=> $data ]; }
php
public function get_num_options(){ /** @var $paths takes all options with i18n property setted*/ $paths = options::get_instance()->find_i18n(); $data = []; /** * creates the property data_widget that will have just num of items found for the option + 1 (the text of the option parent), the * * number of strings translated and the source language indexed to the language */ $primaries = $this->get_primaries_langs(); foreach ($primaries as $p ){ $configured_langs[] = $p['code']; } foreach ( $paths as $p => $val){ $parent = options::get_instance()->get_id_parent($paths[$p]['id']); foreach ( $configured_langs as $lang ) { $count = 0; $items = $paths[$p]['items']; /** push the text of the option into the array of strings */ $items[] = [ 'id' => $paths[$p]['id'], 'text' => $paths[$p]['text'], 'id_parent' => $parent ]; foreach ( $items as $idx => $item ){ if ( $id = $this->db->select_one('bbn_i18n', 'id', [ 'exp'=> $item['text'], 'lang' => $paths[$p]['language'] ])){ if ( $this->db->select_one('bbn_i18n_exp', 'id_exp', [ 'id_exp' => $id, 'lang' => $lang ]) ){ $count ++; } } } $paths[$p]['data_widget']['result'][$lang] = [ 'num' => count($items), 'num_translations' => $count, 'lang' => $lang ]; } $paths[$p]['data_widget']['locale_dirs'] = []; unset($paths[$p]['items']); $data[] = $paths[$p]; } return [ 'data'=> $data ]; }
[ "public", "function", "get_num_options", "(", ")", "{", "/** @var $paths takes all options with i18n property setted*/", "$", "paths", "=", "options", "::", "get_instance", "(", ")", "->", "find_i18n", "(", ")", ";", "$", "data", "=", "[", "]", ";", "/**\n * creates the property data_widget that will have just num of items found for the option + 1 (the text of the option parent), the * * number of strings translated and the source language indexed to the language\n */", "$", "primaries", "=", "$", "this", "->", "get_primaries_langs", "(", ")", ";", "foreach", "(", "$", "primaries", "as", "$", "p", ")", "{", "$", "configured_langs", "[", "]", "=", "$", "p", "[", "'code'", "]", ";", "}", "foreach", "(", "$", "paths", "as", "$", "p", "=>", "$", "val", ")", "{", "$", "parent", "=", "options", "::", "get_instance", "(", ")", "->", "get_id_parent", "(", "$", "paths", "[", "$", "p", "]", "[", "'id'", "]", ")", ";", "foreach", "(", "$", "configured_langs", "as", "$", "lang", ")", "{", "$", "count", "=", "0", ";", "$", "items", "=", "$", "paths", "[", "$", "p", "]", "[", "'items'", "]", ";", "/** push the text of the option into the array of strings */", "$", "items", "[", "]", "=", "[", "'id'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'id'", "]", ",", "'text'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'text'", "]", ",", "'id_parent'", "=>", "$", "parent", "]", ";", "foreach", "(", "$", "items", "as", "$", "idx", "=>", "$", "item", ")", "{", "if", "(", "$", "id", "=", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_i18n'", ",", "'id'", ",", "[", "'exp'", "=>", "$", "item", "[", "'text'", "]", ",", "'lang'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'language'", "]", "]", ")", ")", "{", "if", "(", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_i18n_exp'", ",", "'id_exp'", ",", "[", "'id_exp'", "=>", "$", "id", ",", "'lang'", "=>", "$", "lang", "]", ")", ")", "{", "$", "count", "++", ";", "}", "}", "}", "$", "paths", "[", "$", "p", "]", "[", "'data_widget'", "]", "[", "'result'", "]", "[", "$", "lang", "]", "=", "[", "'num'", "=>", "count", "(", "$", "items", ")", ",", "'num_translations'", "=>", "$", "count", ",", "'lang'", "=>", "$", "lang", "]", ";", "}", "$", "paths", "[", "$", "p", "]", "[", "'data_widget'", "]", "[", "'locale_dirs'", "]", "=", "[", "]", ";", "unset", "(", "$", "paths", "[", "$", "p", "]", "[", "'items'", "]", ")", ";", "$", "data", "[", "]", "=", "$", "paths", "[", "$", "p", "]", ";", "}", "return", "[", "'data'", "=>", "$", "data", "]", ";", "}" ]
get the num of items['text'] in original language and num translations foreach lang in configured langs (for this project uses all primaries as configured langs) @return void
[ "get", "the", "num", "of", "items", "[", "text", "]", "in", "original", "language", "and", "num", "translations", "foreach", "lang", "in", "configured", "langs", "(", "for", "this", "project", "uses", "all", "primaries", "as", "configured", "langs", ")" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L247-L298
nabab/bbn
src/bbn/appui/i18n.php
i18n.get_options
public function get_options(){ /** @var ( array) $paths get all options having i18n property setted and its items */ $paths = options::get_instance()->find_i18n(); $res = []; foreach ( $paths as $p => $val ){ $res[$p] = [ 'text'=> $paths[$p]['text'], 'opt_language' => $paths[$p]['language'], 'strings' => [], 'id_option' => $paths[$p]['id'] ]; /** @todo AT THE MOMENT I'M NOT CONSIDERING LANGUAGES OF TRANSLATION */ foreach ($paths[$p]['items'] as $i => $value){ /* check if the opt text is in bbn_i18n and takes translations from db */ if ( $exp = $this->db->rselect('bbn_i18n',['id', 'exp', 'lang'] , [ 'exp' => $paths[$p]['items'][$i]['text'], 'lang' => $paths[$p]['language'] ] ) ){ $translated = $this->db->rselect_all('bbn_i18n_exp', ['id_exp', 'expression', 'lang'], ['id_exp' => $exp['id'] ]); if ( !empty($translated) ){ /** @var $languages the array of languages found in db for the options*/ $languages = []; $translated_exp = ''; foreach ($translated as $t => $trans){ if ( !in_array($translated[$t]['lang'], $translated) ){ $languages[] = $translated[$t]['lang']; } $translated_exp = $translated[$t]['expression']; } if ( !empty($languages) ){ foreach($languages as $lang){ $res[$p]['strings'][] = [ $lang => [ 'id_exp' => $exp['id'], 'original' => $exp['exp'], 'translation_db' => $translated_exp ] ]; } } } } else { if ( $this->db->insert('bbn_i18n', [ 'exp' => $paths[$p]['items'][$i]['text'], 'lang' => $paths[$p]['language'], //'id_user'=> $this->user->get_id(), //'last_modified' => date('H-m-d H:i:s') ]) ){ $id = $this->db->last_id(); $this->db->insert_ignore( 'bbn_i18n_exp', [ 'id_exp' => $id, 'expression'=> $paths[$p]['items'][$i]['text'], 'lang' => $paths[$p]['language'] ] ); $res[$p]['strings'][] = [ $paths[$p]['language'] => [ 'id_exp' => $id, 'original' => $paths[$p]['items'][$i]['text'], 'translation_db' => $paths[$p]['items'][$i]['text'] ] ]; }; } } } return $res; }
php
public function get_options(){ /** @var ( array) $paths get all options having i18n property setted and its items */ $paths = options::get_instance()->find_i18n(); $res = []; foreach ( $paths as $p => $val ){ $res[$p] = [ 'text'=> $paths[$p]['text'], 'opt_language' => $paths[$p]['language'], 'strings' => [], 'id_option' => $paths[$p]['id'] ]; /** @todo AT THE MOMENT I'M NOT CONSIDERING LANGUAGES OF TRANSLATION */ foreach ($paths[$p]['items'] as $i => $value){ /* check if the opt text is in bbn_i18n and takes translations from db */ if ( $exp = $this->db->rselect('bbn_i18n',['id', 'exp', 'lang'] , [ 'exp' => $paths[$p]['items'][$i]['text'], 'lang' => $paths[$p]['language'] ] ) ){ $translated = $this->db->rselect_all('bbn_i18n_exp', ['id_exp', 'expression', 'lang'], ['id_exp' => $exp['id'] ]); if ( !empty($translated) ){ /** @var $languages the array of languages found in db for the options*/ $languages = []; $translated_exp = ''; foreach ($translated as $t => $trans){ if ( !in_array($translated[$t]['lang'], $translated) ){ $languages[] = $translated[$t]['lang']; } $translated_exp = $translated[$t]['expression']; } if ( !empty($languages) ){ foreach($languages as $lang){ $res[$p]['strings'][] = [ $lang => [ 'id_exp' => $exp['id'], 'original' => $exp['exp'], 'translation_db' => $translated_exp ] ]; } } } } else { if ( $this->db->insert('bbn_i18n', [ 'exp' => $paths[$p]['items'][$i]['text'], 'lang' => $paths[$p]['language'], //'id_user'=> $this->user->get_id(), //'last_modified' => date('H-m-d H:i:s') ]) ){ $id = $this->db->last_id(); $this->db->insert_ignore( 'bbn_i18n_exp', [ 'id_exp' => $id, 'expression'=> $paths[$p]['items'][$i]['text'], 'lang' => $paths[$p]['language'] ] ); $res[$p]['strings'][] = [ $paths[$p]['language'] => [ 'id_exp' => $id, 'original' => $paths[$p]['items'][$i]['text'], 'translation_db' => $paths[$p]['items'][$i]['text'] ] ]; }; } } } return $res; }
[ "public", "function", "get_options", "(", ")", "{", "/** @var ( array) $paths get all options having i18n property setted and its items */", "$", "paths", "=", "options", "::", "get_instance", "(", ")", "->", "find_i18n", "(", ")", ";", "$", "res", "=", "[", "]", ";", "foreach", "(", "$", "paths", "as", "$", "p", "=>", "$", "val", ")", "{", "$", "res", "[", "$", "p", "]", "=", "[", "'text'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'text'", "]", ",", "'opt_language'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'language'", "]", ",", "'strings'", "=>", "[", "]", ",", "'id_option'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'id'", "]", "]", ";", "/** @todo AT THE MOMENT I'M NOT CONSIDERING LANGUAGES OF TRANSLATION */", "foreach", "(", "$", "paths", "[", "$", "p", "]", "[", "'items'", "]", "as", "$", "i", "=>", "$", "value", ")", "{", "/* check if the opt text is in bbn_i18n and takes translations from db */", "if", "(", "$", "exp", "=", "$", "this", "->", "db", "->", "rselect", "(", "'bbn_i18n'", ",", "[", "'id'", ",", "'exp'", ",", "'lang'", "]", ",", "[", "'exp'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'items'", "]", "[", "$", "i", "]", "[", "'text'", "]", ",", "'lang'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'language'", "]", "]", ")", ")", "{", "$", "translated", "=", "$", "this", "->", "db", "->", "rselect_all", "(", "'bbn_i18n_exp'", ",", "[", "'id_exp'", ",", "'expression'", ",", "'lang'", "]", ",", "[", "'id_exp'", "=>", "$", "exp", "[", "'id'", "]", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "translated", ")", ")", "{", "/** @var $languages the array of languages found in db for the options*/", "$", "languages", "=", "[", "]", ";", "$", "translated_exp", "=", "''", ";", "foreach", "(", "$", "translated", "as", "$", "t", "=>", "$", "trans", ")", "{", "if", "(", "!", "in_array", "(", "$", "translated", "[", "$", "t", "]", "[", "'lang'", "]", ",", "$", "translated", ")", ")", "{", "$", "languages", "[", "]", "=", "$", "translated", "[", "$", "t", "]", "[", "'lang'", "]", ";", "}", "$", "translated_exp", "=", "$", "translated", "[", "$", "t", "]", "[", "'expression'", "]", ";", "}", "if", "(", "!", "empty", "(", "$", "languages", ")", ")", "{", "foreach", "(", "$", "languages", "as", "$", "lang", ")", "{", "$", "res", "[", "$", "p", "]", "[", "'strings'", "]", "[", "]", "=", "[", "$", "lang", "=>", "[", "'id_exp'", "=>", "$", "exp", "[", "'id'", "]", ",", "'original'", "=>", "$", "exp", "[", "'exp'", "]", ",", "'translation_db'", "=>", "$", "translated_exp", "]", "]", ";", "}", "}", "}", "}", "else", "{", "if", "(", "$", "this", "->", "db", "->", "insert", "(", "'bbn_i18n'", ",", "[", "'exp'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'items'", "]", "[", "$", "i", "]", "[", "'text'", "]", ",", "'lang'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'language'", "]", ",", "//'id_user'=> $this->user->get_id(),", "//'last_modified' => date('H-m-d H:i:s')", "]", ")", ")", "{", "$", "id", "=", "$", "this", "->", "db", "->", "last_id", "(", ")", ";", "$", "this", "->", "db", "->", "insert_ignore", "(", "'bbn_i18n_exp'", ",", "[", "'id_exp'", "=>", "$", "id", ",", "'expression'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'items'", "]", "[", "$", "i", "]", "[", "'text'", "]", ",", "'lang'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'language'", "]", "]", ")", ";", "$", "res", "[", "$", "p", "]", "[", "'strings'", "]", "[", "]", "=", "[", "$", "paths", "[", "$", "p", "]", "[", "'language'", "]", "=>", "[", "'id_exp'", "=>", "$", "id", ",", "'original'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'items'", "]", "[", "$", "i", "]", "[", "'text'", "]", ",", "'translation_db'", "=>", "$", "paths", "[", "$", "p", "]", "[", "'items'", "]", "[", "$", "i", "]", "[", "'text'", "]", "]", "]", ";", "}", ";", "}", "}", "}", "return", "$", "res", ";", "}" ]
Gets the option with the property i18n setted and its items @return void
[ "Gets", "the", "option", "with", "the", "property", "i18n", "setted", "and", "its", "items" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L307-L385
nabab/bbn
src/bbn/appui/i18n.php
i18n.get_translations_widget
public function get_translations_widget($id_project, $id_option) { $success = false; $result = []; $locale_dirs = []; if ( $id_option && ($o = options::get_instance()->option($id_option)) && !empty($o['language']) && ($parent = options::get_instance()->parent($id_option)) && defined($parent['code']) && isset($o['language']) ){ $domain = $o['text']; // @var $to_explore the path to explore $to_explore = constant($parent['code']); // @var $locale_dir the path to locale dir //exeption for apst_app, don't need the code if( (constant($parent['code']) === BBN_APP_PATH) && (strrpos('mvc/', $o['code'], 0) === 0) ) { $locale_dir = $to_explore.'locale'; } else{ $locale_dir = $to_explore.$o['code'].'locale'; } $domain .= is_file($locale_dir.'/index.txt') ? file_get_contents($locale_dir.'/index.txt') : ''; // @var $dirs scans dirs existing in locale folder for this path if ( is_dir($locale_dir) ){ // @var array $languages dirs in locale folder $dirs = \bbn\file\dir::get_dirs($locale_dir) ?: []; if(!empty($dirs)){ foreach ($dirs as $l ){ $languages[] = basename($l); } } } $new = 0; $i = 0; // @var array the languages found in locale dir if ( !empty($languages) ){ $result = []; foreach ( $languages as $lng ){ // the root to file po & mo $po = $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$domain.'.po'; $mo = $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$domain.'.mo'; // if a file po already exists takes its content if ( is_file($po) ){ $fileHandler = new \Sepia\PoParser\SourceHandler\FileSystem($po); $poParser = new \Sepia\PoParser\Parser($fileHandler); $Catalog = \Sepia\PoParser\Parser::parseFile($po); $num_translations = 0; if ( $translations = $Catalog->getEntries() ){ foreach( $translations as $tr ){ if ( $tr->getMsgStr() ){ $num_translations ++; } } $result[$lng] = [ 'num' => count($translations), 'num_translations' => $num_translations, 'lang' => $lng, 'num_translations_db' => $this->count_translations_db($id_option) ? $this->count_translations_db($id_option)[$lng] : 0 ]; } } // if the file po for the $lng doesn't exist $result is an empty object else{ if( !empty($this->count_translations_db($id_option)[$lng]) ){ $count_translations = $this->count_translations_db($id_option)[$lng]; } else{ $count_translations = 0; } $result[$lng] = [ 'num' => 0, 'num_translations' => 0, 'lang' => $lng, 'num_translations_db' => $count_translations ]; } } } $i++; $success = true; if ( !empty($languages) ){ $locale_dirs = $languages; } } return [ 'locale_dirs' => $locale_dirs, 'result' => $result, 'success' => $success, ]; }
php
public function get_translations_widget($id_project, $id_option) { $success = false; $result = []; $locale_dirs = []; if ( $id_option && ($o = options::get_instance()->option($id_option)) && !empty($o['language']) && ($parent = options::get_instance()->parent($id_option)) && defined($parent['code']) && isset($o['language']) ){ $domain = $o['text']; // @var $to_explore the path to explore $to_explore = constant($parent['code']); // @var $locale_dir the path to locale dir //exeption for apst_app, don't need the code if( (constant($parent['code']) === BBN_APP_PATH) && (strrpos('mvc/', $o['code'], 0) === 0) ) { $locale_dir = $to_explore.'locale'; } else{ $locale_dir = $to_explore.$o['code'].'locale'; } $domain .= is_file($locale_dir.'/index.txt') ? file_get_contents($locale_dir.'/index.txt') : ''; // @var $dirs scans dirs existing in locale folder for this path if ( is_dir($locale_dir) ){ // @var array $languages dirs in locale folder $dirs = \bbn\file\dir::get_dirs($locale_dir) ?: []; if(!empty($dirs)){ foreach ($dirs as $l ){ $languages[] = basename($l); } } } $new = 0; $i = 0; // @var array the languages found in locale dir if ( !empty($languages) ){ $result = []; foreach ( $languages as $lng ){ // the root to file po & mo $po = $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$domain.'.po'; $mo = $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$domain.'.mo'; // if a file po already exists takes its content if ( is_file($po) ){ $fileHandler = new \Sepia\PoParser\SourceHandler\FileSystem($po); $poParser = new \Sepia\PoParser\Parser($fileHandler); $Catalog = \Sepia\PoParser\Parser::parseFile($po); $num_translations = 0; if ( $translations = $Catalog->getEntries() ){ foreach( $translations as $tr ){ if ( $tr->getMsgStr() ){ $num_translations ++; } } $result[$lng] = [ 'num' => count($translations), 'num_translations' => $num_translations, 'lang' => $lng, 'num_translations_db' => $this->count_translations_db($id_option) ? $this->count_translations_db($id_option)[$lng] : 0 ]; } } // if the file po for the $lng doesn't exist $result is an empty object else{ if( !empty($this->count_translations_db($id_option)[$lng]) ){ $count_translations = $this->count_translations_db($id_option)[$lng]; } else{ $count_translations = 0; } $result[$lng] = [ 'num' => 0, 'num_translations' => 0, 'lang' => $lng, 'num_translations_db' => $count_translations ]; } } } $i++; $success = true; if ( !empty($languages) ){ $locale_dirs = $languages; } } return [ 'locale_dirs' => $locale_dirs, 'result' => $result, 'success' => $success, ]; }
[ "public", "function", "get_translations_widget", "(", "$", "id_project", ",", "$", "id_option", ")", "{", "$", "success", "=", "false", ";", "$", "result", "=", "[", "]", ";", "$", "locale_dirs", "=", "[", "]", ";", "if", "(", "$", "id_option", "&&", "(", "$", "o", "=", "options", "::", "get_instance", "(", ")", "->", "option", "(", "$", "id_option", ")", ")", "&&", "!", "empty", "(", "$", "o", "[", "'language'", "]", ")", "&&", "(", "$", "parent", "=", "options", "::", "get_instance", "(", ")", "->", "parent", "(", "$", "id_option", ")", ")", "&&", "defined", "(", "$", "parent", "[", "'code'", "]", ")", "&&", "isset", "(", "$", "o", "[", "'language'", "]", ")", ")", "{", "$", "domain", "=", "$", "o", "[", "'text'", "]", ";", "// @var $to_explore the path to explore ", "$", "to_explore", "=", "constant", "(", "$", "parent", "[", "'code'", "]", ")", ";", "// @var $locale_dir the path to locale dir ", "//exeption for apst_app, don't need the code", "if", "(", "(", "constant", "(", "$", "parent", "[", "'code'", "]", ")", "===", "BBN_APP_PATH", ")", "&&", "(", "strrpos", "(", "'mvc/'", ",", "$", "o", "[", "'code'", "]", ",", "0", ")", "===", "0", ")", ")", "{", "$", "locale_dir", "=", "$", "to_explore", ".", "'locale'", ";", "}", "else", "{", "$", "locale_dir", "=", "$", "to_explore", ".", "$", "o", "[", "'code'", "]", ".", "'locale'", ";", "}", "$", "domain", ".=", "is_file", "(", "$", "locale_dir", ".", "'/index.txt'", ")", "?", "file_get_contents", "(", "$", "locale_dir", ".", "'/index.txt'", ")", ":", "''", ";", "// @var $dirs scans dirs existing in locale folder for this path ", "if", "(", "is_dir", "(", "$", "locale_dir", ")", ")", "{", "// @var array $languages dirs in locale folder", "$", "dirs", "=", "\\", "bbn", "\\", "file", "\\", "dir", "::", "get_dirs", "(", "$", "locale_dir", ")", "?", ":", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "dirs", ")", ")", "{", "foreach", "(", "$", "dirs", "as", "$", "l", ")", "{", "$", "languages", "[", "]", "=", "basename", "(", "$", "l", ")", ";", "}", "}", "}", "$", "new", "=", "0", ";", "$", "i", "=", "0", ";", "// @var array the languages found in locale dir ", "if", "(", "!", "empty", "(", "$", "languages", ")", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "languages", "as", "$", "lng", ")", "{", "// the root to file po & mo ", "$", "po", "=", "$", "locale_dir", ".", "'/'", ".", "$", "lng", ".", "'/LC_MESSAGES/'", ".", "$", "domain", ".", "'.po'", ";", "$", "mo", "=", "$", "locale_dir", ".", "'/'", ".", "$", "lng", ".", "'/LC_MESSAGES/'", ".", "$", "domain", ".", "'.mo'", ";", "// if a file po already exists takes its content ", "if", "(", "is_file", "(", "$", "po", ")", ")", "{", "$", "fileHandler", "=", "new", "\\", "Sepia", "\\", "PoParser", "\\", "SourceHandler", "\\", "FileSystem", "(", "$", "po", ")", ";", "$", "poParser", "=", "new", "\\", "Sepia", "\\", "PoParser", "\\", "Parser", "(", "$", "fileHandler", ")", ";", "$", "Catalog", "=", "\\", "Sepia", "\\", "PoParser", "\\", "Parser", "::", "parseFile", "(", "$", "po", ")", ";", "$", "num_translations", "=", "0", ";", "if", "(", "$", "translations", "=", "$", "Catalog", "->", "getEntries", "(", ")", ")", "{", "foreach", "(", "$", "translations", "as", "$", "tr", ")", "{", "if", "(", "$", "tr", "->", "getMsgStr", "(", ")", ")", "{", "$", "num_translations", "++", ";", "}", "}", "$", "result", "[", "$", "lng", "]", "=", "[", "'num'", "=>", "count", "(", "$", "translations", ")", ",", "'num_translations'", "=>", "$", "num_translations", ",", "'lang'", "=>", "$", "lng", ",", "'num_translations_db'", "=>", "$", "this", "->", "count_translations_db", "(", "$", "id_option", ")", "?", "$", "this", "->", "count_translations_db", "(", "$", "id_option", ")", "[", "$", "lng", "]", ":", "0", "]", ";", "}", "}", "// if the file po for the $lng doesn't exist $result is an empty object ", "else", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "count_translations_db", "(", "$", "id_option", ")", "[", "$", "lng", "]", ")", ")", "{", "$", "count_translations", "=", "$", "this", "->", "count_translations_db", "(", "$", "id_option", ")", "[", "$", "lng", "]", ";", "}", "else", "{", "$", "count_translations", "=", "0", ";", "}", "$", "result", "[", "$", "lng", "]", "=", "[", "'num'", "=>", "0", ",", "'num_translations'", "=>", "0", ",", "'lang'", "=>", "$", "lng", ",", "'num_translations_db'", "=>", "$", "count_translations", "]", ";", "}", "}", "}", "$", "i", "++", ";", "$", "success", "=", "true", ";", "if", "(", "!", "empty", "(", "$", "languages", ")", ")", "{", "$", "locale_dirs", "=", "$", "languages", ";", "}", "}", "return", "[", "'locale_dirs'", "=>", "$", "locale_dirs", ",", "'result'", "=>", "$", "result", ",", "'success'", "=>", "$", "success", ",", "]", ";", "}" ]
Gets the widgets initial data @param [type] $id_project @param [type] $id_option @return void
[ "Gets", "the", "widgets", "initial", "data" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L404-L498
nabab/bbn
src/bbn/appui/i18n.php
i18n.get_po_files
public function get_po_files($id_option){ if (!empty($id_option) && ($o = options::get_instance()->option($id_option)) && ($parent = options::get_instance()->parent($id_option)) && defined($parent['code']) ){ $tmp = []; // @var $to_explore the path to explore $to_explore = constant($parent['code']).$o['code']; // @var $locale_dir locale dir in the path $locale_dir = dirname($to_explore).'/locale'; $dirs = \bbn\file\dir::get_dirs($locale_dir) ?: []; $languages = array_map(function($a){ return basename($a); }, $dirs) ?: []; if ( !empty($languages) ){ foreach ( $languages as $lng ){ // the path of po and mo files $idx = is_file($locale_dir.'/index.txt') ? file_get_contents($locale_dir.'/index.txt') : ''; if ( is_file($locale_dir.'/'.$lng.'/LC_MESSAGES/'.$o['text'].$idx.'.po') ){ $tmp[$lng]= $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$o['text'].$idx.'.po'; } } } return $tmp; } }
php
public function get_po_files($id_option){ if (!empty($id_option) && ($o = options::get_instance()->option($id_option)) && ($parent = options::get_instance()->parent($id_option)) && defined($parent['code']) ){ $tmp = []; // @var $to_explore the path to explore $to_explore = constant($parent['code']).$o['code']; // @var $locale_dir locale dir in the path $locale_dir = dirname($to_explore).'/locale'; $dirs = \bbn\file\dir::get_dirs($locale_dir) ?: []; $languages = array_map(function($a){ return basename($a); }, $dirs) ?: []; if ( !empty($languages) ){ foreach ( $languages as $lng ){ // the path of po and mo files $idx = is_file($locale_dir.'/index.txt') ? file_get_contents($locale_dir.'/index.txt') : ''; if ( is_file($locale_dir.'/'.$lng.'/LC_MESSAGES/'.$o['text'].$idx.'.po') ){ $tmp[$lng]= $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$o['text'].$idx.'.po'; } } } return $tmp; } }
[ "public", "function", "get_po_files", "(", "$", "id_option", ")", "{", "if", "(", "!", "empty", "(", "$", "id_option", ")", "&&", "(", "$", "o", "=", "options", "::", "get_instance", "(", ")", "->", "option", "(", "$", "id_option", ")", ")", "&&", "(", "$", "parent", "=", "options", "::", "get_instance", "(", ")", "->", "parent", "(", "$", "id_option", ")", ")", "&&", "defined", "(", "$", "parent", "[", "'code'", "]", ")", ")", "{", "$", "tmp", "=", "[", "]", ";", "// @var $to_explore the path to explore ", "$", "to_explore", "=", "constant", "(", "$", "parent", "[", "'code'", "]", ")", ".", "$", "o", "[", "'code'", "]", ";", "// @var $locale_dir locale dir in the path", "$", "locale_dir", "=", "dirname", "(", "$", "to_explore", ")", ".", "'/locale'", ";", "$", "dirs", "=", "\\", "bbn", "\\", "file", "\\", "dir", "::", "get_dirs", "(", "$", "locale_dir", ")", "?", ":", "[", "]", ";", "$", "languages", "=", "array_map", "(", "function", "(", "$", "a", ")", "{", "return", "basename", "(", "$", "a", ")", ";", "}", ",", "$", "dirs", ")", "?", ":", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "languages", ")", ")", "{", "foreach", "(", "$", "languages", "as", "$", "lng", ")", "{", "// the path of po and mo files ", "$", "idx", "=", "is_file", "(", "$", "locale_dir", ".", "'/index.txt'", ")", "?", "file_get_contents", "(", "$", "locale_dir", ".", "'/index.txt'", ")", ":", "''", ";", "if", "(", "is_file", "(", "$", "locale_dir", ".", "'/'", ".", "$", "lng", ".", "'/LC_MESSAGES/'", ".", "$", "o", "[", "'text'", "]", ".", "$", "idx", ".", "'.po'", ")", ")", "{", "$", "tmp", "[", "$", "lng", "]", "=", "$", "locale_dir", ".", "'/'", ".", "$", "lng", ".", "'/LC_MESSAGES/'", ".", "$", "o", "[", "'text'", "]", ".", "$", "idx", ".", "'.po'", ";", "}", "}", "}", "return", "$", "tmp", ";", "}", "}" ]
Returns an array containing the po files found for the id_option @param $id_option @return void
[ "Returns", "an", "array", "containing", "the", "po", "files", "found", "for", "the", "id_option" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L506-L534
nabab/bbn
src/bbn/appui/i18n.php
i18n.count_translations_db
public function count_translations_db($id_option){ $count = []; $po = $this->get_po_files($id_option); if (!empty($po)){ foreach ($po as $lang => $file) { $fileHandler = new \Sepia\PoParser\SourceHandler\FileSystem($file); $poParser = new \Sepia\PoParser\Parser($fileHandler); $Catalog = \Sepia\PoParser\Parser::parseFile($file); $fromPo = $Catalog->getEntries(); $source_language = $this->get_language($id_option); $count[$lang] = 0; foreach( $fromPo as $o ){ if ( $exp = $o->getMsgId() ){ $id = $this->db->select_one('bbn_i18n', 'id', ['exp' => $exp, 'lang' => $source_language]); if ( $string = $this->db->select_one('bbn_i18n_exp', 'expression', [ 'id_exp' => $id, 'lang' => $lang ]) ){ $count[$lang]++; } } } } } return $count; }
php
public function count_translations_db($id_option){ $count = []; $po = $this->get_po_files($id_option); if (!empty($po)){ foreach ($po as $lang => $file) { $fileHandler = new \Sepia\PoParser\SourceHandler\FileSystem($file); $poParser = new \Sepia\PoParser\Parser($fileHandler); $Catalog = \Sepia\PoParser\Parser::parseFile($file); $fromPo = $Catalog->getEntries(); $source_language = $this->get_language($id_option); $count[$lang] = 0; foreach( $fromPo as $o ){ if ( $exp = $o->getMsgId() ){ $id = $this->db->select_one('bbn_i18n', 'id', ['exp' => $exp, 'lang' => $source_language]); if ( $string = $this->db->select_one('bbn_i18n_exp', 'expression', [ 'id_exp' => $id, 'lang' => $lang ]) ){ $count[$lang]++; } } } } } return $count; }
[ "public", "function", "count_translations_db", "(", "$", "id_option", ")", "{", "$", "count", "=", "[", "]", ";", "$", "po", "=", "$", "this", "->", "get_po_files", "(", "$", "id_option", ")", ";", "if", "(", "!", "empty", "(", "$", "po", ")", ")", "{", "foreach", "(", "$", "po", "as", "$", "lang", "=>", "$", "file", ")", "{", "$", "fileHandler", "=", "new", "\\", "Sepia", "\\", "PoParser", "\\", "SourceHandler", "\\", "FileSystem", "(", "$", "file", ")", ";", "$", "poParser", "=", "new", "\\", "Sepia", "\\", "PoParser", "\\", "Parser", "(", "$", "fileHandler", ")", ";", "$", "Catalog", "=", "\\", "Sepia", "\\", "PoParser", "\\", "Parser", "::", "parseFile", "(", "$", "file", ")", ";", "$", "fromPo", "=", "$", "Catalog", "->", "getEntries", "(", ")", ";", "$", "source_language", "=", "$", "this", "->", "get_language", "(", "$", "id_option", ")", ";", "$", "count", "[", "$", "lang", "]", "=", "0", ";", "foreach", "(", "$", "fromPo", "as", "$", "o", ")", "{", "if", "(", "$", "exp", "=", "$", "o", "->", "getMsgId", "(", ")", ")", "{", "$", "id", "=", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_i18n'", ",", "'id'", ",", "[", "'exp'", "=>", "$", "exp", ",", "'lang'", "=>", "$", "source_language", "]", ")", ";", "if", "(", "$", "string", "=", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_i18n_exp'", ",", "'expression'", ",", "[", "'id_exp'", "=>", "$", "id", ",", "'lang'", "=>", "$", "lang", "]", ")", ")", "{", "$", "count", "[", "$", "lang", "]", "++", ";", "}", "}", "}", "}", "}", "return", "$", "count", ";", "}" ]
Count how many of the strings contained in po files are already in database @param [type] $id_option @return void
[ "Count", "how", "many", "of", "the", "strings", "contained", "in", "po", "files", "are", "already", "in", "database" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L542-L572
nabab/bbn
src/bbn/appui/i18n.php
i18n.get_translations_strings
public function get_translations_strings($id_option, $source_language, $languages){ if ( !empty($id_option) && !empty($source_language) && ($o = options::get_instance()->option($id_option)) && ($parent = options::get_instance()->option($o['id_parent'])) && \defined($parent['code']) ){ // @var string $to_explore The path to explore path of mvc $to_explore = \constant($parent['code']).($o['code'] === '/' ? '' : $o['code']); $current_path = \constant($parent['code']); if ( constant($parent['code']) === BBN_APP_PATH ){ $current_dirs = bbn\file\dir::get_dirs( constant($parent['code']).($o['code'] === '/' ? '' : $o['code'])); } //all dirs contained in current if not in vendor if ( constant($parent['code']) === BBN_LIB_PATH ){ //case of plugins $src = mb_substr($current_path.$o['code'], 0,-4); $current_dirs = bbn\file\dir::get_dirs($src); } else if ( constant($parent['code']) === BBN_CDN_PATH ){ //case javascript and styles project apst $current_dirs[] = constant($parent['code']).$o['code']; } $to_explore_dirs = []; //creates the array $to_explore_dirs containing mvc, plugins e components if ( !empty($current_dirs) ){ foreach ($current_dirs as $key => $value) { if( constant($parent['code']) === BBN_APP_PATH ){ if (( strpos($value, 'locale') !== 0 ) && ( strpos($value, 'data') !== 0 ) && ( strpos($value, '.') !== 0 )){ $to_explore_dirs = $current_dirs; } } if ( constant($parent['code']) === BBN_CDN_PATH ){ $to_explore_dirs[] = $current_dirs; } else if ( $parent['code'] === 'BBN_LIB_PATH' ){ //case of plugins appui $to_explore_dirs[] = $current_dirs[$key]; } } } // @var $locale_dir the root of locale dir for this id_option $locale_dir = dirname($to_explore).'/locale'; // @var $dirs scans dirs contained in locale folder of this path $res = []; //case of generate called from table if ( empty($languages) ){ /** @var (array) $languages based on locale dirs found in the path*/ $languages = array_map(function($a){ return basename($a); }, \bbn\file\dir::get_dirs($locale_dir)) ?: []; } if ( !empty($to_explore_dirs) && ($parent['code'] !== 'BBN_CDN_PATH' )){ foreach ( $to_explore_dirs as $c ){ $res[] = $this->analyze_folder($c, true); } } else if( ( $parent['code'] === 'BBN_CDN_PATH' ) && (!empty($current_dirs)) ){ foreach($current_dirs as $c ){ $res[] = $this->analyze_folder($c, true); } } //all strings found in the different dirs $to_explore_dirs, merge all index of $res if(!empty($res)){ $res = array_merge(...$res); } $news = []; $done = 0; foreach ( $res as $r => $val ){ // for each string create a property 'path' containing the files' name in which the string is contained $res[$r] = ['path' => $val]; // checks if the table bbn_i18n of db already contains the string $r for this $source_lang if ( !($id = $this->db->select_one('bbn_i18n', 'id', [ 'exp' => $r, 'lang' => $source_language ])) ){ // if the string $r is not in 'bbn_i18n' inserts the string $this->db->insert_ignore('bbn_i18n', [ 'exp' => $r, 'lang' => $source_language, ]); $id = $this->db->last_id(); } // create the property 'id_exp' for the string $r $res[$r]['id_exp'] = $id; // puts the string $r into the property 'original_exp' (I'll use only array_values at the end) * $res[$r]['original_exp'] = $r; // checks in 'bbn_i18n_exp' if the string $r already exist for this $source_lang if( !( $id_exp = $this->db->select_one('bbn_i18n_exp', 'id_exp', [ 'id_exp' => $id, 'lang' => $source_language ]) ) ){ // if the string $r is not in 'bbn_i18n_exp' inserts the string // $done will be the number of strings found in the folder $to_explore that haven't been found in the table // 'bbn_i18n_exp' of db, so $done is the number of new strings inserted in in 'bbn_i18n_exp' $done += (int)$this->db->insert_ignore('bbn_i18n_exp', [ 'id_exp' => $id, 'lang' => $source_language, 'expression' => $r ]); //creates an array of new strings found in the folder; $news[] = $r; } // $languages is the array of languages existing in locale dir foreach ( $languages as $lng ){ // create a property indexed to the code of $lng containing the string $r from 'bbn_i18n_exp' in this $lng $res[$r][$lng] = (string)$this->db->select_one( 'bbn_i18n_exp', 'expression', [ 'id_exp' => $id, 'lang' => $lng ] ); } } return [ 'news' => $news, 'id_option' => $id_option, 'res' => array_values($res), 'done' => $done, 'languages' => $languages, 'path' => $to_explore, 'success' => true ]; } }
php
public function get_translations_strings($id_option, $source_language, $languages){ if ( !empty($id_option) && !empty($source_language) && ($o = options::get_instance()->option($id_option)) && ($parent = options::get_instance()->option($o['id_parent'])) && \defined($parent['code']) ){ // @var string $to_explore The path to explore path of mvc $to_explore = \constant($parent['code']).($o['code'] === '/' ? '' : $o['code']); $current_path = \constant($parent['code']); if ( constant($parent['code']) === BBN_APP_PATH ){ $current_dirs = bbn\file\dir::get_dirs( constant($parent['code']).($o['code'] === '/' ? '' : $o['code'])); } //all dirs contained in current if not in vendor if ( constant($parent['code']) === BBN_LIB_PATH ){ //case of plugins $src = mb_substr($current_path.$o['code'], 0,-4); $current_dirs = bbn\file\dir::get_dirs($src); } else if ( constant($parent['code']) === BBN_CDN_PATH ){ //case javascript and styles project apst $current_dirs[] = constant($parent['code']).$o['code']; } $to_explore_dirs = []; //creates the array $to_explore_dirs containing mvc, plugins e components if ( !empty($current_dirs) ){ foreach ($current_dirs as $key => $value) { if( constant($parent['code']) === BBN_APP_PATH ){ if (( strpos($value, 'locale') !== 0 ) && ( strpos($value, 'data') !== 0 ) && ( strpos($value, '.') !== 0 )){ $to_explore_dirs = $current_dirs; } } if ( constant($parent['code']) === BBN_CDN_PATH ){ $to_explore_dirs[] = $current_dirs; } else if ( $parent['code'] === 'BBN_LIB_PATH' ){ //case of plugins appui $to_explore_dirs[] = $current_dirs[$key]; } } } // @var $locale_dir the root of locale dir for this id_option $locale_dir = dirname($to_explore).'/locale'; // @var $dirs scans dirs contained in locale folder of this path $res = []; //case of generate called from table if ( empty($languages) ){ /** @var (array) $languages based on locale dirs found in the path*/ $languages = array_map(function($a){ return basename($a); }, \bbn\file\dir::get_dirs($locale_dir)) ?: []; } if ( !empty($to_explore_dirs) && ($parent['code'] !== 'BBN_CDN_PATH' )){ foreach ( $to_explore_dirs as $c ){ $res[] = $this->analyze_folder($c, true); } } else if( ( $parent['code'] === 'BBN_CDN_PATH' ) && (!empty($current_dirs)) ){ foreach($current_dirs as $c ){ $res[] = $this->analyze_folder($c, true); } } //all strings found in the different dirs $to_explore_dirs, merge all index of $res if(!empty($res)){ $res = array_merge(...$res); } $news = []; $done = 0; foreach ( $res as $r => $val ){ // for each string create a property 'path' containing the files' name in which the string is contained $res[$r] = ['path' => $val]; // checks if the table bbn_i18n of db already contains the string $r for this $source_lang if ( !($id = $this->db->select_one('bbn_i18n', 'id', [ 'exp' => $r, 'lang' => $source_language ])) ){ // if the string $r is not in 'bbn_i18n' inserts the string $this->db->insert_ignore('bbn_i18n', [ 'exp' => $r, 'lang' => $source_language, ]); $id = $this->db->last_id(); } // create the property 'id_exp' for the string $r $res[$r]['id_exp'] = $id; // puts the string $r into the property 'original_exp' (I'll use only array_values at the end) * $res[$r]['original_exp'] = $r; // checks in 'bbn_i18n_exp' if the string $r already exist for this $source_lang if( !( $id_exp = $this->db->select_one('bbn_i18n_exp', 'id_exp', [ 'id_exp' => $id, 'lang' => $source_language ]) ) ){ // if the string $r is not in 'bbn_i18n_exp' inserts the string // $done will be the number of strings found in the folder $to_explore that haven't been found in the table // 'bbn_i18n_exp' of db, so $done is the number of new strings inserted in in 'bbn_i18n_exp' $done += (int)$this->db->insert_ignore('bbn_i18n_exp', [ 'id_exp' => $id, 'lang' => $source_language, 'expression' => $r ]); //creates an array of new strings found in the folder; $news[] = $r; } // $languages is the array of languages existing in locale dir foreach ( $languages as $lng ){ // create a property indexed to the code of $lng containing the string $r from 'bbn_i18n_exp' in this $lng $res[$r][$lng] = (string)$this->db->select_one( 'bbn_i18n_exp', 'expression', [ 'id_exp' => $id, 'lang' => $lng ] ); } } return [ 'news' => $news, 'id_option' => $id_option, 'res' => array_values($res), 'done' => $done, 'languages' => $languages, 'path' => $to_explore, 'success' => true ]; } }
[ "public", "function", "get_translations_strings", "(", "$", "id_option", ",", "$", "source_language", ",", "$", "languages", ")", "{", "if", "(", "!", "empty", "(", "$", "id_option", ")", "&&", "!", "empty", "(", "$", "source_language", ")", "&&", "(", "$", "o", "=", "options", "::", "get_instance", "(", ")", "->", "option", "(", "$", "id_option", ")", ")", "&&", "(", "$", "parent", "=", "options", "::", "get_instance", "(", ")", "->", "option", "(", "$", "o", "[", "'id_parent'", "]", ")", ")", "&&", "\\", "defined", "(", "$", "parent", "[", "'code'", "]", ")", ")", "{", "// @var string $to_explore The path to explore path of mvc ", "$", "to_explore", "=", "\\", "constant", "(", "$", "parent", "[", "'code'", "]", ")", ".", "(", "$", "o", "[", "'code'", "]", "===", "'/'", "?", "''", ":", "$", "o", "[", "'code'", "]", ")", ";", "$", "current_path", "=", "\\", "constant", "(", "$", "parent", "[", "'code'", "]", ")", ";", "if", "(", "constant", "(", "$", "parent", "[", "'code'", "]", ")", "===", "BBN_APP_PATH", ")", "{", "$", "current_dirs", "=", "bbn", "\\", "file", "\\", "dir", "::", "get_dirs", "(", "constant", "(", "$", "parent", "[", "'code'", "]", ")", ".", "(", "$", "o", "[", "'code'", "]", "===", "'/'", "?", "''", ":", "$", "o", "[", "'code'", "]", ")", ")", ";", "}", "//all dirs contained in current if not in vendor", "if", "(", "constant", "(", "$", "parent", "[", "'code'", "]", ")", "===", "BBN_LIB_PATH", ")", "{", "//case of plugins", "$", "src", "=", "mb_substr", "(", "$", "current_path", ".", "$", "o", "[", "'code'", "]", ",", "0", ",", "-", "4", ")", ";", "$", "current_dirs", "=", "bbn", "\\", "file", "\\", "dir", "::", "get_dirs", "(", "$", "src", ")", ";", "}", "else", "if", "(", "constant", "(", "$", "parent", "[", "'code'", "]", ")", "===", "BBN_CDN_PATH", ")", "{", "//case javascript and styles project apst", "$", "current_dirs", "[", "]", "=", "constant", "(", "$", "parent", "[", "'code'", "]", ")", ".", "$", "o", "[", "'code'", "]", ";", "}", "$", "to_explore_dirs", "=", "[", "]", ";", "//creates the array $to_explore_dirs containing mvc, plugins e components", "if", "(", "!", "empty", "(", "$", "current_dirs", ")", ")", "{", "foreach", "(", "$", "current_dirs", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "constant", "(", "$", "parent", "[", "'code'", "]", ")", "===", "BBN_APP_PATH", ")", "{", "if", "(", "(", "strpos", "(", "$", "value", ",", "'locale'", ")", "!==", "0", ")", "&&", "(", "strpos", "(", "$", "value", ",", "'data'", ")", "!==", "0", ")", "&&", "(", "strpos", "(", "$", "value", ",", "'.'", ")", "!==", "0", ")", ")", "{", "$", "to_explore_dirs", "=", "$", "current_dirs", ";", "}", "}", "if", "(", "constant", "(", "$", "parent", "[", "'code'", "]", ")", "===", "BBN_CDN_PATH", ")", "{", "$", "to_explore_dirs", "[", "]", "=", "$", "current_dirs", ";", "}", "else", "if", "(", "$", "parent", "[", "'code'", "]", "===", "'BBN_LIB_PATH'", ")", "{", "//case of plugins appui", "$", "to_explore_dirs", "[", "]", "=", "$", "current_dirs", "[", "$", "key", "]", ";", "}", "}", "}", "// @var $locale_dir the root of locale dir for this id_option", "$", "locale_dir", "=", "dirname", "(", "$", "to_explore", ")", ".", "'/locale'", ";", "// @var $dirs scans dirs contained in locale folder of this path", "$", "res", "=", "[", "]", ";", "//case of generate called from table", "if", "(", "empty", "(", "$", "languages", ")", ")", "{", "/** @var (array) $languages based on locale dirs found in the path*/", "$", "languages", "=", "array_map", "(", "function", "(", "$", "a", ")", "{", "return", "basename", "(", "$", "a", ")", ";", "}", ",", "\\", "bbn", "\\", "file", "\\", "dir", "::", "get_dirs", "(", "$", "locale_dir", ")", ")", "?", ":", "[", "]", ";", "}", "if", "(", "!", "empty", "(", "$", "to_explore_dirs", ")", "&&", "(", "$", "parent", "[", "'code'", "]", "!==", "'BBN_CDN_PATH'", ")", ")", "{", "foreach", "(", "$", "to_explore_dirs", "as", "$", "c", ")", "{", "$", "res", "[", "]", "=", "$", "this", "->", "analyze_folder", "(", "$", "c", ",", "true", ")", ";", "}", "}", "else", "if", "(", "(", "$", "parent", "[", "'code'", "]", "===", "'BBN_CDN_PATH'", ")", "&&", "(", "!", "empty", "(", "$", "current_dirs", ")", ")", ")", "{", "foreach", "(", "$", "current_dirs", "as", "$", "c", ")", "{", "$", "res", "[", "]", "=", "$", "this", "->", "analyze_folder", "(", "$", "c", ",", "true", ")", ";", "}", "}", "//all strings found in the different dirs $to_explore_dirs, merge all index of $res", "if", "(", "!", "empty", "(", "$", "res", ")", ")", "{", "$", "res", "=", "array_merge", "(", "...", "$", "res", ")", ";", "}", "$", "news", "=", "[", "]", ";", "$", "done", "=", "0", ";", "foreach", "(", "$", "res", "as", "$", "r", "=>", "$", "val", ")", "{", "// for each string create a property 'path' containing the files' name in which the string is contained ", "$", "res", "[", "$", "r", "]", "=", "[", "'path'", "=>", "$", "val", "]", ";", "// checks if the table bbn_i18n of db already contains the string $r for this $source_lang ", "if", "(", "!", "(", "$", "id", "=", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_i18n'", ",", "'id'", ",", "[", "'exp'", "=>", "$", "r", ",", "'lang'", "=>", "$", "source_language", "]", ")", ")", ")", "{", "// if the string $r is not in 'bbn_i18n' inserts the string ", "$", "this", "->", "db", "->", "insert_ignore", "(", "'bbn_i18n'", ",", "[", "'exp'", "=>", "$", "r", ",", "'lang'", "=>", "$", "source_language", ",", "]", ")", ";", "$", "id", "=", "$", "this", "->", "db", "->", "last_id", "(", ")", ";", "}", "// create the property 'id_exp' for the string $r ", "$", "res", "[", "$", "r", "]", "[", "'id_exp'", "]", "=", "$", "id", ";", "// puts the string $r into the property 'original_exp' (I'll use only array_values at the end) *", "$", "res", "[", "$", "r", "]", "[", "'original_exp'", "]", "=", "$", "r", ";", "// checks in 'bbn_i18n_exp' if the string $r already exist for this $source_lang ", "if", "(", "!", "(", "$", "id_exp", "=", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_i18n_exp'", ",", "'id_exp'", ",", "[", "'id_exp'", "=>", "$", "id", ",", "'lang'", "=>", "$", "source_language", "]", ")", ")", ")", "{", "// if the string $r is not in 'bbn_i18n_exp' inserts the string", "// $done will be the number of strings found in the folder $to_explore that haven't been found in the table", "// 'bbn_i18n_exp' of db, so $done is the number of new strings inserted in in 'bbn_i18n_exp'", "$", "done", "+=", "(", "int", ")", "$", "this", "->", "db", "->", "insert_ignore", "(", "'bbn_i18n_exp'", ",", "[", "'id_exp'", "=>", "$", "id", ",", "'lang'", "=>", "$", "source_language", ",", "'expression'", "=>", "$", "r", "]", ")", ";", "//creates an array of new strings found in the folder;", "$", "news", "[", "]", "=", "$", "r", ";", "}", "// $languages is the array of languages existing in locale dir", "foreach", "(", "$", "languages", "as", "$", "lng", ")", "{", "// create a property indexed to the code of $lng containing the string $r from 'bbn_i18n_exp' in this $lng ", "$", "res", "[", "$", "r", "]", "[", "$", "lng", "]", "=", "(", "string", ")", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_i18n_exp'", ",", "'expression'", ",", "[", "'id_exp'", "=>", "$", "id", ",", "'lang'", "=>", "$", "lng", "]", ")", ";", "}", "}", "return", "[", "'news'", "=>", "$", "news", ",", "'id_option'", "=>", "$", "id_option", ",", "'res'", "=>", "array_values", "(", "$", "res", ")", ",", "'done'", "=>", "$", "done", ",", "'languages'", "=>", "$", "languages", ",", "'path'", "=>", "$", "to_explore", ",", "'success'", "=>", "true", "]", ";", "}", "}" ]
Returns the strings contained in the given path @param $id_option @param $source_language @param $languages @return void
[ "Returns", "the", "strings", "contained", "in", "the", "given", "path" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L582-L730
nabab/bbn
src/bbn/appui/i18n.php
i18n.get_translations_table
public function get_translations_table($id_project, $id_option){ if ( !empty($id_option) && ($o = options::get_instance()->option($id_option)) && ($parent = options::get_instance()->parent($id_option)) && defined($parent['code']) ){ // @var $path_source_lang the property language of the id_option (the path) $path_source_lang = options::get_instance()->get_prop($id_option, 'language'); // @var $to_explore the path to explore $to_explore = constant($parent['code']); //exeption for apst_app, don't need the code if( (constant($parent['code']) === BBN_APP_PATH) && (strrpos('mvc/', $o['code'], 0) === 0) ) { $locale_dir = $to_explore.'locale'; } else{ $locale_dir = $to_explore.$o['code'].'locale'; } $languages = array_map(function($a){ return basename($a); }, \bbn\file\dir::get_dirs($locale_dir)) ?: []; $i = 0; $res = []; $project = new bbn\appui\project($this->db, $id_project); if ( !empty($languages) ){ $po_file = []; $success = false; foreach ( $languages as $lng ){ // the path of po and mo files $idx = is_file($locale_dir.'/index.txt') ? file_get_contents($locale_dir.'/index.txt') : ''; $po = $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$o['text'].$idx.'.po'; $mo = $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$o['text'].$idx.'.mo'; // if the file po exist takes its content if (file_exists($po)){ $fileHandler = new \Sepia\PoParser\SourceHandler\FileSystem($po); $poParser = new \Sepia\PoParser\Parser($fileHandler); $Catalog = \Sepia\PoParser\Parser::parseFile($po); if ( !empty( $translations = $Catalog->getEntries() ) ){ foreach ($translations as $i => $t ){ // @var $original the original expression $original = $t->getMsgId(); $po_file[$i][$lng]['original'] = $original; // the translation of the string found in the po file $po_file[$i][$lng]['translations_po'] = $t->getMsgStr(); // @var $id takes the id of the original expression in db if ( $id = $this->db->select_one('bbn_i18n', 'id', [ 'exp' => $original, 'lang' => $path_source_lang ]) ){ $po_file[$i][$lng]['translations_db'] = $this->db->select_one('bbn_i18n_exp', 'expression', ['id_exp' => $id, 'lang' => $lng]); // the id of the string $po_file[$i][$lng]['id_exp'] = $id; // @var (array) takes $paths of files in which the string was found from the file po $paths = $t->getReference(); // get the url to use it for the link to ide from the table foreach ( $paths as $p ){ $po_file[$i][$lng]['paths'][] = $project->real_to_url_i18n($p); } // the number of times the strings is found in the files of the path $po_file[$i][$lng]['occurrence'] = !empty($po_file[$i][$path_source_lang]) ? count($po_file[$i][$path_source_lang]['paths']) : 0; }; } $success = true; } } } } return [ 'path_source_lang' => $path_source_lang, 'path' => $o['text'], 'success' => $success, 'languages' => $languages, 'total' => count(array_values($po_file)), 'strings' => array_values($po_file), 'id_option' => $id_option, ]; } }
php
public function get_translations_table($id_project, $id_option){ if ( !empty($id_option) && ($o = options::get_instance()->option($id_option)) && ($parent = options::get_instance()->parent($id_option)) && defined($parent['code']) ){ // @var $path_source_lang the property language of the id_option (the path) $path_source_lang = options::get_instance()->get_prop($id_option, 'language'); // @var $to_explore the path to explore $to_explore = constant($parent['code']); //exeption for apst_app, don't need the code if( (constant($parent['code']) === BBN_APP_PATH) && (strrpos('mvc/', $o['code'], 0) === 0) ) { $locale_dir = $to_explore.'locale'; } else{ $locale_dir = $to_explore.$o['code'].'locale'; } $languages = array_map(function($a){ return basename($a); }, \bbn\file\dir::get_dirs($locale_dir)) ?: []; $i = 0; $res = []; $project = new bbn\appui\project($this->db, $id_project); if ( !empty($languages) ){ $po_file = []; $success = false; foreach ( $languages as $lng ){ // the path of po and mo files $idx = is_file($locale_dir.'/index.txt') ? file_get_contents($locale_dir.'/index.txt') : ''; $po = $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$o['text'].$idx.'.po'; $mo = $locale_dir.'/'.$lng.'/LC_MESSAGES/'.$o['text'].$idx.'.mo'; // if the file po exist takes its content if (file_exists($po)){ $fileHandler = new \Sepia\PoParser\SourceHandler\FileSystem($po); $poParser = new \Sepia\PoParser\Parser($fileHandler); $Catalog = \Sepia\PoParser\Parser::parseFile($po); if ( !empty( $translations = $Catalog->getEntries() ) ){ foreach ($translations as $i => $t ){ // @var $original the original expression $original = $t->getMsgId(); $po_file[$i][$lng]['original'] = $original; // the translation of the string found in the po file $po_file[$i][$lng]['translations_po'] = $t->getMsgStr(); // @var $id takes the id of the original expression in db if ( $id = $this->db->select_one('bbn_i18n', 'id', [ 'exp' => $original, 'lang' => $path_source_lang ]) ){ $po_file[$i][$lng]['translations_db'] = $this->db->select_one('bbn_i18n_exp', 'expression', ['id_exp' => $id, 'lang' => $lng]); // the id of the string $po_file[$i][$lng]['id_exp'] = $id; // @var (array) takes $paths of files in which the string was found from the file po $paths = $t->getReference(); // get the url to use it for the link to ide from the table foreach ( $paths as $p ){ $po_file[$i][$lng]['paths'][] = $project->real_to_url_i18n($p); } // the number of times the strings is found in the files of the path $po_file[$i][$lng]['occurrence'] = !empty($po_file[$i][$path_source_lang]) ? count($po_file[$i][$path_source_lang]['paths']) : 0; }; } $success = true; } } } } return [ 'path_source_lang' => $path_source_lang, 'path' => $o['text'], 'success' => $success, 'languages' => $languages, 'total' => count(array_values($po_file)), 'strings' => array_values($po_file), 'id_option' => $id_option, ]; } }
[ "public", "function", "get_translations_table", "(", "$", "id_project", ",", "$", "id_option", ")", "{", "if", "(", "!", "empty", "(", "$", "id_option", ")", "&&", "(", "$", "o", "=", "options", "::", "get_instance", "(", ")", "->", "option", "(", "$", "id_option", ")", ")", "&&", "(", "$", "parent", "=", "options", "::", "get_instance", "(", ")", "->", "parent", "(", "$", "id_option", ")", ")", "&&", "defined", "(", "$", "parent", "[", "'code'", "]", ")", ")", "{", "// @var $path_source_lang the property language of the id_option (the path) ", "$", "path_source_lang", "=", "options", "::", "get_instance", "(", ")", "->", "get_prop", "(", "$", "id_option", ",", "'language'", ")", ";", "// @var $to_explore the path to explore ", "$", "to_explore", "=", "constant", "(", "$", "parent", "[", "'code'", "]", ")", ";", "//exeption for apst_app, don't need the code", "if", "(", "(", "constant", "(", "$", "parent", "[", "'code'", "]", ")", "===", "BBN_APP_PATH", ")", "&&", "(", "strrpos", "(", "'mvc/'", ",", "$", "o", "[", "'code'", "]", ",", "0", ")", "===", "0", ")", ")", "{", "$", "locale_dir", "=", "$", "to_explore", ".", "'locale'", ";", "}", "else", "{", "$", "locale_dir", "=", "$", "to_explore", ".", "$", "o", "[", "'code'", "]", ".", "'locale'", ";", "}", "$", "languages", "=", "array_map", "(", "function", "(", "$", "a", ")", "{", "return", "basename", "(", "$", "a", ")", ";", "}", ",", "\\", "bbn", "\\", "file", "\\", "dir", "::", "get_dirs", "(", "$", "locale_dir", ")", ")", "?", ":", "[", "]", ";", "$", "i", "=", "0", ";", "$", "res", "=", "[", "]", ";", "$", "project", "=", "new", "bbn", "\\", "appui", "\\", "project", "(", "$", "this", "->", "db", ",", "$", "id_project", ")", ";", "if", "(", "!", "empty", "(", "$", "languages", ")", ")", "{", "$", "po_file", "=", "[", "]", ";", "$", "success", "=", "false", ";", "foreach", "(", "$", "languages", "as", "$", "lng", ")", "{", "// the path of po and mo files ", "$", "idx", "=", "is_file", "(", "$", "locale_dir", ".", "'/index.txt'", ")", "?", "file_get_contents", "(", "$", "locale_dir", ".", "'/index.txt'", ")", ":", "''", ";", "$", "po", "=", "$", "locale_dir", ".", "'/'", ".", "$", "lng", ".", "'/LC_MESSAGES/'", ".", "$", "o", "[", "'text'", "]", ".", "$", "idx", ".", "'.po'", ";", "$", "mo", "=", "$", "locale_dir", ".", "'/'", ".", "$", "lng", ".", "'/LC_MESSAGES/'", ".", "$", "o", "[", "'text'", "]", ".", "$", "idx", ".", "'.mo'", ";", "// if the file po exist takes its content ", "if", "(", "file_exists", "(", "$", "po", ")", ")", "{", "$", "fileHandler", "=", "new", "\\", "Sepia", "\\", "PoParser", "\\", "SourceHandler", "\\", "FileSystem", "(", "$", "po", ")", ";", "$", "poParser", "=", "new", "\\", "Sepia", "\\", "PoParser", "\\", "Parser", "(", "$", "fileHandler", ")", ";", "$", "Catalog", "=", "\\", "Sepia", "\\", "PoParser", "\\", "Parser", "::", "parseFile", "(", "$", "po", ")", ";", "if", "(", "!", "empty", "(", "$", "translations", "=", "$", "Catalog", "->", "getEntries", "(", ")", ")", ")", "{", "foreach", "(", "$", "translations", "as", "$", "i", "=>", "$", "t", ")", "{", "// @var $original the original expression ", "$", "original", "=", "$", "t", "->", "getMsgId", "(", ")", ";", "$", "po_file", "[", "$", "i", "]", "[", "$", "lng", "]", "[", "'original'", "]", "=", "$", "original", ";", "// the translation of the string found in the po file ", "$", "po_file", "[", "$", "i", "]", "[", "$", "lng", "]", "[", "'translations_po'", "]", "=", "$", "t", "->", "getMsgStr", "(", ")", ";", "// @var $id takes the id of the original expression in db ", "if", "(", "$", "id", "=", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_i18n'", ",", "'id'", ",", "[", "'exp'", "=>", "$", "original", ",", "'lang'", "=>", "$", "path_source_lang", "]", ")", ")", "{", "$", "po_file", "[", "$", "i", "]", "[", "$", "lng", "]", "[", "'translations_db'", "]", "=", "$", "this", "->", "db", "->", "select_one", "(", "'bbn_i18n_exp'", ",", "'expression'", ",", "[", "'id_exp'", "=>", "$", "id", ",", "'lang'", "=>", "$", "lng", "]", ")", ";", "// the id of the string ", "$", "po_file", "[", "$", "i", "]", "[", "$", "lng", "]", "[", "'id_exp'", "]", "=", "$", "id", ";", "// @var (array) takes $paths of files in which the string was found from the file po ", "$", "paths", "=", "$", "t", "->", "getReference", "(", ")", ";", "// get the url to use it for the link to ide from the table ", "foreach", "(", "$", "paths", "as", "$", "p", ")", "{", "$", "po_file", "[", "$", "i", "]", "[", "$", "lng", "]", "[", "'paths'", "]", "[", "]", "=", "$", "project", "->", "real_to_url_i18n", "(", "$", "p", ")", ";", "}", "// the number of times the strings is found in the files of the path ", "$", "po_file", "[", "$", "i", "]", "[", "$", "lng", "]", "[", "'occurrence'", "]", "=", "!", "empty", "(", "$", "po_file", "[", "$", "i", "]", "[", "$", "path_source_lang", "]", ")", "?", "count", "(", "$", "po_file", "[", "$", "i", "]", "[", "$", "path_source_lang", "]", "[", "'paths'", "]", ")", ":", "0", ";", "}", ";", "}", "$", "success", "=", "true", ";", "}", "}", "}", "}", "return", "[", "'path_source_lang'", "=>", "$", "path_source_lang", ",", "'path'", "=>", "$", "o", "[", "'text'", "]", ",", "'success'", "=>", "$", "success", ",", "'languages'", "=>", "$", "languages", ",", "'total'", "=>", "count", "(", "array_values", "(", "$", "po_file", ")", ")", ",", "'strings'", "=>", "array_values", "(", "$", "po_file", ")", ",", "'id_option'", "=>", "$", "id_option", ",", "]", ";", "}", "}" ]
Returns the informations relative to traslation of the given $id_option of a $id_project. The data is formatted to be shown in a table @param [type] $id_project @param [type] $id_option @return void
[ "Returns", "the", "informations", "relative", "to", "traslation", "of", "the", "given", "$id_option", "of", "a", "$id_project", ".", "The", "data", "is", "formatted", "to", "be", "shown", "in", "a", "table" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/i18n.php#L739-L833
graze/data-structure
src/Collection/Collection.php
Collection.filter
public function filter(callable $fn) { $this->items = array_values(array_filter($this->items, $fn)); return $this; }
php
public function filter(callable $fn) { $this->items = array_values(array_filter($this->items, $fn)); return $this; }
[ "public", "function", "filter", "(", "callable", "$", "fn", ")", "{", "$", "this", "->", "items", "=", "array_values", "(", "array_filter", "(", "$", "this", "->", "items", ",", "$", "fn", ")", ")", ";", "return", "$", "this", ";", "}" ]
@param callable $fn @return $this
[ "@param", "callable", "$fn" ]
train
https://github.com/graze/data-structure/blob/24e0544b7828f65b1b93ce69ad702c9efb4a64d0/src/Collection/Collection.php#L72-L77
graze/data-structure
src/Collection/Collection.php
Collection.sortOn
public function sortOn(callable $fn, $order = Sort\ASC) { $this->items = Sort\comparison($this->items, $fn, $order); return $this; }
php
public function sortOn(callable $fn, $order = Sort\ASC) { $this->items = Sort\comparison($this->items, $fn, $order); return $this; }
[ "public", "function", "sortOn", "(", "callable", "$", "fn", ",", "$", "order", "=", "Sort", "\\", "ASC", ")", "{", "$", "this", "->", "items", "=", "Sort", "\\", "comparison", "(", "$", "this", "->", "items", ",", "$", "fn", ",", "$", "order", ")", ";", "return", "$", "this", ";", "}" ]
@param callable $fn @param int $order @return $this
[ "@param", "callable", "$fn", "@param", "int", "$order" ]
train
https://github.com/graze/data-structure/blob/24e0544b7828f65b1b93ce69ad702c9efb4a64d0/src/Collection/Collection.php#L134-L139
dstuecken/notify
src/Handler/HipChatHandler.php
HipChatHandler.handle
public function handle(NotificationInterface $notification, $level) { if ($notification instanceof AttributeAwareInterface) { $notify = $notification->attribute('notify'); $format = $notification->attribute('format') ?: HipChat::FORMAT_HTML; } else { $format = HipChat::FORMAT_HTML; $notify = true; } return $this->hipchat->message_room( $this->room, $this->from, $notification->message(), $notify, $this->levelMapping[$level], $format ); }
php
public function handle(NotificationInterface $notification, $level) { if ($notification instanceof AttributeAwareInterface) { $notify = $notification->attribute('notify'); $format = $notification->attribute('format') ?: HipChat::FORMAT_HTML; } else { $format = HipChat::FORMAT_HTML; $notify = true; } return $this->hipchat->message_room( $this->room, $this->from, $notification->message(), $notify, $this->levelMapping[$level], $format ); }
[ "public", "function", "handle", "(", "NotificationInterface", "$", "notification", ",", "$", "level", ")", "{", "if", "(", "$", "notification", "instanceof", "AttributeAwareInterface", ")", "{", "$", "notify", "=", "$", "notification", "->", "attribute", "(", "'notify'", ")", ";", "$", "format", "=", "$", "notification", "->", "attribute", "(", "'format'", ")", "?", ":", "HipChat", "::", "FORMAT_HTML", ";", "}", "else", "{", "$", "format", "=", "HipChat", "::", "FORMAT_HTML", ";", "$", "notify", "=", "true", ";", "}", "return", "$", "this", "->", "hipchat", "->", "message_room", "(", "$", "this", "->", "room", ",", "$", "this", "->", "from", ",", "$", "notification", "->", "message", "(", ")", ",", "$", "notify", ",", "$", "this", "->", "levelMapping", "[", "$", "level", "]", ",", "$", "format", ")", ";", "}" ]
Handle a notification @return bool
[ "Handle", "a", "notification" ]
train
https://github.com/dstuecken/notify/blob/abccf0a6a272caf66baea74323f18e2212c6e11e/src/Handler/HipChatHandler.php#L59-L80
petrica/php-statsd-system
Gauge/CpuAverageGauge.php
CpuAverageGauge.getCollection
public function getCollection() { $collection = new ValuesCollection(); $load = $this->getLoadAverage(); $value = null; if (!empty($load) && isset($load[0])) { $value = $load[0]; } return $collection->add('load.average', $value); }
php
public function getCollection() { $collection = new ValuesCollection(); $load = $this->getLoadAverage(); $value = null; if (!empty($load) && isset($load[0])) { $value = $load[0]; } return $collection->add('load.average', $value); }
[ "public", "function", "getCollection", "(", ")", "{", "$", "collection", "=", "new", "ValuesCollection", "(", ")", ";", "$", "load", "=", "$", "this", "->", "getLoadAverage", "(", ")", ";", "$", "value", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "load", ")", "&&", "isset", "(", "$", "load", "[", "0", "]", ")", ")", "{", "$", "value", "=", "$", "load", "[", "0", "]", ";", "}", "return", "$", "collection", "->", "add", "(", "'load.average'", ",", "$", "value", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/CpuAverageGauge.php#L28-L40
eghojansu/moe
src/Log.php
Log.write
function write($text,$format='r') { $fw=Base::instance(); $fw->write( $this->file, date($format). (isset($_SERVER['REMOTE_ADDR'])? (' ['.$_SERVER['REMOTE_ADDR'].']'):'').' '. trim($text).PHP_EOL, TRUE ); }
php
function write($text,$format='r') { $fw=Base::instance(); $fw->write( $this->file, date($format). (isset($_SERVER['REMOTE_ADDR'])? (' ['.$_SERVER['REMOTE_ADDR'].']'):'').' '. trim($text).PHP_EOL, TRUE ); }
[ "function", "write", "(", "$", "text", ",", "$", "format", "=", "'r'", ")", "{", "$", "fw", "=", "Base", "::", "instance", "(", ")", ";", "$", "fw", "->", "write", "(", "$", "this", "->", "file", ",", "date", "(", "$", "format", ")", ".", "(", "isset", "(", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ")", "?", "(", "' ['", ".", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ".", "']'", ")", ":", "''", ")", ".", "' '", ".", "trim", "(", "$", "text", ")", ".", "PHP_EOL", ",", "TRUE", ")", ";", "}" ]
Write specified text to log file @return string @param $text string @param $format string
[ "Write", "specified", "text", "to", "log", "file" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Log.php#L18-L28
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/shutdown_handler.php
ezcMailParserShutdownHandler.registerForRemoval
public static function registerForRemoval( $dir ) { if ( self::$isRegistered === false ) { register_shutdown_function( array( "ezcMailParserShutdownHandler", "shutdownCallback" ) ); self::$isRegistered = true; } self::$directories[] = $dir; }
php
public static function registerForRemoval( $dir ) { if ( self::$isRegistered === false ) { register_shutdown_function( array( "ezcMailParserShutdownHandler", "shutdownCallback" ) ); self::$isRegistered = true; } self::$directories[] = $dir; }
[ "public", "static", "function", "registerForRemoval", "(", "$", "dir", ")", "{", "if", "(", "self", "::", "$", "isRegistered", "===", "false", ")", "{", "register_shutdown_function", "(", "array", "(", "\"ezcMailParserShutdownHandler\"", ",", "\"shutdownCallback\"", ")", ")", ";", "self", "::", "$", "isRegistered", "=", "true", ";", "}", "self", "::", "$", "directories", "[", "]", "=", "$", "dir", ";", "}" ]
Registers the directory $dir for removal when PHP shuts down. The directory and all of its contents will be removed recursively. @param string $dir
[ "Registers", "the", "directory", "$dir", "for", "removal", "when", "PHP", "shuts", "down", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/shutdown_handler.php#L51-L59
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/shutdown_handler.php
ezcMailParserShutdownHandler.remove
public static function remove( $itemName ) { $returnVar = true; if ( !is_dir( $itemName ) && file_exists( $itemName ) ) { unlink( $itemName ); return true; } if ( !file_exists( $itemName ) ) { return true; } $dir = dir( $itemName ); $item = $dir->read(); while ( $item !== false ) { if ( $item != '.' && $item != '..' ) { self::remove( $dir->path . DIRECTORY_SEPARATOR . $item ); $returnVar = false; } $item = $dir->read(); } $dir->close(); $returnVar = rmdir( $itemName ) && $returnVar ? true : false; // if rmdir succeeds and everything else succeeded return $returnVar; }
php
public static function remove( $itemName ) { $returnVar = true; if ( !is_dir( $itemName ) && file_exists( $itemName ) ) { unlink( $itemName ); return true; } if ( !file_exists( $itemName ) ) { return true; } $dir = dir( $itemName ); $item = $dir->read(); while ( $item !== false ) { if ( $item != '.' && $item != '..' ) { self::remove( $dir->path . DIRECTORY_SEPARATOR . $item ); $returnVar = false; } $item = $dir->read(); } $dir->close(); $returnVar = rmdir( $itemName ) && $returnVar ? true : false; // if rmdir succeeds and everything else succeeded return $returnVar; }
[ "public", "static", "function", "remove", "(", "$", "itemName", ")", "{", "$", "returnVar", "=", "true", ";", "if", "(", "!", "is_dir", "(", "$", "itemName", ")", "&&", "file_exists", "(", "$", "itemName", ")", ")", "{", "unlink", "(", "$", "itemName", ")", ";", "return", "true", ";", "}", "if", "(", "!", "file_exists", "(", "$", "itemName", ")", ")", "{", "return", "true", ";", "}", "$", "dir", "=", "dir", "(", "$", "itemName", ")", ";", "$", "item", "=", "$", "dir", "->", "read", "(", ")", ";", "while", "(", "$", "item", "!==", "false", ")", "{", "if", "(", "$", "item", "!=", "'.'", "&&", "$", "item", "!=", "'..'", ")", "{", "self", "::", "remove", "(", "$", "dir", "->", "path", ".", "DIRECTORY_SEPARATOR", ".", "$", "item", ")", ";", "$", "returnVar", "=", "false", ";", "}", "$", "item", "=", "$", "dir", "->", "read", "(", ")", ";", "}", "$", "dir", "->", "close", "(", ")", ";", "$", "returnVar", "=", "rmdir", "(", "$", "itemName", ")", "&&", "$", "returnVar", "?", "true", ":", "false", ";", "// if rmdir succeeds and everything else succeeded", "return", "$", "returnVar", ";", "}" ]
Recursively removes a directory and its contents or a file. Returns true on success and false on error. @param string $itemName @return bool
[ "Recursively", "removes", "a", "directory", "and", "its", "contents", "or", "a", "file", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/shutdown_handler.php#L85-L114
shabbyrobe/amiss
src/Sql/Relator/Base.php
Base.createOn
protected function createOn($meta, $fromIndex, $relatedMeta, $toIndex) { if (!isset($meta->indexes[$fromIndex])) { throw new Exception("Index $fromIndex does not exist on {$meta->id}"); } if (!isset($relatedMeta->indexes[$toIndex])) { throw new Exception("Index $toIndex does not exist on {$relatedMeta->id}"); } $on = []; // If an index exists, you don't need to join on all of it. // This assumes that the indexes are properly numbered. If not, BOOM! foreach ($meta->indexes[$fromIndex]['fields'] as $idx=>$fromField) { if (!isset($relatedMeta->indexes[$toIndex]['fields'][$idx])) { break; } $on[$fromField] = $relatedMeta->indexes[$toIndex]['fields'][$idx]; } return $on; }
php
protected function createOn($meta, $fromIndex, $relatedMeta, $toIndex) { if (!isset($meta->indexes[$fromIndex])) { throw new Exception("Index $fromIndex does not exist on {$meta->id}"); } if (!isset($relatedMeta->indexes[$toIndex])) { throw new Exception("Index $toIndex does not exist on {$relatedMeta->id}"); } $on = []; // If an index exists, you don't need to join on all of it. // This assumes that the indexes are properly numbered. If not, BOOM! foreach ($meta->indexes[$fromIndex]['fields'] as $idx=>$fromField) { if (!isset($relatedMeta->indexes[$toIndex]['fields'][$idx])) { break; } $on[$fromField] = $relatedMeta->indexes[$toIndex]['fields'][$idx]; } return $on; }
[ "protected", "function", "createOn", "(", "$", "meta", ",", "$", "fromIndex", ",", "$", "relatedMeta", ",", "$", "toIndex", ")", "{", "if", "(", "!", "isset", "(", "$", "meta", "->", "indexes", "[", "$", "fromIndex", "]", ")", ")", "{", "throw", "new", "Exception", "(", "\"Index $fromIndex does not exist on {$meta->id}\"", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "relatedMeta", "->", "indexes", "[", "$", "toIndex", "]", ")", ")", "{", "throw", "new", "Exception", "(", "\"Index $toIndex does not exist on {$relatedMeta->id}\"", ")", ";", "}", "$", "on", "=", "[", "]", ";", "// If an index exists, you don't need to join on all of it.", "// This assumes that the indexes are properly numbered. If not, BOOM!", "foreach", "(", "$", "meta", "->", "indexes", "[", "$", "fromIndex", "]", "[", "'fields'", "]", "as", "$", "idx", "=>", "$", "fromField", ")", "{", "if", "(", "!", "isset", "(", "$", "relatedMeta", "->", "indexes", "[", "$", "toIndex", "]", "[", "'fields'", "]", "[", "$", "idx", "]", ")", ")", "{", "break", ";", "}", "$", "on", "[", "$", "fromField", "]", "=", "$", "relatedMeta", "->", "indexes", "[", "$", "toIndex", "]", "[", "'fields'", "]", "[", "$", "idx", "]", ";", "}", "return", "$", "on", ";", "}" ]
to be interfered with yet.
[ "to", "be", "interfered", "with", "yet", "." ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Sql/Relator/Base.php#L96-L117
MrJuliuss/syntara-logviewer
src/Mrjuliuss/SyntaraLogviewer/SyntaraLogviewerServiceProvider.php
SyntaraLogviewerServiceProvider.register
public function register() { // load package config $this->app['config']->package('kmd/logviewer', 'kmd/logviewer/config'); $this->app['config']->set('logviewer::base_url', Config::get('syntara::config.uri').'/logviewer'); $this->app['config']->set('logviewer::filters.global', array('before' => 'basicAuth|hasPermissions:superuser')); $this->app['config']->set('logviewer::view', 'syntara-logviewer::viewer'); $this->app['config']->set('logviewer::p_view', 'pagination::slider-3'); $this->app['config']->set('logviewer::log_order', 'desc'); // add the install command to the application $this->app['logviewer:install'] = $this->app->share(function($app) { return new Commands\InstallCommand($app); }); // add the update command to the application $this->app['logviewer:update'] = $this->app->share(function($app) { return new Commands\UpdateCommand($app); }); // add commands $this->commands('logviewer:install'); $this->commands('logviewer:update'); }
php
public function register() { // load package config $this->app['config']->package('kmd/logviewer', 'kmd/logviewer/config'); $this->app['config']->set('logviewer::base_url', Config::get('syntara::config.uri').'/logviewer'); $this->app['config']->set('logviewer::filters.global', array('before' => 'basicAuth|hasPermissions:superuser')); $this->app['config']->set('logviewer::view', 'syntara-logviewer::viewer'); $this->app['config']->set('logviewer::p_view', 'pagination::slider-3'); $this->app['config']->set('logviewer::log_order', 'desc'); // add the install command to the application $this->app['logviewer:install'] = $this->app->share(function($app) { return new Commands\InstallCommand($app); }); // add the update command to the application $this->app['logviewer:update'] = $this->app->share(function($app) { return new Commands\UpdateCommand($app); }); // add commands $this->commands('logviewer:install'); $this->commands('logviewer:update'); }
[ "public", "function", "register", "(", ")", "{", "// load package config", "$", "this", "->", "app", "[", "'config'", "]", "->", "package", "(", "'kmd/logviewer'", ",", "'kmd/logviewer/config'", ")", ";", "$", "this", "->", "app", "[", "'config'", "]", "->", "set", "(", "'logviewer::base_url'", ",", "Config", "::", "get", "(", "'syntara::config.uri'", ")", ".", "'/logviewer'", ")", ";", "$", "this", "->", "app", "[", "'config'", "]", "->", "set", "(", "'logviewer::filters.global'", ",", "array", "(", "'before'", "=>", "'basicAuth|hasPermissions:superuser'", ")", ")", ";", "$", "this", "->", "app", "[", "'config'", "]", "->", "set", "(", "'logviewer::view'", ",", "'syntara-logviewer::viewer'", ")", ";", "$", "this", "->", "app", "[", "'config'", "]", "->", "set", "(", "'logviewer::p_view'", ",", "'pagination::slider-3'", ")", ";", "$", "this", "->", "app", "[", "'config'", "]", "->", "set", "(", "'logviewer::log_order'", ",", "'desc'", ")", ";", "// add the install command to the application", "$", "this", "->", "app", "[", "'logviewer:install'", "]", "=", "$", "this", "->", "app", "->", "share", "(", "function", "(", "$", "app", ")", "{", "return", "new", "Commands", "\\", "InstallCommand", "(", "$", "app", ")", ";", "}", ")", ";", "// add the update command to the application", "$", "this", "->", "app", "[", "'logviewer:update'", "]", "=", "$", "this", "->", "app", "->", "share", "(", "function", "(", "$", "app", ")", "{", "return", "new", "Commands", "\\", "UpdateCommand", "(", "$", "app", ")", ";", "}", ")", ";", "// add commands", "$", "this", "->", "commands", "(", "'logviewer:install'", ")", ";", "$", "this", "->", "commands", "(", "'logviewer:update'", ")", ";", "}" ]
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/MrJuliuss/syntara-logviewer/blob/49ae6f855339013c8d3cf2b1581c1f59452898be/src/Mrjuliuss/SyntaraLogviewer/SyntaraLogviewerServiceProvider.php#L28-L54
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.store
public function store( $id, $data, $attributes = array() ) { $filename = $this->properties['location'] . $this->generateIdentifier( $id, $attributes ); if ( file_exists( $filename ) ) { if ( unlink( $filename ) === false ) { throw new ezcBaseFilePermissionException( $filename, ezcBaseFileException::WRITE, 'Could not delete existsing cache file.' ); } } $dataStr = $this->prepareData( $data ); $dirname = dirname( $filename ); if ( !is_dir( $dirname ) && !mkdir( $dirname, 0777, true ) ) { throw new ezcBaseFilePermissionException( $dirname, ezcBaseFileException::WRITE, 'Could not create directory to stor cache file.' ); } $this->storeRawData( $filename, $dataStr ); if ( ezcBaseFeatures::os() !== "Windows" ) { chmod( $filename, $this->options->permissions ); } return $id; }
php
public function store( $id, $data, $attributes = array() ) { $filename = $this->properties['location'] . $this->generateIdentifier( $id, $attributes ); if ( file_exists( $filename ) ) { if ( unlink( $filename ) === false ) { throw new ezcBaseFilePermissionException( $filename, ezcBaseFileException::WRITE, 'Could not delete existsing cache file.' ); } } $dataStr = $this->prepareData( $data ); $dirname = dirname( $filename ); if ( !is_dir( $dirname ) && !mkdir( $dirname, 0777, true ) ) { throw new ezcBaseFilePermissionException( $dirname, ezcBaseFileException::WRITE, 'Could not create directory to stor cache file.' ); } $this->storeRawData( $filename, $dataStr ); if ( ezcBaseFeatures::os() !== "Windows" ) { chmod( $filename, $this->options->permissions ); } return $id; }
[ "public", "function", "store", "(", "$", "id", ",", "$", "data", ",", "$", "attributes", "=", "array", "(", ")", ")", "{", "$", "filename", "=", "$", "this", "->", "properties", "[", "'location'", "]", ".", "$", "this", "->", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", ")", ";", "if", "(", "file_exists", "(", "$", "filename", ")", ")", "{", "if", "(", "unlink", "(", "$", "filename", ")", "===", "false", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "filename", ",", "ezcBaseFileException", "::", "WRITE", ",", "'Could not delete existsing cache file.'", ")", ";", "}", "}", "$", "dataStr", "=", "$", "this", "->", "prepareData", "(", "$", "data", ")", ";", "$", "dirname", "=", "dirname", "(", "$", "filename", ")", ";", "if", "(", "!", "is_dir", "(", "$", "dirname", ")", "&&", "!", "mkdir", "(", "$", "dirname", ",", "0777", ",", "true", ")", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "dirname", ",", "ezcBaseFileException", "::", "WRITE", ",", "'Could not create directory to stor cache file.'", ")", ";", "}", "$", "this", "->", "storeRawData", "(", "$", "filename", ",", "$", "dataStr", ")", ";", "if", "(", "ezcBaseFeatures", "::", "os", "(", ")", "!==", "\"Windows\"", ")", "{", "chmod", "(", "$", "filename", ",", "$", "this", "->", "options", "->", "permissions", ")", ";", "}", "return", "$", "id", ";", "}" ]
Store data to the cache storage. This method stores the given cache data into the cache, assigning the ID given to it. The type of cache data which is expected by a ezcCacheStorage depends on its implementation. In most cases strings and arrays will be accepted, in some rare cases only strings might be accepted. Using attributes you can describe your cache data further. This allows you to deal with multiple cache data at once later. Some ezcCacheStorage implementations also use the attributes for storage purposes. Attributes form some kind of "extended ID". @param string $id Unique identifier for the data. @param mixed $data The data to store. @param array(string=>string) $attributes Attributes describing the cached data. @return string The ID string of the newly cached data. @throws ezcBaseFilePermissionException If an already existsing cache file could not be unlinked to store the new data (may occur, when a cache item's TTL has expired and the file should be stored with more actual data). This exception means most likely that your cache directory has been corrupted by external influences (file permission change). @throws ezcBaseFilePermissionException If the directory to store the cache file could not be created. This exception means most likely that your cache directory has been corrupted by external influences (file permission change). @throws ezcBaseFileIoException If an error occured while writing the data to the cache. If this exception occurs, a serious error occured and your storage might be corruped (e.g. broken network connection, file system broken, ...). @throws ezcCacheInvalidDataException If the data submitted can not be handled by the implementation of {@link ezcCacheStorageFile}. Most implementations can not handle objects and resources.
[ "Store", "data", "to", "the", "cache", "storage", ".", "This", "method", "stores", "the", "given", "cache", "data", "into", "the", "cache", "assigning", "the", "ID", "given", "to", "it", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L183-L216
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.storeRawData
protected function storeRawData( $filename, $data ) { if ( file_put_contents( $filename, $data ) !== strlen( $data ) ) { throw new ezcBaseFileIoException( $filename, ezcBaseFileException::WRITE, 'Could not write data to cache file.' ); } }
php
protected function storeRawData( $filename, $data ) { if ( file_put_contents( $filename, $data ) !== strlen( $data ) ) { throw new ezcBaseFileIoException( $filename, ezcBaseFileException::WRITE, 'Could not write data to cache file.' ); } }
[ "protected", "function", "storeRawData", "(", "$", "filename", ",", "$", "data", ")", "{", "if", "(", "file_put_contents", "(", "$", "filename", ",", "$", "data", ")", "!==", "strlen", "(", "$", "data", ")", ")", "{", "throw", "new", "ezcBaseFileIoException", "(", "$", "filename", ",", "ezcBaseFileException", "::", "WRITE", ",", "'Could not write data to cache file.'", ")", ";", "}", "}" ]
Actually stores the given data. @param string $filename @param string $data @return void @throws ezcBaseFileIoException if the store fails.
[ "Actually", "stores", "the", "given", "data", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L228-L238
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.restore
public function restore( $id, $attributes = array(), $search = false ) { $filename = $this->properties['location'] . $this->generateIdentifier( $id, $attributes ); if ( file_exists( $filename ) === false ) { if ( $search === true && count( $files = $this->search( $id, $attributes ) ) === 1 ) { $filename = $files[0]; } else { return false; } } // No cached data if ( file_exists( $filename ) === false ) { return false; } // Cached data outdated, purge it. if ( $this->calcLifetime( $filename ) == 0 && $this->properties['options']['ttl'] !== false ) { $this->delete( $id, $attributes ); return false; } return ( $this->fetchData( $filename ) ); }
php
public function restore( $id, $attributes = array(), $search = false ) { $filename = $this->properties['location'] . $this->generateIdentifier( $id, $attributes ); if ( file_exists( $filename ) === false ) { if ( $search === true && count( $files = $this->search( $id, $attributes ) ) === 1 ) { $filename = $files[0]; } else { return false; } } // No cached data if ( file_exists( $filename ) === false ) { return false; } // Cached data outdated, purge it. if ( $this->calcLifetime( $filename ) == 0 && $this->properties['options']['ttl'] !== false ) { $this->delete( $id, $attributes ); return false; } return ( $this->fetchData( $filename ) ); }
[ "public", "function", "restore", "(", "$", "id", ",", "$", "attributes", "=", "array", "(", ")", ",", "$", "search", "=", "false", ")", "{", "$", "filename", "=", "$", "this", "->", "properties", "[", "'location'", "]", ".", "$", "this", "->", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", ")", ";", "if", "(", "file_exists", "(", "$", "filename", ")", "===", "false", ")", "{", "if", "(", "$", "search", "===", "true", "&&", "count", "(", "$", "files", "=", "$", "this", "->", "search", "(", "$", "id", ",", "$", "attributes", ")", ")", "===", "1", ")", "{", "$", "filename", "=", "$", "files", "[", "0", "]", ";", "}", "else", "{", "return", "false", ";", "}", "}", "// No cached data", "if", "(", "file_exists", "(", "$", "filename", ")", "===", "false", ")", "{", "return", "false", ";", "}", "// Cached data outdated, purge it.", "if", "(", "$", "this", "->", "calcLifetime", "(", "$", "filename", ")", "==", "0", "&&", "$", "this", "->", "properties", "[", "'options'", "]", "[", "'ttl'", "]", "!==", "false", ")", "{", "$", "this", "->", "delete", "(", "$", "id", ",", "$", "attributes", ")", ";", "return", "false", ";", "}", "return", "(", "$", "this", "->", "fetchData", "(", "$", "filename", ")", ")", ";", "}" ]
Restore data from the cache. Restores the data associated with the given cache and returns it. Please see {@link ezcCacheStorage::store()} for more detailed information of cachable datatypes. During access to cached data the caches are automatically expired. This means, that the ezcCacheStorage object checks before returning the data if it's still actual. If the cache has expired, data will be deleted and false is returned. You should always provide the attributes you assigned, although the cache storages must be able to find a cache ID even without them. BEWARE: Finding cache data only by ID can be much slower than finding it by ID and attributes. Note that with the {@link ezcCacheStorageFilePlain} all restored data will be of type string. If you expect a different data type you need to perform a cast after restoring. @param string $id The item ID to restore. @param array(string=>string) $attributes Attributes describing the data to restore. @param bool $search Whether to search for items if not found directly. @return mixed|bool The cached data on success, otherwise false. @throws ezcBaseFilePermissionException If an already existsing cache file could not be unlinked. This exception means most likely that your cache directory has been corrupted by external influences (file permission change).
[ "Restore", "data", "from", "the", "cache", ".", "Restores", "the", "data", "associated", "with", "the", "given", "cache", "and", "returns", "it", ".", "Please", "see", "{", "@link", "ezcCacheStorage", "::", "store", "()", "}", "for", "more", "detailed", "information", "of", "cachable", "datatypes", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L274-L303
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.delete
public function delete( $id = null, $attributes = array(), $search = false ) { $filename = $this->properties['location'] . $this->generateIdentifier( $id, $attributes ); $filesToDelete = array(); if ( file_exists( $filename ) ) { $filesToDelete[] = $filename; } else if ( $search === true ) { $filesToDelete = $this->search( $id, $attributes ); } $deletedIds = array(); foreach ( $filesToDelete as $filename ) { if ( unlink( $filename ) === false ) { throw new ezcBaseFilePermissionException( $filename, ezcBaseFileException::WRITE, 'Could not unlink cache file.' ); } $deleted = $this->extractIdentifier( $filename ); $deletedIds[] = $deleted['id']; } return $deletedIds; }
php
public function delete( $id = null, $attributes = array(), $search = false ) { $filename = $this->properties['location'] . $this->generateIdentifier( $id, $attributes ); $filesToDelete = array(); if ( file_exists( $filename ) ) { $filesToDelete[] = $filename; } else if ( $search === true ) { $filesToDelete = $this->search( $id, $attributes ); } $deletedIds = array(); foreach ( $filesToDelete as $filename ) { if ( unlink( $filename ) === false ) { throw new ezcBaseFilePermissionException( $filename, ezcBaseFileException::WRITE, 'Could not unlink cache file.' ); } $deleted = $this->extractIdentifier( $filename ); $deletedIds[] = $deleted['id']; } return $deletedIds; }
[ "public", "function", "delete", "(", "$", "id", "=", "null", ",", "$", "attributes", "=", "array", "(", ")", ",", "$", "search", "=", "false", ")", "{", "$", "filename", "=", "$", "this", "->", "properties", "[", "'location'", "]", ".", "$", "this", "->", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", ")", ";", "$", "filesToDelete", "=", "array", "(", ")", ";", "if", "(", "file_exists", "(", "$", "filename", ")", ")", "{", "$", "filesToDelete", "[", "]", "=", "$", "filename", ";", "}", "else", "if", "(", "$", "search", "===", "true", ")", "{", "$", "filesToDelete", "=", "$", "this", "->", "search", "(", "$", "id", ",", "$", "attributes", ")", ";", "}", "$", "deletedIds", "=", "array", "(", ")", ";", "foreach", "(", "$", "filesToDelete", "as", "$", "filename", ")", "{", "if", "(", "unlink", "(", "$", "filename", ")", "===", "false", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "filename", ",", "ezcBaseFileException", "::", "WRITE", ",", "'Could not unlink cache file.'", ")", ";", "}", "$", "deleted", "=", "$", "this", "->", "extractIdentifier", "(", "$", "filename", ")", ";", "$", "deletedIds", "[", "]", "=", "$", "deleted", "[", "'id'", "]", ";", "}", "return", "$", "deletedIds", ";", "}" ]
Delete data from the cache. Purges the cached data for a given ID and or attributes. Using an ID purges only the cache data for just this ID. Additional attributes provided will matched additionally. This can give you an immense speed improvement against just searching for ID ( see {@link ezcCacheStorage::restore()} ). If you only provide attributes for deletion of cache data, all cache data matching these attributes will be purged. @param string $id The item ID to purge. @param array(string=>string) $attributes Attributes describing the data to restore. @param bool $search Whether to search for items if not found directly. @return void @throws ezcBaseFilePermissionException If an already existsing cache file could not be unlinked. This exception means most likely that your cache directory has been corrupted by external influences (file permission change).
[ "Delete", "data", "from", "the", "cache", ".", "Purges", "the", "cached", "data", "for", "a", "given", "ID", "and", "or", "attributes", ".", "Using", "an", "ID", "purges", "only", "the", "cache", "data", "for", "just", "this", "ID", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L330-L360
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.getRemainingLifetime
public function getRemainingLifetime( $id, $attributes = array() ) { if ( count( $objects = $this->search( $id, $attributes ) ) > 0 ) { return $this->calcLifetime( $objects[0] ); } return 0; }
php
public function getRemainingLifetime( $id, $attributes = array() ) { if ( count( $objects = $this->search( $id, $attributes ) ) > 0 ) { return $this->calcLifetime( $objects[0] ); } return 0; }
[ "public", "function", "getRemainingLifetime", "(", "$", "id", ",", "$", "attributes", "=", "array", "(", ")", ")", "{", "if", "(", "count", "(", "$", "objects", "=", "$", "this", "->", "search", "(", "$", "id", ",", "$", "attributes", ")", ")", ">", "0", ")", "{", "return", "$", "this", "->", "calcLifetime", "(", "$", "objects", "[", "0", "]", ")", ";", "}", "return", "0", ";", "}" ]
Returns the time ( in seconds ) which remains for a cache object, before it gets outdated. In case the cache object is already outdated or does not exist, this method returns 0. @param string $id The item ID. @param array(string=>string) $attributes Attributes describing the data to restore. @access public @return int The remaining lifetime (0 if nonexists or oudated).
[ "Returns", "the", "time", "(", "in", "seconds", ")", "which", "remains", "for", "a", "cache", "object", "before", "it", "gets", "outdated", ".", "In", "case", "the", "cache", "object", "is", "already", "outdated", "or", "does", "not", "exist", "this", "method", "returns", "0", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L388-L395
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.purge
public function purge( $limit = null ) { $purgeCount = 0; return $this->purgeRecursive( $this->properties['location'], $limit, $purgeCount ); }
php
public function purge( $limit = null ) { $purgeCount = 0; return $this->purgeRecursive( $this->properties['location'], $limit, $purgeCount ); }
[ "public", "function", "purge", "(", "$", "limit", "=", "null", ")", "{", "$", "purgeCount", "=", "0", ";", "return", "$", "this", "->", "purgeRecursive", "(", "$", "this", "->", "properties", "[", "'location'", "]", ",", "$", "limit", ",", "$", "purgeCount", ")", ";", "}" ]
Purges the given number of cache items. This method minimally purges the $limit number of outdated cache items from the storage. If limit is left out, all outdated items are purged. The purged item IDs are returned. @param int $limit @return array(string)
[ "Purges", "the", "given", "number", "of", "cache", "items", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L407-L411
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.purgeRecursive
private function purgeRecursive( $dir, $limit, &$purgeCount ) { $purgedIds = array(); // Deal with files in the directory if ( ( $files = glob( "{$dir}*{$this->properties['options']->extension}" ) ) === false ) { throw new ezcBaseFileNotFoundException( $dir, 'cache location', 'Produced an error while globbing for files.' ); } foreach ( $files as $file ) { if ( $this->calcLifetime( $file ) == 0 ) { if ( @unlink( $file ) === false ) { throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::WRITE, 'Could not unlink cache file.' ); } $fileInfo = $this->extractIdentifier( $file ); $purgedIds[] = $fileInfo['id']; ++$purgeCount; } // Stop purging if limit is reached if ( $limit !== null && $purgeCount >= $limit ) { return $purgedIds; } } // Deal with sub dirs, this function expects them to be marked with a // slash because of the property $location if ( ( $dirs = glob( "$dir*", GLOB_ONLYDIR | GLOB_MARK ) ) === false ) { throw new ezcBaseFileNotFoundException( $dir, 'cache location', 'Produced an error while globbing for directories.' ); } foreach ( $dirs as $dir ) { $purgedIds = array_merge( $purgedIds, $this->purgeRecursive( $dir, $limit, $purgeCount ) ); // Stop purging if limit is reached if ( $limit !== null && $purgeCount >= $limit ) { return $purgedIds; } } // Finished purging, return IDs. return $purgedIds; }
php
private function purgeRecursive( $dir, $limit, &$purgeCount ) { $purgedIds = array(); // Deal with files in the directory if ( ( $files = glob( "{$dir}*{$this->properties['options']->extension}" ) ) === false ) { throw new ezcBaseFileNotFoundException( $dir, 'cache location', 'Produced an error while globbing for files.' ); } foreach ( $files as $file ) { if ( $this->calcLifetime( $file ) == 0 ) { if ( @unlink( $file ) === false ) { throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::WRITE, 'Could not unlink cache file.' ); } $fileInfo = $this->extractIdentifier( $file ); $purgedIds[] = $fileInfo['id']; ++$purgeCount; } // Stop purging if limit is reached if ( $limit !== null && $purgeCount >= $limit ) { return $purgedIds; } } // Deal with sub dirs, this function expects them to be marked with a // slash because of the property $location if ( ( $dirs = glob( "$dir*", GLOB_ONLYDIR | GLOB_MARK ) ) === false ) { throw new ezcBaseFileNotFoundException( $dir, 'cache location', 'Produced an error while globbing for directories.' ); } foreach ( $dirs as $dir ) { $purgedIds = array_merge( $purgedIds, $this->purgeRecursive( $dir, $limit, $purgeCount ) ); // Stop purging if limit is reached if ( $limit !== null && $purgeCount >= $limit ) { return $purgedIds; } } // Finished purging, return IDs. return $purgedIds; }
[ "private", "function", "purgeRecursive", "(", "$", "dir", ",", "$", "limit", ",", "&", "$", "purgeCount", ")", "{", "$", "purgedIds", "=", "array", "(", ")", ";", "// Deal with files in the directory", "if", "(", "(", "$", "files", "=", "glob", "(", "\"{$dir}*{$this->properties['options']->extension}\"", ")", ")", "===", "false", ")", "{", "throw", "new", "ezcBaseFileNotFoundException", "(", "$", "dir", ",", "'cache location'", ",", "'Produced an error while globbing for files.'", ")", ";", "}", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "if", "(", "$", "this", "->", "calcLifetime", "(", "$", "file", ")", "==", "0", ")", "{", "if", "(", "@", "unlink", "(", "$", "file", ")", "===", "false", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "file", ",", "ezcBaseFileException", "::", "WRITE", ",", "'Could not unlink cache file.'", ")", ";", "}", "$", "fileInfo", "=", "$", "this", "->", "extractIdentifier", "(", "$", "file", ")", ";", "$", "purgedIds", "[", "]", "=", "$", "fileInfo", "[", "'id'", "]", ";", "++", "$", "purgeCount", ";", "}", "// Stop purging if limit is reached", "if", "(", "$", "limit", "!==", "null", "&&", "$", "purgeCount", ">=", "$", "limit", ")", "{", "return", "$", "purgedIds", ";", "}", "}", "// Deal with sub dirs, this function expects them to be marked with a", "// slash because of the property $location", "if", "(", "(", "$", "dirs", "=", "glob", "(", "\"$dir*\"", ",", "GLOB_ONLYDIR", "|", "GLOB_MARK", ")", ")", "===", "false", ")", "{", "throw", "new", "ezcBaseFileNotFoundException", "(", "$", "dir", ",", "'cache location'", ",", "'Produced an error while globbing for directories.'", ")", ";", "}", "foreach", "(", "$", "dirs", "as", "$", "dir", ")", "{", "$", "purgedIds", "=", "array_merge", "(", "$", "purgedIds", ",", "$", "this", "->", "purgeRecursive", "(", "$", "dir", ",", "$", "limit", ",", "$", "purgeCount", ")", ")", ";", "// Stop purging if limit is reached", "if", "(", "$", "limit", "!==", "null", "&&", "$", "purgeCount", ">=", "$", "limit", ")", "{", "return", "$", "purgedIds", ";", "}", "}", "// Finished purging, return IDs.", "return", "$", "purgedIds", ";", "}" ]
Recursively purge cache items. Recursively purges $dir until $limit is reached. $purgeCount is the number of already purged items. @param string $dir @param int $limit @param int $purgeCount
[ "Recursively", "purge", "cache", "items", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L423-L485
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.reset
public function reset() { $files = glob( "{$this->properties['location']}*" ); foreach ( $files as $file ) { if ( is_dir( $file ) ) { ezcBaseFile::removeRecursive( $file ); } else { if ( @unlink( $file ) === false ) { throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::REMOVE, 'Could not unlink cache file.' ); } } } }
php
public function reset() { $files = glob( "{$this->properties['location']}*" ); foreach ( $files as $file ) { if ( is_dir( $file ) ) { ezcBaseFile::removeRecursive( $file ); } else { if ( @unlink( $file ) === false ) { throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::REMOVE, 'Could not unlink cache file.' ); } } } }
[ "public", "function", "reset", "(", ")", "{", "$", "files", "=", "glob", "(", "\"{$this->properties['location']}*\"", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "if", "(", "is_dir", "(", "$", "file", ")", ")", "{", "ezcBaseFile", "::", "removeRecursive", "(", "$", "file", ")", ";", "}", "else", "{", "if", "(", "@", "unlink", "(", "$", "file", ")", "===", "false", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "file", ",", "ezcBaseFileException", "::", "REMOVE", ",", "'Could not unlink cache file.'", ")", ";", "}", "}", "}", "}" ]
Resets the whole storage. Deletes all data in the storage including {@link ezcCacheStackMetaData} that was stored using {@link storeMetaData()}.
[ "Resets", "the", "whole", "storage", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L493-L514
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.search
protected function search( $id = null, $attributes = array() ) { $globArr = explode( "-", $this->generateIdentifier( $id, $attributes ), 2 ); if ( sizeof( $globArr ) > 1 ) { $glob = $globArr[0] . "-" . strtr( $globArr[1], array( '-' => '*', '.' => '*' ) ); } else { $glob = strtr( $globArr[0], array( '-' => '*', '.' => '*' ) ); } $glob = ( $id === null ? '*' : '' ) . $glob; return $this->searchRecursive( $glob, $this->properties['location'] ); }
php
protected function search( $id = null, $attributes = array() ) { $globArr = explode( "-", $this->generateIdentifier( $id, $attributes ), 2 ); if ( sizeof( $globArr ) > 1 ) { $glob = $globArr[0] . "-" . strtr( $globArr[1], array( '-' => '*', '.' => '*' ) ); } else { $glob = strtr( $globArr[0], array( '-' => '*', '.' => '*' ) ); } $glob = ( $id === null ? '*' : '' ) . $glob; return $this->searchRecursive( $glob, $this->properties['location'] ); }
[ "protected", "function", "search", "(", "$", "id", "=", "null", ",", "$", "attributes", "=", "array", "(", ")", ")", "{", "$", "globArr", "=", "explode", "(", "\"-\"", ",", "$", "this", "->", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", ")", ",", "2", ")", ";", "if", "(", "sizeof", "(", "$", "globArr", ")", ">", "1", ")", "{", "$", "glob", "=", "$", "globArr", "[", "0", "]", ".", "\"-\"", ".", "strtr", "(", "$", "globArr", "[", "1", "]", ",", "array", "(", "'-'", "=>", "'*'", ",", "'.'", "=>", "'*'", ")", ")", ";", "}", "else", "{", "$", "glob", "=", "strtr", "(", "$", "globArr", "[", "0", "]", ",", "array", "(", "'-'", "=>", "'*'", ",", "'.'", "=>", "'*'", ")", ")", ";", "}", "$", "glob", "=", "(", "$", "id", "===", "null", "?", "'*'", ":", "''", ")", ".", "$", "glob", ";", "return", "$", "this", "->", "searchRecursive", "(", "$", "glob", ",", "$", "this", "->", "properties", "[", "'location'", "]", ")", ";", "}" ]
Search the storage for data. @param string $id An item ID. @param array(string=>string) $attributes Attributes describing the data to restore. @return array(int=>string) Found cache items.
[ "Search", "the", "storage", "for", "data", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L524-L537
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.searchRecursive
protected function searchRecursive( $pattern, $directory ) { $itemArr = glob( $directory . $pattern ); $dirArr = glob( $directory . "*", GLOB_ONLYDIR ); foreach ( $dirArr as $dirEntry ) { $result = $this->searchRecursive( $pattern, "$dirEntry/" ); $itemArr = array_merge( $itemArr, $result ); } return $itemArr; }
php
protected function searchRecursive( $pattern, $directory ) { $itemArr = glob( $directory . $pattern ); $dirArr = glob( $directory . "*", GLOB_ONLYDIR ); foreach ( $dirArr as $dirEntry ) { $result = $this->searchRecursive( $pattern, "$dirEntry/" ); $itemArr = array_merge( $itemArr, $result ); } return $itemArr; }
[ "protected", "function", "searchRecursive", "(", "$", "pattern", ",", "$", "directory", ")", "{", "$", "itemArr", "=", "glob", "(", "$", "directory", ".", "$", "pattern", ")", ";", "$", "dirArr", "=", "glob", "(", "$", "directory", ".", "\"*\"", ",", "GLOB_ONLYDIR", ")", ";", "foreach", "(", "$", "dirArr", "as", "$", "dirEntry", ")", "{", "$", "result", "=", "$", "this", "->", "searchRecursive", "(", "$", "pattern", ",", "\"$dirEntry/\"", ")", ";", "$", "itemArr", "=", "array_merge", "(", "$", "itemArr", ",", "$", "result", ")", ";", "}", "return", "$", "itemArr", ";", "}" ]
Search the storage for data recursively. @param string $pattern Pattern used with {@link glob()}. @param mixed $directory Directory to search in. @return array(int=>string) Found cache items.
[ "Search", "the", "storage", "for", "data", "recursively", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L546-L556
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.generateIdentifier
public function generateIdentifier( $id, $attributes = null ) { $filename = (string) $id; $illegalFileNameChars = array( ' ' => '_', '/' => DIRECTORY_SEPARATOR, '\\' => DIRECTORY_SEPARATOR, ); $filename = strtr( $filename, $illegalFileNameChars ); // Chars used for filename concatination $illegalChars = array( '-' => '#', ' ' => '%', '=' => '+', '.' => '+', ); if ( is_array( $attributes ) && count( $attributes ) > 0 ) { ksort( $attributes ); foreach ( $attributes as $key => $val ) { $attrStr = '-' . strtr( $key, $illegalChars ) . '=' . strtr( $val, $illegalChars ); if ( strlen( $filename . $attrStr ) > 250 ) { // Max filename length break; } $filename .= $attrStr; } } else { $filename .= '-'; } return $filename . $this->properties['options']['extension']; }
php
public function generateIdentifier( $id, $attributes = null ) { $filename = (string) $id; $illegalFileNameChars = array( ' ' => '_', '/' => DIRECTORY_SEPARATOR, '\\' => DIRECTORY_SEPARATOR, ); $filename = strtr( $filename, $illegalFileNameChars ); // Chars used for filename concatination $illegalChars = array( '-' => '#', ' ' => '%', '=' => '+', '.' => '+', ); if ( is_array( $attributes ) && count( $attributes ) > 0 ) { ksort( $attributes ); foreach ( $attributes as $key => $val ) { $attrStr = '-' . strtr( $key, $illegalChars ) . '=' . strtr( $val, $illegalChars ); if ( strlen( $filename . $attrStr ) > 250 ) { // Max filename length break; } $filename .= $attrStr; } } else { $filename .= '-'; } return $filename . $this->properties['options']['extension']; }
[ "public", "function", "generateIdentifier", "(", "$", "id", ",", "$", "attributes", "=", "null", ")", "{", "$", "filename", "=", "(", "string", ")", "$", "id", ";", "$", "illegalFileNameChars", "=", "array", "(", "' '", "=>", "'_'", ",", "'/'", "=>", "DIRECTORY_SEPARATOR", ",", "'\\\\'", "=>", "DIRECTORY_SEPARATOR", ",", ")", ";", "$", "filename", "=", "strtr", "(", "$", "filename", ",", "$", "illegalFileNameChars", ")", ";", "// Chars used for filename concatination", "$", "illegalChars", "=", "array", "(", "'-'", "=>", "'#'", ",", "' '", "=>", "'%'", ",", "'='", "=>", "'+'", ",", "'.'", "=>", "'+'", ",", ")", ";", "if", "(", "is_array", "(", "$", "attributes", ")", "&&", "count", "(", "$", "attributes", ")", ">", "0", ")", "{", "ksort", "(", "$", "attributes", ")", ";", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "attrStr", "=", "'-'", ".", "strtr", "(", "$", "key", ",", "$", "illegalChars", ")", ".", "'='", ".", "strtr", "(", "$", "val", ",", "$", "illegalChars", ")", ";", "if", "(", "strlen", "(", "$", "filename", ".", "$", "attrStr", ")", ">", "250", ")", "{", "// Max filename length", "break", ";", "}", "$", "filename", ".=", "$", "attrStr", ";", "}", "}", "else", "{", "$", "filename", ".=", "'-'", ";", "}", "return", "$", "filename", ".", "$", "this", "->", "properties", "[", "'options'", "]", "[", "'extension'", "]", ";", "}" ]
Generate the storage internal identifier from ID and attributes. Generates the storage internal identifier out of the provided ID and the attributes. This is the default implementation and can be overloaded if necessary. @param string $id The ID. @param array(string=>string) $attributes Attributes describing the data to restore. @return string The generated identifier
[ "Generate", "the", "storage", "internal", "identifier", "from", "ID", "and", "attributes", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L622-L659
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.lock
public function lock() { $lockFile = $this->properties['location'] . $this->properties['options']->lockFile; while ( $this->lockResource === false ) { clearstatcache(); $this->lockResource = @fopen( $lockFile, 'x' ); // Wait for lock to get freed if ( $this->lockResource === false ) { usleep( $this->properties['options']->lockWaitTime ); } // Check if lock is to be considered dead. Might result in a // nonrelevant race condition if the lock file disappears between // fs calls. To avoid warnings in this case, the calls are // silenced. if ( file_exists( $lockFile ) && ( time() - @filemtime( $lockFile ) ) > $this->properties['options']->maxLockTime ) { @unlink( $lockFile ); } } }
php
public function lock() { $lockFile = $this->properties['location'] . $this->properties['options']->lockFile; while ( $this->lockResource === false ) { clearstatcache(); $this->lockResource = @fopen( $lockFile, 'x' ); // Wait for lock to get freed if ( $this->lockResource === false ) { usleep( $this->properties['options']->lockWaitTime ); } // Check if lock is to be considered dead. Might result in a // nonrelevant race condition if the lock file disappears between // fs calls. To avoid warnings in this case, the calls are // silenced. if ( file_exists( $lockFile ) && ( time() - @filemtime( $lockFile ) ) > $this->properties['options']->maxLockTime ) { @unlink( $lockFile ); } } }
[ "public", "function", "lock", "(", ")", "{", "$", "lockFile", "=", "$", "this", "->", "properties", "[", "'location'", "]", ".", "$", "this", "->", "properties", "[", "'options'", "]", "->", "lockFile", ";", "while", "(", "$", "this", "->", "lockResource", "===", "false", ")", "{", "clearstatcache", "(", ")", ";", "$", "this", "->", "lockResource", "=", "@", "fopen", "(", "$", "lockFile", ",", "'x'", ")", ";", "// Wait for lock to get freed", "if", "(", "$", "this", "->", "lockResource", "===", "false", ")", "{", "usleep", "(", "$", "this", "->", "properties", "[", "'options'", "]", "->", "lockWaitTime", ")", ";", "}", "// Check if lock is to be considered dead. Might result in a ", "// nonrelevant race condition if the lock file disappears between ", "// fs calls. To avoid warnings in this case, the calls are ", "// silenced.", "if", "(", "file_exists", "(", "$", "lockFile", ")", "&&", "(", "time", "(", ")", "-", "@", "filemtime", "(", "$", "lockFile", ")", ")", ">", "$", "this", "->", "properties", "[", "'options'", "]", "->", "maxLockTime", ")", "{", "@", "unlink", "(", "$", "lockFile", ")", ";", "}", "}", "}" ]
Acquire a lock on the storage. This method acquires a lock on the storage. If locked, the storage must block all other method calls until the lock is freed again using {@link ezcCacheStackMetaDataStorage::unlock()}. Methods that are called within the request that successfully acquired the lock must succeed as usual. @return void
[ "Acquire", "a", "lock", "on", "the", "storage", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L720-L744
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.unlock
public function unlock() { // If the resource is already removed, nothing to do if ( $this->lockResource !== false ) { fclose( $this->lockResource ); @unlink( $this->properties['location'] . $this->properties['options']->lockFile ); $this->lockResource = false; } }
php
public function unlock() { // If the resource is already removed, nothing to do if ( $this->lockResource !== false ) { fclose( $this->lockResource ); @unlink( $this->properties['location'] . $this->properties['options']->lockFile ); $this->lockResource = false; } }
[ "public", "function", "unlock", "(", ")", "{", "// If the resource is already removed, nothing to do", "if", "(", "$", "this", "->", "lockResource", "!==", "false", ")", "{", "fclose", "(", "$", "this", "->", "lockResource", ")", ";", "@", "unlink", "(", "$", "this", "->", "properties", "[", "'location'", "]", ".", "$", "this", "->", "properties", "[", "'options'", "]", "->", "lockFile", ")", ";", "$", "this", "->", "lockResource", "=", "false", ";", "}", "}" ]
Release a lock on the storage. This method releases the lock of the storage, that has been acquired via {@link ezcCacheStackMetaDataStorage::lock()}. After this method has been called, blocked method calls (including calls to lock()) can suceed again. @return void
[ "Release", "a", "lock", "on", "the", "storage", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L756-L767
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.setOptions
public function setOptions( $options ) { if ( is_array( $options ) ) { $this->properties['options']->merge( $options ); } else if ( $options instanceof ezcCacheStorageFileOptions ) { $this->properties['options'] = $options; } else if ( $options instanceof ezcCacheStorageOptions ) { $this->properties['options']->mergeStorageOptions( $options ); } else { throw new ezcBaseValueException( 'options', $options, 'instance of ezcCacheStorageFileOptions or (deprecated) ezcCacheStorageOptions' ); } }
php
public function setOptions( $options ) { if ( is_array( $options ) ) { $this->properties['options']->merge( $options ); } else if ( $options instanceof ezcCacheStorageFileOptions ) { $this->properties['options'] = $options; } else if ( $options instanceof ezcCacheStorageOptions ) { $this->properties['options']->mergeStorageOptions( $options ); } else { throw new ezcBaseValueException( 'options', $options, 'instance of ezcCacheStorageFileOptions or (deprecated) ezcCacheStorageOptions' ); } }
[ "public", "function", "setOptions", "(", "$", "options", ")", "{", "if", "(", "is_array", "(", "$", "options", ")", ")", "{", "$", "this", "->", "properties", "[", "'options'", "]", "->", "merge", "(", "$", "options", ")", ";", "}", "else", "if", "(", "$", "options", "instanceof", "ezcCacheStorageFileOptions", ")", "{", "$", "this", "->", "properties", "[", "'options'", "]", "=", "$", "options", ";", "}", "else", "if", "(", "$", "options", "instanceof", "ezcCacheStorageOptions", ")", "{", "$", "this", "->", "properties", "[", "'options'", "]", "->", "mergeStorageOptions", "(", "$", "options", ")", ";", "}", "else", "{", "throw", "new", "ezcBaseValueException", "(", "'options'", ",", "$", "options", ",", "'instance of ezcCacheStorageFileOptions or (deprecated) ezcCacheStorageOptions'", ")", ";", "}", "}" ]
Set new options. This method allows you to change the options of a cache file storage. Change of options take effect directly after this method has been called. The available options depend on the ezcCacheStorageFile implementation. All implementations have to offer the following options: - ttl The time-to-life. After this time span, a cache item becomes invalid and will be purged. The {@link ezcCacheStorage::restore()} method will then return false. - extension The "extension" for your cache items. This is usually the file name extension, when you deal with file system based caches or e.g. a database ID extension. - permissions The file permissions to set for new files. The usage of ezcCacheStorageOptions and arrays for setting options is deprecated, but still supported. You should migrate to ezcCacheStorageFileOptions. @param ezcCacheStorageFileOptions $options The options to set (accepts ezcCacheStorageOptions or array for compatibility reasons, too). @throws ezcBasePropertyNotFoundException If you tried to set a non-existent option value. The accepted options depend on the ezcCacheStorage implementation and may vary. @throws ezcBaseValueException If the value is not valid for the desired option. @throws ezcBaseValueException If you submit neither an instance of ezcCacheStorageFileOptions, nor an instance of ezcCacheStorageOptions nor an array.
[ "Set", "new", "options", ".", "This", "method", "allows", "you", "to", "change", "the", "options", "of", "a", "cache", "file", "storage", ".", "Change", "of", "options", "take", "effect", "directly", "after", "this", "method", "has", "been", "called", ".", "The", "available", "options", "depend", "on", "the", "ezcCacheStorageFile", "implementation", ".", "All", "implementations", "have", "to", "offer", "the", "following", "options", ":" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L804-L826
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.calcLifetime
protected function calcLifetime( $file ) { $ttl = $this->options->ttl; if ( file_exists( $file ) && ( $modTime = filemtime( $file ) ) !== false ) { if ( $ttl === false ) { return 1; } return ( ( $lifeTime = time() - $modTime ) < $ttl ? $ttl - $lifeTime : 0 ); } return 0; }
php
protected function calcLifetime( $file ) { $ttl = $this->options->ttl; if ( file_exists( $file ) && ( $modTime = filemtime( $file ) ) !== false ) { if ( $ttl === false ) { return 1; } return ( ( $lifeTime = time() - $modTime ) < $ttl ? $ttl - $lifeTime : 0 ); } return 0; }
[ "protected", "function", "calcLifetime", "(", "$", "file", ")", "{", "$", "ttl", "=", "$", "this", "->", "options", "->", "ttl", ";", "if", "(", "file_exists", "(", "$", "file", ")", "&&", "(", "$", "modTime", "=", "filemtime", "(", "$", "file", ")", ")", "!==", "false", ")", "{", "if", "(", "$", "ttl", "===", "false", ")", "{", "return", "1", ";", "}", "return", "(", "(", "$", "lifeTime", "=", "time", "(", ")", "-", "$", "modTime", ")", "<", "$", "ttl", "?", "$", "ttl", "-", "$", "lifeTime", ":", "0", ")", ";", "}", "return", "0", ";", "}" ]
Calculates the lifetime remaining for a cache object. This calculates the time a cached object stays valid and returns it. In case the TTL is set to false, this method always returns a value of 1. @param string $file The file to calculate the remaining lifetime for. @return int The remaining lifetime in seconds (0 if no time remaining).
[ "Calculates", "the", "lifetime", "remaining", "for", "a", "cache", "object", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L872-L888
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php
ezcCacheStorageFile.extractIdentifier
private function extractIdentifier( $filename ) { // Regex to split up the file name into id, attributes and extension $regex = '( (?:' . preg_quote( $this->properties['location'] ) . ') (?P<id>.*) (?P<attr>(?:-[^-=]+=[^-]+)*) -? # This is added if no attributes are supplied. For whatever reason... (?P<ext>' . preg_quote( $this->options->extension ) . ') )Ux'; if ( preg_match( $regex, $filename, $matches ) !== 1 ) { // @TODO: Should this be an exception? return array( 'id' => '', 'attributes' => '', 'extension' => $this->options->extension, ); } else { // Successfully split return array( 'id' => $matches['id'], 'attributes' => $matches['attr'], 'extension' => $matches['ext'], ); } }
php
private function extractIdentifier( $filename ) { // Regex to split up the file name into id, attributes and extension $regex = '( (?:' . preg_quote( $this->properties['location'] ) . ') (?P<id>.*) (?P<attr>(?:-[^-=]+=[^-]+)*) -? # This is added if no attributes are supplied. For whatever reason... (?P<ext>' . preg_quote( $this->options->extension ) . ') )Ux'; if ( preg_match( $regex, $filename, $matches ) !== 1 ) { // @TODO: Should this be an exception? return array( 'id' => '', 'attributes' => '', 'extension' => $this->options->extension, ); } else { // Successfully split return array( 'id' => $matches['id'], 'attributes' => $matches['attr'], 'extension' => $matches['ext'], ); } }
[ "private", "function", "extractIdentifier", "(", "$", "filename", ")", "{", "// Regex to split up the file name into id, attributes and extension", "$", "regex", "=", "'(\n (?:'", ".", "preg_quote", "(", "$", "this", "->", "properties", "[", "'location'", "]", ")", ".", "')\n (?P<id>.*)\n (?P<attr>(?:-[^-=]+=[^-]+)*)\n -? # This is added if no attributes are supplied. For whatever reason...\n (?P<ext>'", ".", "preg_quote", "(", "$", "this", "->", "options", "->", "extension", ")", ".", "')\n )Ux'", ";", "if", "(", "preg_match", "(", "$", "regex", ",", "$", "filename", ",", "$", "matches", ")", "!==", "1", ")", "{", "// @TODO: Should this be an exception?", "return", "array", "(", "'id'", "=>", "''", ",", "'attributes'", "=>", "''", ",", "'extension'", "=>", "$", "this", "->", "options", "->", "extension", ",", ")", ";", "}", "else", "{", "// Successfully split", "return", "array", "(", "'id'", "=>", "$", "matches", "[", "'id'", "]", ",", "'attributes'", "=>", "$", "matches", "[", "'attr'", "]", ",", "'extension'", "=>", "$", "matches", "[", "'ext'", "]", ",", ")", ";", "}", "}" ]
Extracts ID, attributes and the file extension from a filename. @param string $filename @return array('id'=>string,'attributes'=>string,'ext'=>string)
[ "Extracts", "ID", "attributes", "and", "the", "file", "extension", "from", "a", "filename", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/storage/file.php#L896-L925
dreamfactorysoftware/df-cache
src/Models/RedisConfig.php
RedisConfig.fromJson
public function fromJson($value, $asObject = false) { $value = json_decode($value, !$asObject); if (is_array($value) && isset($value['ssl'])) { if (!is_array($value['ssl'])) { $value['ssl'] = json_decode($value['ssl'], true); } } return $value; }
php
public function fromJson($value, $asObject = false) { $value = json_decode($value, !$asObject); if (is_array($value) && isset($value['ssl'])) { if (!is_array($value['ssl'])) { $value['ssl'] = json_decode($value['ssl'], true); } } return $value; }
[ "public", "function", "fromJson", "(", "$", "value", ",", "$", "asObject", "=", "false", ")", "{", "$", "value", "=", "json_decode", "(", "$", "value", ",", "!", "$", "asObject", ")", ";", "if", "(", "is_array", "(", "$", "value", ")", "&&", "isset", "(", "$", "value", "[", "'ssl'", "]", ")", ")", "{", "if", "(", "!", "is_array", "(", "$", "value", "[", "'ssl'", "]", ")", ")", "{", "$", "value", "[", "'ssl'", "]", "=", "json_decode", "(", "$", "value", "[", "'ssl'", "]", ",", "true", ")", ";", "}", "}", "return", "$", "value", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/dreamfactorysoftware/df-cache/blob/6a2aa5dc2fc7963ce89fd7e8f3d51483d2499451/src/Models/RedisConfig.php#L26-L37
raideer/twitch-api
src/Resources/Blocks.php
Blocks.getBlockedUsers
public function getBlockedUsers($channel, $params = []) { $this->wrapper->checkScope('user_blocks_read'); $defaults = [ 'limit' => 25, 'offset' => 0, ]; return $this->wrapper->request('GET', "users/$channel/blocks", ['query' => $this->resolveOptions($params, $defaults)], true); }
php
public function getBlockedUsers($channel, $params = []) { $this->wrapper->checkScope('user_blocks_read'); $defaults = [ 'limit' => 25, 'offset' => 0, ]; return $this->wrapper->request('GET', "users/$channel/blocks", ['query' => $this->resolveOptions($params, $defaults)], true); }
[ "public", "function", "getBlockedUsers", "(", "$", "channel", ",", "$", "params", "=", "[", "]", ")", "{", "$", "this", "->", "wrapper", "->", "checkScope", "(", "'user_blocks_read'", ")", ";", "$", "defaults", "=", "[", "'limit'", "=>", "25", ",", "'offset'", "=>", "0", ",", "]", ";", "return", "$", "this", "->", "wrapper", "->", "request", "(", "'GET'", ",", "\"users/$channel/blocks\"", ",", "[", "'query'", "=>", "$", "this", "->", "resolveOptions", "(", "$", "params", ",", "$", "defaults", ")", "]", ",", "true", ")", ";", "}" ]
AUTHENTICATED REQUEST. Returns a list of blocks objects on authenticated user's block list. Sorted by recency, newest first. Required scope: user_blocks_read Learn more: https://github.com/justintv/Twitch-API/blob/master/v3_resources/blocks.md#get-usersuserblocks @param string $channel Target Channel name @param array $params @return array
[ "AUTHENTICATED", "REQUEST", "." ]
train
https://github.com/raideer/twitch-api/blob/27ebf1dcb0315206300d507600b6a82ebe33d57e/src/Resources/Blocks.php#L36-L46
raideer/twitch-api
src/Resources/Blocks.php
Blocks.blockUser
public function blockUser($channel, $target) { $this->wrapper->checkScope('user_blocks_edit'); return $this->wrapper->request('PUT', "users/$channel/blocks/$target", [], true); }
php
public function blockUser($channel, $target) { $this->wrapper->checkScope('user_blocks_edit'); return $this->wrapper->request('PUT', "users/$channel/blocks/$target", [], true); }
[ "public", "function", "blockUser", "(", "$", "channel", ",", "$", "target", ")", "{", "$", "this", "->", "wrapper", "->", "checkScope", "(", "'user_blocks_edit'", ")", ";", "return", "$", "this", "->", "wrapper", "->", "request", "(", "'PUT'", ",", "\"users/$channel/blocks/$target\"", ",", "[", "]", ",", "true", ")", ";", "}" ]
AUTHENTICATED REQUEST. Adds $target to authenticated user's block list. Returns a blocks object. Required scope: user_blocks_edit Learn more: https://github.com/justintv/Twitch-API/blob/master/v3_resources/blocks.md#put-usersuserblockstarget @param string $channel Target Channel name @param string $target Target username @return array
[ "AUTHENTICATED", "REQUEST", "." ]
train
https://github.com/raideer/twitch-api/blob/27ebf1dcb0315206300d507600b6a82ebe33d57e/src/Resources/Blocks.php#L63-L68
raideer/twitch-api
src/Resources/Blocks.php
Blocks.unblockUser
public function unblockUser($user, $target) { $this->wrapper->checkScope('user_blocks_edit'); return $this->wrapper->request('DELETE', "users/$user/blocks/$target", [], true); }
php
public function unblockUser($user, $target) { $this->wrapper->checkScope('user_blocks_edit'); return $this->wrapper->request('DELETE', "users/$user/blocks/$target", [], true); }
[ "public", "function", "unblockUser", "(", "$", "user", ",", "$", "target", ")", "{", "$", "this", "->", "wrapper", "->", "checkScope", "(", "'user_blocks_edit'", ")", ";", "return", "$", "this", "->", "wrapper", "->", "request", "(", "'DELETE'", ",", "\"users/$user/blocks/$target\"", ",", "[", "]", ",", "true", ")", ";", "}" ]
AUTHENTICATED REQUEST. Removes $target from $user's block list. Required scope: user_blocks_edit Learn more: https://github.com/justintv/Twitch-API/blob/master/v3_resources/blocks.md#delete-usersuserblockstarget @param string $user Target Channel name @param string $target Target username @return array
[ "AUTHENTICATED", "REQUEST", "." ]
train
https://github.com/raideer/twitch-api/blob/27ebf1dcb0315206300d507600b6a82ebe33d57e/src/Resources/Blocks.php#L85-L90
ouropencode/dachi
src/Kernel.php
Kernel.initialize
public static function initialize() { if(defined('DACHI_KERNEL')) return false; define('DACHI_KERNEL', true); require_once('Kernel.functions.php'); getExecutionTime(); date_default_timezone_set(Configuration::get('dachi.timezone')); error_reporting(-1); define('WORKING_DIRECTORY', getcwd()); Session::start(Configuration::get('sessions.name'), Configuration::get('sessions.domain', false), Configuration::get('sessions.secure', false)); }
php
public static function initialize() { if(defined('DACHI_KERNEL')) return false; define('DACHI_KERNEL', true); require_once('Kernel.functions.php'); getExecutionTime(); date_default_timezone_set(Configuration::get('dachi.timezone')); error_reporting(-1); define('WORKING_DIRECTORY', getcwd()); Session::start(Configuration::get('sessions.name'), Configuration::get('sessions.domain', false), Configuration::get('sessions.secure', false)); }
[ "public", "static", "function", "initialize", "(", ")", "{", "if", "(", "defined", "(", "'DACHI_KERNEL'", ")", ")", "return", "false", ";", "define", "(", "'DACHI_KERNEL'", ",", "true", ")", ";", "require_once", "(", "'Kernel.functions.php'", ")", ";", "getExecutionTime", "(", ")", ";", "date_default_timezone_set", "(", "Configuration", "::", "get", "(", "'dachi.timezone'", ")", ")", ";", "error_reporting", "(", "-", "1", ")", ";", "define", "(", "'WORKING_DIRECTORY'", ",", "getcwd", "(", ")", ")", ";", "Session", "::", "start", "(", "Configuration", "::", "get", "(", "'sessions.name'", ")", ",", "Configuration", "::", "get", "(", "'sessions.domain'", ",", "false", ")", ",", "Configuration", "::", "get", "(", "'sessions.secure'", ",", "false", ")", ")", ";", "}" ]
Initialize the Dachi kernel. @return null
[ "Initialize", "the", "Dachi", "kernel", "." ]
train
https://github.com/ouropencode/dachi/blob/a0e1daf269d0345afbb859ce20ef9da6decd7efe/src/Kernel.php#L26-L40
ouropencode/dachi
src/Kernel.php
Kernel.getEnvironment
public static function getEnvironment($forceCheck = false) { if(self::$environment && !$forceCheck) return self::$environment; self::$environment = "local"; if(file_exists("dachi_environment")) self::$environment = trim(file_get_contents("dachi_environment")); return self::$environment; }
php
public static function getEnvironment($forceCheck = false) { if(self::$environment && !$forceCheck) return self::$environment; self::$environment = "local"; if(file_exists("dachi_environment")) self::$environment = trim(file_get_contents("dachi_environment")); return self::$environment; }
[ "public", "static", "function", "getEnvironment", "(", "$", "forceCheck", "=", "false", ")", "{", "if", "(", "self", "::", "$", "environment", "&&", "!", "$", "forceCheck", ")", "return", "self", "::", "$", "environment", ";", "self", "::", "$", "environment", "=", "\"local\"", ";", "if", "(", "file_exists", "(", "\"dachi_environment\"", ")", ")", "self", "::", "$", "environment", "=", "trim", "(", "file_get_contents", "(", "\"dachi_environment\"", ")", ")", ";", "return", "self", "::", "$", "environment", ";", "}" ]
Get the current environment we are executing in. This is only available if running via the internal LemonDigits.com build toolkit, or if your CI can be configured to output the environment to the 'dachi_environment' file. (this could also be done manually by a developer during deployment) @param bool $forceCheck Should we ignore the cached environment and forceably check the filesystem? @return string
[ "Get", "the", "current", "environment", "we", "are", "executing", "in", "." ]
train
https://github.com/ouropencode/dachi/blob/a0e1daf269d0345afbb859ce20ef9da6decd7efe/src/Kernel.php#L52-L62
ouropencode/dachi
src/Kernel.php
Kernel.getGitHash
public static function getGitHash($forceCheck = false) { if(self::$git_hash && !$forceCheck) return self::$git_hash; self::$git_hash = "ffffff"; if(file_exists("dachi_git_hash")) self::$git_hash = trim(file_get_contents("dachi_git_hash")); return self::$git_hash; }
php
public static function getGitHash($forceCheck = false) { if(self::$git_hash && !$forceCheck) return self::$git_hash; self::$git_hash = "ffffff"; if(file_exists("dachi_git_hash")) self::$git_hash = trim(file_get_contents("dachi_git_hash")); return self::$git_hash; }
[ "public", "static", "function", "getGitHash", "(", "$", "forceCheck", "=", "false", ")", "{", "if", "(", "self", "::", "$", "git_hash", "&&", "!", "$", "forceCheck", ")", "return", "self", "::", "$", "git_hash", ";", "self", "::", "$", "git_hash", "=", "\"ffffff\"", ";", "if", "(", "file_exists", "(", "\"dachi_git_hash\"", ")", ")", "self", "::", "$", "git_hash", "=", "trim", "(", "file_get_contents", "(", "\"dachi_git_hash\"", ")", ")", ";", "return", "self", "::", "$", "git_hash", ";", "}" ]
Get the current short git hash for the revision of code we are executing. This is only available if running via the internal LemonDigits.com build toolkit, or if your CI can be configured to output the short hash (6-chars) to the 'dachi_git_hash' file (this could also be done manually by a developer during deployment) @param bool $forceCheck Should we ignore the cached git hash and forceably check the filesystem? @return string
[ "Get", "the", "current", "short", "git", "hash", "for", "the", "revision", "of", "code", "we", "are", "executing", "." ]
train
https://github.com/ouropencode/dachi/blob/a0e1daf269d0345afbb859ce20ef9da6decd7efe/src/Kernel.php#L74-L84
ouropencode/dachi
src/Kernel.php
Kernel.getVersion
public static function getVersion($fullVersion = false) { return ($fullVersion ? ("v" . self::$version . "." . self::$version_patch) : self::$version); }
php
public static function getVersion($fullVersion = false) { return ($fullVersion ? ("v" . self::$version . "." . self::$version_patch) : self::$version); }
[ "public", "static", "function", "getVersion", "(", "$", "fullVersion", "=", "false", ")", "{", "return", "(", "$", "fullVersion", "?", "(", "\"v\"", ".", "self", "::", "$", "version", ".", "\".\"", ".", "self", "::", "$", "version_patch", ")", ":", "self", "::", "$", "version", ")", ";", "}" ]
Get the Dachi version. @param bool $fullVersion If TRUE, outputs the whole version number (including patch). If FALSE, only outputs the major version. @return string
[ "Get", "the", "Dachi", "version", "." ]
train
https://github.com/ouropencode/dachi/blob/a0e1daf269d0345afbb859ce20ef9da6decd7efe/src/Kernel.php#L91-L93
songshenzong/log
src/Bridge/PropelCollector.php
PropelCollector.convertLogLevel
protected function convertLogLevel($level) { $map = [ Propel::LOG_EMERG => LogLevel::EMERGENCY, Propel::LOG_ALERT => LogLevel::ALERT, Propel::LOG_CRIT => LogLevel::CRITICAL, Propel::LOG_ERR => LogLevel::ERROR, Propel::LOG_WARNING => LogLevel::WARNING, Propel::LOG_NOTICE => LogLevel::NOTICE, Propel::LOG_DEBUG => LogLevel::DEBUG, ]; return $map[$level]; }
php
protected function convertLogLevel($level) { $map = [ Propel::LOG_EMERG => LogLevel::EMERGENCY, Propel::LOG_ALERT => LogLevel::ALERT, Propel::LOG_CRIT => LogLevel::CRITICAL, Propel::LOG_ERR => LogLevel::ERROR, Propel::LOG_WARNING => LogLevel::WARNING, Propel::LOG_NOTICE => LogLevel::NOTICE, Propel::LOG_DEBUG => LogLevel::DEBUG, ]; return $map[$level]; }
[ "protected", "function", "convertLogLevel", "(", "$", "level", ")", "{", "$", "map", "=", "[", "Propel", "::", "LOG_EMERG", "=>", "LogLevel", "::", "EMERGENCY", ",", "Propel", "::", "LOG_ALERT", "=>", "LogLevel", "::", "ALERT", ",", "Propel", "::", "LOG_CRIT", "=>", "LogLevel", "::", "CRITICAL", ",", "Propel", "::", "LOG_ERR", "=>", "LogLevel", "::", "ERROR", ",", "Propel", "::", "LOG_WARNING", "=>", "LogLevel", "::", "WARNING", ",", "Propel", "::", "LOG_NOTICE", "=>", "LogLevel", "::", "NOTICE", ",", "Propel", "::", "LOG_DEBUG", "=>", "LogLevel", "::", "DEBUG", ",", "]", ";", "return", "$", "map", "[", "$", "level", "]", ";", "}" ]
Converts Propel log levels to PSR log levels @param int $level @return string
[ "Converts", "Propel", "log", "levels", "to", "PSR", "log", "levels" ]
train
https://github.com/songshenzong/log/blob/b1e01f7994da47737866eabf82367490eab17c46/src/Bridge/PropelCollector.php#L207-L219
songshenzong/log
src/Bridge/PropelCollector.php
PropelCollector.parseAndLogSqlQuery
protected function parseAndLogSqlQuery($message) { $parts = explode('|', $message, 4); $sql = trim($parts[3]); $duration = 0; if (preg_match('/([0-9]+\.[0-9]+)/', $parts[1], $matches)) { $duration = (float) $matches[1]; } $memory = 0; if (preg_match('/([0-9]+\.[0-9]+) ([A-Z]{1,2})/', $parts[2], $matches)) { $memory = (float) $matches[1]; if ($matches[2] == 'KB') { $memory *= 1024; } elseif ($matches[2] == 'MB') { $memory *= 1024 * 1024; } } $this->statements[] = [ 'sql' => $sql, 'is_success' => true, 'duration' => $duration, 'duration_str' => $this->formatDuration($duration), 'memory' => $memory, 'memory_str' => $this->formatBytes($memory), ]; $this->accumulatedTime += $duration; $this->peakMemory = max($this->peakMemory, $memory); return [$sql, $this->formatDuration($duration)]; }
php
protected function parseAndLogSqlQuery($message) { $parts = explode('|', $message, 4); $sql = trim($parts[3]); $duration = 0; if (preg_match('/([0-9]+\.[0-9]+)/', $parts[1], $matches)) { $duration = (float) $matches[1]; } $memory = 0; if (preg_match('/([0-9]+\.[0-9]+) ([A-Z]{1,2})/', $parts[2], $matches)) { $memory = (float) $matches[1]; if ($matches[2] == 'KB') { $memory *= 1024; } elseif ($matches[2] == 'MB') { $memory *= 1024 * 1024; } } $this->statements[] = [ 'sql' => $sql, 'is_success' => true, 'duration' => $duration, 'duration_str' => $this->formatDuration($duration), 'memory' => $memory, 'memory_str' => $this->formatBytes($memory), ]; $this->accumulatedTime += $duration; $this->peakMemory = max($this->peakMemory, $memory); return [$sql, $this->formatDuration($duration)]; }
[ "protected", "function", "parseAndLogSqlQuery", "(", "$", "message", ")", "{", "$", "parts", "=", "explode", "(", "'|'", ",", "$", "message", ",", "4", ")", ";", "$", "sql", "=", "trim", "(", "$", "parts", "[", "3", "]", ")", ";", "$", "duration", "=", "0", ";", "if", "(", "preg_match", "(", "'/([0-9]+\\.[0-9]+)/'", ",", "$", "parts", "[", "1", "]", ",", "$", "matches", ")", ")", "{", "$", "duration", "=", "(", "float", ")", "$", "matches", "[", "1", "]", ";", "}", "$", "memory", "=", "0", ";", "if", "(", "preg_match", "(", "'/([0-9]+\\.[0-9]+) ([A-Z]{1,2})/'", ",", "$", "parts", "[", "2", "]", ",", "$", "matches", ")", ")", "{", "$", "memory", "=", "(", "float", ")", "$", "matches", "[", "1", "]", ";", "if", "(", "$", "matches", "[", "2", "]", "==", "'KB'", ")", "{", "$", "memory", "*=", "1024", ";", "}", "elseif", "(", "$", "matches", "[", "2", "]", "==", "'MB'", ")", "{", "$", "memory", "*=", "1024", "*", "1024", ";", "}", "}", "$", "this", "->", "statements", "[", "]", "=", "[", "'sql'", "=>", "$", "sql", ",", "'is_success'", "=>", "true", ",", "'duration'", "=>", "$", "duration", ",", "'duration_str'", "=>", "$", "this", "->", "formatDuration", "(", "$", "duration", ")", ",", "'memory'", "=>", "$", "memory", ",", "'memory_str'", "=>", "$", "this", "->", "formatBytes", "(", "$", "memory", ")", ",", "]", ";", "$", "this", "->", "accumulatedTime", "+=", "$", "duration", ";", "$", "this", "->", "peakMemory", "=", "max", "(", "$", "this", "->", "peakMemory", ",", "$", "memory", ")", ";", "return", "[", "$", "sql", ",", "$", "this", "->", "formatDuration", "(", "$", "duration", ")", "]", ";", "}" ]
Parse a log line to extract query information @param string $message @return array
[ "Parse", "a", "log", "line", "to", "extract", "query", "information" ]
train
https://github.com/songshenzong/log/blob/b1e01f7994da47737866eabf82367490eab17c46/src/Bridge/PropelCollector.php#L228-L259
heidelpay/PhpDoc
src/phpDocumentor/Configuration/Loader.php
Loader.load
public function load($templatePath, $userConfigurationPath, $class = 'phpDocumentor\Configuration') { $userConfigFilePath = $this->fetchUserConfigFileFromCommandLineOptions(); if ($this->isValidFile($userConfigFilePath)) { chdir(dirname($userConfigFilePath)); } else { $userConfigFilePath = null; } return $this->createConfigurationObject($templatePath, $userConfigurationPath, $userConfigFilePath, $class); }
php
public function load($templatePath, $userConfigurationPath, $class = 'phpDocumentor\Configuration') { $userConfigFilePath = $this->fetchUserConfigFileFromCommandLineOptions(); if ($this->isValidFile($userConfigFilePath)) { chdir(dirname($userConfigFilePath)); } else { $userConfigFilePath = null; } return $this->createConfigurationObject($templatePath, $userConfigurationPath, $userConfigFilePath, $class); }
[ "public", "function", "load", "(", "$", "templatePath", ",", "$", "userConfigurationPath", ",", "$", "class", "=", "'phpDocumentor\\Configuration'", ")", "{", "$", "userConfigFilePath", "=", "$", "this", "->", "fetchUserConfigFileFromCommandLineOptions", "(", ")", ";", "if", "(", "$", "this", "->", "isValidFile", "(", "$", "userConfigFilePath", ")", ")", "{", "chdir", "(", "dirname", "(", "$", "userConfigFilePath", ")", ")", ";", "}", "else", "{", "$", "userConfigFilePath", "=", "null", ";", "}", "return", "$", "this", "->", "createConfigurationObject", "(", "$", "templatePath", ",", "$", "userConfigurationPath", ",", "$", "userConfigFilePath", ",", "$", "class", ")", ";", "}" ]
Loads the configuration from the provided paths and returns a populated configuration object. @param string $templatePath Path to configuration file containing default settings. @param string $userConfigurationPath Path to a file containing user overrides. @param string $class The class to instantiate and populate with these options. @return object
[ "Loads", "the", "configuration", "from", "the", "provided", "paths", "and", "returns", "a", "populated", "configuration", "object", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Configuration/Loader.php#L52-L63
heidelpay/PhpDoc
src/phpDocumentor/Configuration/Loader.php
Loader.fetchUserConfigFileFromCommandLineOptions
private function fetchUserConfigFileFromCommandLineOptions() { $input = new ArgvInput(); $userConfigFilePath = $input->getParameterOption('--config'); if (!$userConfigFilePath) { $userConfigFilePath = $input->getParameterOption('-c'); } if ($userConfigFilePath !== false) { $userConfigFilePath = realpath($userConfigFilePath); } return $userConfigFilePath; }
php
private function fetchUserConfigFileFromCommandLineOptions() { $input = new ArgvInput(); $userConfigFilePath = $input->getParameterOption('--config'); if (!$userConfigFilePath) { $userConfigFilePath = $input->getParameterOption('-c'); } if ($userConfigFilePath !== false) { $userConfigFilePath = realpath($userConfigFilePath); } return $userConfigFilePath; }
[ "private", "function", "fetchUserConfigFileFromCommandLineOptions", "(", ")", "{", "$", "input", "=", "new", "ArgvInput", "(", ")", ";", "$", "userConfigFilePath", "=", "$", "input", "->", "getParameterOption", "(", "'--config'", ")", ";", "if", "(", "!", "$", "userConfigFilePath", ")", "{", "$", "userConfigFilePath", "=", "$", "input", "->", "getParameterOption", "(", "'-c'", ")", ";", "}", "if", "(", "$", "userConfigFilePath", "!==", "false", ")", "{", "$", "userConfigFilePath", "=", "realpath", "(", "$", "userConfigFilePath", ")", ";", "}", "return", "$", "userConfigFilePath", ";", "}" ]
Reads the `--config`, or `-c`, command line option and returns a path to the configuration file from those options or false if no existing path was given. @return bool|string
[ "Reads", "the", "--", "config", "or", "-", "c", "command", "line", "option", "and", "returns", "a", "path", "to", "the", "configuration", "file", "from", "those", "options", "or", "false", "if", "no", "existing", "path", "was", "given", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Configuration/Loader.php#L71-L85
heidelpay/PhpDoc
src/phpDocumentor/Configuration/Loader.php
Loader.createConfigurationObject
private function createConfigurationObject($templatePath, $defaultUserConfigPath, $customUserConfigPath, $class) { $config = $this->serializer->deserialize(file_get_contents($templatePath), $class, 'xml'); $customUserConfigPath = $customUserConfigPath ? : $defaultUserConfigPath; if ($customUserConfigPath !== null && is_readable($customUserConfigPath)) { $userConfigFile = $this->serializer->deserialize(file_get_contents($customUserConfigPath), $class, 'xml'); $config = $this->merger->run($config, $userConfigFile); } return $config; }
php
private function createConfigurationObject($templatePath, $defaultUserConfigPath, $customUserConfigPath, $class) { $config = $this->serializer->deserialize(file_get_contents($templatePath), $class, 'xml'); $customUserConfigPath = $customUserConfigPath ? : $defaultUserConfigPath; if ($customUserConfigPath !== null && is_readable($customUserConfigPath)) { $userConfigFile = $this->serializer->deserialize(file_get_contents($customUserConfigPath), $class, 'xml'); $config = $this->merger->run($config, $userConfigFile); } return $config; }
[ "private", "function", "createConfigurationObject", "(", "$", "templatePath", ",", "$", "defaultUserConfigPath", ",", "$", "customUserConfigPath", ",", "$", "class", ")", "{", "$", "config", "=", "$", "this", "->", "serializer", "->", "deserialize", "(", "file_get_contents", "(", "$", "templatePath", ")", ",", "$", "class", ",", "'xml'", ")", ";", "$", "customUserConfigPath", "=", "$", "customUserConfigPath", "?", ":", "$", "defaultUserConfigPath", ";", "if", "(", "$", "customUserConfigPath", "!==", "null", "&&", "is_readable", "(", "$", "customUserConfigPath", ")", ")", "{", "$", "userConfigFile", "=", "$", "this", "->", "serializer", "->", "deserialize", "(", "file_get_contents", "(", "$", "customUserConfigPath", ")", ",", "$", "class", ",", "'xml'", ")", ";", "$", "config", "=", "$", "this", "->", "merger", "->", "run", "(", "$", "config", ",", "$", "userConfigFile", ")", ";", "}", "return", "$", "config", ";", "}" ]
Combines the given configuration files and serializes a new Configuration object from them. @param string $templatePath Path to the template configuration file. @param string $defaultUserConfigPath Path to the phpdoc.xml or phpdoc,dist.xml in the current working directory. @param null|bool|string $customUserConfigPath Path to the user-defined config file given using the command-line. @param string $class Base Configuration class name to construct and populate. @return null|object
[ "Combines", "the", "given", "configuration", "files", "and", "serializes", "a", "new", "Configuration", "object", "from", "them", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Configuration/Loader.php#L110-L122
zhouyl/mellivora
Mellivora/Database/Schema/PostgresBuilder.php
PostgresBuilder.hasTable
public function hasTable($table) { if (is_array($schema = $this->connection->getConfig('schema'))) { $schema = head($schema); } $table = $this->connection->getTablePrefix() . $table; return count($this->connection->select( $this->grammar->compileTableExists(), [$schema, $table] )) > 0; }
php
public function hasTable($table) { if (is_array($schema = $this->connection->getConfig('schema'))) { $schema = head($schema); } $table = $this->connection->getTablePrefix() . $table; return count($this->connection->select( $this->grammar->compileTableExists(), [$schema, $table] )) > 0; }
[ "public", "function", "hasTable", "(", "$", "table", ")", "{", "if", "(", "is_array", "(", "$", "schema", "=", "$", "this", "->", "connection", "->", "getConfig", "(", "'schema'", ")", ")", ")", "{", "$", "schema", "=", "head", "(", "$", "schema", ")", ";", "}", "$", "table", "=", "$", "this", "->", "connection", "->", "getTablePrefix", "(", ")", ".", "$", "table", ";", "return", "count", "(", "$", "this", "->", "connection", "->", "select", "(", "$", "this", "->", "grammar", "->", "compileTableExists", "(", ")", ",", "[", "$", "schema", ",", "$", "table", "]", ")", ")", ">", "0", ";", "}" ]
Determine if the given table exists. @param string $table @return bool
[ "Determine", "if", "the", "given", "table", "exists", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Schema/PostgresBuilder.php#L14-L26
10quality/wp-file
src/File.php
File.authenticate
public function authenticate( $url = null ) { if ( empty( $url ) ) $url = site_url() . '/wp-admin/'; if ( ! function_exists( 'get_filesystem_method' ) ) require_once( get_wp_home_path().'/wp-admin/includes/file.php' ); if ( ! function_exists( 'submit_button' ) ) require_once( get_wp_home_path().'/wp-admin/includes/template.php' ); if ( get_filesystem_method() === 'direct' ) { ob_start(); $creds = request_filesystem_credentials( $url, '', false, false, array() ); $html = ob_get_clean(); if ( ! WP_Filesystem( $creds ) || ! empty( $html ) ) { $this->authenticated = false; } $this->authenticated = true; } else { add_action( 'admin_notice', [ &$this, 'admin_notice' ] ); } }
php
public function authenticate( $url = null ) { if ( empty( $url ) ) $url = site_url() . '/wp-admin/'; if ( ! function_exists( 'get_filesystem_method' ) ) require_once( get_wp_home_path().'/wp-admin/includes/file.php' ); if ( ! function_exists( 'submit_button' ) ) require_once( get_wp_home_path().'/wp-admin/includes/template.php' ); if ( get_filesystem_method() === 'direct' ) { ob_start(); $creds = request_filesystem_credentials( $url, '', false, false, array() ); $html = ob_get_clean(); if ( ! WP_Filesystem( $creds ) || ! empty( $html ) ) { $this->authenticated = false; } $this->authenticated = true; } else { add_action( 'admin_notice', [ &$this, 'admin_notice' ] ); } }
[ "public", "function", "authenticate", "(", "$", "url", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "url", ")", ")", "$", "url", "=", "site_url", "(", ")", ".", "'/wp-admin/'", ";", "if", "(", "!", "function_exists", "(", "'get_filesystem_method'", ")", ")", "require_once", "(", "get_wp_home_path", "(", ")", ".", "'/wp-admin/includes/file.php'", ")", ";", "if", "(", "!", "function_exists", "(", "'submit_button'", ")", ")", "require_once", "(", "get_wp_home_path", "(", ")", ".", "'/wp-admin/includes/template.php'", ")", ";", "if", "(", "get_filesystem_method", "(", ")", "===", "'direct'", ")", "{", "ob_start", "(", ")", ";", "$", "creds", "=", "request_filesystem_credentials", "(", "$", "url", ",", "''", ",", "false", ",", "false", ",", "array", "(", ")", ")", ";", "$", "html", "=", "ob_get_clean", "(", ")", ";", "if", "(", "!", "WP_Filesystem", "(", "$", "creds", ")", "||", "!", "empty", "(", "$", "html", ")", ")", "{", "$", "this", "->", "authenticated", "=", "false", ";", "}", "$", "this", "->", "authenticated", "=", "true", ";", "}", "else", "{", "add_action", "(", "'admin_notice'", ",", "[", "&", "$", "this", ",", "'admin_notice'", "]", ")", ";", "}", "}" ]
Authenticates with wordpress and validates filesystem credentials. @since 0.9.0 @since 0.9.2 Bug fix for when functions are not loaded. @since 0.9.4 Bug fix missing "submit_button". @param string $url Url to authenticate with.
[ "Authenticates", "with", "wordpress", "and", "validates", "filesystem", "credentials", ".", "@since", "0", ".", "9", ".", "0", "@since", "0", ".", "9", ".", "2", "Bug", "fix", "for", "when", "functions", "are", "not", "loaded", ".", "@since", "0", ".", "9", ".", "4", "Bug", "fix", "missing", "submit_button", "." ]
train
https://github.com/10quality/wp-file/blob/282f0f6733a9e18b392a8b9999dcd8949275a77b/src/File.php#L57-L76
10quality/wp-file
src/File.php
File.write
public function write( $filename, $content ) { if (!$this->authenticated) return false; global $wp_filesystem; return $wp_filesystem->put_contents( $filename, $content, defined( FS_CHMOD_FILE ) ? FS_CHMOD_FILE : ( 0644 & ~ umask() ) ); }
php
public function write( $filename, $content ) { if (!$this->authenticated) return false; global $wp_filesystem; return $wp_filesystem->put_contents( $filename, $content, defined( FS_CHMOD_FILE ) ? FS_CHMOD_FILE : ( 0644 & ~ umask() ) ); }
[ "public", "function", "write", "(", "$", "filename", ",", "$", "content", ")", "{", "if", "(", "!", "$", "this", "->", "authenticated", ")", "return", "false", ";", "global", "$", "wp_filesystem", ";", "return", "$", "wp_filesystem", "->", "put_contents", "(", "$", "filename", ",", "$", "content", ",", "defined", "(", "FS_CHMOD_FILE", ")", "?", "FS_CHMOD_FILE", ":", "(", "0644", "&", "~", "umask", "(", ")", ")", ")", ";", "}" ]
Writes content in a file. @since 0.9.0 @since 0.9.3 Fixes undefined constant FS_CHMOD_FILE. @global $wp_filesytem @param string $filename File name. @param mixed $content File content.
[ "Writes", "content", "in", "a", "file", ".", "@since", "0", ".", "9", ".", "0", "@since", "0", ".", "9", ".", "3", "Fixes", "undefined", "constant", "FS_CHMOD_FILE", "." ]
train
https://github.com/10quality/wp-file/blob/282f0f6733a9e18b392a8b9999dcd8949275a77b/src/File.php#L106-L115
hametuha/wpametu
src/WPametu/UI/Field/Base.php
Base.render
public function render( \WP_Post $post = null ){ $required = $this->get_required($post); $label = esc_html($this->label); $desc_str = $this->description; $desc = !empty($desc_str) ? sprintf('<p class="description">%s</p>', $this->description) : ''; $input = $this->get_field($post); echo $this->render_row($label, $required, $input, $desc, $post); }
php
public function render( \WP_Post $post = null ){ $required = $this->get_required($post); $label = esc_html($this->label); $desc_str = $this->description; $desc = !empty($desc_str) ? sprintf('<p class="description">%s</p>', $this->description) : ''; $input = $this->get_field($post); echo $this->render_row($label, $required, $input, $desc, $post); }
[ "public", "function", "render", "(", "\\", "WP_Post", "$", "post", "=", "null", ")", "{", "$", "required", "=", "$", "this", "->", "get_required", "(", "$", "post", ")", ";", "$", "label", "=", "esc_html", "(", "$", "this", "->", "label", ")", ";", "$", "desc_str", "=", "$", "this", "->", "description", ";", "$", "desc", "=", "!", "empty", "(", "$", "desc_str", ")", "?", "sprintf", "(", "'<p class=\"description\">%s</p>'", ",", "$", "this", "->", "description", ")", ":", "''", ";", "$", "input", "=", "$", "this", "->", "get_field", "(", "$", "post", ")", ";", "echo", "$", "this", "->", "render_row", "(", "$", "label", ",", "$", "required", ",", "$", "input", ",", "$", "desc", ",", "$", "post", ")", ";", "}" ]
Render input field @param \WP_Post $post
[ "Render", "input", "field" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Base.php#L74-L81
hametuha/wpametu
src/WPametu/UI/Field/Base.php
Base.get_data
protected function get_data( \WP_Post $post ){ switch( $this->name ){ case 'excerpt': return $post->post_excerpt; break; default: if( false !== array_search(Taxonomy::class, class_uses(get_called_class())) ){ // This is taxonomy $terms = get_the_terms($post, $this->name); $term_id = 0; if( $terms && !is_wp_error($terms) ){ foreach($terms as $term){ $term_id = $term->term_id; } } return $term_id; }else{ // This is post meta return get_post_meta($post->ID, $this->name, true); } break; } }
php
protected function get_data( \WP_Post $post ){ switch( $this->name ){ case 'excerpt': return $post->post_excerpt; break; default: if( false !== array_search(Taxonomy::class, class_uses(get_called_class())) ){ // This is taxonomy $terms = get_the_terms($post, $this->name); $term_id = 0; if( $terms && !is_wp_error($terms) ){ foreach($terms as $term){ $term_id = $term->term_id; } } return $term_id; }else{ // This is post meta return get_post_meta($post->ID, $this->name, true); } break; } }
[ "protected", "function", "get_data", "(", "\\", "WP_Post", "$", "post", ")", "{", "switch", "(", "$", "this", "->", "name", ")", "{", "case", "'excerpt'", ":", "return", "$", "post", "->", "post_excerpt", ";", "break", ";", "default", ":", "if", "(", "false", "!==", "array_search", "(", "Taxonomy", "::", "class", ",", "class_uses", "(", "get_called_class", "(", ")", ")", ")", ")", "{", "// This is taxonomy", "$", "terms", "=", "get_the_terms", "(", "$", "post", ",", "$", "this", "->", "name", ")", ";", "$", "term_id", "=", "0", ";", "if", "(", "$", "terms", "&&", "!", "is_wp_error", "(", "$", "terms", ")", ")", "{", "foreach", "(", "$", "terms", "as", "$", "term", ")", "{", "$", "term_id", "=", "$", "term", "->", "term_id", ";", "}", "}", "return", "$", "term_id", ";", "}", "else", "{", "// This is post meta", "return", "get_post_meta", "(", "$", "post", "->", "ID", ",", "$", "this", "->", "name", ",", "true", ")", ";", "}", "break", ";", "}", "}" ]
Get saved data @param \WP_Post $post @return mixed
[ "Get", "saved", "data" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Base.php#L131-L154
hametuha/wpametu
src/WPametu/UI/Field/Base.php
Base.update
public function update($value, \WP_Post $post = null){ if( $this->validate($value) ){ $this->save($value, $post); } }
php
public function update($value, \WP_Post $post = null){ if( $this->validate($value) ){ $this->save($value, $post); } }
[ "public", "function", "update", "(", "$", "value", ",", "\\", "WP_Post", "$", "post", "=", "null", ")", "{", "if", "(", "$", "this", "->", "validate", "(", "$", "value", ")", ")", "{", "$", "this", "->", "save", "(", "$", "value", ",", "$", "post", ")", ";", "}", "}" ]
Save data as value @param mixed $value @param \WP_Post $post
[ "Save", "data", "as", "value" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Base.php#L162-L166
hametuha/wpametu
src/WPametu/UI/Field/Base.php
Base.save
protected function save($value, \WP_Post $post = null){ update_post_meta($post->ID, $this->name, $value); }
php
protected function save($value, \WP_Post $post = null){ update_post_meta($post->ID, $this->name, $value); }
[ "protected", "function", "save", "(", "$", "value", ",", "\\", "WP_Post", "$", "post", "=", "null", ")", "{", "update_post_meta", "(", "$", "post", "->", "ID", ",", "$", "this", "->", "name", ",", "$", "value", ")", ";", "}" ]
Save post data @param mixed $value @param \WP_Post $post
[ "Save", "post", "data" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Base.php#L174-L176
mauretto78/array-query
src/QueryBuilder.php
QueryBuilder.sortedBy
public function sortedBy($key, $operator = 'ASC', $format = null) { if (!$this->isAValidSortingOperator($operator)) { throw new NotValidSortingOperatorException($operator.' is not a valid sorting operator.'); } $this->sortedBy = [ 'key' => $key, 'order' => $operator, 'format' => $format ]; return $this; }
php
public function sortedBy($key, $operator = 'ASC', $format = null) { if (!$this->isAValidSortingOperator($operator)) { throw new NotValidSortingOperatorException($operator.' is not a valid sorting operator.'); } $this->sortedBy = [ 'key' => $key, 'order' => $operator, 'format' => $format ]; return $this; }
[ "public", "function", "sortedBy", "(", "$", "key", ",", "$", "operator", "=", "'ASC'", ",", "$", "format", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "isAValidSortingOperator", "(", "$", "operator", ")", ")", "{", "throw", "new", "NotValidSortingOperatorException", "(", "$", "operator", ".", "' is not a valid sorting operator.'", ")", ";", "}", "$", "this", "->", "sortedBy", "=", "[", "'key'", "=>", "$", "key", ",", "'order'", "=>", "$", "operator", ",", "'format'", "=>", "$", "format", "]", ";", "return", "$", "this", ";", "}" ]
@param $key @param string $operator @return $this @throws NotValidSortingOperatorException
[ "@param", "$key", "@param", "string", "$operator" ]
train
https://github.com/mauretto78/array-query/blob/f6079258c8c6eea67e05a671a3f85dd28c4f5915/src/QueryBuilder.php#L159-L172
mauretto78/array-query
src/QueryBuilder.php
QueryBuilder.join
public function join($array, $arrayName, $parentKey, $foreignKey) { $this->join[] = [ 'array' => $array, 'arrayName' => $arrayName, 'parentKey' => $parentKey, 'foreignKey' => $foreignKey, ]; return $this; }
php
public function join($array, $arrayName, $parentKey, $foreignKey) { $this->join[] = [ 'array' => $array, 'arrayName' => $arrayName, 'parentKey' => $parentKey, 'foreignKey' => $foreignKey, ]; return $this; }
[ "public", "function", "join", "(", "$", "array", ",", "$", "arrayName", ",", "$", "parentKey", ",", "$", "foreignKey", ")", "{", "$", "this", "->", "join", "[", "]", "=", "[", "'array'", "=>", "$", "array", ",", "'arrayName'", "=>", "$", "arrayName", ",", "'parentKey'", "=>", "$", "parentKey", ",", "'foreignKey'", "=>", "$", "foreignKey", ",", "]", ";", "return", "$", "this", ";", "}" ]
@param $array @param $arrayName @param $parentKey @param $foreignKey @return $this
[ "@param", "$array", "@param", "$arrayName", "@param", "$parentKey", "@param", "$foreignKey" ]
train
https://github.com/mauretto78/array-query/blob/f6079258c8c6eea67e05a671a3f85dd28c4f5915/src/QueryBuilder.php#L223-L233
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/utilities_pgsql.php
ezcDbUtilitiesPgsql.cleanup
public function cleanup() { $this->db->beginTransaction(); // drop tables $rslt = $this->db->query( "SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename NOT LIKE 'pg_%'" ); $rslt->setFetchMode( PDO::FETCH_NUM ); $rows = $rslt->fetchAll(); unset( $rslt ); foreach ( $rows as $row ) { $table = $row[0]; $this->db->exec( "DROP TABLE $table" ); } // drop sequences $rslt = $this->db->query( "SELECT relname FROM pg_catalog.pg_class WHERE relkind='S'" ); $rslt->setFetchMode( PDO::FETCH_NUM ); $rows = $rslt->fetchAll(); foreach ( $rows as $row ) { $seq = $row[0]; $this->db->exec( "DROP SEQUENCE $seq" ); } // FIXME: drop triggers? $this->db->commit(); }
php
public function cleanup() { $this->db->beginTransaction(); // drop tables $rslt = $this->db->query( "SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename NOT LIKE 'pg_%'" ); $rslt->setFetchMode( PDO::FETCH_NUM ); $rows = $rslt->fetchAll(); unset( $rslt ); foreach ( $rows as $row ) { $table = $row[0]; $this->db->exec( "DROP TABLE $table" ); } // drop sequences $rslt = $this->db->query( "SELECT relname FROM pg_catalog.pg_class WHERE relkind='S'" ); $rslt->setFetchMode( PDO::FETCH_NUM ); $rows = $rslt->fetchAll(); foreach ( $rows as $row ) { $seq = $row[0]; $this->db->exec( "DROP SEQUENCE $seq" ); } // FIXME: drop triggers? $this->db->commit(); }
[ "public", "function", "cleanup", "(", ")", "{", "$", "this", "->", "db", "->", "beginTransaction", "(", ")", ";", "// drop tables", "$", "rslt", "=", "$", "this", "->", "db", "->", "query", "(", "\"SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename NOT LIKE 'pg_%'\"", ")", ";", "$", "rslt", "->", "setFetchMode", "(", "PDO", "::", "FETCH_NUM", ")", ";", "$", "rows", "=", "$", "rslt", "->", "fetchAll", "(", ")", ";", "unset", "(", "$", "rslt", ")", ";", "foreach", "(", "$", "rows", "as", "$", "row", ")", "{", "$", "table", "=", "$", "row", "[", "0", "]", ";", "$", "this", "->", "db", "->", "exec", "(", "\"DROP TABLE $table\"", ")", ";", "}", "// drop sequences", "$", "rslt", "=", "$", "this", "->", "db", "->", "query", "(", "\"SELECT relname FROM pg_catalog.pg_class WHERE relkind='S'\"", ")", ";", "$", "rslt", "->", "setFetchMode", "(", "PDO", "::", "FETCH_NUM", ")", ";", "$", "rows", "=", "$", "rslt", "->", "fetchAll", "(", ")", ";", "foreach", "(", "$", "rows", "as", "$", "row", ")", "{", "$", "seq", "=", "$", "row", "[", "0", "]", ";", "$", "this", "->", "db", "->", "exec", "(", "\"DROP SEQUENCE $seq\"", ")", ";", "}", "// FIXME: drop triggers?", "$", "this", "->", "db", "->", "commit", "(", ")", ";", "}" ]
Remove all tables from the database.
[ "Remove", "all", "tables", "from", "the", "database", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/utilities_pgsql.php#L41-L69
alevilar/ristorantino-vendor
Printers/Lib/DriverView/Helper/HasarSMHP321fFiscalHelper.php
HasarSMHP321fFiscalHelper.printLineItem
public function printLineItem($descripcion_articulo, $cantidad, $monto, $porcentaje_iva = 21, $suma = true, $impuesto_interno = 0, $display = 0, $precio_total = true){ $fs = $this->cm('FS'); $descripcion_articulo = substr($descripcion_articulo,0,23); if(!is_numeric($cantidad)) return false; if(!is_numeric($monto)) return false; $suma_monto = $suma?'M':'m'; $precio_total = $precio_total?'T':'B'; $comando = "B".$fs.$descripcion_articulo.$fs.$cantidad.$fs.$monto.$fs.$porcentaje_iva.$fs.$suma_monto.$fs.$impuesto_interno.$fs.$display.$fs.$precio_total; return $comando; }
php
public function printLineItem($descripcion_articulo, $cantidad, $monto, $porcentaje_iva = 21, $suma = true, $impuesto_interno = 0, $display = 0, $precio_total = true){ $fs = $this->cm('FS'); $descripcion_articulo = substr($descripcion_articulo,0,23); if(!is_numeric($cantidad)) return false; if(!is_numeric($monto)) return false; $suma_monto = $suma?'M':'m'; $precio_total = $precio_total?'T':'B'; $comando = "B".$fs.$descripcion_articulo.$fs.$cantidad.$fs.$monto.$fs.$porcentaje_iva.$fs.$suma_monto.$fs.$impuesto_interno.$fs.$display.$fs.$precio_total; return $comando; }
[ "public", "function", "printLineItem", "(", "$", "descripcion_articulo", ",", "$", "cantidad", ",", "$", "monto", ",", "$", "porcentaje_iva", "=", "21", ",", "$", "suma", "=", "true", ",", "$", "impuesto_interno", "=", "0", ",", "$", "display", "=", "0", ",", "$", "precio_total", "=", "true", ")", "{", "$", "fs", "=", "$", "this", "->", "cm", "(", "'FS'", ")", ";", "$", "descripcion_articulo", "=", "substr", "(", "$", "descripcion_articulo", ",", "0", ",", "23", ")", ";", "if", "(", "!", "is_numeric", "(", "$", "cantidad", ")", ")", "return", "false", ";", "if", "(", "!", "is_numeric", "(", "$", "monto", ")", ")", "return", "false", ";", "$", "suma_monto", "=", "$", "suma", "?", "'M'", ":", "'m'", ";", "$", "precio_total", "=", "$", "precio_total", "?", "'T'", ":", "'B'", ";", "$", "comando", "=", "\"B\"", ".", "$", "fs", ".", "$", "descripcion_articulo", ".", "$", "fs", ".", "$", "cantidad", ".", "$", "fs", ".", "$", "monto", ".", "$", "fs", ".", "$", "porcentaje_iva", ".", "$", "fs", ".", "$", "suma_monto", ".", "$", "fs", ".", "$", "impuesto_interno", ".", "$", "fs", ".", "$", "display", ".", "$", "fs", ".", "$", "precio_total", ";", "return", "$", "comando", ";", "}" ]
Imprime un articulo, o sea una linea del articulo con su description y su precio, cantidad, etc @param string $descripcion_articulo descripcion del articulo EJ: Coca-Cola hasta 23 caracteres @param number $cantidad puede ser un entero o un float depende de la impresora @param number $monto float o integer depende de laimpresora @param number $porcentaje_iva depende de la impresora algunas hay queponerle el porcentaje estilo 21.00, y otras va un 0.21 @param boolean $suma dice si el item suma o resta @param number $impuesto_interno puede ser float o integer dependiendo laimpresora @param number $display si la impresora tiene display aca va un digito especial para que sepa que mostrar en el display @param boolean $precio_totalsi es precio tital quiere decir que el precio que le pasé como parametro tiene el IVA incluido, caso contrario, el precio es sin IVA y la impresora se lo va a sumar automaticamente de acuerdo al IVA qe se le pasó cmo parametro
[ "Imprime", "un", "articulo", "o", "sea", "una", "linea", "del", "articulo", "con", "su", "description", "y", "su", "precio", "cantidad", "etc" ]
train
https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Printers/Lib/DriverView/Helper/HasarSMHP321fFiscalHelper.php#L77-L88