repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
staudenmeir/belongs-to-through
src/Traits/BelongsToThrough.php
BelongsToThrough.newBelongsToThrough
protected function newBelongsToThrough(Builder $query, Model $parent, array $throughParents, $localKey, $prefix, array $foreignKeyLookup) { return new Relation($query, $parent, $throughParents, $localKey, $prefix, $foreignKeyLookup); }
php
protected function newBelongsToThrough(Builder $query, Model $parent, array $throughParents, $localKey, $prefix, array $foreignKeyLookup) { return new Relation($query, $parent, $throughParents, $localKey, $prefix, $foreignKeyLookup); }
[ "protected", "function", "newBelongsToThrough", "(", "Builder", "$", "query", ",", "Model", "$", "parent", ",", "array", "$", "throughParents", ",", "$", "localKey", ",", "$", "prefix", ",", "array", "$", "foreignKeyLookup", ")", "{", "return", "new", "Relat...
Instantiate a new BelongsToThrough relationship. @param \Illuminate\Database\Eloquent\Builder $query @param \Illuminate\Database\Eloquent\Model $parent @param \Illuminate\Database\Eloquent\Model[] $throughParents @param string $localKey @param string $prefix @param array $foreignKeyLookup @return \Znck\Eloquent\Relations\BelongsToThrough
[ "Instantiate", "a", "new", "BelongsToThrough", "relationship", "." ]
b7be672324bdfc709787b49c22df84fd97734726
https://github.com/staudenmeir/belongs-to-through/blob/b7be672324bdfc709787b49c22df84fd97734726/src/Traits/BelongsToThrough.php#L69-L72
train
staudenmeir/belongs-to-through
src/Relations/BelongsToThrough.php
BelongsToThrough.getForeignKeyName
protected function getForeignKeyName(Model $model) { $table = $model->getTable(); if (array_key_exists($table, $this->foreignKeyLookup)) { return $this->foreignKeyLookup[$table]; } return Str::singular($table).'_id'; }
php
protected function getForeignKeyName(Model $model) { $table = $model->getTable(); if (array_key_exists($table, $this->foreignKeyLookup)) { return $this->foreignKeyLookup[$table]; } return Str::singular($table).'_id'; }
[ "protected", "function", "getForeignKeyName", "(", "Model", "$", "model", ")", "{", "$", "table", "=", "$", "model", "->", "getTable", "(", ")", ";", "if", "(", "array_key_exists", "(", "$", "table", ",", "$", "this", "->", "foreignKeyLookup", ")", ")", ...
Get the foreign key for a model. @param \Illuminate\Database\Eloquent\Model $model @return string
[ "Get", "the", "foreign", "key", "for", "a", "model", "." ]
b7be672324bdfc709787b49c22df84fd97734726
https://github.com/staudenmeir/belongs-to-through/blob/b7be672324bdfc709787b49c22df84fd97734726/src/Relations/BelongsToThrough.php#L112-L121
train
greggilbert/recaptcha
src/RecaptchaServiceProvider.php
RecaptchaServiceProvider.addValidator
public function addValidator() { $this->app->validator->extendImplicit('recaptcha', function ($attribute, $value, $parameters) { $captcha = app('recaptcha.service'); $challenge = app('request')->input($captcha->getResponseKey()); return $captcha->check($challenge, $value); }, 'Please ensure that you are a human!'); }
php
public function addValidator() { $this->app->validator->extendImplicit('recaptcha', function ($attribute, $value, $parameters) { $captcha = app('recaptcha.service'); $challenge = app('request')->input($captcha->getResponseKey()); return $captcha->check($challenge, $value); }, 'Please ensure that you are a human!'); }
[ "public", "function", "addValidator", "(", ")", "{", "$", "this", "->", "app", "->", "validator", "->", "extendImplicit", "(", "'recaptcha'", ",", "function", "(", "$", "attribute", ",", "$", "value", ",", "$", "parameters", ")", "{", "$", "captcha", "="...
Extends Validator to include a recaptcha type
[ "Extends", "Validator", "to", "include", "a", "recaptcha", "type" ]
c2ed383785a4fe20467ce470c97c303e5c5b85de
https://github.com/greggilbert/recaptcha/blob/c2ed383785a4fe20467ce470c97c303e5c5b85de/src/RecaptchaServiceProvider.php#L36-L44
train
greggilbert/recaptcha
src/Recaptcha.php
Recaptcha.render
public function render($options = [ ]) { $mergedOptions = array_merge($this->config['options'], $options); $data = [ 'public_key' => value($this->config['public_key']), 'options' => $mergedOptions, 'dataParams' => $this->extractDataParams($mergedOptions), ]; if (array_key_exists('lang', $mergedOptions) && "" !== trim($mergedOptions['lang'])) { $data['lang'] = $mergedOptions['lang']; } $view = $this->getView($options); return app('view')->make($view, $data); }
php
public function render($options = [ ]) { $mergedOptions = array_merge($this->config['options'], $options); $data = [ 'public_key' => value($this->config['public_key']), 'options' => $mergedOptions, 'dataParams' => $this->extractDataParams($mergedOptions), ]; if (array_key_exists('lang', $mergedOptions) && "" !== trim($mergedOptions['lang'])) { $data['lang'] = $mergedOptions['lang']; } $view = $this->getView($options); return app('view')->make($view, $data); }
[ "public", "function", "render", "(", "$", "options", "=", "[", "]", ")", "{", "$", "mergedOptions", "=", "array_merge", "(", "$", "this", "->", "config", "[", "'options'", "]", ",", "$", "options", ")", ";", "$", "data", "=", "[", "'public_key'", "=>...
Render the recaptcha @param array $options @return view
[ "Render", "the", "recaptcha" ]
c2ed383785a4fe20467ce470c97c303e5c5b85de
https://github.com/greggilbert/recaptcha/blob/c2ed383785a4fe20467ce470c97c303e5c5b85de/src/Recaptcha.php#L28-L45
train
greggilbert/recaptcha
src/Recaptcha.php
Recaptcha.getView
protected function getView($options = [ ]) { $view = 'recaptcha::' . $this->service->getTemplate(); $configTemplate = $this->config['template']; if (array_key_exists('template', $options)) { $view = $options['template']; } elseif ("" !== trim($configTemplate)) { $view = $configTemplate; } return $view; }
php
protected function getView($options = [ ]) { $view = 'recaptcha::' . $this->service->getTemplate(); $configTemplate = $this->config['template']; if (array_key_exists('template', $options)) { $view = $options['template']; } elseif ("" !== trim($configTemplate)) { $view = $configTemplate; } return $view; }
[ "protected", "function", "getView", "(", "$", "options", "=", "[", "]", ")", "{", "$", "view", "=", "'recaptcha::'", ".", "$", "this", "->", "service", "->", "getTemplate", "(", ")", ";", "$", "configTemplate", "=", "$", "this", "->", "config", "[", ...
Generate the view path @param array $options @return string
[ "Generate", "the", "view", "path" ]
c2ed383785a4fe20467ce470c97c303e5c5b85de
https://github.com/greggilbert/recaptcha/blob/c2ed383785a4fe20467ce470c97c303e5c5b85de/src/Recaptcha.php#L54-L67
train
parsecsv/parsecsv-for-php
src/enums/DatatypeEnum.php
DatatypeEnum.getValidTypeFromSample
public static function getValidTypeFromSample($value) { $value = trim((string) $value); if (empty($value)) { return false; } foreach (self::$validators as $type => $validator) { if ($validator === null) { continue; } if (method_exists(__CLASS__, $validator) && self::$validator($value)) { return $type; } } return self::__DEFAULT; }
php
public static function getValidTypeFromSample($value) { $value = trim((string) $value); if (empty($value)) { return false; } foreach (self::$validators as $type => $validator) { if ($validator === null) { continue; } if (method_exists(__CLASS__, $validator) && self::$validator($value)) { return $type; } } return self::__DEFAULT; }
[ "public", "static", "function", "getValidTypeFromSample", "(", "$", "value", ")", "{", "$", "value", "=", "trim", "(", "(", "string", ")", "$", "value", ")", ";", "if", "(", "empty", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "f...
Checks data type for given string. @param string $value @return bool|string
[ "Checks", "data", "type", "for", "given", "string", "." ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/enums/DatatypeEnum.php#L57-L75
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv.parse
public function parse($input = null, $offset = null, $limit = null, $conditions = null) { if (is_null($input)) { $input = $this->file; } if (empty($input)) { return false; } $this->init($offset, $limit, $conditions); if (strlen($input) <= PHP_MAXPATHLEN && is_readable($input)) { $this->file = $input; $this->data = $this->parse_file(); } else { $this->file = null; $this->file_data = &$input; $this->data = $this->parse_string(); } return $this->data !== false; }
php
public function parse($input = null, $offset = null, $limit = null, $conditions = null) { if (is_null($input)) { $input = $this->file; } if (empty($input)) { return false; } $this->init($offset, $limit, $conditions); if (strlen($input) <= PHP_MAXPATHLEN && is_readable($input)) { $this->file = $input; $this->data = $this->parse_file(); } else { $this->file = null; $this->file_data = &$input; $this->data = $this->parse_string(); } return $this->data !== false; }
[ "public", "function", "parse", "(", "$", "input", "=", "null", ",", "$", "offset", "=", "null", ",", "$", "limit", "=", "null", ",", "$", "conditions", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "input", ")", ")", "{", "$", "input", ...
Parse Parse a CSV file or string @param string|null $input The CSV string or a direct file path @param integer $offset Number of rows to ignore from the beginning of the data @param integer $limit Limits the number of returned rows to specified amount @param string $conditions Basic SQL-like conditions for row matching @return bool True on success
[ "Parse", "Parse", "a", "CSV", "file", "or", "string" ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L368-L389
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv.output
public function output($filename = null, $data = array(), $fields = array(), $delimiter = null) { if (empty($filename)) { $filename = $this->output_filename; } if ($delimiter === null) { $delimiter = $this->output_delimiter; } $flat_string = $this->unparse($data, $fields, null, null, $delimiter); if (!is_null($filename)) { $mime = $delimiter === "\t" ? 'text/tab-separated-values' : 'application/csv'; header('Content-type: ' . $mime); header('Content-Length: ' . strlen($flat_string)); header('Cache-Control: no-cache, must-revalidate'); header('Pragma: no-cache'); header('Expires: 0'); header('Content-Disposition: attachment; filename="' . $filename . '"; modification-date="' . date('r') . '";'); echo $flat_string; } return $flat_string; }
php
public function output($filename = null, $data = array(), $fields = array(), $delimiter = null) { if (empty($filename)) { $filename = $this->output_filename; } if ($delimiter === null) { $delimiter = $this->output_delimiter; } $flat_string = $this->unparse($data, $fields, null, null, $delimiter); if (!is_null($filename)) { $mime = $delimiter === "\t" ? 'text/tab-separated-values' : 'application/csv'; header('Content-type: ' . $mime); header('Content-Length: ' . strlen($flat_string)); header('Cache-Control: no-cache, must-revalidate'); header('Pragma: no-cache'); header('Expires: 0'); header('Content-Disposition: attachment; filename="' . $filename . '"; modification-date="' . date('r') . '";'); echo $flat_string; } return $flat_string; }
[ "public", "function", "output", "(", "$", "filename", "=", "null", ",", "$", "data", "=", "array", "(", ")", ",", "$", "fields", "=", "array", "(", ")", ",", "$", "delimiter", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "filename", ")", ...
Output Generate a CSV based string for output. @param string|null $filename If a filename is specified here or in the object, headers and data will be output directly to browser as a downloadable file. This file doesn't have to exist on the server; the parameter only affects how the download is called to the browser. @param array[] $data 2D array with data @param array $fields Field names @param string|null $delimiter character used to separate data @return string The resulting CSV string
[ "Output", "Generate", "a", "CSV", "based", "string", "for", "output", "." ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L432-L458
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv.encoding
public function encoding($input = null, $output = null) { $this->convert_encoding = true; if (!is_null($input)) { $this->input_encoding = $input; } if (!is_null($output)) { $this->output_encoding = $output; } }
php
public function encoding($input = null, $output = null) { $this->convert_encoding = true; if (!is_null($input)) { $this->input_encoding = $input; } if (!is_null($output)) { $this->output_encoding = $output; } }
[ "public", "function", "encoding", "(", "$", "input", "=", "null", ",", "$", "output", "=", "null", ")", "{", "$", "this", "->", "convert_encoding", "=", "true", ";", "if", "(", "!", "is_null", "(", "$", "input", ")", ")", "{", "$", "this", "->", ...
Encoding Convert character encoding @param string $input Input character encoding, uses default if left blank @param string $output Output character encoding, uses default if left blank
[ "Encoding", "Convert", "character", "encoding" ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L467-L476
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv.unparse
public function unparse($data = array(), $fields = array(), $append = FileProcessingModeEnum::MODE_FILE_OVERWRITE, $is_php = false, $delimiter = null) { if (!is_array($data) || empty($data)) { $data = &$this->data; } else { /** @noinspection ReferenceMismatchInspection */ $this->data = $data; } if (!is_array($fields) || empty($fields)) { $fields = &$this->titles; } if ($delimiter === null) { $delimiter = $this->delimiter; } $string = $is_php ? "<?php header('Status: 403'); die(' '); ?>" . $this->linefeed : ''; $entry = array(); // create heading /** @noinspection ReferenceMismatchInspection */ $fieldOrder = $this->_validate_fields_for_unparse($fields); if (!$fieldOrder && !empty($data)) { $column_count = count($data[0]); $columns = range(0, $column_count - 1, 1); $fieldOrder = array_combine($columns, $columns); } if ($this->heading && !$append && !empty($fields)) { foreach ($fieldOrder as $column_name) { $entry[] = $this->_enclose_value($column_name, $delimiter); } $string .= implode($delimiter, $entry) . $this->linefeed; $entry = array(); } // create data foreach ($data as $key => $row) { foreach (array_keys($fieldOrder) as $index) { $cell_value = $row[$index]; $entry[] = $this->_enclose_value($cell_value, $delimiter); } $string .= implode($delimiter, $entry) . $this->linefeed; $entry = array(); } if ($this->convert_encoding) { $string = iconv($this->input_encoding, $this->output_encoding, $string); } return $string; }
php
public function unparse($data = array(), $fields = array(), $append = FileProcessingModeEnum::MODE_FILE_OVERWRITE, $is_php = false, $delimiter = null) { if (!is_array($data) || empty($data)) { $data = &$this->data; } else { /** @noinspection ReferenceMismatchInspection */ $this->data = $data; } if (!is_array($fields) || empty($fields)) { $fields = &$this->titles; } if ($delimiter === null) { $delimiter = $this->delimiter; } $string = $is_php ? "<?php header('Status: 403'); die(' '); ?>" . $this->linefeed : ''; $entry = array(); // create heading /** @noinspection ReferenceMismatchInspection */ $fieldOrder = $this->_validate_fields_for_unparse($fields); if (!$fieldOrder && !empty($data)) { $column_count = count($data[0]); $columns = range(0, $column_count - 1, 1); $fieldOrder = array_combine($columns, $columns); } if ($this->heading && !$append && !empty($fields)) { foreach ($fieldOrder as $column_name) { $entry[] = $this->_enclose_value($column_name, $delimiter); } $string .= implode($delimiter, $entry) . $this->linefeed; $entry = array(); } // create data foreach ($data as $key => $row) { foreach (array_keys($fieldOrder) as $index) { $cell_value = $row[$index]; $entry[] = $this->_enclose_value($cell_value, $delimiter); } $string .= implode($delimiter, $entry) . $this->linefeed; $entry = array(); } if ($this->convert_encoding) { $string = iconv($this->input_encoding, $this->output_encoding, $string); } return $string; }
[ "public", "function", "unparse", "(", "$", "data", "=", "array", "(", ")", ",", "$", "fields", "=", "array", "(", ")", ",", "$", "append", "=", "FileProcessingModeEnum", "::", "MODE_FILE_OVERWRITE", ",", "$", "is_php", "=", "false", ",", "$", "delimiter"...
Create CSV data string from array @param array[] $data 2D array with data @param array $fields field names @param bool $append if true, field names will not be output @param bool $is_php if a php die() call should be put on the first line of the file, this is later ignored when read. @param string|null $delimiter field delimiter to use @return string CSV data
[ "Create", "CSV", "data", "string", "from", "array" ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L784-L837
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv._validate_row_condition
protected function _validate_row_condition($row, $condition) { $operators = array( '=', 'equals', 'is', '!=', 'is not', '<', 'is less than', '>', 'is greater than', '<=', 'is less than or equals', '>=', 'is greater than or equals', 'contains', 'does not contain', ); $operators_regex = array(); foreach ($operators as $value) { $operators_regex[] = preg_quote($value, '/'); } $operators_regex = implode('|', $operators_regex); if (preg_match('/^(.+) (' . $operators_regex . ') (.+)$/i', trim($condition), $capture)) { $field = $capture[1]; $op = $capture[2]; $value = $capture[3]; if (preg_match('/^([\'\"]{1})(.*)([\'\"]{1})$/', $value, $capture) && $capture[1] == $capture[3]) { $value = strtr($capture[2], array( "\\n" => "\n", "\\r" => "\r", "\\t" => "\t", )); $value = stripslashes($value); } if (array_key_exists($field, $row)) { if (($op == '=' || $op == 'equals' || $op == 'is') && $row[$field] == $value) { return '1'; } elseif (($op == '!=' || $op == 'is not') && $row[$field] != $value) { return '1'; } elseif (($op == '<' || $op == 'is less than') && $row[$field] < $value) { return '1'; } elseif (($op == '>' || $op == 'is greater than') && $row[$field] > $value) { return '1'; } elseif (($op == '<=' || $op == 'is less than or equals') && $row[$field] <= $value) { return '1'; } elseif (($op == '>=' || $op == 'is greater than or equals') && $row[$field] >= $value) { return '1'; } elseif ($op == 'contains' && preg_match('/' . preg_quote($value, '/') . '/i', $row[$field])) { return '1'; } elseif ($op == 'does not contain' && !preg_match('/' . preg_quote($value, '/') . '/i', $row[$field])) { return '1'; } else { return '0'; } } } return '1'; }
php
protected function _validate_row_condition($row, $condition) { $operators = array( '=', 'equals', 'is', '!=', 'is not', '<', 'is less than', '>', 'is greater than', '<=', 'is less than or equals', '>=', 'is greater than or equals', 'contains', 'does not contain', ); $operators_regex = array(); foreach ($operators as $value) { $operators_regex[] = preg_quote($value, '/'); } $operators_regex = implode('|', $operators_regex); if (preg_match('/^(.+) (' . $operators_regex . ') (.+)$/i', trim($condition), $capture)) { $field = $capture[1]; $op = $capture[2]; $value = $capture[3]; if (preg_match('/^([\'\"]{1})(.*)([\'\"]{1})$/', $value, $capture) && $capture[1] == $capture[3]) { $value = strtr($capture[2], array( "\\n" => "\n", "\\r" => "\r", "\\t" => "\t", )); $value = stripslashes($value); } if (array_key_exists($field, $row)) { if (($op == '=' || $op == 'equals' || $op == 'is') && $row[$field] == $value) { return '1'; } elseif (($op == '!=' || $op == 'is not') && $row[$field] != $value) { return '1'; } elseif (($op == '<' || $op == 'is less than') && $row[$field] < $value) { return '1'; } elseif (($op == '>' || $op == 'is greater than') && $row[$field] > $value) { return '1'; } elseif (($op == '<=' || $op == 'is less than or equals') && $row[$field] <= $value) { return '1'; } elseif (($op == '>=' || $op == 'is greater than or equals') && $row[$field] >= $value) { return '1'; } elseif ($op == 'contains' && preg_match('/' . preg_quote($value, '/') . '/i', $row[$field])) { return '1'; } elseif ($op == 'does not contain' && !preg_match('/' . preg_quote($value, '/') . '/i', $row[$field])) { return '1'; } else { return '0'; } } } return '1'; }
[ "protected", "function", "_validate_row_condition", "(", "$", "row", ",", "$", "condition", ")", "{", "$", "operators", "=", "array", "(", "'='", ",", "'equals'", ",", "'is'", ",", "'!='", ",", "'is not'", ",", "'<'", ",", "'is less than'", ",", "'>'", "...
Validate a row against a single condition @param array $row array with values from a row @param string $condition specified condition that the row must match @return string single 0 or 1
[ "Validate", "a", "row", "against", "a", "single", "condition" ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L989-L1055
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv._check_data
protected function _check_data($file = null) { if (empty($this->file_data)) { if (is_null($file)) { $file = $this->file; } return $this->load_data($file); } return true; }
php
protected function _check_data($file = null) { if (empty($this->file_data)) { if (is_null($file)) { $file = $this->file; } return $this->load_data($file); } return true; }
[ "protected", "function", "_check_data", "(", "$", "file", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "file_data", ")", ")", "{", "if", "(", "is_null", "(", "$", "file", ")", ")", "{", "$", "file", "=", "$", "this", "->", ...
Check file data @param string|null $file local filename @return bool
[ "Check", "file", "data" ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L1104-L1114
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv._check_count
protected function _check_count($char, $array, $depth, $preferred) { if ($depth === count($array)) { $first = null; $equal = null; $almost = false; foreach ($array as $key => $value) { if ($first == null) { $first = $value; } elseif ($value == $first && $equal !== false) { $equal = true; } elseif ($value == $first + 1 && $equal !== false) { $equal = true; $almost = true; } else { $equal = false; } } if ($equal) { $match = $almost ? 2 : 1; $pref = strpos($preferred, $char); $pref = ($pref !== false) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999'; return $pref . $match . '.' . (99999 - str_pad($first, 5, '0', STR_PAD_LEFT)); } else { return false; } } return false; }
php
protected function _check_count($char, $array, $depth, $preferred) { if ($depth === count($array)) { $first = null; $equal = null; $almost = false; foreach ($array as $key => $value) { if ($first == null) { $first = $value; } elseif ($value == $first && $equal !== false) { $equal = true; } elseif ($value == $first + 1 && $equal !== false) { $equal = true; $almost = true; } else { $equal = false; } } if ($equal) { $match = $almost ? 2 : 1; $pref = strpos($preferred, $char); $pref = ($pref !== false) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999'; return $pref . $match . '.' . (99999 - str_pad($first, 5, '0', STR_PAD_LEFT)); } else { return false; } } return false; }
[ "protected", "function", "_check_count", "(", "$", "char", ",", "$", "array", ",", "$", "depth", ",", "$", "preferred", ")", "{", "if", "(", "$", "depth", "===", "count", "(", "$", "array", ")", ")", "{", "$", "first", "=", "null", ";", "$", "equ...
Check if passed info might be delimiter Only used by find_delimiter @param string $char Potential field separating character @param array $array Frequency @param int $depth Number of analyzed rows @param string $preferred Preferred delimiter characters @return string|false special string used for delimiter selection, or false
[ "Check", "if", "passed", "info", "might", "be", "delimiter", "Only", "used", "by", "find_delimiter" ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L1127-L1156
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv._rfile
protected function _rfile($file) { if (is_readable($file)) { $data = file_get_contents($file); if ($data === false) { return false; } return rtrim($data, "\r\n"); } return false; }
php
protected function _rfile($file) { if (is_readable($file)) { $data = file_get_contents($file); if ($data === false) { return false; } return rtrim($data, "\r\n"); } return false; }
[ "protected", "function", "_rfile", "(", "$", "file", ")", "{", "if", "(", "is_readable", "(", "$", "file", ")", ")", "{", "$", "data", "=", "file_get_contents", "(", "$", "file", ")", ";", "if", "(", "$", "data", "===", "false", ")", "{", "return",...
Read local file. @param string $file local filename @return string|false Data from file, or false on failure
[ "Read", "local", "file", "." ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L1165-L1175
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv._wfile
protected function _wfile($file, $content = '', $mode = 'wb', $lock = LOCK_EX) { if ($fp = fopen($file, $mode)) { flock($fp, $lock); $re = fwrite($fp, $content); $re2 = fclose($fp); if ($re !== false && $re2 !== false) { return true; } } return false; }
php
protected function _wfile($file, $content = '', $mode = 'wb', $lock = LOCK_EX) { if ($fp = fopen($file, $mode)) { flock($fp, $lock); $re = fwrite($fp, $content); $re2 = fclose($fp); if ($re !== false && $re2 !== false) { return true; } } return false; }
[ "protected", "function", "_wfile", "(", "$", "file", ",", "$", "content", "=", "''", ",", "$", "mode", "=", "'wb'", ",", "$", "lock", "=", "LOCK_EX", ")", "{", "if", "(", "$", "fp", "=", "fopen", "(", "$", "file", ",", "$", "mode", ")", ")", ...
Write to local file @param string $file local filename @param string $content data to write to file @param string $mode fopen() mode @param int $lock flock() mode @return true or false
[ "Write", "to", "local", "file" ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L1187-L1199
train
parsecsv/parsecsv-for-php
src/Csv.php
Csv._detect_and_remove_sep_row_from_data
protected function _detect_and_remove_sep_row_from_data(&$data_string) { $sep = $this->_get_delimiter_from_sep_row($data_string); if ($sep === false) { return false; } $this->delimiter = $sep; // likely to be 5, but let's not assume we're always single-byte. $pos = 4 + strlen($sep); // the next characters should be a line-end if (substr($data_string, $pos, 1) === "\r") { $pos++; } if (substr($data_string, $pos, 1) === "\n") { $pos++; } // remove delimiter and its line-end (the data param is by-ref!) /** @noinspection CallableParameterUseCaseInTypeContextInspection */ $data_string = substr($data_string, $pos); return true; }
php
protected function _detect_and_remove_sep_row_from_data(&$data_string) { $sep = $this->_get_delimiter_from_sep_row($data_string); if ($sep === false) { return false; } $this->delimiter = $sep; // likely to be 5, but let's not assume we're always single-byte. $pos = 4 + strlen($sep); // the next characters should be a line-end if (substr($data_string, $pos, 1) === "\r") { $pos++; } if (substr($data_string, $pos, 1) === "\n") { $pos++; } // remove delimiter and its line-end (the data param is by-ref!) /** @noinspection CallableParameterUseCaseInTypeContextInspection */ $data_string = substr($data_string, $pos); return true; }
[ "protected", "function", "_detect_and_remove_sep_row_from_data", "(", "&", "$", "data_string", ")", "{", "$", "sep", "=", "$", "this", "->", "_get_delimiter_from_sep_row", "(", "$", "data_string", ")", ";", "if", "(", "$", "sep", "===", "false", ")", "{", "r...
Support for Excel-compatible sep=? row. @param string $data_string file data to be updated @return bool TRUE if sep= line was found at the very beginning of the file
[ "Support", "for", "Excel", "-", "compatible", "sep", "=", "?", "row", "." ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/Csv.php#L1228-L1250
train
parsecsv/parsecsv-for-php
src/extensions/DatatypeTrait.php
DatatypeTrait.getMostFrequentDatatypeForColumn
private function getMostFrequentDatatypeForColumn($datatypes) { // remove 'false' from array (can happen if CSV cell is empty) $typesFiltered = array_filter($datatypes); if (empty($typesFiltered)) { return false; } $typesFreq = array_count_values($typesFiltered); arsort($typesFreq); reset($typesFreq); return key($typesFreq); }
php
private function getMostFrequentDatatypeForColumn($datatypes) { // remove 'false' from array (can happen if CSV cell is empty) $typesFiltered = array_filter($datatypes); if (empty($typesFiltered)) { return false; } $typesFreq = array_count_values($typesFiltered); arsort($typesFreq); reset($typesFreq); return key($typesFreq); }
[ "private", "function", "getMostFrequentDatatypeForColumn", "(", "$", "datatypes", ")", "{", "// remove 'false' from array (can happen if CSV cell is empty)", "$", "typesFiltered", "=", "array_filter", "(", "$", "datatypes", ")", ";", "if", "(", "empty", "(", "$", "types...
Check data type for one column. Check for most commonly data type for one column. @param array $datatypes @return string|false
[ "Check", "data", "type", "for", "one", "column", ".", "Check", "for", "most", "commonly", "data", "type", "for", "one", "column", "." ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/extensions/DatatypeTrait.php#L26-L40
train
parsecsv/parsecsv-for-php
src/extensions/DatatypeTrait.php
DatatypeTrait.getDatatypes
public function getDatatypes() { if (empty($this->data)) { $this->data = $this->parse_string(); } if (!is_array($this->data)) { throw new \UnexpectedValueException('No data set yet.'); } $result = []; foreach ($this->titles as $cName) { $column = array_column($this->data, $cName); $cDatatypes = array_map(DatatypeEnum::class . '::getValidTypeFromSample', $column); $result[$cName] = $this->getMostFrequentDatatypeForColumn($cDatatypes); } $this->data_types = $result; return !empty($this->data_types) ? $this->data_types : []; }
php
public function getDatatypes() { if (empty($this->data)) { $this->data = $this->parse_string(); } if (!is_array($this->data)) { throw new \UnexpectedValueException('No data set yet.'); } $result = []; foreach ($this->titles as $cName) { $column = array_column($this->data, $cName); $cDatatypes = array_map(DatatypeEnum::class . '::getValidTypeFromSample', $column); $result[$cName] = $this->getMostFrequentDatatypeForColumn($cDatatypes); } $this->data_types = $result; return !empty($this->data_types) ? $this->data_types : []; }
[ "public", "function", "getDatatypes", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "data", ")", ")", "{", "$", "this", "->", "data", "=", "$", "this", "->", "parse_string", "(", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", ...
Check data type foreach Column Check data type for each column and returns the most commonly. Requires PHP >= 5.5 @uses DatatypeEnum::getValidTypeFromSample @return array|bool
[ "Check", "data", "type", "foreach", "Column", "Check", "data", "type", "for", "each", "column", "and", "returns", "the", "most", "commonly", "." ]
5874b768b91d2016d0094e7bba8918273a9f7fc5
https://github.com/parsecsv/parsecsv-for-php/blob/5874b768b91d2016d0094e7bba8918273a9f7fc5/src/extensions/DatatypeTrait.php#L52-L71
train
thephpleague/route
src/Strategy/ApplicationStrategy.php
ApplicationStrategy.throwThrowableMiddleware
protected function throwThrowableMiddleware(Throwable $error) : MiddlewareInterface { return new class($error) implements MiddlewareInterface { protected $error; public function __construct(Throwable $error) { $this->error = $error; } public function process( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) : ResponseInterface { throw $this->error; } }; }
php
protected function throwThrowableMiddleware(Throwable $error) : MiddlewareInterface { return new class($error) implements MiddlewareInterface { protected $error; public function __construct(Throwable $error) { $this->error = $error; } public function process( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) : ResponseInterface { throw $this->error; } }; }
[ "protected", "function", "throwThrowableMiddleware", "(", "Throwable", "$", "error", ")", ":", "MiddlewareInterface", "{", "return", "new", "class", "(", "$", "error", ")", "implements", "MiddlewareInterface", "{", "protected", "$", "error", ";", "public", "functi...
Return a middleware that simply throws an error @param \Throwable $error @return \Psr\Http\Server\MiddlewareInterface
[ "Return", "a", "middleware", "that", "simply", "throws", "an", "error" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Strategy/ApplicationStrategy.php#L52-L70
train
thephpleague/route
src/Router.php
Router.buildNameIndex
protected function buildNameIndex() : void { foreach ($this->routes as $key => $route) { if (! is_null($route->getName())) { unset($this->routes[$key]); $this->namedRoutes[$route->getName()] = $route; } } }
php
protected function buildNameIndex() : void { foreach ($this->routes as $key => $route) { if (! is_null($route->getName())) { unset($this->routes[$key]); $this->namedRoutes[$route->getName()] = $route; } } }
[ "protected", "function", "buildNameIndex", "(", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "routes", "as", "$", "key", "=>", "$", "route", ")", "{", "if", "(", "!", "is_null", "(", "$", "route", "->", "getName", "(", ")", ")", ")", ...
Build an index of named routes. @return void
[ "Build", "an", "index", "of", "named", "routes", "." ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Router.php#L151-L159
train
thephpleague/route
src/Router.php
Router.processGroups
protected function processGroups(ServerRequestInterface $request) : void { $activePath = $request->getUri()->getPath(); foreach ($this->groups as $key => $group) { // we want to determine if we are technically in a group even if the // route is not matched so exceptions are handled correctly if (strncmp($activePath, $group->getPrefix(), strlen($group->getPrefix())) === 0 && ! is_null($group->getStrategy()) ) { $this->setStrategy($group->getStrategy()); } unset($this->groups[$key]); $group(); } }
php
protected function processGroups(ServerRequestInterface $request) : void { $activePath = $request->getUri()->getPath(); foreach ($this->groups as $key => $group) { // we want to determine if we are technically in a group even if the // route is not matched so exceptions are handled correctly if (strncmp($activePath, $group->getPrefix(), strlen($group->getPrefix())) === 0 && ! is_null($group->getStrategy()) ) { $this->setStrategy($group->getStrategy()); } unset($this->groups[$key]); $group(); } }
[ "protected", "function", "processGroups", "(", "ServerRequestInterface", "$", "request", ")", ":", "void", "{", "$", "activePath", "=", "$", "request", "->", "getUri", "(", ")", "->", "getPath", "(", ")", ";", "foreach", "(", "$", "this", "->", "groups", ...
Process all groups Adds all of the group routes to the collection and determines if the group strategy should be be used. @param \Psr\Http\Message\ServerRequestInterface $request @return void
[ "Process", "all", "groups" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Router.php#L171-L187
train
thephpleague/route
src/Router.php
Router.getNamedRoute
public function getNamedRoute(string $name) : Route { $this->buildNameIndex(); if (isset($this->namedRoutes[$name])) { return $this->namedRoutes[$name]; } throw new InvalidArgumentException(sprintf('No route of the name (%s) exists', $name)); }
php
public function getNamedRoute(string $name) : Route { $this->buildNameIndex(); if (isset($this->namedRoutes[$name])) { return $this->namedRoutes[$name]; } throw new InvalidArgumentException(sprintf('No route of the name (%s) exists', $name)); }
[ "public", "function", "getNamedRoute", "(", "string", "$", "name", ")", ":", "Route", "{", "$", "this", "->", "buildNameIndex", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "namedRoutes", "[", "$", "name", "]", ")", ")", "{", "return", ...
Get a named route @param string $name @throws \InvalidArgumentException when no route of the provided name exists. @return \League\Route\Route
[ "Get", "a", "named", "route" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Router.php#L198-L207
train
thephpleague/route
src/Router.php
Router.addPatternMatcher
public function addPatternMatcher(string $alias, string $regex) : self { $pattern = '/{(.+?):' . $alias . '}/'; $regex = '{$1:' . $regex . '}'; $this->patternMatchers[$pattern] = $regex; return $this; }
php
public function addPatternMatcher(string $alias, string $regex) : self { $pattern = '/{(.+?):' . $alias . '}/'; $regex = '{$1:' . $regex . '}'; $this->patternMatchers[$pattern] = $regex; return $this; }
[ "public", "function", "addPatternMatcher", "(", "string", "$", "alias", ",", "string", "$", "regex", ")", ":", "self", "{", "$", "pattern", "=", "'/{(.+?):'", ".", "$", "alias", ".", "'}/'", ";", "$", "regex", "=", "'{$1:'", ".", "$", "regex", ".", "...
Add a convenient pattern matcher to the internal array for use with all routes @param string $alias @param string $regex @return self
[ "Add", "a", "convenient", "pattern", "matcher", "to", "the", "internal", "array", "for", "use", "with", "all", "routes" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Router.php#L217-L225
train
thephpleague/route
src/Router.php
Router.parseRoutePath
protected function parseRoutePath(string $path) : string { return preg_replace(array_keys($this->patternMatchers), array_values($this->patternMatchers), $path); }
php
protected function parseRoutePath(string $path) : string { return preg_replace(array_keys($this->patternMatchers), array_values($this->patternMatchers), $path); }
[ "protected", "function", "parseRoutePath", "(", "string", "$", "path", ")", ":", "string", "{", "return", "preg_replace", "(", "array_keys", "(", "$", "this", "->", "patternMatchers", ")", ",", "array_values", "(", "$", "this", "->", "patternMatchers", ")", ...
Replace word patterns with regex in route path @param string $path @return string
[ "Replace", "word", "patterns", "with", "regex", "in", "route", "path" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Router.php#L234-L237
train
thephpleague/route
src/Strategy/AbstractStrategy.php
AbstractStrategy.addDefaultResponseHeader
public function addDefaultResponseHeader(string $name, string $value) : AbstractStrategy { $this->defaultResponseHeaders[strtolower($name)] = $value; return $this; }
php
public function addDefaultResponseHeader(string $name, string $value) : AbstractStrategy { $this->defaultResponseHeaders[strtolower($name)] = $value; return $this; }
[ "public", "function", "addDefaultResponseHeader", "(", "string", "$", "name", ",", "string", "$", "value", ")", ":", "AbstractStrategy", "{", "$", "this", "->", "defaultResponseHeaders", "[", "strtolower", "(", "$", "name", ")", "]", "=", "$", "value", ";", ...
Add or replace a default response header @param string $name @param string $value @return static
[ "Add", "or", "replace", "a", "default", "response", "header" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Strategy/AbstractStrategy.php#L30-L35
train
thephpleague/route
src/Strategy/AbstractStrategy.php
AbstractStrategy.addDefaultResponseHeaders
public function addDefaultResponseHeaders(array $headers) : AbstractStrategy { foreach ($headers as $name => $value) { $this->addDefaultResponseHeader($name, $value); } return $this; }
php
public function addDefaultResponseHeaders(array $headers) : AbstractStrategy { foreach ($headers as $name => $value) { $this->addDefaultResponseHeader($name, $value); } return $this; }
[ "public", "function", "addDefaultResponseHeaders", "(", "array", "$", "headers", ")", ":", "AbstractStrategy", "{", "foreach", "(", "$", "headers", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "this", "->", "addDefaultResponseHeader", "(", "$", "nam...
Add multiple default response headers @param array $headers @return static
[ "Add", "multiple", "default", "response", "headers" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Strategy/AbstractStrategy.php#L44-L51
train
thephpleague/route
src/Strategy/AbstractStrategy.php
AbstractStrategy.applyDefaultResponseHeaders
protected function applyDefaultResponseHeaders(ResponseInterface $response) : ResponseInterface { foreach ($this->defaultResponseHeaders as $name => $value) { if (! $response->hasHeader($name)) { $response = $response->withHeader($name, $value); } } return $response; }
php
protected function applyDefaultResponseHeaders(ResponseInterface $response) : ResponseInterface { foreach ($this->defaultResponseHeaders as $name => $value) { if (! $response->hasHeader($name)) { $response = $response->withHeader($name, $value); } } return $response; }
[ "protected", "function", "applyDefaultResponseHeaders", "(", "ResponseInterface", "$", "response", ")", ":", "ResponseInterface", "{", "foreach", "(", "$", "this", "->", "defaultResponseHeaders", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "!", ...
Apply default response headers Headers that already exist on the response will NOT be replaced. @param \Psr\Http\Message\ResponseInterface $response @return \Psr\Http\Message\ResponseInterface
[ "Apply", "default", "response", "headers" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Strategy/AbstractStrategy.php#L62-L71
train
thephpleague/route
src/Dispatcher.php
Dispatcher.dispatchRequest
public function dispatchRequest(ServerRequestInterface $request) : ResponseInterface { $match = $this->dispatch($request->getMethod(), $request->getUri()->getPath()); switch ($match[0]) { case FastRoute::NOT_FOUND: $this->setNotFoundDecoratorMiddleware(); break; case FastRoute::METHOD_NOT_ALLOWED: $allowed = (array) $match[1]; $this->setMethodNotAllowedDecoratorMiddleware($allowed); break; case FastRoute::FOUND: $match[1]->setVars($match[2]); $this->setFoundMiddleware($match[1]); break; } return $this->handle($request); }
php
public function dispatchRequest(ServerRequestInterface $request) : ResponseInterface { $match = $this->dispatch($request->getMethod(), $request->getUri()->getPath()); switch ($match[0]) { case FastRoute::NOT_FOUND: $this->setNotFoundDecoratorMiddleware(); break; case FastRoute::METHOD_NOT_ALLOWED: $allowed = (array) $match[1]; $this->setMethodNotAllowedDecoratorMiddleware($allowed); break; case FastRoute::FOUND: $match[1]->setVars($match[2]); $this->setFoundMiddleware($match[1]); break; } return $this->handle($request); }
[ "public", "function", "dispatchRequest", "(", "ServerRequestInterface", "$", "request", ")", ":", "ResponseInterface", "{", "$", "match", "=", "$", "this", "->", "dispatch", "(", "$", "request", "->", "getMethod", "(", ")", ",", "$", "request", "->", "getUri...
Dispatch the current route @param \Psr\Http\Message\ServerRequestInterface $request @return \Psr\Http\Message\ResponseInterface
[ "Dispatch", "the", "current", "route" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Dispatcher.php#L29-L48
train
thephpleague/route
src/Dispatcher.php
Dispatcher.setFoundMiddleware
protected function setFoundMiddleware(Route $route) : void { if (is_null($route->getStrategy())) { $route->setStrategy($this->getStrategy()); } // wrap entire dispatch process in exception handler $this->prependMiddleware($route->getStrategy()->getExceptionHandler()); // add group and route specific middleware if ($group = $route->getParentGroup()) { $this->middlewares($group->getMiddlewareStack()); } $this->middlewares($route->getMiddlewareStack()); // add actual route to end of stack $this->middleware($route); }
php
protected function setFoundMiddleware(Route $route) : void { if (is_null($route->getStrategy())) { $route->setStrategy($this->getStrategy()); } // wrap entire dispatch process in exception handler $this->prependMiddleware($route->getStrategy()->getExceptionHandler()); // add group and route specific middleware if ($group = $route->getParentGroup()) { $this->middlewares($group->getMiddlewareStack()); } $this->middlewares($route->getMiddlewareStack()); // add actual route to end of stack $this->middleware($route); }
[ "protected", "function", "setFoundMiddleware", "(", "Route", "$", "route", ")", ":", "void", "{", "if", "(", "is_null", "(", "$", "route", "->", "getStrategy", "(", ")", ")", ")", "{", "$", "route", "->", "setStrategy", "(", "$", "this", "->", "getStra...
Set up middleware for a found route @param \League\Route\Route $route @return void
[ "Set", "up", "middleware", "for", "a", "found", "route" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Dispatcher.php#L71-L89
train
thephpleague/route
src/Dispatcher.php
Dispatcher.setNotFoundDecoratorMiddleware
protected function setNotFoundDecoratorMiddleware() : void { $middleware = $this->getStrategy()->getNotFoundDecorator(new NotFoundException); $this->prependMiddleware($middleware); }
php
protected function setNotFoundDecoratorMiddleware() : void { $middleware = $this->getStrategy()->getNotFoundDecorator(new NotFoundException); $this->prependMiddleware($middleware); }
[ "protected", "function", "setNotFoundDecoratorMiddleware", "(", ")", ":", "void", "{", "$", "middleware", "=", "$", "this", "->", "getStrategy", "(", ")", "->", "getNotFoundDecorator", "(", "new", "NotFoundException", ")", ";", "$", "this", "->", "prependMiddlew...
Set up middleware for a not found route @return void
[ "Set", "up", "middleware", "for", "a", "not", "found", "route" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Dispatcher.php#L96-L100
train
thephpleague/route
src/Dispatcher.php
Dispatcher.setMethodNotAllowedDecoratorMiddleware
protected function setMethodNotAllowedDecoratorMiddleware(array $allowed) : void { $middleware = $this->getStrategy()->getMethodNotAllowedDecorator( new MethodNotAllowedException($allowed) ); $this->prependMiddleware($middleware); }
php
protected function setMethodNotAllowedDecoratorMiddleware(array $allowed) : void { $middleware = $this->getStrategy()->getMethodNotAllowedDecorator( new MethodNotAllowedException($allowed) ); $this->prependMiddleware($middleware); }
[ "protected", "function", "setMethodNotAllowedDecoratorMiddleware", "(", "array", "$", "allowed", ")", ":", "void", "{", "$", "middleware", "=", "$", "this", "->", "getStrategy", "(", ")", "->", "getMethodNotAllowedDecorator", "(", "new", "MethodNotAllowedException", ...
Set up middleware for a not allowed route @param array $allowed @return void
[ "Set", "up", "middleware", "for", "a", "not", "allowed", "route" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Dispatcher.php#L109-L116
train
thephpleague/route
src/Route.php
Route.getCallable
public function getCallable(?ContainerInterface $container = null) : callable { $callable = $this->handler; if (is_string($callable) && strpos($callable, '::') !== false) { $callable = explode('::', $callable); } if (is_array($callable) && isset($callable[0]) && is_object($callable[0])) { $callable = [$callable[0], $callable[1]]; } if (is_array($callable) && isset($callable[0]) && is_string($callable[0])) { $callable = [$this->resolveClass($container, $callable[0]), $callable[1]]; } if (is_string($callable) && method_exists($callable, '__invoke')) { $callable = $this->resolveClass($container, $callable); } if (! is_callable($callable)) { throw new InvalidArgumentException('Could not resolve a callable for this route'); } return $callable; }
php
public function getCallable(?ContainerInterface $container = null) : callable { $callable = $this->handler; if (is_string($callable) && strpos($callable, '::') !== false) { $callable = explode('::', $callable); } if (is_array($callable) && isset($callable[0]) && is_object($callable[0])) { $callable = [$callable[0], $callable[1]]; } if (is_array($callable) && isset($callable[0]) && is_string($callable[0])) { $callable = [$this->resolveClass($container, $callable[0]), $callable[1]]; } if (is_string($callable) && method_exists($callable, '__invoke')) { $callable = $this->resolveClass($container, $callable); } if (! is_callable($callable)) { throw new InvalidArgumentException('Could not resolve a callable for this route'); } return $callable; }
[ "public", "function", "getCallable", "(", "?", "ContainerInterface", "$", "container", "=", "null", ")", ":", "callable", "{", "$", "callable", "=", "$", "this", "->", "handler", ";", "if", "(", "is_string", "(", "$", "callable", ")", "&&", "strpos", "("...
Get the controller callable @param \Psr\Container\ContainerInterface|null $container @throws \InvalidArgumentException @return callable
[ "Get", "the", "controller", "callable" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Route.php#L73-L98
train
thephpleague/route
src/Route.php
Route.resolveClass
protected function resolveClass(?ContainerInterface $container = null, string $class) { if ($container instanceof ContainerInterface && $container->has($class)) { return $container->get($class); } return new $class(); }
php
protected function resolveClass(?ContainerInterface $container = null, string $class) { if ($container instanceof ContainerInterface && $container->has($class)) { return $container->get($class); } return new $class(); }
[ "protected", "function", "resolveClass", "(", "?", "ContainerInterface", "$", "container", "=", "null", ",", "string", "$", "class", ")", "{", "if", "(", "$", "container", "instanceof", "ContainerInterface", "&&", "$", "container", "->", "has", "(", "$", "cl...
Get an object instance from a class name @param \Psr\Container\ContainerInterface|null $container @param string $class @return object
[ "Get", "an", "object", "instance", "from", "a", "class", "name" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Route.php#L108-L115
train
thephpleague/route
src/Strategy/JsonStrategy.php
JsonStrategy.isJsonEncodable
protected function isJsonEncodable($response) : bool { if ($response instanceof ResponseInterface) { return false; } return (is_array($response) || is_object($response)); }
php
protected function isJsonEncodable($response) : bool { if ($response instanceof ResponseInterface) { return false; } return (is_array($response) || is_object($response)); }
[ "protected", "function", "isJsonEncodable", "(", "$", "response", ")", ":", "bool", "{", "if", "(", "$", "response", "instanceof", "ResponseInterface", ")", "{", "return", "false", ";", "}", "return", "(", "is_array", "(", "$", "response", ")", "||", "is_o...
Check if the response can be converted to JSON Arrays can always be converted, objects can be converted if they're not a response already @param mixed $response @return bool
[ "Check", "if", "the", "response", "can", "be", "converted", "to", "JSON" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Strategy/JsonStrategy.php#L62-L69
train
thephpleague/route
src/Strategy/JsonStrategy.php
JsonStrategy.buildJsonResponseMiddleware
protected function buildJsonResponseMiddleware(HttpException $exception) : MiddlewareInterface { return new class($this->responseFactory->createResponse(), $exception) implements MiddlewareInterface { protected $response; protected $exception; public function __construct(ResponseInterface $response, HttpException $exception) { $this->response = $response; $this->exception = $exception; } public function process( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) : ResponseInterface { return $this->exception->buildJsonResponse($this->response); } }; }
php
protected function buildJsonResponseMiddleware(HttpException $exception) : MiddlewareInterface { return new class($this->responseFactory->createResponse(), $exception) implements MiddlewareInterface { protected $response; protected $exception; public function __construct(ResponseInterface $response, HttpException $exception) { $this->response = $response; $this->exception = $exception; } public function process( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) : ResponseInterface { return $this->exception->buildJsonResponse($this->response); } }; }
[ "protected", "function", "buildJsonResponseMiddleware", "(", "HttpException", "$", "exception", ")", ":", "MiddlewareInterface", "{", "return", "new", "class", "(", "$", "this", "->", "responseFactory", "->", "createResponse", "(", ")", ",", "$", "exception", ")",...
Return a middleware the creates a JSON response from an HTTP exception @param \League\Route\Http\Exception $exception @return \Psr\Http\Server\MiddlewareInterface
[ "Return", "a", "middleware", "the", "creates", "a", "JSON", "response", "from", "an", "HTTP", "exception" ]
773bb4eae2c77708847e5c3b64bfa873b1b7caf8
https://github.com/thephpleague/route/blob/773bb4eae2c77708847e5c3b64bfa873b1b7caf8/src/Strategy/JsonStrategy.php#L94-L114
train
themsaid/laravel-langman
src/Commands/SyncCommand.php
SyncCommand.syncKeysFromFiles
private function syncKeysFromFiles($translationFiles) { $this->info('Reading translation keys from files...'); // An array of all translation keys as found in project files. $allKeysInFiles = $this->manager->collectFromFiles(); foreach ($translationFiles as $fileName => $languages) { foreach ($languages as $languageKey => $path) { $fileContent = $this->manager->getFileContent($path); if (isset($allKeysInFiles[$fileName])) { $missingKeys = array_diff($allKeysInFiles[$fileName], array_keys(array_dot($fileContent))); foreach ($missingKeys as $i => $missingKey) { if (Arr::has($fileContent, $missingKey)) { unset($missingKeys[$i]); } } $this->fillMissingKeys($fileName, $missingKeys, $languageKey); } } } }
php
private function syncKeysFromFiles($translationFiles) { $this->info('Reading translation keys from files...'); // An array of all translation keys as found in project files. $allKeysInFiles = $this->manager->collectFromFiles(); foreach ($translationFiles as $fileName => $languages) { foreach ($languages as $languageKey => $path) { $fileContent = $this->manager->getFileContent($path); if (isset($allKeysInFiles[$fileName])) { $missingKeys = array_diff($allKeysInFiles[$fileName], array_keys(array_dot($fileContent))); foreach ($missingKeys as $i => $missingKey) { if (Arr::has($fileContent, $missingKey)) { unset($missingKeys[$i]); } } $this->fillMissingKeys($fileName, $missingKeys, $languageKey); } } } }
[ "private", "function", "syncKeysFromFiles", "(", "$", "translationFiles", ")", "{", "$", "this", "->", "info", "(", "'Reading translation keys from files...'", ")", ";", "// An array of all translation keys as found in project files.", "$", "allKeysInFiles", "=", "$", "this...
Synchronize keys found in project files but missing in languages. @param $translationFiles @throws \Illuminate\Contracts\Filesystem\FileNotFoundException @return void
[ "Synchronize", "keys", "found", "in", "project", "files", "but", "missing", "in", "languages", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/SyncCommand.php#L68-L92
train
themsaid/laravel-langman
src/Commands/SyncCommand.php
SyncCommand.fillMissingKeys
private function fillMissingKeys($fileName, array $foundMissingKeys, $languageKey) { $missingKeys = []; foreach ($foundMissingKeys as $missingKey) { $missingKeys[$missingKey] = [$languageKey => '']; $this->output->writeln("\"<fg=yellow>{$fileName}.{$missingKey}.{$languageKey}</>\" was added."); } $this->manager->fillKeys( $fileName, $missingKeys ); }
php
private function fillMissingKeys($fileName, array $foundMissingKeys, $languageKey) { $missingKeys = []; foreach ($foundMissingKeys as $missingKey) { $missingKeys[$missingKey] = [$languageKey => '']; $this->output->writeln("\"<fg=yellow>{$fileName}.{$missingKey}.{$languageKey}</>\" was added."); } $this->manager->fillKeys( $fileName, $missingKeys ); }
[ "private", "function", "fillMissingKeys", "(", "$", "fileName", ",", "array", "$", "foundMissingKeys", ",", "$", "languageKey", ")", "{", "$", "missingKeys", "=", "[", "]", ";", "foreach", "(", "$", "foundMissingKeys", "as", "$", "missingKey", ")", "{", "$...
Fill the missing keys with an empty string in the given file. @param string $fileName @param array $foundMissingKeys @param string $languageKey @return void
[ "Fill", "the", "missing", "keys", "with", "an", "empty", "string", "in", "the", "given", "file", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/SyncCommand.php#L102-L116
train
themsaid/laravel-langman
src/Commands/SyncCommand.php
SyncCommand.syncKeysBetweenLanguages
private function syncKeysBetweenLanguages($translationFiles) { $this->info('Synchronizing language files...'); $filesResults = []; // Here we collect the file results foreach ($translationFiles as $fileName => $languageFiles) { foreach ($languageFiles as $languageKey => $filePath) { $filesResults[$fileName][$languageKey] = $this->manager->getFileContent($filePath); } } $values = Arr::dot($filesResults); $missing = $this->manager->getKeysExistingInALanguageButNotTheOther($values); foreach ($missing as &$missingKey) { list($file, $key) = explode('.', $missingKey, 2); list($key, $language) = explode(':', $key, 2); $this->fillMissingKeys($file, [$key], $language); } }
php
private function syncKeysBetweenLanguages($translationFiles) { $this->info('Synchronizing language files...'); $filesResults = []; // Here we collect the file results foreach ($translationFiles as $fileName => $languageFiles) { foreach ($languageFiles as $languageKey => $filePath) { $filesResults[$fileName][$languageKey] = $this->manager->getFileContent($filePath); } } $values = Arr::dot($filesResults); $missing = $this->manager->getKeysExistingInALanguageButNotTheOther($values); foreach ($missing as &$missingKey) { list($file, $key) = explode('.', $missingKey, 2); list($key, $language) = explode(':', $key, 2); $this->fillMissingKeys($file, [$key], $language); } }
[ "private", "function", "syncKeysBetweenLanguages", "(", "$", "translationFiles", ")", "{", "$", "this", "->", "info", "(", "'Synchronizing language files...'", ")", ";", "$", "filesResults", "=", "[", "]", ";", "// Here we collect the file results", "foreach", "(", ...
Synchronize keys that exist in a language but not the other. @param $translationFiles @throws \Illuminate\Contracts\Filesystem\FileNotFoundException @return void
[ "Synchronize", "keys", "that", "exist", "in", "a", "language", "but", "not", "the", "other", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/SyncCommand.php#L125-L149
train
themsaid/laravel-langman
src/Commands/MissingCommand.php
MissingCommand.getDefaultValue
private function getDefaultValue($missingKey) { if (! $this->option('default')) { return null; } try { $missingKey = explode(':', $missingKey)[0]; list($file, $key) = explode('.', $missingKey); $filePath = $this->manager->files()[$file][config('app.locale')]; return config('app.locale').":{$this->manager->getFileContent($filePath)[$key]}"; } catch (\Exception $e) { return null; } }
php
private function getDefaultValue($missingKey) { if (! $this->option('default')) { return null; } try { $missingKey = explode(':', $missingKey)[0]; list($file, $key) = explode('.', $missingKey); $filePath = $this->manager->files()[$file][config('app.locale')]; return config('app.locale').":{$this->manager->getFileContent($filePath)[$key]}"; } catch (\Exception $e) { return null; } }
[ "private", "function", "getDefaultValue", "(", "$", "missingKey", ")", "{", "if", "(", "!", "$", "this", "->", "option", "(", "'default'", ")", ")", "{", "return", "null", ";", "}", "try", "{", "$", "missingKey", "=", "explode", "(", "':'", ",", "$",...
Get translation in default locale for the given key. @param string $missingKey @return string
[ "Get", "translation", "in", "default", "locale", "for", "the", "given", "key", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/MissingCommand.php#L112-L129
train
themsaid/laravel-langman
src/Commands/MissingCommand.php
MissingCommand.getMissing
private function getMissing(array $languages) { $files = $this->manager->files(); // Array of content of all files indexed by fileName.languageKey $filesResults = []; // The final output of the method $missing = []; // Here we collect the file results foreach ($files as $fileName => $languageFiles) { foreach ($languageFiles as $languageKey => $filePath) { $filesResults[$fileName][$languageKey] = $this->manager->getFileContent($filePath); } } $values = Arr::dot($filesResults); $emptyValues = array_filter($values, function ($value) { return $value == ''; }); // Adding all keys that has values = '' foreach ($emptyValues as $dottedValue => $emptyValue) { list($fileName, $languageKey, $key) = explode('.', $dottedValue, 3); $missing[] = "{$fileName}.{$key}:{$languageKey}"; } $missing = array_merge($missing, $this->manager->getKeysExistingInALanguageButNotTheOther($values)); return $missing; }
php
private function getMissing(array $languages) { $files = $this->manager->files(); // Array of content of all files indexed by fileName.languageKey $filesResults = []; // The final output of the method $missing = []; // Here we collect the file results foreach ($files as $fileName => $languageFiles) { foreach ($languageFiles as $languageKey => $filePath) { $filesResults[$fileName][$languageKey] = $this->manager->getFileContent($filePath); } } $values = Arr::dot($filesResults); $emptyValues = array_filter($values, function ($value) { return $value == ''; }); // Adding all keys that has values = '' foreach ($emptyValues as $dottedValue => $emptyValue) { list($fileName, $languageKey, $key) = explode('.', $dottedValue, 3); $missing[] = "{$fileName}.{$key}:{$languageKey}"; } $missing = array_merge($missing, $this->manager->getKeysExistingInALanguageButNotTheOther($values)); return $missing; }
[ "private", "function", "getMissing", "(", "array", "$", "languages", ")", "{", "$", "files", "=", "$", "this", "->", "manager", "->", "files", "(", ")", ";", "// Array of content of all files indexed by fileName.languageKey", "$", "filesResults", "=", "[", "]", ...
Get an array of keys that have missing values with a hint from another language translation file if possible. ex: [ ['key' => 'product.color.nl', 'hint' => 'en = "color"'] ] @param array $languages @return array
[ "Get", "an", "array", "of", "keys", "that", "have", "missing", "values", "with", "a", "hint", "from", "another", "language", "translation", "file", "if", "possible", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/MissingCommand.php#L140-L173
train
themsaid/laravel-langman
src/Commands/ShowCommand.php
ShowCommand.shouldShowKey
private function shouldShowKey($key) { if ($this->key) { if (Str::contains($key, '.') && Str::startsWith($key, $this->key)) { return true; } if (! $this->option('close') && $key != $this->key) { return false; } if ($this->option('close') && ! Str::contains($key, $this->key)) { return false; } } return true; }
php
private function shouldShowKey($key) { if ($this->key) { if (Str::contains($key, '.') && Str::startsWith($key, $this->key)) { return true; } if (! $this->option('close') && $key != $this->key) { return false; } if ($this->option('close') && ! Str::contains($key, $this->key)) { return false; } } return true; }
[ "private", "function", "shouldShowKey", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "key", ")", "{", "if", "(", "Str", "::", "contains", "(", "$", "key", ",", "'.'", ")", "&&", "Str", "::", "startsWith", "(", "$", "key", ",", "$", ...
Determine if the given key should exist in the output. @param $key @return bool
[ "Determine", "if", "the", "given", "key", "should", "exist", "in", "the", "output", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/ShowCommand.php#L191-L208
train
themsaid/laravel-langman
src/Commands/ShowCommand.php
ShowCommand.getLanguages
private function getLanguages() { $allLanguages = $this->manager->languages(); if (! $this->option('lang')) { return $allLanguages; } $userLanguages = explode(',', (string) $this->option('lang')); if ($missingLanguages = array_diff($userLanguages, $allLanguages)) { throw new InvalidArgumentException('Unknown Language(s) ['.implode(',', $missingLanguages).'].'); } return $userLanguages; }
php
private function getLanguages() { $allLanguages = $this->manager->languages(); if (! $this->option('lang')) { return $allLanguages; } $userLanguages = explode(',', (string) $this->option('lang')); if ($missingLanguages = array_diff($userLanguages, $allLanguages)) { throw new InvalidArgumentException('Unknown Language(s) ['.implode(',', $missingLanguages).'].'); } return $userLanguages; }
[ "private", "function", "getLanguages", "(", ")", "{", "$", "allLanguages", "=", "$", "this", "->", "manager", "->", "languages", "(", ")", ";", "if", "(", "!", "$", "this", "->", "option", "(", "'lang'", ")", ")", "{", "return", "$", "allLanguages", ...
Get the languages to be displayed in the command output. @return array
[ "Get", "the", "languages", "to", "be", "displayed", "in", "the", "command", "output", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/ShowCommand.php#L215-L230
train
themsaid/laravel-langman
src/Manager.php
Manager.files
public function files() { $files = Collection::make($this->disk->allFiles($this->path))->filter(function ($file) { return $this->disk->extension($file) == 'php'; }); $filesByFile = $files->groupBy(function ($file) { $fileName = $file->getBasename('.'.$file->getExtension()); if (Str::contains($file->getPath(), 'vendor')) { $fileName = str_replace('.php', '', $file->getFileName()); $packageName = basename(dirname($file->getPath())); return "{$packageName}::{$fileName}"; } else { return $fileName; } })->map(function ($files) { return $files->keyBy(function ($file) { return basename($file->getPath()); })->map(function ($file) { return $file->getRealPath(); }); }); // If the path does not contain "vendor" then we're looking at the // main language files of the application, in this case we will // neglect all vendor files. if (! Str::contains($this->path, 'vendor')) { $filesByFile = $this->neglectVendorFiles($filesByFile); } return $filesByFile; }
php
public function files() { $files = Collection::make($this->disk->allFiles($this->path))->filter(function ($file) { return $this->disk->extension($file) == 'php'; }); $filesByFile = $files->groupBy(function ($file) { $fileName = $file->getBasename('.'.$file->getExtension()); if (Str::contains($file->getPath(), 'vendor')) { $fileName = str_replace('.php', '', $file->getFileName()); $packageName = basename(dirname($file->getPath())); return "{$packageName}::{$fileName}"; } else { return $fileName; } })->map(function ($files) { return $files->keyBy(function ($file) { return basename($file->getPath()); })->map(function ($file) { return $file->getRealPath(); }); }); // If the path does not contain "vendor" then we're looking at the // main language files of the application, in this case we will // neglect all vendor files. if (! Str::contains($this->path, 'vendor')) { $filesByFile = $this->neglectVendorFiles($filesByFile); } return $filesByFile; }
[ "public", "function", "files", "(", ")", "{", "$", "files", "=", "Collection", "::", "make", "(", "$", "this", "->", "disk", "->", "allFiles", "(", "$", "this", "->", "path", ")", ")", "->", "filter", "(", "function", "(", "$", "file", ")", "{", ...
Array of language files grouped by file name. ex: ['user' => ['en' => 'user.php', 'nl' => 'user.php']] @return array
[ "Array", "of", "language", "files", "grouped", "by", "file", "name", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L54-L88
train
themsaid/laravel-langman
src/Manager.php
Manager.neglectVendorFiles
private function neglectVendorFiles($filesByFile) { $return = []; foreach ($filesByFile->toArray() as $key => $value) { if (! Str::contains($key, ':')) { $return[$key] = $value; } } return $return; }
php
private function neglectVendorFiles($filesByFile) { $return = []; foreach ($filesByFile->toArray() as $key => $value) { if (! Str::contains($key, ':')) { $return[$key] = $value; } } return $return; }
[ "private", "function", "neglectVendorFiles", "(", "$", "filesByFile", ")", "{", "$", "return", "=", "[", "]", ";", "foreach", "(", "$", "filesByFile", "->", "toArray", "(", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "Str", ...
Nelgect all vendor files. @param $filesByFile Collection @return array
[ "Nelgect", "all", "vendor", "files", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L96-L107
train
themsaid/laravel-langman
src/Manager.php
Manager.languages
public function languages() { $languages = array_map(function ($directory) { return basename($directory); }, $this->disk->directories($this->path)); $languages = array_filter($languages, function ($directory) { return $directory != 'vendor' && $directory != 'json'; }); sort($languages); return Arr::except($languages, ['vendor', 'json']); }
php
public function languages() { $languages = array_map(function ($directory) { return basename($directory); }, $this->disk->directories($this->path)); $languages = array_filter($languages, function ($directory) { return $directory != 'vendor' && $directory != 'json'; }); sort($languages); return Arr::except($languages, ['vendor', 'json']); }
[ "public", "function", "languages", "(", ")", "{", "$", "languages", "=", "array_map", "(", "function", "(", "$", "directory", ")", "{", "return", "basename", "(", "$", "directory", ")", ";", "}", ",", "$", "this", "->", "disk", "->", "directories", "("...
Array of supported languages. ex: ['en', 'sp'] @return array
[ "Array", "of", "supported", "languages", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L116-L129
train
themsaid/laravel-langman
src/Manager.php
Manager.createFile
public function createFile($fileName) { foreach ($this->languages() as $languageKey) { $file = $this->path."/{$languageKey}/{$fileName}.php"; if (! $this->disk->exists($file)) { file_put_contents($file, "<?php \n\n return[];"); } } }
php
public function createFile($fileName) { foreach ($this->languages() as $languageKey) { $file = $this->path."/{$languageKey}/{$fileName}.php"; if (! $this->disk->exists($file)) { file_put_contents($file, "<?php \n\n return[];"); } } }
[ "public", "function", "createFile", "(", "$", "fileName", ")", "{", "foreach", "(", "$", "this", "->", "languages", "(", ")", "as", "$", "languageKey", ")", "{", "$", "file", "=", "$", "this", "->", "path", ".", "\"/{$languageKey}/{$fileName}.php\"", ";", ...
Create a file for all languages if does not exist already. @param $fileName @return void
[ "Create", "a", "file", "for", "all", "languages", "if", "does", "not", "exist", "already", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L137-L145
train
themsaid/laravel-langman
src/Manager.php
Manager.fillKeys
public function fillKeys($fileName, array $keys) { $appends = []; foreach ($keys as $key => $values) { foreach ($values as $languageKey => $value) { $filePath = $this->path."/{$languageKey}/{$fileName}.php"; Arr::set($appends[$filePath], $key, $value); } } foreach ($appends as $filePath => $values) { $fileContent = $this->getFileContent($filePath, true); $newContent = array_replace_recursive($fileContent, $values); $this->writeFile($filePath, $newContent); } }
php
public function fillKeys($fileName, array $keys) { $appends = []; foreach ($keys as $key => $values) { foreach ($values as $languageKey => $value) { $filePath = $this->path."/{$languageKey}/{$fileName}.php"; Arr::set($appends[$filePath], $key, $value); } } foreach ($appends as $filePath => $values) { $fileContent = $this->getFileContent($filePath, true); $newContent = array_replace_recursive($fileContent, $values); $this->writeFile($filePath, $newContent); } }
[ "public", "function", "fillKeys", "(", "$", "fileName", ",", "array", "$", "keys", ")", "{", "$", "appends", "=", "[", "]", ";", "foreach", "(", "$", "keys", "as", "$", "key", "=>", "$", "values", ")", "{", "foreach", "(", "$", "values", "as", "$...
Fills translation lines for given keys in different languages. ex. for $keys = ['name' => ['en' => 'name', 'nl' => 'naam'] @param string $fileName @param array $keys @return void
[ "Fills", "translation", "lines", "for", "given", "keys", "in", "different", "languages", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L156-L175
train
themsaid/laravel-langman
src/Manager.php
Manager.removeKey
public function removeKey($fileName, $key) { foreach ($this->languages() as $language) { $filePath = $this->path."/{$language}/{$fileName}.php"; $fileContent = $this->getFileContent($filePath); Arr::forget($fileContent, $key); $this->writeFile($filePath, $fileContent); } }
php
public function removeKey($fileName, $key) { foreach ($this->languages() as $language) { $filePath = $this->path."/{$language}/{$fileName}.php"; $fileContent = $this->getFileContent($filePath); Arr::forget($fileContent, $key); $this->writeFile($filePath, $fileContent); } }
[ "public", "function", "removeKey", "(", "$", "fileName", ",", "$", "key", ")", "{", "foreach", "(", "$", "this", "->", "languages", "(", ")", "as", "$", "language", ")", "{", "$", "filePath", "=", "$", "this", "->", "path", ".", "\"/{$language}/{$fileN...
Remove a key from all language files. @param string $fileName @param string $key @return void
[ "Remove", "a", "key", "from", "all", "language", "files", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L184-L195
train
themsaid/laravel-langman
src/Manager.php
Manager.writeFile
public function writeFile($filePath, array $translations) { $content = "<?php \n\nreturn ["; $content .= $this->stringLineMaker($translations); $content .= "\n];"; file_put_contents($filePath, $content); }
php
public function writeFile($filePath, array $translations) { $content = "<?php \n\nreturn ["; $content .= $this->stringLineMaker($translations); $content .= "\n];"; file_put_contents($filePath, $content); }
[ "public", "function", "writeFile", "(", "$", "filePath", ",", "array", "$", "translations", ")", "{", "$", "content", "=", "\"<?php \\n\\nreturn [\"", ";", "$", "content", ".=", "$", "this", "->", "stringLineMaker", "(", "$", "translations", ")", ";", "$", ...
Write a language file from array. @param string $filePath @param array $translations @return void
[ "Write", "a", "language", "file", "from", "array", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L204-L213
train
themsaid/laravel-langman
src/Manager.php
Manager.stringLineMaker
private function stringLineMaker($array, $prepend = '') { $output = ''; foreach ($array as $key => $value) { if (is_array($value)) { $value = $this->stringLineMaker($value, $prepend.' '); $output .= "\n{$prepend} '{$key}' => [{$value}\n{$prepend} ],"; } else { $value = str_replace('\"', '"', addslashes($value)); $output .= "\n{$prepend} '{$key}' => '{$value}',"; } } return $output; }
php
private function stringLineMaker($array, $prepend = '') { $output = ''; foreach ($array as $key => $value) { if (is_array($value)) { $value = $this->stringLineMaker($value, $prepend.' '); $output .= "\n{$prepend} '{$key}' => [{$value}\n{$prepend} ],"; } else { $value = str_replace('\"', '"', addslashes($value)); $output .= "\n{$prepend} '{$key}' => '{$value}',"; } } return $output; }
[ "private", "function", "stringLineMaker", "(", "$", "array", ",", "$", "prepend", "=", "''", ")", "{", "$", "output", "=", "''", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "...
Write the lines of the inner array of the language file. @param $array @return string
[ "Write", "the", "lines", "of", "the", "inner", "array", "of", "the", "language", "file", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L221-L238
train
themsaid/laravel-langman
src/Manager.php
Manager.collectFromFiles
public function collectFromFiles() { $translationKeys = []; foreach ($this->getAllViewFilesWithTranslations() as $file => $matches) { foreach ($matches as $key) { try { list($fileName, $keyName) = explode('.', $key, 2); } catch (\ErrorException $e) { continue; } if (isset($translationKeys[$fileName]) && in_array($keyName, $translationKeys[$fileName])) { continue; } $translationKeys[$fileName][] = $keyName; } } return $translationKeys; }
php
public function collectFromFiles() { $translationKeys = []; foreach ($this->getAllViewFilesWithTranslations() as $file => $matches) { foreach ($matches as $key) { try { list($fileName, $keyName) = explode('.', $key, 2); } catch (\ErrorException $e) { continue; } if (isset($translationKeys[$fileName]) && in_array($keyName, $translationKeys[$fileName])) { continue; } $translationKeys[$fileName][] = $keyName; } } return $translationKeys; }
[ "public", "function", "collectFromFiles", "(", ")", "{", "$", "translationKeys", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getAllViewFilesWithTranslations", "(", ")", "as", "$", "file", "=>", "$", "matches", ")", "{", "foreach", "(", "$", "...
Collect all translation keys from views files. e.g. ['users' => ['city', 'name', 'phone']] @return array
[ "Collect", "all", "translation", "keys", "from", "views", "files", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L274-L295
train
themsaid/laravel-langman
src/Manager.php
Manager.getKeysExistingInALanguageButNotTheOther
public function getKeysExistingInALanguageButNotTheOther($values) { $missing = []; // Array of keys indexed by fileName.key, those are the keys we looked // at before so we save them in order for us to not look at them // again in a different language iteration. $searched = []; // Now we add keys that exist in a language but missing in any of the // other languages. Those keys combined with ones with values = '' // will be sent to the console user to fill and save in disk. foreach ($values as $key => $value) { list($fileName, $languageKey, $key) = explode('.', $key, 3); if (in_array("{$fileName}.{$key}", $searched)) { continue; } foreach ($this->languages() as $languageName) { if (! Arr::has($values, "{$fileName}.{$languageName}.{$key}") && ! array_key_exists("{$fileName}.{$languageName}.{$key}", $values)) { $missing[] = "{$fileName}.{$key}:{$languageName}"; } } $searched[] = "{$fileName}.{$key}"; } return $missing; }
php
public function getKeysExistingInALanguageButNotTheOther($values) { $missing = []; // Array of keys indexed by fileName.key, those are the keys we looked // at before so we save them in order for us to not look at them // again in a different language iteration. $searched = []; // Now we add keys that exist in a language but missing in any of the // other languages. Those keys combined with ones with values = '' // will be sent to the console user to fill and save in disk. foreach ($values as $key => $value) { list($fileName, $languageKey, $key) = explode('.', $key, 3); if (in_array("{$fileName}.{$key}", $searched)) { continue; } foreach ($this->languages() as $languageName) { if (! Arr::has($values, "{$fileName}.{$languageName}.{$key}") && ! array_key_exists("{$fileName}.{$languageName}.{$key}", $values)) { $missing[] = "{$fileName}.{$key}:{$languageName}"; } } $searched[] = "{$fileName}.{$key}"; } return $missing; }
[ "public", "function", "getKeysExistingInALanguageButNotTheOther", "(", "$", "values", ")", "{", "$", "missing", "=", "[", "]", ";", "// Array of keys indexed by fileName.key, those are the keys we looked", "// at before so we save them in order for us to not look at them", "// again ...
Extract keys that exists in a language but not the other. Given a dot array of all keys in the format 'file.language.key', this method searches for keys that exist in one language but not the other and outputs an array consists of those keys. @param $values @return array
[ "Extract", "keys", "that", "exists", "in", "a", "language", "but", "not", "the", "other", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Manager.php#L361-L390
train
themsaid/laravel-langman
src/Commands/RenameCommand.php
RenameCommand.renameKey
private function renameKey() { try { list($file, $key) = explode('.', $this->argument('oldKey'), 2); } catch (\ErrorException $e) { $this->error('Could not recognize the key you want to rename.'); return; } if (Str::contains($this->argument('newKey'), '.')) { $this->error('Please provide the new key must not contain a dot.'); return; } $newKey = preg_replace('/(\w+)$/i', $this->argument('newKey'), $key); $files = $this->manager->files()[$file]; $currentValues = []; foreach ($files as $languageKey => $filePath) { $content = Arr::dot($this->manager->getFileContent($filePath)); $currentValues[$languageKey] = isset($content[$key]) ? $content[$key] : ''; } $this->manager->removeKey($file, $key); $this->manager->fillKeys( $file, [$newKey => $currentValues] ); }
php
private function renameKey() { try { list($file, $key) = explode('.', $this->argument('oldKey'), 2); } catch (\ErrorException $e) { $this->error('Could not recognize the key you want to rename.'); return; } if (Str::contains($this->argument('newKey'), '.')) { $this->error('Please provide the new key must not contain a dot.'); return; } $newKey = preg_replace('/(\w+)$/i', $this->argument('newKey'), $key); $files = $this->manager->files()[$file]; $currentValues = []; foreach ($files as $languageKey => $filePath) { $content = Arr::dot($this->manager->getFileContent($filePath)); $currentValues[$languageKey] = isset($content[$key]) ? $content[$key] : ''; } $this->manager->removeKey($file, $key); $this->manager->fillKeys( $file, [$newKey => $currentValues] ); }
[ "private", "function", "renameKey", "(", ")", "{", "try", "{", "list", "(", "$", "file", ",", "$", "key", ")", "=", "explode", "(", "'.'", ",", "$", "this", "->", "argument", "(", "'oldKey'", ")", ",", "2", ")", ";", "}", "catch", "(", "\\", "E...
Rename the given oldKey to the newKey. @return void
[ "Rename", "the", "given", "oldKey", "to", "the", "newKey", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/RenameCommand.php#L72-L106
train
themsaid/laravel-langman
src/Commands/RenameCommand.php
RenameCommand.listFilesContainingOldKey
private function listFilesContainingOldKey() { if ($files = $this->getFilesContainingOldKey()) { $this->info('Renamed key was found in '.count($files).' file(s).'); $this->table(['Encounters', 'File'], $this->getTableRows($files)); } }
php
private function listFilesContainingOldKey() { if ($files = $this->getFilesContainingOldKey()) { $this->info('Renamed key was found in '.count($files).' file(s).'); $this->table(['Encounters', 'File'], $this->getTableRows($files)); } }
[ "private", "function", "listFilesContainingOldKey", "(", ")", "{", "if", "(", "$", "files", "=", "$", "this", "->", "getFilesContainingOldKey", "(", ")", ")", "{", "$", "this", "->", "info", "(", "'Renamed key was found in '", ".", "count", "(", "$", "files"...
Show a table with application files containing the old key. @return void
[ "Show", "a", "table", "with", "application", "files", "containing", "the", "old", "key", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/RenameCommand.php#L113-L120
train
themsaid/laravel-langman
src/Commands/RenameCommand.php
RenameCommand.getFilesContainingOldKey
private function getFilesContainingOldKey() { $affectedFiles = []; foreach ($this->manager->getAllViewFilesWithTranslations() as $file => $keys) { foreach ($keys as $key) { if ($key == $this->argument('oldKey')) { $affectedFiles[$file][] = $key; } } } return $affectedFiles; }
php
private function getFilesContainingOldKey() { $affectedFiles = []; foreach ($this->manager->getAllViewFilesWithTranslations() as $file => $keys) { foreach ($keys as $key) { if ($key == $this->argument('oldKey')) { $affectedFiles[$file][] = $key; } } } return $affectedFiles; }
[ "private", "function", "getFilesContainingOldKey", "(", ")", "{", "$", "affectedFiles", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "manager", "->", "getAllViewFilesWithTranslations", "(", ")", "as", "$", "file", "=>", "$", "keys", ")", "{", "fo...
Get an array of application files containing the old key. @return array
[ "Get", "an", "array", "of", "application", "files", "containing", "the", "old", "key", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/RenameCommand.php#L127-L140
train
themsaid/laravel-langman
src/Commands/RenameCommand.php
RenameCommand.getTableRows
private function getTableRows($files) { $rows = []; foreach ($files as $file => $keys) { $rows[] = [count($keys), $file]; } return $rows; }
php
private function getTableRows($files) { $rows = []; foreach ($files as $file => $keys) { $rows[] = [count($keys), $file]; } return $rows; }
[ "private", "function", "getTableRows", "(", "$", "files", ")", "{", "$", "rows", "=", "[", "]", ";", "foreach", "(", "$", "files", "as", "$", "file", "=>", "$", "keys", ")", "{", "$", "rows", "[", "]", "=", "[", "count", "(", "$", "keys", ")", ...
Get table rows for the list of files containing the old key. @param array $files @return array
[ "Get", "table", "rows", "for", "the", "list", "of", "files", "containing", "the", "old", "key", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/RenameCommand.php#L148-L157
train
themsaid/laravel-langman
src/Commands/TransCommand.php
TransCommand.fillKey
private function fillKey() { $languages = $this->manager->languages(); if ($this->languageKey) { if (! in_array($this->languageKey, $languages)) { $this->error(sprintf('Language (%s) could not be found!', $this->languageKey)); return; } // If a language key was specified then we prompt for it only. $languages = [$this->languageKey]; } $values = $this->collectValues($languages); $this->manager->fillKeys( str_replace($this->packageName.'::', '', $this->fileName), [$this->key => $values] ); foreach ($values as $languageKey => $value) { $this->line("<fg=yellow>{$this->fileName}.{$this->key}:{$languageKey}</> was set to \"<fg=yellow>{$value}</>\" successfully."); } }
php
private function fillKey() { $languages = $this->manager->languages(); if ($this->languageKey) { if (! in_array($this->languageKey, $languages)) { $this->error(sprintf('Language (%s) could not be found!', $this->languageKey)); return; } // If a language key was specified then we prompt for it only. $languages = [$this->languageKey]; } $values = $this->collectValues($languages); $this->manager->fillKeys( str_replace($this->packageName.'::', '', $this->fileName), [$this->key => $values] ); foreach ($values as $languageKey => $value) { $this->line("<fg=yellow>{$this->fileName}.{$this->key}:{$languageKey}</> was set to \"<fg=yellow>{$value}</>\" successfully."); } }
[ "private", "function", "fillKey", "(", ")", "{", "$", "languages", "=", "$", "this", "->", "manager", "->", "languages", "(", ")", ";", "if", "(", "$", "this", "->", "languageKey", ")", "{", "if", "(", "!", "in_array", "(", "$", "this", "->", "lang...
Fill a translation key in all languages. @return void
[ "Fill", "a", "translation", "key", "in", "all", "languages", "." ]
27cdaa7eca53a0fe7a54c413285de6112f3166de
https://github.com/themsaid/laravel-langman/blob/27cdaa7eca53a0fe7a54c413285de6112f3166de/src/Commands/TransCommand.php#L160-L185
train
editor-js/editorjs-php
EditorJS/EditorJS.php
EditorJS.getBlocks
public function getBlocks() { $sanitizedBlocks = []; foreach ($this->blocks as $block) { $sanitizedBlock = $this->handler->sanitizeBlock($block['type'], $block['data']); if (!empty($sanitizedBlock)) { array_push($sanitizedBlocks, $sanitizedBlock); } } return $sanitizedBlocks; }
php
public function getBlocks() { $sanitizedBlocks = []; foreach ($this->blocks as $block) { $sanitizedBlock = $this->handler->sanitizeBlock($block['type'], $block['data']); if (!empty($sanitizedBlock)) { array_push($sanitizedBlocks, $sanitizedBlock); } } return $sanitizedBlocks; }
[ "public", "function", "getBlocks", "(", ")", "{", "$", "sanitizedBlocks", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "blocks", "as", "$", "block", ")", "{", "$", "sanitizedBlock", "=", "$", "this", "->", "handler", "->", "sanitizeBlock", "(...
Sanitize and return array of blocks according to the Handler's rules. @return array
[ "Sanitize", "and", "return", "array", "of", "blocks", "according", "to", "the", "Handler", "s", "rules", "." ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/EditorJS.php#L104-L116
train
editor-js/editorjs-php
EditorJS/EditorJS.php
EditorJS.validateBlocks
private function validateBlocks() { foreach ($this->blocks as $block) { if (!$this->handler->validateBlock($block['type'], $block['data'])) { return false; } } return true; }
php
private function validateBlocks() { foreach ($this->blocks as $block) { if (!$this->handler->validateBlock($block['type'], $block['data'])) { return false; } } return true; }
[ "private", "function", "validateBlocks", "(", ")", "{", "foreach", "(", "$", "this", "->", "blocks", "as", "$", "block", ")", "{", "if", "(", "!", "$", "this", "->", "handler", "->", "validateBlock", "(", "$", "block", "[", "'type'", "]", ",", "$", ...
Validate blocks structure according to the Handler's rules. @return bool
[ "Validate", "blocks", "structure", "according", "to", "the", "Handler", "s", "rules", "." ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/EditorJS.php#L123-L132
train
editor-js/editorjs-php
EditorJS/BlockHandler.php
BlockHandler.validateBlock
public function validateBlock($blockType, $blockData) { /** * Default action for blocks that are not mentioned in a configuration */ if (!array_key_exists($blockType, $this->rules->tools)) { throw new EditorJSException("Tool `$blockType` not found in the configuration"); } $rule = $this->rules->tools[$blockType]; return $this->validate($rule, $blockData); }
php
public function validateBlock($blockType, $blockData) { /** * Default action for blocks that are not mentioned in a configuration */ if (!array_key_exists($blockType, $this->rules->tools)) { throw new EditorJSException("Tool `$blockType` not found in the configuration"); } $rule = $this->rules->tools[$blockType]; return $this->validate($rule, $blockData); }
[ "public", "function", "validateBlock", "(", "$", "blockType", ",", "$", "blockData", ")", "{", "/**\n * Default action for blocks that are not mentioned in a configuration\n */", "if", "(", "!", "array_key_exists", "(", "$", "blockType", ",", "$", "this", ...
Validate block for correctness @param string $blockType @param array $blockData @throws EditorJSException @return bool
[ "Validate", "block", "for", "correctness" ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/BlockHandler.php#L44-L56
train
editor-js/editorjs-php
EditorJS/BlockHandler.php
BlockHandler.sanitizeBlock
public function sanitizeBlock($blockType, $blockData) { $rule = $this->rules->tools[$blockType]; return [ 'type' => $blockType, 'data' => $this->sanitize($rule, $blockData) ]; }
php
public function sanitizeBlock($blockType, $blockData) { $rule = $this->rules->tools[$blockType]; return [ 'type' => $blockType, 'data' => $this->sanitize($rule, $blockData) ]; }
[ "public", "function", "sanitizeBlock", "(", "$", "blockType", ",", "$", "blockData", ")", "{", "$", "rule", "=", "$", "this", "->", "rules", "->", "tools", "[", "$", "blockType", "]", ";", "return", "[", "'type'", "=>", "$", "blockType", ",", "'data'",...
Apply sanitizing rules according to the block type @param string $blockType @param array $blockData @throws EditorJSException @return array|bool
[ "Apply", "sanitizing", "rules", "according", "to", "the", "block", "type" ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/BlockHandler.php#L68-L76
train
editor-js/editorjs-php
EditorJS/BlockHandler.php
BlockHandler.validate
private function validate($rules, $blockData) { /** * Make sure that every required param exists in data block */ foreach ($rules as $key => $value) { if (($key != BlockHandler::DEFAULT_ARRAY_KEY) && (isset($value['required']) ? $value['required'] : true)) { if (!isset($blockData[$key])) { throw new EditorJSException("Not found required param `$key`"); } } } /** * Check if there is not extra params (not mentioned in configuration rule) */ foreach ($blockData as $key => $value) { if (!is_integer($key) && !isset($rules[$key])) { throw new EditorJSException("Found extra param `$key`"); } } /** * Validate every key in data block */ foreach ($blockData as $key => $value) { /** * PHP Array has integer keys */ if (is_integer($key)) { $key = BlockHandler::DEFAULT_ARRAY_KEY; } $rule = $rules[$key]; $rule = $this->expandToolSettings($rule); $elementType = $rule['type']; /** * Process canBeOnly rule */ if (isset($rule['canBeOnly'])) { if (!in_array($value, $rule['canBeOnly'])) { throw new EditorJSException("Option '$key' with value `$value` has invalid value. Check canBeOnly param."); } // Do not perform additional elements validation in any case continue; } /** * Validate element types */ switch ($elementType) { case 'string': if (!is_string($value)) { throw new EditorJSException("Option '$key' with value `$value` must be string"); } break; case 'integer': case 'int': if (!is_integer($value)) { throw new EditorJSException("Option '$key' with value `$value` must be integer"); } break; case 'array': $this->validate($rule['data'], $value); break; case 'boolean': case 'bool': if (!is_bool($value)) { throw new EditorJSException("Option '$key' with value `$value` must be boolean"); } break; default: throw new EditorJSException("Unhandled type `$elementType`"); } } return true; }
php
private function validate($rules, $blockData) { /** * Make sure that every required param exists in data block */ foreach ($rules as $key => $value) { if (($key != BlockHandler::DEFAULT_ARRAY_KEY) && (isset($value['required']) ? $value['required'] : true)) { if (!isset($blockData[$key])) { throw new EditorJSException("Not found required param `$key`"); } } } /** * Check if there is not extra params (not mentioned in configuration rule) */ foreach ($blockData as $key => $value) { if (!is_integer($key) && !isset($rules[$key])) { throw new EditorJSException("Found extra param `$key`"); } } /** * Validate every key in data block */ foreach ($blockData as $key => $value) { /** * PHP Array has integer keys */ if (is_integer($key)) { $key = BlockHandler::DEFAULT_ARRAY_KEY; } $rule = $rules[$key]; $rule = $this->expandToolSettings($rule); $elementType = $rule['type']; /** * Process canBeOnly rule */ if (isset($rule['canBeOnly'])) { if (!in_array($value, $rule['canBeOnly'])) { throw new EditorJSException("Option '$key' with value `$value` has invalid value. Check canBeOnly param."); } // Do not perform additional elements validation in any case continue; } /** * Validate element types */ switch ($elementType) { case 'string': if (!is_string($value)) { throw new EditorJSException("Option '$key' with value `$value` must be string"); } break; case 'integer': case 'int': if (!is_integer($value)) { throw new EditorJSException("Option '$key' with value `$value` must be integer"); } break; case 'array': $this->validate($rule['data'], $value); break; case 'boolean': case 'bool': if (!is_bool($value)) { throw new EditorJSException("Option '$key' with value `$value` must be boolean"); } break; default: throw new EditorJSException("Unhandled type `$elementType`"); } } return true; }
[ "private", "function", "validate", "(", "$", "rules", ",", "$", "blockData", ")", "{", "/**\n * Make sure that every required param exists in data block\n */", "foreach", "(", "$", "rules", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", ...
Apply validation rule to the data block @param array $rules @param array $blockData @throws EditorJSException @return bool
[ "Apply", "validation", "rule", "to", "the", "data", "block" ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/BlockHandler.php#L88-L173
train
editor-js/editorjs-php
EditorJS/BlockHandler.php
BlockHandler.sanitize
private function sanitize($rules, $blockData) { /** * Sanitize every key in data block */ foreach ($blockData as $key => $value) { /** * PHP Array has integer keys */ if (is_integer($key)) { $rule = $rules[BlockHandler::DEFAULT_ARRAY_KEY]; } else { $rule = $rules[$key]; } $rule = $this->expandToolSettings($rule); $elementType = $rule['type']; /** * Sanitize string with Purifier */ if ($elementType == 'string') { $allowedTags = isset($rule['allowedTags']) ? $rule['allowedTags'] : ''; if ($allowedTags !== '*') { $blockData[$key] = $this->getPurifier($allowedTags)->purify($value); } } /** * Sanitize nested elements */ if ($elementType == 'array') { $blockData[$key] = $this->sanitize($rule['data'], $value); } } return $blockData; }
php
private function sanitize($rules, $blockData) { /** * Sanitize every key in data block */ foreach ($blockData as $key => $value) { /** * PHP Array has integer keys */ if (is_integer($key)) { $rule = $rules[BlockHandler::DEFAULT_ARRAY_KEY]; } else { $rule = $rules[$key]; } $rule = $this->expandToolSettings($rule); $elementType = $rule['type']; /** * Sanitize string with Purifier */ if ($elementType == 'string') { $allowedTags = isset($rule['allowedTags']) ? $rule['allowedTags'] : ''; if ($allowedTags !== '*') { $blockData[$key] = $this->getPurifier($allowedTags)->purify($value); } } /** * Sanitize nested elements */ if ($elementType == 'array') { $blockData[$key] = $this->sanitize($rule['data'], $value); } } return $blockData; }
[ "private", "function", "sanitize", "(", "$", "rules", ",", "$", "blockData", ")", "{", "/**\n * Sanitize every key in data block\n */", "foreach", "(", "$", "blockData", "as", "$", "key", "=>", "$", "value", ")", "{", "/**\n * PHP Array has...
Sanitize strings in the data block @param array $rules @param array $blockData @throws EditorJSException @return array
[ "Sanitize", "strings", "in", "the", "data", "block" ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/BlockHandler.php#L185-L222
train
editor-js/editorjs-php
EditorJS/BlockHandler.php
BlockHandler.getPurifier
private function getPurifier($allowedTags) { $sanitizer = $this->getDefaultPurifier(); $sanitizer->set('HTML.Allowed', $allowedTags); /** * Define custom HTML Definition for mark tool */ if ($def = $sanitizer->maybeGetRawHTMLDefinition()) { $def->addElement('mark', 'Inline', 'Inline', 'Common'); } $purifier = new \HTMLPurifier($sanitizer); return $purifier; }
php
private function getPurifier($allowedTags) { $sanitizer = $this->getDefaultPurifier(); $sanitizer->set('HTML.Allowed', $allowedTags); /** * Define custom HTML Definition for mark tool */ if ($def = $sanitizer->maybeGetRawHTMLDefinition()) { $def->addElement('mark', 'Inline', 'Inline', 'Common'); } $purifier = new \HTMLPurifier($sanitizer); return $purifier; }
[ "private", "function", "getPurifier", "(", "$", "allowedTags", ")", "{", "$", "sanitizer", "=", "$", "this", "->", "getDefaultPurifier", "(", ")", ";", "$", "sanitizer", "->", "set", "(", "'HTML.Allowed'", ",", "$", "allowedTags", ")", ";", "/**\n * ...
Create and return new default purifier @param $allowedTags @return \HTMLPurifier
[ "Create", "and", "return", "new", "default", "purifier" ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/BlockHandler.php#L231-L247
train
editor-js/editorjs-php
EditorJS/BlockHandler.php
BlockHandler.getDefaultPurifier
private function getDefaultPurifier() { $sanitizer = \HTMLPurifier_Config::createDefault(); $sanitizer->set('HTML.TargetBlank', true); $sanitizer->set('URI.AllowedSchemes', ['http' => true, 'https' => true]); $sanitizer->set('AutoFormat.RemoveEmpty', true); $sanitizer->set('HTML.DefinitionID', 'html5-definitions'); if (!is_dir('/tmp/purifier')) { mkdir('/tmp/purifier', 0777, true); } $sanitizer->set('Cache.SerializerPath', '/tmp/purifier'); return $sanitizer; }
php
private function getDefaultPurifier() { $sanitizer = \HTMLPurifier_Config::createDefault(); $sanitizer->set('HTML.TargetBlank', true); $sanitizer->set('URI.AllowedSchemes', ['http' => true, 'https' => true]); $sanitizer->set('AutoFormat.RemoveEmpty', true); $sanitizer->set('HTML.DefinitionID', 'html5-definitions'); if (!is_dir('/tmp/purifier')) { mkdir('/tmp/purifier', 0777, true); } $sanitizer->set('Cache.SerializerPath', '/tmp/purifier'); return $sanitizer; }
[ "private", "function", "getDefaultPurifier", "(", ")", "{", "$", "sanitizer", "=", "\\", "HTMLPurifier_Config", "::", "createDefault", "(", ")", ";", "$", "sanitizer", "->", "set", "(", "'HTML.TargetBlank'", ",", "true", ")", ";", "$", "sanitizer", "->", "se...
Initialize HTML Purifier with default settings
[ "Initialize", "HTML", "Purifier", "with", "default", "settings" ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/BlockHandler.php#L252-L268
train
editor-js/editorjs-php
EditorJS/BlockHandler.php
BlockHandler.expandToolSettings
private function expandToolSettings($rule) { if (is_string($rule)) { // 'blockName': 'string' – tool with string type and default settings $expandedRule = ["type" => $rule]; } elseif (is_array($rule)) { if ($this->isAssoc($rule)) { $expandedRule = $rule; } else { // 'blockName': [] – tool with canBeOnly and default settings $expandedRule = ["type" => "string", "canBeOnly" => $rule]; } } else { throw new EditorJSException("Cannot determine element type of the rule `$rule`."); } return $expandedRule; }
php
private function expandToolSettings($rule) { if (is_string($rule)) { // 'blockName': 'string' – tool with string type and default settings $expandedRule = ["type" => $rule]; } elseif (is_array($rule)) { if ($this->isAssoc($rule)) { $expandedRule = $rule; } else { // 'blockName': [] – tool with canBeOnly and default settings $expandedRule = ["type" => "string", "canBeOnly" => $rule]; } } else { throw new EditorJSException("Cannot determine element type of the rule `$rule`."); } return $expandedRule; }
[ "private", "function", "expandToolSettings", "(", "$", "rule", ")", "{", "if", "(", "is_string", "(", "$", "rule", ")", ")", "{", "// 'blockName': 'string' – tool with string type and default settings", "$", "expandedRule", "=", "[", "\"type\"", "=>", "$", "rule", ...
Expand shortified tool settings @param $rule – tool settings @throws EditorJSException @return array – expanded tool settings
[ "Expand", "shortified", "tool", "settings" ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/BlockHandler.php#L295-L312
train
editor-js/editorjs-php
EditorJS/ConfigLoader.php
ConfigLoader.loadTools
private function loadTools($config) { if (!isset($config['tools'])) { throw new EditorJSException('Tools not found in configuration'); } foreach ($config['tools'] as $toolName => $toolData) { if (isset($this->tools[$toolName])) { throw new EditorJSException("Duplicate tool $toolName in configuration"); } $this->tools[$toolName] = $this->loadTool($toolData); } }
php
private function loadTools($config) { if (!isset($config['tools'])) { throw new EditorJSException('Tools not found in configuration'); } foreach ($config['tools'] as $toolName => $toolData) { if (isset($this->tools[$toolName])) { throw new EditorJSException("Duplicate tool $toolName in configuration"); } $this->tools[$toolName] = $this->loadTool($toolData); } }
[ "private", "function", "loadTools", "(", "$", "config", ")", "{", "if", "(", "!", "isset", "(", "$", "config", "[", "'tools'", "]", ")", ")", "{", "throw", "new", "EditorJSException", "(", "'Tools not found in configuration'", ")", ";", "}", "foreach", "("...
Load settings for tools from configuration @param array $config @throws EditorJSException
[ "Load", "settings", "for", "tools", "from", "configuration" ]
36de3db0a2b9733ac62de0f71832a16fcb71e7f3
https://github.com/editor-js/editorjs-php/blob/36de3db0a2b9733ac62de0f71832a16fcb71e7f3/EditorJS/ConfigLoader.php#L38-L51
train
imanghafoori1/laravel-heyman
src/Core/ChainCollection.php
ChainCollection.init
public function init($manager, array $values, string $param = 'default') { $chain = resolve('heyman.chain'); $chain->set('manager', $manager); $chain->set('watchedEntities', $values); $chain->set('event', $param); }
php
public function init($manager, array $values, string $param = 'default') { $chain = resolve('heyman.chain'); $chain->set('manager', $manager); $chain->set('watchedEntities', $values); $chain->set('event', $param); }
[ "public", "function", "init", "(", "$", "manager", ",", "array", "$", "values", ",", "string", "$", "param", "=", "'default'", ")", "{", "$", "chain", "=", "resolve", "(", "'heyman.chain'", ")", ";", "$", "chain", "->", "set", "(", "'manager'", ",", ...
initialize the chain. @param $manager @param array $values @param string $param
[ "initialize", "the", "chain", "." ]
1f0fcd63e7c71fe621d3b26d4f1d960b71ed0218
https://github.com/imanghafoori1/laravel-heyman/blob/1f0fcd63e7c71fe621d3b26d4f1d960b71ed0218/src/Core/ChainCollection.php#L48-L54
train
spatie/regex
src/MatchResult.php
MatchResult.group
public function group($group): string { if (! isset($this->matches[$group])) { throw RegexFailed::groupDoesntExist($this->pattern, $this->subject, $group); } return $this->matches[$group]; }
php
public function group($group): string { if (! isset($this->matches[$group])) { throw RegexFailed::groupDoesntExist($this->pattern, $this->subject, $group); } return $this->matches[$group]; }
[ "public", "function", "group", "(", "$", "group", ")", ":", "string", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "matches", "[", "$", "group", "]", ")", ")", "{", "throw", "RegexFailed", "::", "groupDoesntExist", "(", "$", "this", "->", ...
Match group by index or name. @param int|string $group @return string @throws RegexFailed
[ "Match", "group", "by", "index", "or", "name", "." ]
eca5dab5cfcc313def6e674cf9a4f3f0c81a7c11
https://github.com/spatie/regex/blob/eca5dab5cfcc313def6e674cf9a4f3f0c81a7c11/src/MatchResult.php#L86-L93
train
spiritix/lada-cache
src/Spiritix/LadaCache/Invalidator.php
Invalidator.invalidate
public function invalidate(array $tags) { $hashes = $this->getHashes($tags); // Prefix tags in order to delete them foreach ($tags as $key => $tag) { $tags[$key] = $this->redis->prefix($tag); } $this->deleteItems($hashes); $this->deleteItems($tags); return $hashes; }
php
public function invalidate(array $tags) { $hashes = $this->getHashes($tags); // Prefix tags in order to delete them foreach ($tags as $key => $tag) { $tags[$key] = $this->redis->prefix($tag); } $this->deleteItems($hashes); $this->deleteItems($tags); return $hashes; }
[ "public", "function", "invalidate", "(", "array", "$", "tags", ")", "{", "$", "hashes", "=", "$", "this", "->", "getHashes", "(", "$", "tags", ")", ";", "// Prefix tags in order to delete them", "foreach", "(", "$", "tags", "as", "$", "key", "=>", "$", "...
Invalidates all items in the cache having at least one of the given tags. Requests the affected items (hashes) from the storage for all tags provided. Afterwards simply deletes all items and all tag sets. @param array $tags @return array The hashes that were invalidated
[ "Invalidates", "all", "items", "in", "the", "cache", "having", "at", "least", "one", "of", "the", "given", "tags", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Invalidator.php#L49-L62
train
spiritix/lada-cache
src/Spiritix/LadaCache/Invalidator.php
Invalidator.getHashes
private function getHashes(array $tags) { $hashes = []; foreach ($tags as $tag) { $tag = $this->redis->prefix($tag); if (!$this->redis->exists($tag)) { continue; } $hashes = array_merge($hashes, $this->redis->smembers($tag)); } return array_unique($hashes); }
php
private function getHashes(array $tags) { $hashes = []; foreach ($tags as $tag) { $tag = $this->redis->prefix($tag); if (!$this->redis->exists($tag)) { continue; } $hashes = array_merge($hashes, $this->redis->smembers($tag)); } return array_unique($hashes); }
[ "private", "function", "getHashes", "(", "array", "$", "tags", ")", "{", "$", "hashes", "=", "[", "]", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "$", "tag", "=", "$", "this", "->", "redis", "->", "prefix", "(", "$", "tag", "...
Returns a list of all affected hashes for a given set of tags. @param array $tags @return array
[ "Returns", "a", "list", "of", "all", "affected", "hashes", "for", "a", "given", "set", "of", "tags", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Invalidator.php#L71-L86
train
spiritix/lada-cache
src/Spiritix/LadaCache/Tagger.php
Tagger.getTags
public function getTags() { // Get affected database and tables, add prefixes $database = $this->prefix($this->reflector->getDatabase(), self::PREFIX_DATABASE); // Get affected tables, don't add prefixes yet $tables = $this->reflector->getTables(); // If rows should not be considered, we don't have to differ between specific and unspecific queries // We can simply prefix all tables with the database and return them if ($this->considerRows === false) { return $this->prefix($tables, $database); } // Get affected rows as multidimensional array per table $rows = $this->reflector->getRows(); // Create the table tags with corresponding prefix // Depending on whether the queries are specific or not $tags = $this->getTableTags($tables, $rows); // Then we loop trough all these tags and add a tag for each row // Consisting of the prefixed table and the row with prefix foreach ($tables as $table) { if (!isset($rows[$table])) { continue; } $tablePrefix = $this->prefix($table, self::PREFIX_TABLE_SPECIFIC); $rowPrefix = $this->prefix(self::PREFIX_ROW, $tablePrefix); $tags = array_merge($tags, $this->prefix($rows[$table], $rowPrefix)); } return $this->prefix($tags, $database); }
php
public function getTags() { // Get affected database and tables, add prefixes $database = $this->prefix($this->reflector->getDatabase(), self::PREFIX_DATABASE); // Get affected tables, don't add prefixes yet $tables = $this->reflector->getTables(); // If rows should not be considered, we don't have to differ between specific and unspecific queries // We can simply prefix all tables with the database and return them if ($this->considerRows === false) { return $this->prefix($tables, $database); } // Get affected rows as multidimensional array per table $rows = $this->reflector->getRows(); // Create the table tags with corresponding prefix // Depending on whether the queries are specific or not $tags = $this->getTableTags($tables, $rows); // Then we loop trough all these tags and add a tag for each row // Consisting of the prefixed table and the row with prefix foreach ($tables as $table) { if (!isset($rows[$table])) { continue; } $tablePrefix = $this->prefix($table, self::PREFIX_TABLE_SPECIFIC); $rowPrefix = $this->prefix(self::PREFIX_ROW, $tablePrefix); $tags = array_merge($tags, $this->prefix($rows[$table], $rowPrefix)); } return $this->prefix($tags, $database); }
[ "public", "function", "getTags", "(", ")", "{", "// Get affected database and tables, add prefixes", "$", "database", "=", "$", "this", "->", "prefix", "(", "$", "this", "->", "reflector", "->", "getDatabase", "(", ")", ",", "self", "::", "PREFIX_DATABASE", ")",...
Compiles and returns the tags. @return array
[ "Compiles", "and", "returns", "the", "tags", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Tagger.php#L72-L108
train
spiritix/lada-cache
src/Spiritix/LadaCache/Tagger.php
Tagger.getTableTags
private function getTableTags($tables, $rows) { $tags = []; $type = $this->reflector->getType(); foreach ($tables as $table) { $isSpecific = (isset($rows[$table]) && !empty($rows[$table])); // These types of queries require a specific tag if (($type === Reflector::QUERY_TYPE_SELECT && $isSpecific) || ($type === Reflector::QUERY_TYPE_UPDATE && !$isSpecific) || ($type === Reflector::QUERY_TYPE_DELETE && !$isSpecific) || ($type === Reflector::QUERY_TYPE_TRUNCATE)) { $tags[] = $this->prefix($table, self::PREFIX_TABLE_SPECIFIC); } // While these ones require an unspecific one if (($type === Reflector::QUERY_TYPE_SELECT && !$isSpecific) || ($type === Reflector::QUERY_TYPE_UPDATE) || ($type === Reflector::QUERY_TYPE_DELETE) || ($type === Reflector::QUERY_TYPE_INSERT)) { $tags[] = $this->prefix($table, self::PREFIX_TABLE_UNSPECIFIC); } } return $tags; }
php
private function getTableTags($tables, $rows) { $tags = []; $type = $this->reflector->getType(); foreach ($tables as $table) { $isSpecific = (isset($rows[$table]) && !empty($rows[$table])); // These types of queries require a specific tag if (($type === Reflector::QUERY_TYPE_SELECT && $isSpecific) || ($type === Reflector::QUERY_TYPE_UPDATE && !$isSpecific) || ($type === Reflector::QUERY_TYPE_DELETE && !$isSpecific) || ($type === Reflector::QUERY_TYPE_TRUNCATE)) { $tags[] = $this->prefix($table, self::PREFIX_TABLE_SPECIFIC); } // While these ones require an unspecific one if (($type === Reflector::QUERY_TYPE_SELECT && !$isSpecific) || ($type === Reflector::QUERY_TYPE_UPDATE) || ($type === Reflector::QUERY_TYPE_DELETE) || ($type === Reflector::QUERY_TYPE_INSERT)) { $tags[] = $this->prefix($table, self::PREFIX_TABLE_UNSPECIFIC); } } return $tags; }
[ "private", "function", "getTableTags", "(", "$", "tables", ",", "$", "rows", ")", "{", "$", "tags", "=", "[", "]", ";", "$", "type", "=", "$", "this", "->", "reflector", "->", "getType", "(", ")", ";", "foreach", "(", "$", "tables", "as", "$", "t...
Returns the prefixed table tags for a set of tables and rows. @param array $tables The tables to be tagged @param array $rows A multidimensional array containing the rows per table @return array
[ "Returns", "the", "prefixed", "table", "tags", "for", "a", "set", "of", "tables", "and", "rows", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Tagger.php#L118-L146
train
spiritix/lada-cache
src/Spiritix/LadaCache/Tagger.php
Tagger.prefix
protected function prefix($value, $prefix) { if (is_array($value)) { return array_map(function ($item) use ($prefix) { return $this->prefix($item, $prefix); }, $value); } return $prefix . $value; }
php
protected function prefix($value, $prefix) { if (is_array($value)) { return array_map(function ($item) use ($prefix) { return $this->prefix($item, $prefix); }, $value); } return $prefix . $value; }
[ "protected", "function", "prefix", "(", "$", "value", ",", "$", "prefix", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "return", "array_map", "(", "function", "(", "$", "item", ")", "use", "(", "$", "prefix", ")", "{", "return...
Prepends a prefix to one or multiple values. @param string|array $value Either a string or an array of strings. @param string $prefix The prefix to be prepended. @return string|array
[ "Prepends", "a", "prefix", "to", "one", "or", "multiple", "values", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Tagger.php#L156-L165
train
spiritix/lada-cache
src/Spiritix/LadaCache/Cache.php
Cache.has
public function has($key) { return (bool) $this->redis->exists($this->redis->prefix($key)); }
php
public function has($key) { return (bool) $this->redis->exists($this->redis->prefix($key)); }
[ "public", "function", "has", "(", "$", "key", ")", "{", "return", "(", "bool", ")", "$", "this", "->", "redis", "->", "exists", "(", "$", "this", "->", "redis", "->", "prefix", "(", "$", "key", ")", ")", ";", "}" ]
Check if a key exists in the cache. @param string $key @return bool
[ "Check", "if", "a", "key", "exists", "in", "the", "cache", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Cache.php#L65-L68
train
spiritix/lada-cache
src/Spiritix/LadaCache/Cache.php
Cache.set
public function set($key, array $tags, $data) { $key = $this->redis->prefix($key); $this->redis->set($key, $this->encoder->encode($data)); if (is_int($this->expirationTime) && $this->expirationTime > 0) { $this->redis->expire($key, $this->expirationTime); } foreach ($tags as $tag) { $this->redis->sadd($this->redis->prefix($tag), $key); } }
php
public function set($key, array $tags, $data) { $key = $this->redis->prefix($key); $this->redis->set($key, $this->encoder->encode($data)); if (is_int($this->expirationTime) && $this->expirationTime > 0) { $this->redis->expire($key, $this->expirationTime); } foreach ($tags as $tag) { $this->redis->sadd($this->redis->prefix($tag), $key); } }
[ "public", "function", "set", "(", "$", "key", ",", "array", "$", "tags", ",", "$", "data", ")", "{", "$", "key", "=", "$", "this", "->", "redis", "->", "prefix", "(", "$", "key", ")", ";", "$", "this", "->", "redis", "->", "set", "(", "$", "k...
Store a value for a given key in the cache. This method does not check if there is a value available for the given key, may cause unexpected behavior if not. Use has() to prevent this issue. @param string $key @param array $tags @param mixed $data
[ "Store", "a", "value", "for", "a", "given", "key", "in", "the", "cache", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Cache.php#L80-L92
train
spiritix/lada-cache
src/Spiritix/LadaCache/Cache.php
Cache.get
public function get($key) { $encoded = $this->redis->get($this->redis->prefix($key)); // Prevent decoding if redis returns null (key does not exist). if ($encoded === null) { return null; } return $this->encoder->decode($encoded); }
php
public function get($key) { $encoded = $this->redis->get($this->redis->prefix($key)); // Prevent decoding if redis returns null (key does not exist). if ($encoded === null) { return null; } return $this->encoder->decode($encoded); }
[ "public", "function", "get", "(", "$", "key", ")", "{", "$", "encoded", "=", "$", "this", "->", "redis", "->", "get", "(", "$", "this", "->", "redis", "->", "prefix", "(", "$", "key", ")", ")", ";", "// Prevent decoding if redis returns null (key does not ...
Returns value of a cached key. This method does not check if there is a value available for the given key, may return unexpected values if not. Use has() to prevent this issue. @param string $key @return mixed
[ "Returns", "value", "of", "a", "cached", "key", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Cache.php#L104-L114
train
spiritix/lada-cache
src/Spiritix/LadaCache/Cache.php
Cache.flush
public function flush() { $keys = $this->redis->keys($this->redis->prefix('*')); foreach ($keys as $key) { $this->redis->del($key); } }
php
public function flush() { $keys = $this->redis->keys($this->redis->prefix('*')); foreach ($keys as $key) { $this->redis->del($key); } }
[ "public", "function", "flush", "(", ")", "{", "$", "keys", "=", "$", "this", "->", "redis", "->", "keys", "(", "$", "this", "->", "redis", "->", "prefix", "(", "'*'", ")", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", ...
Deletes all items from cache. This should only be used for maintenance purposes (slow performance).
[ "Deletes", "all", "items", "from", "cache", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Cache.php#L121-L128
train
spiritix/lada-cache
src/Spiritix/LadaCache/Hasher.php
Hasher.getHash
public function getHash() { // Never remove the database from the identifier // Most SQL queries do not include the target database $identifier = $this->reflector->getDatabase() . $this->reflector->getSql() . serialize($this->reflector->getParameters()); return md5($identifier); }
php
public function getHash() { // Never remove the database from the identifier // Most SQL queries do not include the target database $identifier = $this->reflector->getDatabase() . $this->reflector->getSql() . serialize($this->reflector->getParameters()); return md5($identifier); }
[ "public", "function", "getHash", "(", ")", "{", "// Never remove the database from the identifier", "// Most SQL queries do not include the target database", "$", "identifier", "=", "$", "this", "->", "reflector", "->", "getDatabase", "(", ")", ".", "$", "this", "->", "...
Returns the hash. @return string
[ "Returns", "the", "hash", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Hasher.php#L44-L53
train
spiritix/lada-cache
src/Spiritix/LadaCache/Console/Command.php
Command.writeConfig
protected function writeConfig($key, $value) { $file = config_path(LadaCacheServiceProvider::CONFIG_FILE); if (!File::exists($file)) { $this->call('vendor:publish'); } try { $contents = File::get($file); $contents = preg_replace( "/'" . $key . "'(.*?),\s?\n/s", "'" . $key . "' => " . $value . ",\n\n", $contents ); File::put($file, $contents); } catch (Exception $e) { $this->error('Could not write config file'); return false; } $this->call('config:clear'); return true; }
php
protected function writeConfig($key, $value) { $file = config_path(LadaCacheServiceProvider::CONFIG_FILE); if (!File::exists($file)) { $this->call('vendor:publish'); } try { $contents = File::get($file); $contents = preg_replace( "/'" . $key . "'(.*?),\s?\n/s", "'" . $key . "' => " . $value . ",\n\n", $contents ); File::put($file, $contents); } catch (Exception $e) { $this->error('Could not write config file'); return false; } $this->call('config:clear'); return true; }
[ "protected", "function", "writeConfig", "(", "$", "key", ",", "$", "value", ")", "{", "$", "file", "=", "config_path", "(", "LadaCacheServiceProvider", "::", "CONFIG_FILE", ")", ";", "if", "(", "!", "File", "::", "exists", "(", "$", "file", ")", ")", "...
Writes a value to package configuration file.
[ "Writes", "a", "value", "to", "package", "configuration", "file", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Console/Command.php#L30-L58
train
spiritix/lada-cache
src/Spiritix/LadaCache/LadaCacheServiceProvider.php
LadaCacheServiceProvider.registerSingletons
private function registerSingletons() { $this->app->singleton('lada.redis', function($app) { return new Redis(); }); $this->app->singleton('lada.cache', function($app) { return new Cache($app->make('lada.redis'), new Encoder()); }); $this->app->singleton('lada.invalidator', function($app) { return new Invalidator($app->make('lada.redis')); }); $this->app->singleton('lada.handler', function($app) { return new QueryHandler($app->make('lada.cache'), $app->make('lada.invalidator')); }); }
php
private function registerSingletons() { $this->app->singleton('lada.redis', function($app) { return new Redis(); }); $this->app->singleton('lada.cache', function($app) { return new Cache($app->make('lada.redis'), new Encoder()); }); $this->app->singleton('lada.invalidator', function($app) { return new Invalidator($app->make('lada.redis')); }); $this->app->singleton('lada.handler', function($app) { return new QueryHandler($app->make('lada.cache'), $app->make('lada.invalidator')); }); }
[ "private", "function", "registerSingletons", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'lada.redis'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "Redis", "(", ")", ";", "}", ")", ";", "$", "this", "->", "app"...
Registers the cache services in the IoC container.
[ "Registers", "the", "cache", "services", "in", "the", "IoC", "container", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/LadaCacheServiceProvider.php#L85-L102
train
spiritix/lada-cache
src/Spiritix/LadaCache/LadaCacheServiceProvider.php
LadaCacheServiceProvider.registerConnections
private function registerConnections() { $this->app->bind('db.connection.mysql', function ($app, $parameters) { list($connection, $database, $prefix, $config) = $parameters; return new MysqlConnection($connection, $database, $prefix, $config); }); $this->app->bind('db.connection.postgres', function ($app, $parameters) { list($connection, $database, $prefix, $config) = $parameters; return new PostgresConnection($connection, $database, $prefix, $config); }); $this->app->bind('db.connection.sqllite', function ($app, $parameters) { list($connection, $database, $prefix, $config) = $parameters; return new SqlLiteConnection($connection, $database, $prefix, $config); }); $this->app->bind('db.connection.sqlserver', function ($app, $parameters) { list($connection, $database, $prefix, $config) = $parameters; return new SqlServerConnection($connection, $database, $prefix, $config); }); }
php
private function registerConnections() { $this->app->bind('db.connection.mysql', function ($app, $parameters) { list($connection, $database, $prefix, $config) = $parameters; return new MysqlConnection($connection, $database, $prefix, $config); }); $this->app->bind('db.connection.postgres', function ($app, $parameters) { list($connection, $database, $prefix, $config) = $parameters; return new PostgresConnection($connection, $database, $prefix, $config); }); $this->app->bind('db.connection.sqllite', function ($app, $parameters) { list($connection, $database, $prefix, $config) = $parameters; return new SqlLiteConnection($connection, $database, $prefix, $config); }); $this->app->bind('db.connection.sqlserver', function ($app, $parameters) { list($connection, $database, $prefix, $config) = $parameters; return new SqlServerConnection($connection, $database, $prefix, $config); }); }
[ "private", "function", "registerConnections", "(", ")", "{", "$", "this", "->", "app", "->", "bind", "(", "'db.connection.mysql'", ",", "function", "(", "$", "app", ",", "$", "parameters", ")", "{", "list", "(", "$", "connection", ",", "$", "database", "...
Register connections. Here we are overriding all connection singleton's from Laravel. This is the only way to make them use our custom query builder which then uses our cache.
[ "Register", "connections", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/LadaCacheServiceProvider.php#L110-L131
train
spiritix/lada-cache
src/Spiritix/LadaCache/LadaCacheServiceProvider.php
LadaCacheServiceProvider.registerCommand
private function registerCommand() { $this->app->singleton('command.lada-cache.flush', function() { return new FlushCommand(); }); $this->app->singleton('command.lada-cache.enable', function() { return new EnableCommand(); }); $this->app->singleton('command.lada-cache.disable', function() { return new DisableCommand(); }); $this->commands([ 'command.lada-cache.flush', 'command.lada-cache.enable', 'command.lada-cache.disable', ]); }
php
private function registerCommand() { $this->app->singleton('command.lada-cache.flush', function() { return new FlushCommand(); }); $this->app->singleton('command.lada-cache.enable', function() { return new EnableCommand(); }); $this->app->singleton('command.lada-cache.disable', function() { return new DisableCommand(); }); $this->commands([ 'command.lada-cache.flush', 'command.lada-cache.enable', 'command.lada-cache.disable', ]); }
[ "private", "function", "registerCommand", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'command.lada-cache.flush'", ",", "function", "(", ")", "{", "return", "new", "FlushCommand", "(", ")", ";", "}", ")", ";", "$", "this", "->", "ap...
Register custom commands.
[ "Register", "custom", "commands", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/LadaCacheServiceProvider.php#L136-L155
train
spiritix/lada-cache
src/Spiritix/LadaCache/LadaCacheServiceProvider.php
LadaCacheServiceProvider.registerDebugbarCollector
private function registerDebugbarCollector() { $this->app->singleton('lada.collector', function() { return new CacheCollector(); }); $debugBar = $this->app->make('debugbar'); $debugBar->addCollector($this->app->make('lada.collector')); }
php
private function registerDebugbarCollector() { $this->app->singleton('lada.collector', function() { return new CacheCollector(); }); $debugBar = $this->app->make('debugbar'); $debugBar->addCollector($this->app->make('lada.collector')); }
[ "private", "function", "registerDebugbarCollector", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'lada.collector'", ",", "function", "(", ")", "{", "return", "new", "CacheCollector", "(", ")", ";", "}", ")", ";", "$", "debugBar", "=", ...
Register our custom debugbar collector.
[ "Register", "our", "custom", "debugbar", "collector", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/LadaCacheServiceProvider.php#L160-L168
train
spiritix/lada-cache
src/Spiritix/LadaCache/Debug/CacheCollector.php
CacheCollector.endMeasuring
public function endMeasuring($type, $hash, $tags, $sql, $parameters) { $name = '[' . ucfirst($type) . '] ' . $sql; $endTime = microtime(true); $params = [ 'hash' => $hash, 'tags' => $tags, 'parameters' => $parameters, ]; $this->addMeasure($name, $this->startTime, $endTime, $params); }
php
public function endMeasuring($type, $hash, $tags, $sql, $parameters) { $name = '[' . ucfirst($type) . '] ' . $sql; $endTime = microtime(true); $params = [ 'hash' => $hash, 'tags' => $tags, 'parameters' => $parameters, ]; $this->addMeasure($name, $this->startTime, $endTime, $params); }
[ "public", "function", "endMeasuring", "(", "$", "type", ",", "$", "hash", ",", "$", "tags", ",", "$", "sql", ",", "$", "parameters", ")", "{", "$", "name", "=", "'['", ".", "ucfirst", "(", "$", "type", ")", ".", "'] '", ".", "$", "sql", ";", "$...
Ends measuring a cache request. @param string $type Request type, either a miss or a hit @param string $hash The hash of the cache request @param array $tags The cache request tags @param string $sql The underlying SQL query string @param array $parameters The SQL query parameters
[ "Ends", "measuring", "a", "cache", "request", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Debug/CacheCollector.php#L53-L65
train
spiritix/lada-cache
src/Spiritix/LadaCache/Reflector.php
Reflector.getTables
public function getTables() { // Get main table $tables = [$this->queryBuilder->from]; // Add possible join tables $joins = $this->queryBuilder->joins ? : []; foreach ($joins as $join) { if (!in_array($join->table, $tables) && is_string($join->table)) { $tables[] = $join->table; } } return $tables; }
php
public function getTables() { // Get main table $tables = [$this->queryBuilder->from]; // Add possible join tables $joins = $this->queryBuilder->joins ? : []; foreach ($joins as $join) { if (!in_array($join->table, $tables) && is_string($join->table)) { $tables[] = $join->table; } } return $tables; }
[ "public", "function", "getTables", "(", ")", "{", "// Get main table", "$", "tables", "=", "[", "$", "this", "->", "queryBuilder", "->", "from", "]", ";", "// Add possible join tables", "$", "joins", "=", "$", "this", "->", "queryBuilder", "->", "joins", "?"...
Returns all affected tables, including joined ones. @return array
[ "Returns", "all", "affected", "tables", "including", "joined", "ones", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Reflector.php#L111-L126
train
spiritix/lada-cache
src/Spiritix/LadaCache/Reflector.php
Reflector.getRows
public function getRows() { $rows = []; $wheres = $this->queryBuilder->wheres ?: []; foreach ($wheres as $where) { // Skip unsupported clauses if (!isset($where['column'])) { continue; } // If it doesn't contain the table name assume it's the "FROM" table if (strpos($where['column'], '.') === false) { $where['column'] = implode('.', [$this->queryBuilder->from, $where['column']]); } list($table, $column) = $this->splitTableAndColumn($where['column']); // Make sure that the where clause applies for the primary key column if ($column !== self::PRIMARY_KEY_COLUMN) { continue; } // Initialize a set for the current table if (!isset($rows[$table])) { $rows[$table] = []; } // Add the rows to the current table set if ($where['type'] === 'Basic') { if ($where['operator'] === '=' && is_numeric($where['value'])) { $rows[$table][] = $where['value']; } } else if ($where['type'] === 'In') { $rows[$table] += $where['values']; } } return $rows; }
php
public function getRows() { $rows = []; $wheres = $this->queryBuilder->wheres ?: []; foreach ($wheres as $where) { // Skip unsupported clauses if (!isset($where['column'])) { continue; } // If it doesn't contain the table name assume it's the "FROM" table if (strpos($where['column'], '.') === false) { $where['column'] = implode('.', [$this->queryBuilder->from, $where['column']]); } list($table, $column) = $this->splitTableAndColumn($where['column']); // Make sure that the where clause applies for the primary key column if ($column !== self::PRIMARY_KEY_COLUMN) { continue; } // Initialize a set for the current table if (!isset($rows[$table])) { $rows[$table] = []; } // Add the rows to the current table set if ($where['type'] === 'Basic') { if ($where['operator'] === '=' && is_numeric($where['value'])) { $rows[$table][] = $where['value']; } } else if ($where['type'] === 'In') { $rows[$table] += $where['values']; } } return $rows; }
[ "public", "function", "getRows", "(", ")", "{", "$", "rows", "=", "[", "]", ";", "$", "wheres", "=", "$", "this", "->", "queryBuilder", "->", "wheres", "?", ":", "[", "]", ";", "foreach", "(", "$", "wheres", "as", "$", "where", ")", "{", "// Skip...
Returns all affected rows as a multidimensional array, split up by table. @return array
[ "Returns", "all", "affected", "rows", "as", "a", "multidimensional", "array", "split", "up", "by", "table", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Reflector.php#L133-L174
train
spiritix/lada-cache
src/Spiritix/LadaCache/Reflector.php
Reflector.getType
public function getType() { $sql = $this->getSql(); $type = strtok(strtolower(trim($sql)), ' '); $type = preg_replace ('/[^a-z]/i', '', $type); $allowedTypes = [ self::QUERY_TYPE_SELECT, self::QUERY_TYPE_INSERT, self::QUERY_TYPE_UPDATE, self::QUERY_TYPE_DELETE, self::QUERY_TYPE_TRUNCATE, ]; if (!in_array($type, $allowedTypes)) { throw new RuntimeException('Invalid query type'); } return $type; }
php
public function getType() { $sql = $this->getSql(); $type = strtok(strtolower(trim($sql)), ' '); $type = preg_replace ('/[^a-z]/i', '', $type); $allowedTypes = [ self::QUERY_TYPE_SELECT, self::QUERY_TYPE_INSERT, self::QUERY_TYPE_UPDATE, self::QUERY_TYPE_DELETE, self::QUERY_TYPE_TRUNCATE, ]; if (!in_array($type, $allowedTypes)) { throw new RuntimeException('Invalid query type'); } return $type; }
[ "public", "function", "getType", "(", ")", "{", "$", "sql", "=", "$", "this", "->", "getSql", "(", ")", ";", "$", "type", "=", "strtok", "(", "strtolower", "(", "trim", "(", "$", "sql", ")", ")", ",", "' '", ")", ";", "$", "type", "=", "preg_re...
Returns the type of the query. @return string
[ "Returns", "the", "type", "of", "the", "query", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Reflector.php#L181-L201
train
spiritix/lada-cache
src/Spiritix/LadaCache/Reflector.php
Reflector.getSql
public function getSql() { $compileFunction = $this->getCompileFunction(); $grammar = $this->queryBuilder->getGrammar(); $sql = call_user_func_array([$grammar, $compileFunction], [ 'builder' => $this->queryBuilder, 'values' => $this->values, 'sequence' => '', ]); // For some DBMS like SQLite Laravel issues two queries as an array instead of one string // This is seriously not ok, but anyway... if (is_array($sql)) { $sql = implode('; ', array_keys($sql)); } return $sql; }
php
public function getSql() { $compileFunction = $this->getCompileFunction(); $grammar = $this->queryBuilder->getGrammar(); $sql = call_user_func_array([$grammar, $compileFunction], [ 'builder' => $this->queryBuilder, 'values' => $this->values, 'sequence' => '', ]); // For some DBMS like SQLite Laravel issues two queries as an array instead of one string // This is seriously not ok, but anyway... if (is_array($sql)) { $sql = implode('; ', array_keys($sql)); } return $sql; }
[ "public", "function", "getSql", "(", ")", "{", "$", "compileFunction", "=", "$", "this", "->", "getCompileFunction", "(", ")", ";", "$", "grammar", "=", "$", "this", "->", "queryBuilder", "->", "getGrammar", "(", ")", ";", "$", "sql", "=", "call_user_fun...
Returns the compiled SQL string. @return string
[ "Returns", "the", "compiled", "SQL", "string", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Reflector.php#L208-L226
train
spiritix/lada-cache
src/Spiritix/LadaCache/Reflector.php
Reflector.splitTableAndColumn
private function splitTableAndColumn($sqlString) { // Most column identifiers don't contain a database or table name // In this case just return what we've got if (strpos($sqlString, '.') === false) { return [null, $sqlString]; } $parts = explode('.', $sqlString); // If we have three parts, the identifier also contains the database name if (count($parts) === 3) { $table = $parts[1]; } // Otherwise it contains table and column else { $table = $parts[0]; } // Column is always the last part $column = end($parts); return [$table, $column]; }
php
private function splitTableAndColumn($sqlString) { // Most column identifiers don't contain a database or table name // In this case just return what we've got if (strpos($sqlString, '.') === false) { return [null, $sqlString]; } $parts = explode('.', $sqlString); // If we have three parts, the identifier also contains the database name if (count($parts) === 3) { $table = $parts[1]; } // Otherwise it contains table and column else { $table = $parts[0]; } // Column is always the last part $column = end($parts); return [$table, $column]; }
[ "private", "function", "splitTableAndColumn", "(", "$", "sqlString", ")", "{", "// Most column identifiers don't contain a database or table name", "// In this case just return what we've got", "if", "(", "strpos", "(", "$", "sqlString", ",", "'.'", ")", "===", "false", ")"...
Splits an SQL column identifier into table and column. @param string $sqlString SQL column identifier @return array [table|null, column]
[ "Splits", "an", "SQL", "column", "identifier", "into", "table", "and", "column", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Reflector.php#L245-L268
train
spiritix/lada-cache
src/Spiritix/LadaCache/Reflector.php
Reflector.getCompileFunction
private function getCompileFunction() { switch (strtolower($this->sqlOperation)) { case self::QUERY_TYPE_INSERT: return 'compileInsert'; break; case 'insertgetid': return 'compileInsertGetId'; break; case self::QUERY_TYPE_UPDATE: return 'compileUpdate'; break; case self::QUERY_TYPE_DELETE: return 'compileDelete'; break; case self::QUERY_TYPE_TRUNCATE: return 'compileTruncate'; break; default: return 'compileSelect'; break; } }
php
private function getCompileFunction() { switch (strtolower($this->sqlOperation)) { case self::QUERY_TYPE_INSERT: return 'compileInsert'; break; case 'insertgetid': return 'compileInsertGetId'; break; case self::QUERY_TYPE_UPDATE: return 'compileUpdate'; break; case self::QUERY_TYPE_DELETE: return 'compileDelete'; break; case self::QUERY_TYPE_TRUNCATE: return 'compileTruncate'; break; default: return 'compileSelect'; break; } }
[ "private", "function", "getCompileFunction", "(", ")", "{", "switch", "(", "strtolower", "(", "$", "this", "->", "sqlOperation", ")", ")", "{", "case", "self", "::", "QUERY_TYPE_INSERT", ":", "return", "'compileInsert'", ";", "break", ";", "case", "'insertgeti...
Get the Eloquent grammar compile function. @return string
[ "Get", "the", "Eloquent", "grammar", "compile", "function", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Reflector.php#L275-L302
train
spiritix/lada-cache
src/Spiritix/LadaCache/Manager.php
Manager.tablesCachable
private function tablesCachable() { $tables = $this->reflector->getTables(); if ($this->isInclusive()) { foreach ($tables as $table) { if (!$this->tableIncluded($table)) { return false; } } return true; } foreach ($tables as $table) { if ($this->tableExcluded($table)) { return false; } } return true; }
php
private function tablesCachable() { $tables = $this->reflector->getTables(); if ($this->isInclusive()) { foreach ($tables as $table) { if (!$this->tableIncluded($table)) { return false; } } return true; } foreach ($tables as $table) { if ($this->tableExcluded($table)) { return false; } } return true; }
[ "private", "function", "tablesCachable", "(", ")", "{", "$", "tables", "=", "$", "this", "->", "reflector", "->", "getTables", "(", ")", ";", "if", "(", "$", "this", "->", "isInclusive", "(", ")", ")", "{", "foreach", "(", "$", "tables", "as", "$", ...
Checks if the tables returned by the reflector are cachable. If "include-tables" are available, it will only return true if ALL affected tables exists in "include-tables". If "exclude-tables" are enabled, it will only return false if ANY affected table exists in "exclude-tables". @return bool
[ "Checks", "if", "the", "tables", "returned", "by", "the", "reflector", "are", "cachable", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/Manager.php#L96-L117
train
spiritix/lada-cache
src/Spiritix/LadaCache/QueryHandler.php
QueryHandler.collectSubQueryTags
public function collectSubQueryTags() { /* @var Reflector $reflector */ $reflector = new Reflector($this->builder); /* @var Manager $manager */ $manager = new Manager($reflector); // Skip if caching is disabled for current query if (!$manager->shouldCache()) { return; } /* @var Tagger $tagger */ $tagger = new Tagger($reflector); // Add tags to collection $this->subQueryTags = array_unique(array_merge( $this->subQueryTags, $tagger->getTags() )); }
php
public function collectSubQueryTags() { /* @var Reflector $reflector */ $reflector = new Reflector($this->builder); /* @var Manager $manager */ $manager = new Manager($reflector); // Skip if caching is disabled for current query if (!$manager->shouldCache()) { return; } /* @var Tagger $tagger */ $tagger = new Tagger($reflector); // Add tags to collection $this->subQueryTags = array_unique(array_merge( $this->subQueryTags, $tagger->getTags() )); }
[ "public", "function", "collectSubQueryTags", "(", ")", "{", "/* @var Reflector $reflector */", "$", "reflector", "=", "new", "Reflector", "(", "$", "this", "->", "builder", ")", ";", "/* @var Manager $manager */", "$", "manager", "=", "new", "Manager", "(", "$", ...
Collects the tags of a subquery for later handling of the main query.
[ "Collects", "the", "tags", "of", "a", "subquery", "for", "later", "handling", "of", "the", "main", "query", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/QueryHandler.php#L90-L111
train
spiritix/lada-cache
src/Spiritix/LadaCache/QueryHandler.php
QueryHandler.cacheQuery
public function cacheQuery($queryClosure) { $this->constructCollector(); // Make sure to reset the sub query tags already here // Otherwise we'll get into trouble if caching is disabled for main query but not for subquery $subQueryTags = $this->subQueryTags; $this->subQueryTags = []; /* @var Reflector $reflector */ $reflector = new Reflector($this->builder); /* @var Manager $manager */ $manager = new Manager($reflector); // If cache is disabled, abort already here to save time if (!$manager->shouldCache()) { return $queryClosure(); } /* @var Hasher $hasher */ $hasher = new Hasher($reflector); /* @var Tagger $tagger */ $tagger = new Tagger($reflector); $result = null; $key = $hasher->getHash(); $tags = array_unique(array_merge($tagger->getTags(), $subQueryTags)); // Check if a cached version is available if ($this->cache->has($key)) { $result = $this->cache->get($key); } $action = ($result === null) ? 'Miss' : 'Hit'; // If not, execute the query closure and cache the result if ($result === null) { $result = $queryClosure(); $this->cache->set($key, $tags, $result); } $this->destructCollector($reflector, $tags, $key, $action); return $result; }
php
public function cacheQuery($queryClosure) { $this->constructCollector(); // Make sure to reset the sub query tags already here // Otherwise we'll get into trouble if caching is disabled for main query but not for subquery $subQueryTags = $this->subQueryTags; $this->subQueryTags = []; /* @var Reflector $reflector */ $reflector = new Reflector($this->builder); /* @var Manager $manager */ $manager = new Manager($reflector); // If cache is disabled, abort already here to save time if (!$manager->shouldCache()) { return $queryClosure(); } /* @var Hasher $hasher */ $hasher = new Hasher($reflector); /* @var Tagger $tagger */ $tagger = new Tagger($reflector); $result = null; $key = $hasher->getHash(); $tags = array_unique(array_merge($tagger->getTags(), $subQueryTags)); // Check if a cached version is available if ($this->cache->has($key)) { $result = $this->cache->get($key); } $action = ($result === null) ? 'Miss' : 'Hit'; // If not, execute the query closure and cache the result if ($result === null) { $result = $queryClosure(); $this->cache->set($key, $tags, $result); } $this->destructCollector($reflector, $tags, $key, $action); return $result; }
[ "public", "function", "cacheQuery", "(", "$", "queryClosure", ")", "{", "$", "this", "->", "constructCollector", "(", ")", ";", "// Make sure to reset the sub query tags already here", "// Otherwise we'll get into trouble if caching is disabled for main query but not for subquery", ...
Caches a query and returns its result. @param callable $queryClosure A closure which executes the query and returns the result @return array
[ "Caches", "a", "query", "and", "returns", "its", "result", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/QueryHandler.php#L120-L166
train
spiritix/lada-cache
src/Spiritix/LadaCache/QueryHandler.php
QueryHandler.invalidateQuery
public function invalidateQuery($statementType, $values = []) { $this->constructCollector(); /* @var Reflector $reflector */ $reflector = new Reflector($this->builder, $statementType, $values); /* @var Tagger $tagger */ $tagger = new Tagger($reflector); $tags = $tagger->getTags(); $hashes = $this->invalidator->invalidate($tags); $action = 'Invalidation (' . $statementType . ')'; $this->destructCollector($reflector, $tags, $hashes, $action); }
php
public function invalidateQuery($statementType, $values = []) { $this->constructCollector(); /* @var Reflector $reflector */ $reflector = new Reflector($this->builder, $statementType, $values); /* @var Tagger $tagger */ $tagger = new Tagger($reflector); $tags = $tagger->getTags(); $hashes = $this->invalidator->invalidate($tags); $action = 'Invalidation (' . $statementType . ')'; $this->destructCollector($reflector, $tags, $hashes, $action); }
[ "public", "function", "invalidateQuery", "(", "$", "statementType", ",", "$", "values", "=", "[", "]", ")", "{", "$", "this", "->", "constructCollector", "(", ")", ";", "/* @var Reflector $reflector */", "$", "reflector", "=", "new", "Reflector", "(", "$", "...
Invalidates a query. @param string $statementType The type of the statement that caused the invalidation @param array $values The values to be modified
[ "Invalidates", "a", "query", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/QueryHandler.php#L174-L189
train
spiritix/lada-cache
src/Spiritix/LadaCache/QueryHandler.php
QueryHandler.constructCollector
private function constructCollector() { try { $this->collector = app()->make('lada.collector'); $this->collector->startMeasuring(); } catch (ReflectionException $e) { $this->collector = null; } }
php
private function constructCollector() { try { $this->collector = app()->make('lada.collector'); $this->collector->startMeasuring(); } catch (ReflectionException $e) { $this->collector = null; } }
[ "private", "function", "constructCollector", "(", ")", "{", "try", "{", "$", "this", "->", "collector", "=", "app", "(", ")", "->", "make", "(", "'lada.collector'", ")", ";", "$", "this", "->", "collector", "->", "startMeasuring", "(", ")", ";", "}", "...
Constructs a collector instance. If debug bar is not available (collector service not booted), the collector will be set to null.
[ "Constructs", "a", "collector", "instance", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/QueryHandler.php#L196-L205
train
spiritix/lada-cache
src/Spiritix/LadaCache/QueryHandler.php
QueryHandler.destructCollector
private function destructCollector(Reflector $reflector, $tags, $hashes, $action) { if ($this->collector === null) { return; } $this->collector->endMeasuring( $action, is_array($hashes) ? $hashes : [$hashes], $tags, $reflector->getSql(), $reflector->getParameters() ); }
php
private function destructCollector(Reflector $reflector, $tags, $hashes, $action) { if ($this->collector === null) { return; } $this->collector->endMeasuring( $action, is_array($hashes) ? $hashes : [$hashes], $tags, $reflector->getSql(), $reflector->getParameters() ); }
[ "private", "function", "destructCollector", "(", "Reflector", "$", "reflector", ",", "$", "tags", ",", "$", "hashes", ",", "$", "action", ")", "{", "if", "(", "$", "this", "->", "collector", "===", "null", ")", "{", "return", ";", "}", "$", "this", "...
Destructs the collector. @param Reflector $reflector The reflector instance @param array $tags The tags for the executed query @param string|array $hashes The hash(es) for the executed query @param string $action The action that happened
[ "Destructs", "the", "collector", "." ]
f39525565beef03e80717245b54b4044f98791aa
https://github.com/spiritix/lada-cache/blob/f39525565beef03e80717245b54b4044f98791aa/src/Spiritix/LadaCache/QueryHandler.php#L215-L228
train
zoonman/linkedin-api-php-client
src/AccessToken.php
AccessToken.fromResponseArray
public static function fromResponseArray($responseArray) { if (!is_array($responseArray)) { throw new \InvalidArgumentException( 'Argument is not array' ); } if (!isset($responseArray['access_token'])) { throw new \InvalidArgumentException( 'Access token is not available' ); } if (!isset($responseArray['expires_in'])) { throw new \InvalidArgumentException( 'Access token expiration date is not specified' ); } return new static( $responseArray['access_token'], $responseArray['expires_in'] + time() ); }
php
public static function fromResponseArray($responseArray) { if (!is_array($responseArray)) { throw new \InvalidArgumentException( 'Argument is not array' ); } if (!isset($responseArray['access_token'])) { throw new \InvalidArgumentException( 'Access token is not available' ); } if (!isset($responseArray['expires_in'])) { throw new \InvalidArgumentException( 'Access token expiration date is not specified' ); } return new static( $responseArray['access_token'], $responseArray['expires_in'] + time() ); }
[ "public", "static", "function", "fromResponseArray", "(", "$", "responseArray", ")", "{", "if", "(", "!", "is_array", "(", "$", "responseArray", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Argument is not array'", ")", ";", "}", "if...
Instantiate access token object @param $responseArray @return \LinkedIn\AccessToken
[ "Instantiate", "access", "token", "object" ]
2837dd3a2935fffef734b7f5129e8b7758f2726c
https://github.com/zoonman/linkedin-api-php-client/blob/2837dd3a2935fffef734b7f5129e8b7758f2726c/src/AccessToken.php#L159-L180
train
zoonman/linkedin-api-php-client
src/Client.php
Client.getAccessToken
public function getAccessToken($code = '') { if (!empty($code)) { $uri = $this->buildUrl('accessToken', []); $guzzle = new GuzzleClient([ 'headers' => [ 'Content-Type' => 'application/json', 'x-li-format' => 'json', 'Connection' => 'Keep-Alive' ] ]); try { $response = $guzzle->post($uri, ['form_params' => [ 'grant_type' => self::OAUTH2_GRANT_TYPE, self::OAUTH2_RESPONSE_TYPE => $code, 'redirect_uri' => $this->getRedirectUrl(), 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), ]]); } catch (RequestException $exception) { throw Exception::fromRequestException($exception); } $this->setAccessToken( AccessToken::fromResponse($response) ); } return $this->accessToken; }
php
public function getAccessToken($code = '') { if (!empty($code)) { $uri = $this->buildUrl('accessToken', []); $guzzle = new GuzzleClient([ 'headers' => [ 'Content-Type' => 'application/json', 'x-li-format' => 'json', 'Connection' => 'Keep-Alive' ] ]); try { $response = $guzzle->post($uri, ['form_params' => [ 'grant_type' => self::OAUTH2_GRANT_TYPE, self::OAUTH2_RESPONSE_TYPE => $code, 'redirect_uri' => $this->getRedirectUrl(), 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), ]]); } catch (RequestException $exception) { throw Exception::fromRequestException($exception); } $this->setAccessToken( AccessToken::fromResponse($response) ); } return $this->accessToken; }
[ "public", "function", "getAccessToken", "(", "$", "code", "=", "''", ")", "{", "if", "(", "!", "empty", "(", "$", "code", ")", ")", "{", "$", "uri", "=", "$", "this", "->", "buildUrl", "(", "'accessToken'", ",", "[", "]", ")", ";", "$", "guzzle",...
Retrieve Access Token from LinkedIn if we have code provided. If code is not provided, return current Access Token. If current access token is not set, will return null @param string $code @return \LinkedIn\AccessToken|null @throws \LinkedIn\Exception
[ "Retrieve", "Access", "Token", "from", "LinkedIn", "if", "we", "have", "code", "provided", ".", "If", "code", "is", "not", "provided", "return", "current", "Access", "Token", ".", "If", "current", "access", "token", "is", "not", "set", "will", "return", "n...
2837dd3a2935fffef734b7f5129e8b7758f2726c
https://github.com/zoonman/linkedin-api-php-client/blob/2837dd3a2935fffef734b7f5129e8b7758f2726c/src/Client.php#L273-L300
train
zoonman/linkedin-api-php-client
src/Client.php
Client.setAccessToken
public function setAccessToken($accessToken) { if (is_string($accessToken)) { $accessToken = new AccessToken($accessToken); } if (is_object($accessToken) && $accessToken instanceof AccessToken) { $this->accessToken = $accessToken; } else { throw new \InvalidArgumentException('$accessToken must be instance of \LinkedIn\AccessToken class'); } return $this; }
php
public function setAccessToken($accessToken) { if (is_string($accessToken)) { $accessToken = new AccessToken($accessToken); } if (is_object($accessToken) && $accessToken instanceof AccessToken) { $this->accessToken = $accessToken; } else { throw new \InvalidArgumentException('$accessToken must be instance of \LinkedIn\AccessToken class'); } return $this; }
[ "public", "function", "setAccessToken", "(", "$", "accessToken", ")", "{", "if", "(", "is_string", "(", "$", "accessToken", ")", ")", "{", "$", "accessToken", "=", "new", "AccessToken", "(", "$", "accessToken", ")", ";", "}", "if", "(", "is_object", "(",...
Set AccessToken object @param AccessToken|string $accessToken @return Client
[ "Set", "AccessToken", "object" ]
2837dd3a2935fffef734b7f5129e8b7758f2726c
https://github.com/zoonman/linkedin-api-php-client/blob/2837dd3a2935fffef734b7f5129e8b7758f2726c/src/Client.php#L324-L335
train