id
int32
0
241k
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
41,600
aleksip/plugin-data-transform
src/Drupal/Component/Utility/SortArray.php
SortArray.sortByKeyInt
public static function sortByKeyInt($a, $b, $key) { $a_weight = (is_array($a) && isset($a[$key])) ? $a[$key] : 0; $b_weight = (is_array($b) && isset($b[$key])) ? $b[$key] : 0; if ($a_weight == $b_weight) { return 0; } return ($a_weight < $b_weight) ? -1 : 1; }
php
public static function sortByKeyInt($a, $b, $key) { $a_weight = (is_array($a) && isset($a[$key])) ? $a[$key] : 0; $b_weight = (is_array($b) && isset($b[$key])) ? $b[$key] : 0; if ($a_weight == $b_weight) { return 0; } return ($a_weight < $b_weight) ? -1 : 1; }
[ "public", "static", "function", "sortByKeyInt", "(", "$", "a", ",", "$", "b", ",", "$", "key", ")", "{", "$", "a_weight", "=", "(", "is_array", "(", "$", "a", ")", "&&", "isset", "(", "$", "a", "[", "$", "key", "]", ")", ")", "?", "$", "a", ...
Sorts an integer array item by an arbitrary key. @param array $a First item for comparison. @param array $b Second item for comparison. @param string $key The key to use in the comparison. @return int The comparison result for uasort().
[ "Sorts", "an", "integer", "array", "item", "by", "an", "arbitrary", "key", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/SortArray.php#L126-L135
41,601
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Number.php
Number.validStep
public static function validStep($value, $step, $offset = 0.0) { $double_value = (double) abs($value - $offset); // The fractional part of a double has 53 bits. The greatest number that // could be represented with that is 2^53. If the given value is even bigger // than $step * 2^53, then dividing by $step will result in a very small // remainder. Since that remainder can't even be represented with a single // precision float the following computation of the remainder makes no sense // and we can safely ignore it instead. if ($double_value / pow(2.0, 53) > $step) { return TRUE; } // Now compute that remainder of a division by $step. $remainder = (double) abs($double_value - $step * round($double_value / $step)); // $remainder is a double precision floating point number. Remainders that // can't be represented with single precision floats are acceptable. The // fractional part of a float has 24 bits. That means remainders smaller than // $step * 2^-24 are acceptable. $computed_acceptable_error = (double)($step / pow(2.0, 24)); return $computed_acceptable_error >= $remainder || $remainder >= ($step - $computed_acceptable_error); }
php
public static function validStep($value, $step, $offset = 0.0) { $double_value = (double) abs($value - $offset); // The fractional part of a double has 53 bits. The greatest number that // could be represented with that is 2^53. If the given value is even bigger // than $step * 2^53, then dividing by $step will result in a very small // remainder. Since that remainder can't even be represented with a single // precision float the following computation of the remainder makes no sense // and we can safely ignore it instead. if ($double_value / pow(2.0, 53) > $step) { return TRUE; } // Now compute that remainder of a division by $step. $remainder = (double) abs($double_value - $step * round($double_value / $step)); // $remainder is a double precision floating point number. Remainders that // can't be represented with single precision floats are acceptable. The // fractional part of a float has 24 bits. That means remainders smaller than // $step * 2^-24 are acceptable. $computed_acceptable_error = (double)($step / pow(2.0, 24)); return $computed_acceptable_error >= $remainder || $remainder >= ($step - $computed_acceptable_error); }
[ "public", "static", "function", "validStep", "(", "$", "value", ",", "$", "step", ",", "$", "offset", "=", "0.0", ")", "{", "$", "double_value", "=", "(", "double", ")", "abs", "(", "$", "value", "-", "$", "offset", ")", ";", "// The fractional part of...
Verifies that a number is a multiple of a given step. The implementation assumes it is dealing with IEEE 754 double precision floating point numbers that are used by PHP on most systems. This is based on the number/range verification methods of webkit. @param numeric $value The value that needs to be checked. @param numeric $step The step scale factor. Must be positive. @param numeric $offset (optional) An offset, to which the difference must be a multiple of the given step. @return bool TRUE if no step mismatch has occurred, or FALSE otherwise. @see http://opensource.apple.com/source/WebCore/WebCore-1298/html/NumberInputType.cpp
[ "Verifies", "that", "a", "number", "is", "a", "multiple", "of", "a", "given", "step", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Number.php#L37-L60
41,602
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Number.php
Number.intToAlphadecimal
public static function intToAlphadecimal($i = 0) { $num = base_convert((int) $i, 10, 36); $length = strlen($num); return chr($length + ord('0') - 1) . $num; }
php
public static function intToAlphadecimal($i = 0) { $num = base_convert((int) $i, 10, 36); $length = strlen($num); return chr($length + ord('0') - 1) . $num; }
[ "public", "static", "function", "intToAlphadecimal", "(", "$", "i", "=", "0", ")", "{", "$", "num", "=", "base_convert", "(", "(", "int", ")", "$", "i", ",", "10", ",", "36", ")", ";", "$", "length", "=", "strlen", "(", "$", "num", ")", ";", "r...
Generates a sorting code from an integer. Consists of a leading character indicating length, followed by N digits with a numerical value in base 36 (alphadecimal). These codes can be sorted as strings without altering numerical order. It goes: 00, 01, 02, ..., 0y, 0z, 110, 111, ... , 1zy, 1zz, 2100, 2101, ..., 2zzy, 2zzz, 31000, 31001, ... @param int $i The integer value to convert. @return string The alpha decimal value. @see \Drupal\Component\Utility\Number::alphadecimalToInt
[ "Generates", "a", "sorting", "code", "from", "an", "integer", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Number.php#L83-L88
41,603
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Crypt.php
Crypt.hmacBase64
public static function hmacBase64($data, $key) { // $data and $key being strings here is necessary to avoid empty string // results of the hash function if they are not scalar values. As this // function is used in security-critical contexts like token validation it // is important that it never returns an empty string. if (!is_scalar($data) || !is_scalar($key)) { throw new \InvalidArgumentException('Both parameters passed to \Drupal\Component\Utility\Crypt::hmacBase64 must be scalar values.'); } $hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE)); // Modify the hmac so it's safe to use in URLs. return str_replace(['+', '/', '='], ['-', '_', ''], $hmac); }
php
public static function hmacBase64($data, $key) { // $data and $key being strings here is necessary to avoid empty string // results of the hash function if they are not scalar values. As this // function is used in security-critical contexts like token validation it // is important that it never returns an empty string. if (!is_scalar($data) || !is_scalar($key)) { throw new \InvalidArgumentException('Both parameters passed to \Drupal\Component\Utility\Crypt::hmacBase64 must be scalar values.'); } $hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE)); // Modify the hmac so it's safe to use in URLs. return str_replace(['+', '/', '='], ['-', '_', ''], $hmac); }
[ "public", "static", "function", "hmacBase64", "(", "$", "data", ",", "$", "key", ")", "{", "// $data and $key being strings here is necessary to avoid empty string", "// results of the hash function if they are not scalar values. As this", "// function is used in security-critical contex...
Calculates a base-64 encoded, URL-safe sha-256 hmac. @param mixed $data Scalar value to be validated with the hmac. @param mixed $key A secret key, this can be any scalar value. @return string A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and any = padding characters removed.
[ "Calculates", "a", "base", "-", "64", "encoded", "URL", "-", "safe", "sha", "-", "256", "hmac", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Crypt.php#L105-L117
41,604
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Crypt.php
Crypt.hashEquals
public static function hashEquals($known_string, $user_string) { if (function_exists('hash_equals')) { return hash_equals($known_string, $user_string); } else { // Backport of hash_equals() function from PHP 5.6 // @see https://github.com/php/php-src/blob/PHP-5.6/ext/hash/hash.c#L739 if (!is_string($known_string)) { trigger_error(sprintf("Expected known_string to be a string, %s given", gettype($known_string)), E_USER_WARNING); return FALSE; } if (!is_string($user_string)) { trigger_error(sprintf("Expected user_string to be a string, %s given", gettype($user_string)), E_USER_WARNING); return FALSE; } $known_len = strlen($known_string); if ($known_len !== strlen($user_string)) { return FALSE; } // This is security sensitive code. Do not optimize this for speed. $result = 0; for ($i = 0; $i < $known_len; $i++) { $result |= (ord($known_string[$i]) ^ ord($user_string[$i])); } return $result === 0; } }
php
public static function hashEquals($known_string, $user_string) { if (function_exists('hash_equals')) { return hash_equals($known_string, $user_string); } else { // Backport of hash_equals() function from PHP 5.6 // @see https://github.com/php/php-src/blob/PHP-5.6/ext/hash/hash.c#L739 if (!is_string($known_string)) { trigger_error(sprintf("Expected known_string to be a string, %s given", gettype($known_string)), E_USER_WARNING); return FALSE; } if (!is_string($user_string)) { trigger_error(sprintf("Expected user_string to be a string, %s given", gettype($user_string)), E_USER_WARNING); return FALSE; } $known_len = strlen($known_string); if ($known_len !== strlen($user_string)) { return FALSE; } // This is security sensitive code. Do not optimize this for speed. $result = 0; for ($i = 0; $i < $known_len; $i++) { $result |= (ord($known_string[$i]) ^ ord($user_string[$i])); } return $result === 0; } }
[ "public", "static", "function", "hashEquals", "(", "$", "known_string", ",", "$", "user_string", ")", "{", "if", "(", "function_exists", "(", "'hash_equals'", ")", ")", "{", "return", "hash_equals", "(", "$", "known_string", ",", "$", "user_string", ")", ";"...
Compares strings in constant time. @param string $known_string The expected string. @param string $user_string The user supplied string to check. @return bool Returns TRUE when the two strings are equal, FALSE otherwise.
[ "Compares", "strings", "in", "constant", "time", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Crypt.php#L146-L176
41,605
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Timer.php
Timer.start
static public function start($name) { static::$timers[$name]['start'] = microtime(TRUE); static::$timers[$name]['count'] = isset(static::$timers[$name]['count']) ? ++static::$timers[$name]['count'] : 1; }
php
static public function start($name) { static::$timers[$name]['start'] = microtime(TRUE); static::$timers[$name]['count'] = isset(static::$timers[$name]['count']) ? ++static::$timers[$name]['count'] : 1; }
[ "static", "public", "function", "start", "(", "$", "name", ")", "{", "static", "::", "$", "timers", "[", "$", "name", "]", "[", "'start'", "]", "=", "microtime", "(", "TRUE", ")", ";", "static", "::", "$", "timers", "[", "$", "name", "]", "[", "'...
Starts the timer with the specified name. If you start and stop the same timer multiple times, the measured intervals will be accumulated. @param $name The name of the timer.
[ "Starts", "the", "timer", "with", "the", "specified", "name", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Timer.php#L28-L31
41,606
aleksip/plugin-data-transform
src/Drupal/Component/Utility/Timer.php
Timer.read
static public function read($name) { if (isset(static::$timers[$name]['start'])) { $stop = microtime(TRUE); $diff = round(($stop - static::$timers[$name]['start']) * 1000, 2); if (isset(static::$timers[$name]['time'])) { $diff += static::$timers[$name]['time']; } return $diff; } return static::$timers[$name]['time']; }
php
static public function read($name) { if (isset(static::$timers[$name]['start'])) { $stop = microtime(TRUE); $diff = round(($stop - static::$timers[$name]['start']) * 1000, 2); if (isset(static::$timers[$name]['time'])) { $diff += static::$timers[$name]['time']; } return $diff; } return static::$timers[$name]['time']; }
[ "static", "public", "function", "read", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "static", "::", "$", "timers", "[", "$", "name", "]", "[", "'start'", "]", ")", ")", "{", "$", "stop", "=", "microtime", "(", "TRUE", ")", ";", "$", "d...
Reads the current timer value without stopping the timer. @param string $name The name of the timer. @return int The current timer value in ms.
[ "Reads", "the", "current", "timer", "value", "without", "stopping", "the", "timer", "." ]
7fc113993903b7d64dfd98bc32f5450e164313a7
https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Timer.php#L42-L53
41,607
KilikFr/TableBundle
Components/Column.php
Column.getAutoInvertedSort
public function getAutoInvertedSort() { $result = []; foreach ($this->getSort() as $sort => $order) { $result[$sort] = ($order == 'asc' ? 'desc' : 'asc'); } return $result; }
php
public function getAutoInvertedSort() { $result = []; foreach ($this->getSort() as $sort => $order) { $result[$sort] = ($order == 'asc' ? 'desc' : 'asc'); } return $result; }
[ "public", "function", "getAutoInvertedSort", "(", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getSort", "(", ")", "as", "$", "sort", "=>", "$", "order", ")", "{", "$", "result", "[", "$", "sort", "]", "=", "("...
Get sort, with auto inverted orders. @return array
[ "Get", "sort", "with", "auto", "inverted", "orders", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Components/Column.php#L253-L261
41,608
KilikFr/TableBundle
Components/Column.php
Column.setDisplayFormat
public function setDisplayFormat($displayFormat) { if (!in_array($displayFormat, static::FORMATS)) { throw new \InvalidArgumentException("bad format '{$displayFormat}'"); } $this->displayFormat = $displayFormat; return $this; }
php
public function setDisplayFormat($displayFormat) { if (!in_array($displayFormat, static::FORMATS)) { throw new \InvalidArgumentException("bad format '{$displayFormat}'"); } $this->displayFormat = $displayFormat; return $this; }
[ "public", "function", "setDisplayFormat", "(", "$", "displayFormat", ")", "{", "if", "(", "!", "in_array", "(", "$", "displayFormat", ",", "static", "::", "FORMATS", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"bad format '{$displayFo...
Set the display format. @param string $displayFormat @return static
[ "Set", "the", "display", "format", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Components/Column.php#L366-L374
41,609
KilikFr/TableBundle
Components/Column.php
Column.getValue
public function getValue(array $row, array $rows = []) { if (isset($row[$this->getName()])) { $rawValue = $row[$this->getName()]; } else { $rawValue = null; } // if a callback is set $callback = $this->getDisplayCallback(); if (!is_null($callback)) { if (!is_callable($callback)) { throw new \Exception('displayCallback is not callable'); } return $callback($rawValue, $row, $rows); } else { switch ($this->getDisplayFormat()) { case static::FORMAT_DATE: $formatParams = $this->getDisplayFormatParams(); if (is_null($formatParams)) { $formatParams = 'Y-m-d H:i:s'; } if (!is_null($rawValue) && is_object($rawValue) && get_class($rawValue) == 'DateTime') { return $rawValue->format($formatParams); } else { return ''; } break; case static::FORMAT_TEXT: default: if (is_array($rawValue)) { return implode(',', $rawValue); } else { return $rawValue; } break; } } }
php
public function getValue(array $row, array $rows = []) { if (isset($row[$this->getName()])) { $rawValue = $row[$this->getName()]; } else { $rawValue = null; } // if a callback is set $callback = $this->getDisplayCallback(); if (!is_null($callback)) { if (!is_callable($callback)) { throw new \Exception('displayCallback is not callable'); } return $callback($rawValue, $row, $rows); } else { switch ($this->getDisplayFormat()) { case static::FORMAT_DATE: $formatParams = $this->getDisplayFormatParams(); if (is_null($formatParams)) { $formatParams = 'Y-m-d H:i:s'; } if (!is_null($rawValue) && is_object($rawValue) && get_class($rawValue) == 'DateTime') { return $rawValue->format($formatParams); } else { return ''; } break; case static::FORMAT_TEXT: default: if (is_array($rawValue)) { return implode(',', $rawValue); } else { return $rawValue; } break; } } }
[ "public", "function", "getValue", "(", "array", "$", "row", ",", "array", "$", "rows", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "row", "[", "$", "this", "->", "getName", "(", ")", "]", ")", ")", "{", "$", "rawValue", "=", "$", "...
Get the formatted value to display. priority formatter methods: - callback - known formats - default (raw text) @param $row @param array $rows @return string @throws \Exception
[ "Get", "the", "formatted", "value", "to", "display", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Components/Column.php#L562-L600
41,610
KilikFr/TableBundle
Components/Table.php
Table.setDefaultIdentifierFieldNames
public function setDefaultIdentifierFieldNames() { //Default identifier for table rows $rootEntity = $this->queryBuilder->getRootEntities()[0]; $metadata = $this->queryBuilder->getEntityManager()->getMetadataFactory()->getMetadataFor($rootEntity); $identifiers = array(); foreach ($metadata->getIdentifierFieldNames() as $identifierFieldName) { $identifiers[] = $this->getAlias().'.'.$identifierFieldName; } $rootEntityIdentifier = implode(',', $identifiers); $this->setIdentifierFieldNames($rootEntityIdentifier ?: null); return $this; }
php
public function setDefaultIdentifierFieldNames() { //Default identifier for table rows $rootEntity = $this->queryBuilder->getRootEntities()[0]; $metadata = $this->queryBuilder->getEntityManager()->getMetadataFactory()->getMetadataFor($rootEntity); $identifiers = array(); foreach ($metadata->getIdentifierFieldNames() as $identifierFieldName) { $identifiers[] = $this->getAlias().'.'.$identifierFieldName; } $rootEntityIdentifier = implode(',', $identifiers); $this->setIdentifierFieldNames($rootEntityIdentifier ?: null); return $this; }
[ "public", "function", "setDefaultIdentifierFieldNames", "(", ")", "{", "//Default identifier for table rows", "$", "rootEntity", "=", "$", "this", "->", "queryBuilder", "->", "getRootEntities", "(", ")", "[", "0", "]", ";", "$", "metadata", "=", "$", "this", "->...
Defines default identifiers from query builder in order to optimize count queries. @return $this @throws \Doctrine\Common\Persistence\Mapping\MappingException
[ "Defines", "default", "identifiers", "from", "query", "builder", "in", "order", "to", "optimize", "count", "queries", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Components/Table.php#L80-L93
41,611
KilikFr/TableBundle
Services/TableApiService.php
TableApiService.parseFilters
private function parseFilters(TableInterface $table, Request $request) { $filters = []; $queryParams = $request->get($table->getFormId()); foreach ($table->getAllFilters() as $filter) { if (isset($queryParams[$filter->getName()])) { $searchParamRaw = trim($queryParams[$filter->getName()]); if ($searchParamRaw != '') { $filters[$filter->getName()] = $searchParamRaw; } } } return $filters; }
php
private function parseFilters(TableInterface $table, Request $request) { $filters = []; $queryParams = $request->get($table->getFormId()); foreach ($table->getAllFilters() as $filter) { if (isset($queryParams[$filter->getName()])) { $searchParamRaw = trim($queryParams[$filter->getName()]); if ($searchParamRaw != '') { $filters[$filter->getName()] = $searchParamRaw; } } } return $filters; }
[ "private", "function", "parseFilters", "(", "TableInterface", "$", "table", ",", "Request", "$", "request", ")", "{", "$", "filters", "=", "[", "]", ";", "$", "queryParams", "=", "$", "request", "->", "get", "(", "$", "table", "->", "getFormId", "(", "...
Parse filters. @param TableInterface $table @param Request $request @return array
[ "Parse", "filters", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Services/TableApiService.php#L22-L38
41,612
KilikFr/TableBundle
Services/TableApiService.php
TableApiService.parseOrderBy
private function parseOrderBy(TableInterface $table, Request $request) { $orderBy = []; $queryParams = $request->get($table->getFormId()); if (isset($queryParams['sortColumn']) && $queryParams['sortColumn'] != '') { $column = $table->getColumnByName($queryParams['sortColumn']); // if column exists if (!is_null($column)) { if (!is_null($column->getSort())) { if (isset($queryParams['sortReverse'])) { $sortReverse = $queryParams['sortReverse']; } else { $sortReverse = false; } foreach ($column->getAutoSort($sortReverse) as $sortField => $sortOrder) { $orderBy[$sortField] = $sortOrder; } } } } return $orderBy; }
php
private function parseOrderBy(TableInterface $table, Request $request) { $orderBy = []; $queryParams = $request->get($table->getFormId()); if (isset($queryParams['sortColumn']) && $queryParams['sortColumn'] != '') { $column = $table->getColumnByName($queryParams['sortColumn']); // if column exists if (!is_null($column)) { if (!is_null($column->getSort())) { if (isset($queryParams['sortReverse'])) { $sortReverse = $queryParams['sortReverse']; } else { $sortReverse = false; } foreach ($column->getAutoSort($sortReverse) as $sortField => $sortOrder) { $orderBy[$sortField] = $sortOrder; } } } } return $orderBy; }
[ "private", "function", "parseOrderBy", "(", "TableInterface", "$", "table", ",", "Request", "$", "request", ")", "{", "$", "orderBy", "=", "[", "]", ";", "$", "queryParams", "=", "$", "request", "->", "get", "(", "$", "table", "->", "getFormId", "(", "...
Parse OrderBy. @param TableInterface $table @param Request $request @return array
[ "Parse", "OrderBy", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Services/TableApiService.php#L48-L72
41,613
KilikFr/TableBundle
Services/TableService.php
TableService.setTotalRows
protected function setTotalRows(Table $table) { $qb = $table->getQueryBuilder(); $qbtr = clone $qb; $identifiers = $table->getIdentifierFieldNames(); if (is_null($identifiers)) { $paginatorTotal = new Paginator($qbtr->getQuery()); $count = $paginatorTotal->count(); } else { $qbtr->select($qbtr->expr()->count($identifiers)); $count = (int) $qbtr->getQuery()->getSingleScalarResult(); } $table->setTotalRows($count); }
php
protected function setTotalRows(Table $table) { $qb = $table->getQueryBuilder(); $qbtr = clone $qb; $identifiers = $table->getIdentifierFieldNames(); if (is_null($identifiers)) { $paginatorTotal = new Paginator($qbtr->getQuery()); $count = $paginatorTotal->count(); } else { $qbtr->select($qbtr->expr()->count($identifiers)); $count = (int) $qbtr->getQuery()->getSingleScalarResult(); } $table->setTotalRows($count); }
[ "protected", "function", "setTotalRows", "(", "Table", "$", "table", ")", "{", "$", "qb", "=", "$", "table", "->", "getQueryBuilder", "(", ")", ";", "$", "qbtr", "=", "clone", "$", "qb", ";", "$", "identifiers", "=", "$", "table", "->", "getIdentifierF...
Set total rows count without filters. @param Table $table
[ "Set", "total", "rows", "count", "without", "filters", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Services/TableService.php#L139-L155
41,614
KilikFr/TableBundle
Services/TableService.php
TableService.setFilteredRows
private function setFilteredRows(Table $table, Request $request) { $qb = $table->getQueryBuilder(); $qbfr = clone $qb; $this->addSearch($table, $request, $qbfr); $identifiers = $table->getIdentifierFieldNames(); if (is_null($identifiers)) { $paginatorFiltered = new Paginator($qbfr->getQuery()); $count = $paginatorFiltered->count(); } else { $qbfr->select($qbfr->expr()->count($identifiers)); $count = (int) $qbfr->getQuery()->getSingleScalarResult(); } $table->setFilteredRows($count); }
php
private function setFilteredRows(Table $table, Request $request) { $qb = $table->getQueryBuilder(); $qbfr = clone $qb; $this->addSearch($table, $request, $qbfr); $identifiers = $table->getIdentifierFieldNames(); if (is_null($identifiers)) { $paginatorFiltered = new Paginator($qbfr->getQuery()); $count = $paginatorFiltered->count(); } else { $qbfr->select($qbfr->expr()->count($identifiers)); $count = (int) $qbfr->getQuery()->getSingleScalarResult(); } $table->setFilteredRows($count); }
[ "private", "function", "setFilteredRows", "(", "Table", "$", "table", ",", "Request", "$", "request", ")", "{", "$", "qb", "=", "$", "table", "->", "getQueryBuilder", "(", ")", ";", "$", "qbfr", "=", "clone", "$", "qb", ";", "$", "this", "->", "addSe...
Set total rows count with filters. @param Table $table @param Request $request
[ "Set", "total", "rows", "count", "with", "filters", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Services/TableService.php#L163-L180
41,615
KilikFr/TableBundle
Components/Filter.php
Filter.getOperatorAndValue
public function getOperatorAndValue($input) { switch ($this->getType()) { case self::TYPE_GREATER: case self::TYPE_GREATER_OR_EQUAL: case self::TYPE_LESS: case self::TYPE_LESS_OR_EQUAL: case self::TYPE_NOT_LIKE: case self::TYPE_LIKE: case self::TYPE_NOT_EQUAL: case self::TYPE_EQUAL_STRICT: case self::TYPE_LIKE_WORDS_AND: case self::TYPE_LIKE_WORDS_OR: return array($this->getType(), $input); case self::TYPE_AUTO: default: // handle blank search is different to search 0 value if ((string) $input != '') { $simpleOperator = substr($input, 0, 1); $doubleOperator = substr($input, 0, 2); // if start with operators switch ($doubleOperator) { case self::TYPE_GREATER_OR_EQUAL: case self::TYPE_LESS_OR_EQUAL: case self::TYPE_NOT_EQUAL: case self::TYPE_EQUAL_STRICT: return array($doubleOperator, substr($input, 2)); break; default: switch ($simpleOperator) { case self::TYPE_GREATER: case self::TYPE_LESS: case self::TYPE_EQUAL: case self::TYPE_NOT_LIKE: return array($simpleOperator, substr($input, 1)); break; default: return array(self::TYPE_LIKE, $input); break; } break; } break; } return array(self::TYPE_LIKE, false); } }
php
public function getOperatorAndValue($input) { switch ($this->getType()) { case self::TYPE_GREATER: case self::TYPE_GREATER_OR_EQUAL: case self::TYPE_LESS: case self::TYPE_LESS_OR_EQUAL: case self::TYPE_NOT_LIKE: case self::TYPE_LIKE: case self::TYPE_NOT_EQUAL: case self::TYPE_EQUAL_STRICT: case self::TYPE_LIKE_WORDS_AND: case self::TYPE_LIKE_WORDS_OR: return array($this->getType(), $input); case self::TYPE_AUTO: default: // handle blank search is different to search 0 value if ((string) $input != '') { $simpleOperator = substr($input, 0, 1); $doubleOperator = substr($input, 0, 2); // if start with operators switch ($doubleOperator) { case self::TYPE_GREATER_OR_EQUAL: case self::TYPE_LESS_OR_EQUAL: case self::TYPE_NOT_EQUAL: case self::TYPE_EQUAL_STRICT: return array($doubleOperator, substr($input, 2)); break; default: switch ($simpleOperator) { case self::TYPE_GREATER: case self::TYPE_LESS: case self::TYPE_EQUAL: case self::TYPE_NOT_LIKE: return array($simpleOperator, substr($input, 1)); break; default: return array(self::TYPE_LIKE, $input); break; } break; } break; } return array(self::TYPE_LIKE, false); } }
[ "public", "function", "getOperatorAndValue", "(", "$", "input", ")", "{", "switch", "(", "$", "this", "->", "getType", "(", ")", ")", "{", "case", "self", "::", "TYPE_GREATER", ":", "case", "self", "::", "TYPE_GREATER_OR_EQUAL", ":", "case", "self", "::", ...
Get the operator and the value of an input string. @param string $input @return array [string operator,string value]
[ "Get", "the", "operator", "and", "the", "value", "of", "an", "input", "string", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Components/Filter.php#L274-L321
41,616
KilikFr/TableBundle
Components/Filter.php
Filter.getFormattedInput
public function getFormattedInput($operator, $input) { // if we use custom formatter if (is_callable($this->inputFormatter)) { $function = $this->inputFormatter; return $function($this, $operator, $input); } // else, use standard input converter switch ($this->getDataFormat()) { // date/time format dd/mm/YYYY HH:ii:ss case self::FORMAT_DATE: $params = explode('/', str_replace(array('-', ' ',':'), '/', $input)); // only year ? if (count($params) == 1) { $fInput = $params[0]; } // month/year ? elseif (count($params) == 2) { $fInput = sprintf('%04d-%02d', $params[1], $params[0]); } // day/month/year ? elseif (count($params) == 3) { $fInput = sprintf('%04d-%02d-%02d', $params[2], $params[1], $params[0]); } // day/month/year hour ? elseif (count($params) == 4) { $fInput = sprintf('%04d-%02d-%02d %02d', $params[2], $params[1], $params[0], $params[3]); } // day/month/year hour:minute ? elseif (count($params) == 5) { $fInput = sprintf( '%04d-%02d-%02d %02d:%02d', $params[2], $params[1], $params[0], $params[3], $params[4] ); } // day/month/year hour:minute:second ? elseif (count($params) == 6) { $fInput = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $params[2], $params[1], $params[0], $params[3], $params[4], $params[5] ); } // default, same has raw value else { $fInput = $input; } break; case self::FORMAT_INTEGER: $fInput = (int) $input; switch ($operator) { case self::TYPE_NOT_LIKE: $operator = self::TYPE_NOT_EQUAL; break; case self::TYPE_LIKE: case self::TYPE_LIKE_WORDS_AND: case self::TYPE_LIKE_WORDS_OR: case self::TYPE_AUTO: $operator = self::TYPE_EQUAL_STRICT; break; } break; case self::FORMAT_TEXT: default: $fInput = $input; break; } return array($operator, $fInput); }
php
public function getFormattedInput($operator, $input) { // if we use custom formatter if (is_callable($this->inputFormatter)) { $function = $this->inputFormatter; return $function($this, $operator, $input); } // else, use standard input converter switch ($this->getDataFormat()) { // date/time format dd/mm/YYYY HH:ii:ss case self::FORMAT_DATE: $params = explode('/', str_replace(array('-', ' ',':'), '/', $input)); // only year ? if (count($params) == 1) { $fInput = $params[0]; } // month/year ? elseif (count($params) == 2) { $fInput = sprintf('%04d-%02d', $params[1], $params[0]); } // day/month/year ? elseif (count($params) == 3) { $fInput = sprintf('%04d-%02d-%02d', $params[2], $params[1], $params[0]); } // day/month/year hour ? elseif (count($params) == 4) { $fInput = sprintf('%04d-%02d-%02d %02d', $params[2], $params[1], $params[0], $params[3]); } // day/month/year hour:minute ? elseif (count($params) == 5) { $fInput = sprintf( '%04d-%02d-%02d %02d:%02d', $params[2], $params[1], $params[0], $params[3], $params[4] ); } // day/month/year hour:minute:second ? elseif (count($params) == 6) { $fInput = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $params[2], $params[1], $params[0], $params[3], $params[4], $params[5] ); } // default, same has raw value else { $fInput = $input; } break; case self::FORMAT_INTEGER: $fInput = (int) $input; switch ($operator) { case self::TYPE_NOT_LIKE: $operator = self::TYPE_NOT_EQUAL; break; case self::TYPE_LIKE: case self::TYPE_LIKE_WORDS_AND: case self::TYPE_LIKE_WORDS_OR: case self::TYPE_AUTO: $operator = self::TYPE_EQUAL_STRICT; break; } break; case self::FORMAT_TEXT: default: $fInput = $input; break; } return array($operator, $fInput); }
[ "public", "function", "getFormattedInput", "(", "$", "operator", ",", "$", "input", ")", "{", "// if we use custom formatter", "if", "(", "is_callable", "(", "$", "this", "->", "inputFormatter", ")", ")", "{", "$", "function", "=", "$", "this", "->", "inputF...
Get formatted input. @param string $operator @param string $input @return array searchOperator, formatted input
[ "Get", "formatted", "input", "." ]
55169b3e8c24b03b063c4cf8b79e5000bf2a0497
https://github.com/KilikFr/TableBundle/blob/55169b3e8c24b03b063c4cf8b79e5000bf2a0497/Components/Filter.php#L345-L417
41,617
oat-sa/extension-tao-itemqti-pic
controller/PicLoader.php
PicLoader.load
public function load() { try { $this->returnJson($this->getPicRegistry()->getLatestRuntimes()); } catch (PortableElementException $e) { $this->returnJson($e->getMessage(), 500); } }
php
public function load() { try { $this->returnJson($this->getPicRegistry()->getLatestRuntimes()); } catch (PortableElementException $e) { $this->returnJson($e->getMessage(), 500); } }
[ "public", "function", "load", "(", ")", "{", "try", "{", "$", "this", "->", "returnJson", "(", "$", "this", "->", "getPicRegistry", "(", ")", "->", "getLatestRuntimes", "(", ")", ")", ";", "}", "catch", "(", "PortableElementException", "$", "e", ")", "...
Load latest PCI runtimes
[ "Load", "latest", "PCI", "runtimes" ]
14e26ad6b788ec1a0f37025fb70af12dce0a2231
https://github.com/oat-sa/extension-tao-itemqti-pic/blob/14e26ad6b788ec1a0f37025fb70af12dce0a2231/controller/PicLoader.php#L36-L43
41,618
oat-sa/extension-tao-itemqti-pic
model/export/OatPicExporter.php
OatPicExporter.copyAssetFiles
public function copyAssetFiles(&$replacementList){ $object = $this->object; $portableAssetsToExport = []; $service = new PortableElementService(); $service->setServiceLocator(ServiceManager::getServiceManager()); $files = $object->getModel()->getValidator()->getAssets($object, 'runtime'); $baseUrl = $this->qtiItemExporter->buildBasePath() . DIRECTORY_SEPARATOR . $object->getTypeIdentifier(); foreach ($files as $url) { // Skip shared libraries into portable element if (strpos($url, './') !== 0) { \common_Logger::i('Shared libraries skipped : ' . $url); $portableAssetsToExport[$url] = $url; continue; } $stream = $service->getFileStream($object, $url); $replacement = $this->qtiItemExporter->copyAssetFile($stream, $baseUrl, $url, $replacementList); $portableAssetToExport = preg_replace('/^(.\/)(.*)/', $object->getTypeIdentifier() . "/$2", $replacement); $portableAssetsToExport[$url] = $portableAssetToExport; \common_Logger::i('File copied: "' . $url . '" for portable element ' . $object->getTypeIdentifier()); } return $this->portableAssetsToExport = $portableAssetsToExport; }
php
public function copyAssetFiles(&$replacementList){ $object = $this->object; $portableAssetsToExport = []; $service = new PortableElementService(); $service->setServiceLocator(ServiceManager::getServiceManager()); $files = $object->getModel()->getValidator()->getAssets($object, 'runtime'); $baseUrl = $this->qtiItemExporter->buildBasePath() . DIRECTORY_SEPARATOR . $object->getTypeIdentifier(); foreach ($files as $url) { // Skip shared libraries into portable element if (strpos($url, './') !== 0) { \common_Logger::i('Shared libraries skipped : ' . $url); $portableAssetsToExport[$url] = $url; continue; } $stream = $service->getFileStream($object, $url); $replacement = $this->qtiItemExporter->copyAssetFile($stream, $baseUrl, $url, $replacementList); $portableAssetToExport = preg_replace('/^(.\/)(.*)/', $object->getTypeIdentifier() . "/$2", $replacement); $portableAssetsToExport[$url] = $portableAssetToExport; \common_Logger::i('File copied: "' . $url . '" for portable element ' . $object->getTypeIdentifier()); } return $this->portableAssetsToExport = $portableAssetsToExport; }
[ "public", "function", "copyAssetFiles", "(", "&", "$", "replacementList", ")", "{", "$", "object", "=", "$", "this", "->", "object", ";", "$", "portableAssetsToExport", "=", "[", "]", ";", "$", "service", "=", "new", "PortableElementService", "(", ")", ";"...
Copy the asset files of the PIC to the item exporter and return the list of copied assets @param $replacementList @return array
[ "Copy", "the", "asset", "files", "of", "the", "PIC", "to", "the", "item", "exporter", "and", "return", "the", "list", "of", "copied", "assets" ]
14e26ad6b788ec1a0f37025fb70af12dce0a2231
https://github.com/oat-sa/extension-tao-itemqti-pic/blob/14e26ad6b788ec1a0f37025fb70af12dce0a2231/model/export/OatPicExporter.php#L37-L58
41,619
CraftCamp/php-abac
src/Abac.php
Abac.enforce
public function enforce(string $ruleName, $user, $resource = null, array $options = []): bool { $this->errors = []; // If there is dynamic attributes, we pass them to the comparison manager // When a comparison will be performed, the passed values will be retrieved and used if (isset($options[ 'dynamic_attributes' ])) { $this->comparisonManager->setDynamicAttributes($options[ 'dynamic_attributes' ]); } // Retrieve cache value for the current rule and values if cache item is valid if (($cacheResult = isset($options[ 'cache_result' ]) && $options[ 'cache_result' ] === true) === true) { $cacheItem = $this->cacheManager->getItem("$ruleName-{$user->getId()}-" . (($resource !== null) ? $resource->getId() : ''), (isset($options[ 'cache_driver' ])) ? $options[ 'cache_driver' ] : null, (isset($options[ 'cache_ttl' ])) ? $options[ 'cache_ttl' ] : null); // We check if the cache value s valid before returning it if (($cacheValue = $cacheItem->get()) !== null) { return $cacheValue; } } $policyRules = $this->policyRuleManager->getRule($ruleName, $user, $resource); foreach ($policyRules as $policyRule) { // For each policy rule attribute, we retrieve the attribute value and proceed configured extra data foreach ($policyRule->getPolicyRuleAttributes() as $pra) { /** @var PolicyRuleAttribute $pra */ $attribute = $pra->getAttribute(); $getter_params = $this->prepareGetterParams($pra->getGetterParams(), $user, $resource); $attribute->setValue($this->attributeManager->retrieveAttribute($attribute, $user, $resource, $getter_params)); if (count($pra->getExtraData()) > 0) { $this->processExtraData($pra, $user, $resource); } $this->comparisonManager->compare($pra); } // The given result could be an array of rejected attributes or true // True means that the rule is correctly enforced for the given user and resource $this->errors = $this->comparisonManager->getResult(); if (count($this->errors) === 0) { break; } } if ($cacheResult) { $cacheItem->set((count($this->errors) > 0) ? $this->errors : true); $this->cacheManager->save($cacheItem); } return count($this->errors) === 0; }
php
public function enforce(string $ruleName, $user, $resource = null, array $options = []): bool { $this->errors = []; // If there is dynamic attributes, we pass them to the comparison manager // When a comparison will be performed, the passed values will be retrieved and used if (isset($options[ 'dynamic_attributes' ])) { $this->comparisonManager->setDynamicAttributes($options[ 'dynamic_attributes' ]); } // Retrieve cache value for the current rule and values if cache item is valid if (($cacheResult = isset($options[ 'cache_result' ]) && $options[ 'cache_result' ] === true) === true) { $cacheItem = $this->cacheManager->getItem("$ruleName-{$user->getId()}-" . (($resource !== null) ? $resource->getId() : ''), (isset($options[ 'cache_driver' ])) ? $options[ 'cache_driver' ] : null, (isset($options[ 'cache_ttl' ])) ? $options[ 'cache_ttl' ] : null); // We check if the cache value s valid before returning it if (($cacheValue = $cacheItem->get()) !== null) { return $cacheValue; } } $policyRules = $this->policyRuleManager->getRule($ruleName, $user, $resource); foreach ($policyRules as $policyRule) { // For each policy rule attribute, we retrieve the attribute value and proceed configured extra data foreach ($policyRule->getPolicyRuleAttributes() as $pra) { /** @var PolicyRuleAttribute $pra */ $attribute = $pra->getAttribute(); $getter_params = $this->prepareGetterParams($pra->getGetterParams(), $user, $resource); $attribute->setValue($this->attributeManager->retrieveAttribute($attribute, $user, $resource, $getter_params)); if (count($pra->getExtraData()) > 0) { $this->processExtraData($pra, $user, $resource); } $this->comparisonManager->compare($pra); } // The given result could be an array of rejected attributes or true // True means that the rule is correctly enforced for the given user and resource $this->errors = $this->comparisonManager->getResult(); if (count($this->errors) === 0) { break; } } if ($cacheResult) { $cacheItem->set((count($this->errors) > 0) ? $this->errors : true); $this->cacheManager->save($cacheItem); } return count($this->errors) === 0; }
[ "public", "function", "enforce", "(", "string", "$", "ruleName", ",", "$", "user", ",", "$", "resource", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", ":", "bool", "{", "$", "this", "->", "errors", "=", "[", "]", ";", "// If there ...
Return true if both user and object respects all the rules conditions If the objectId is null, policy rules about its attributes will be ignored In case of mismatch between attributes and expected values, an array with the concerned attributes slugs will be returned. Available options are : * dynamic_attributes: array * cache_result: boolean * cache_ttl: integer * cache_driver: string Available cache drivers are : * memory
[ "Return", "true", "if", "both", "user", "and", "object", "respects", "all", "the", "rules", "conditions", "If", "the", "objectId", "is", "null", "policy", "rules", "about", "its", "attributes", "will", "be", "ignored", "In", "case", "of", "mismatch", "betwee...
567a7f7d5beec6df23413ec5ffb1a3774adc7999
https://github.com/CraftCamp/php-abac/blob/567a7f7d5beec6df23413ec5ffb1a3774adc7999/src/Abac.php#L49-L92
41,620
CraftCamp/php-abac
src/Manager/ComparisonManager.php
ComparisonManager.getDynamicAttribute
public function getDynamicAttribute(string $attributeSlug) { if (!isset($this->dynamicAttributes[$attributeSlug])) { throw new \InvalidArgumentException("The dynamic value for attribute $attributeSlug was not given"); } return $this->dynamicAttributes[$attributeSlug]; }
php
public function getDynamicAttribute(string $attributeSlug) { if (!isset($this->dynamicAttributes[$attributeSlug])) { throw new \InvalidArgumentException("The dynamic value for attribute $attributeSlug was not given"); } return $this->dynamicAttributes[$attributeSlug]; }
[ "public", "function", "getDynamicAttribute", "(", "string", "$", "attributeSlug", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "dynamicAttributes", "[", "$", "attributeSlug", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", ...
A dynamic attribute is a value given by the user code as an option If a policy rule attribute is dynamic, we check that the developer has given a dynamic value in the options Dynamic attributes are given with slugs as key @param string $attributeSlug @return mixed @throws \InvalidArgumentException
[ "A", "dynamic", "attribute", "is", "a", "value", "given", "by", "the", "user", "code", "as", "an", "option", "If", "a", "policy", "rule", "attribute", "is", "dynamic", "we", "check", "that", "the", "developer", "has", "given", "a", "dynamic", "value", "i...
567a7f7d5beec6df23413ec5ffb1a3774adc7999
https://github.com/CraftCamp/php-abac/blob/567a7f7d5beec6df23413ec5ffb1a3774adc7999/src/Manager/ComparisonManager.php#L100-L106
41,621
CraftCamp/php-abac
src/Manager/ComparisonManager.php
ComparisonManager.getResult
public function getResult(): array { $result = (count($this->rejectedAttributes) > 0) ? $this->rejectedAttributes : [] ; $this->rejectedAttributes = []; return $result; }
php
public function getResult(): array { $result = (count($this->rejectedAttributes) > 0) ? $this->rejectedAttributes : [] ; $this->rejectedAttributes = []; return $result; }
[ "public", "function", "getResult", "(", ")", ":", "array", "{", "$", "result", "=", "(", "count", "(", "$", "this", "->", "rejectedAttributes", ")", ">", "0", ")", "?", "$", "this", "->", "rejectedAttributes", ":", "[", "]", ";", "$", "this", "->", ...
This method is called when all the policy rule attributes are checked All along the comparisons, the failing attributes slugs are stored If the rejected attributes array is not empty, it means that the rule is not enforced
[ "This", "method", "is", "called", "when", "all", "the", "policy", "rule", "attributes", "are", "checked", "All", "along", "the", "comparisons", "the", "failing", "attributes", "slugs", "are", "stored", "If", "the", "rejected", "attributes", "array", "is", "not...
567a7f7d5beec6df23413ec5ffb1a3774adc7999
https://github.com/CraftCamp/php-abac/blob/567a7f7d5beec6df23413ec5ffb1a3774adc7999/src/Manager/ComparisonManager.php#L123-L132
41,622
CraftCamp/php-abac
example/User.php
User.getVisa
public function getVisa($country_code) { /** @var Visa $visa */ $visas = []; foreach ($this->visas as $visa) { if ($visa->getCountry()->getCode() == $country_code) { $visas[] = $visa; } } return $visas; }
php
public function getVisa($country_code) { /** @var Visa $visa */ $visas = []; foreach ($this->visas as $visa) { if ($visa->getCountry()->getCode() == $country_code) { $visas[] = $visa; } } return $visas; }
[ "public", "function", "getVisa", "(", "$", "country_code", ")", "{", "/** @var Visa $visa */", "$", "visas", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "visas", "as", "$", "visa", ")", "{", "if", "(", "$", "visa", "->", "getCountry", "(", ...
Return a specific visa @param Visa $visa @return mixed|null
[ "Return", "a", "specific", "visa" ]
567a7f7d5beec6df23413ec5ffb1a3774adc7999
https://github.com/CraftCamp/php-abac/blob/567a7f7d5beec6df23413ec5ffb1a3774adc7999/example/User.php#L138-L148
41,623
CraftCamp/php-abac
src/Manager/PolicyRuleManager.php
PolicyRuleManager.processRuleAttributes
public function processRuleAttributes(array $attributes, $user, $resource) { foreach ($attributes as $attributeName => $attribute) { $pra = (new PolicyRuleAttribute()) ->setAttribute($this->attributeManager->getAttribute($attributeName)) ->setComparison($attribute['comparison']) ->setComparisonType($attribute['comparison_type']) ->setValue((isset($attribute['value'])) ? $attribute['value'] : null) ->setGetterParams(isset($attribute[ 'getter_params' ]) ? $attribute[ 'getter_params' ] : []); $this->processRuleAttributeComparisonType($pra, $user, $resource); // In the case the user configured more keys than the basic ones // it will be stored as extra data foreach ($attribute as $key => $value) { if (!in_array($key, ['comparison', 'comparison_type', 'value','getter_params'])) { $pra->addExtraData($key, $value); } } // This generator avoid useless memory consumption instead of returning a whole array yield $pra; } }
php
public function processRuleAttributes(array $attributes, $user, $resource) { foreach ($attributes as $attributeName => $attribute) { $pra = (new PolicyRuleAttribute()) ->setAttribute($this->attributeManager->getAttribute($attributeName)) ->setComparison($attribute['comparison']) ->setComparisonType($attribute['comparison_type']) ->setValue((isset($attribute['value'])) ? $attribute['value'] : null) ->setGetterParams(isset($attribute[ 'getter_params' ]) ? $attribute[ 'getter_params' ] : []); $this->processRuleAttributeComparisonType($pra, $user, $resource); // In the case the user configured more keys than the basic ones // it will be stored as extra data foreach ($attribute as $key => $value) { if (!in_array($key, ['comparison', 'comparison_type', 'value','getter_params'])) { $pra->addExtraData($key, $value); } } // This generator avoid useless memory consumption instead of returning a whole array yield $pra; } }
[ "public", "function", "processRuleAttributes", "(", "array", "$", "attributes", ",", "$", "user", ",", "$", "resource", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "attributeName", "=>", "$", "attribute", ")", "{", "$", "pra", "=", "(", "new"...
This method is meant to convert attribute data from array to formatted policy rule attribute
[ "This", "method", "is", "meant", "to", "convert", "attribute", "data", "from", "array", "to", "formatted", "policy", "rule", "attribute" ]
567a7f7d5beec6df23413ec5ffb1a3774adc7999
https://github.com/CraftCamp/php-abac/blob/567a7f7d5beec6df23413ec5ffb1a3774adc7999/src/Manager/PolicyRuleManager.php#L52-L72
41,624
kaoken/markdown-it-php
src/MarkdownIt/RulesInline/StateInline.php
StateInline.push
public function push($type, $tag, $nesting) { if ($this->pending) { $this->pushPending(); } $token = $this->createToken($type, $tag, $nesting); if ($nesting < 0) { $this->level--; } $token->level = $this->level; if ($nesting > 0) { $this->level++; } $this->pendingLevel = $this->level; $this->tokens[] = $token; return $token; }
php
public function push($type, $tag, $nesting) { if ($this->pending) { $this->pushPending(); } $token = $this->createToken($type, $tag, $nesting); if ($nesting < 0) { $this->level--; } $token->level = $this->level; if ($nesting > 0) { $this->level++; } $this->pendingLevel = $this->level; $this->tokens[] = $token; return $token; }
[ "public", "function", "push", "(", "$", "type", ",", "$", "tag", ",", "$", "nesting", ")", "{", "if", "(", "$", "this", "->", "pending", ")", "{", "$", "this", "->", "pushPending", "(", ")", ";", "}", "$", "token", "=", "$", "this", "->", "crea...
Push new token to "stream". If pending text exists - flush it as text token @param string $type @param string $tag @param integer $nesting @return Token
[ "Push", "new", "token", "to", "stream", ".", "If", "pending", "text", "exists", "-", "flush", "it", "as", "text", "token" ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/RulesInline/StateInline.php#L91-L106
41,625
kaoken/markdown-it-php
src/MarkdownIt/RulesInline/StateInline.php
StateInline.scanDelims
public function scanDelims($start, $canSplitWord) { $pos = $start; $left_flanking = true; $right_flanking = true; $max = $this->posMax; $marker = $this->md->utils->currentCharUTF8($this->src, $start, $outLen); // treat beginning of the line as a whitespace // $lastChar = $start > 0 ? $this->src[$start-1] : ' '; $lastPos = $start; if( $start > 0 ){ $lastChar = $this->md->utils->lastCharUTF8($this->src, $start, $lastPos); if( $lastChar === '' ){ throw new \Exception('scanDelims(), last char unexpected error...'); } } else $lastChar = ' '; //while ($pos < $max && $this->src[$pos] === $marker) { $pos++; } while ($pos < $max && ($nextChar=$this->md->utils->currentCharUTF8($this->src, $pos, $outLen)) === $marker) { $pos+=$outLen; } ; $count = $pos - $start; // treat end of the line as a whitespace $nextChar = $pos < $max ? $nextChar : ' '; $isLastPunctChar = $this->md->utils->isMdAsciiPunct($lastChar) || $this->md->utils->isPunctChar($lastChar); $isNextPunctChar = $this->md->utils->isMdAsciiPunct($nextChar) || $this->md->utils->isPunctChar($nextChar); $isLastWhiteSpace = $this->md->utils->isWhiteSpace($lastChar); $isNextWhiteSpace = $this->md->utils->isWhiteSpace($nextChar); if ($isNextWhiteSpace) { $left_flanking = false; } else if ($isNextPunctChar) { if (!($isLastWhiteSpace || $isLastPunctChar)) { $left_flanking = false; } } if ($isLastWhiteSpace) { $right_flanking = false; } else if ($isLastPunctChar) { if (!($isNextWhiteSpace || $isNextPunctChar)) { $right_flanking = false; } } if (!$canSplitWord) { $can_open = $left_flanking && (!$right_flanking || $isLastPunctChar); $can_close = $right_flanking && (!$left_flanking || $isNextPunctChar); } else { $can_open = $left_flanking; $can_close = $right_flanking; } $obj = new \stdClass(); $obj->can_open = $can_open; $obj->can_close = $can_close; $obj->length = $count; return $obj; }
php
public function scanDelims($start, $canSplitWord) { $pos = $start; $left_flanking = true; $right_flanking = true; $max = $this->posMax; $marker = $this->md->utils->currentCharUTF8($this->src, $start, $outLen); // treat beginning of the line as a whitespace // $lastChar = $start > 0 ? $this->src[$start-1] : ' '; $lastPos = $start; if( $start > 0 ){ $lastChar = $this->md->utils->lastCharUTF8($this->src, $start, $lastPos); if( $lastChar === '' ){ throw new \Exception('scanDelims(), last char unexpected error...'); } } else $lastChar = ' '; //while ($pos < $max && $this->src[$pos] === $marker) { $pos++; } while ($pos < $max && ($nextChar=$this->md->utils->currentCharUTF8($this->src, $pos, $outLen)) === $marker) { $pos+=$outLen; } ; $count = $pos - $start; // treat end of the line as a whitespace $nextChar = $pos < $max ? $nextChar : ' '; $isLastPunctChar = $this->md->utils->isMdAsciiPunct($lastChar) || $this->md->utils->isPunctChar($lastChar); $isNextPunctChar = $this->md->utils->isMdAsciiPunct($nextChar) || $this->md->utils->isPunctChar($nextChar); $isLastWhiteSpace = $this->md->utils->isWhiteSpace($lastChar); $isNextWhiteSpace = $this->md->utils->isWhiteSpace($nextChar); if ($isNextWhiteSpace) { $left_flanking = false; } else if ($isNextPunctChar) { if (!($isLastWhiteSpace || $isLastPunctChar)) { $left_flanking = false; } } if ($isLastWhiteSpace) { $right_flanking = false; } else if ($isLastPunctChar) { if (!($isNextWhiteSpace || $isNextPunctChar)) { $right_flanking = false; } } if (!$canSplitWord) { $can_open = $left_flanking && (!$right_flanking || $isLastPunctChar); $can_close = $right_flanking && (!$left_flanking || $isNextPunctChar); } else { $can_open = $left_flanking; $can_close = $right_flanking; } $obj = new \stdClass(); $obj->can_open = $can_open; $obj->can_close = $can_close; $obj->length = $count; return $obj; }
[ "public", "function", "scanDelims", "(", "$", "start", ",", "$", "canSplitWord", ")", "{", "$", "pos", "=", "$", "start", ";", "$", "left_flanking", "=", "true", ";", "$", "right_flanking", "=", "true", ";", "$", "max", "=", "$", "this", "->", "posMa...
Scan a sequence of emphasis-like markers, and determine whether it can start an emphasis sequence or end an emphasis sequence. @param integer $start position to scan from (it should point at a valid marker); @param boolean $canSplitWord determine if these markers can be found inside a word @return \stdClass @throws \Exception
[ "Scan", "a", "sequence", "of", "emphasis", "-", "like", "markers", "and", "determine", "whether", "it", "can", "start", "an", "emphasis", "sequence", "or", "end", "an", "emphasis", "sequence", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/RulesInline/StateInline.php#L117-L184
41,626
kaoken/markdown-it-php
src/MarkdownIt/Helpers/ParseLinkDestination.php
ParseLinkDestination.parseLinkDestination
public function parseLinkDestination($str, $pos, $max) { $lines = 0; $start = $pos; $result = new \stdClass(); $result->ok = false; $result->pos = 0; $result->lines = 0; $result->str = ''; if( $pos === $max ) return $result; if ($str[$pos] === '<') { $pos++; while ($pos < $max) { $ch= $str[$pos]; if ($str[$pos] == "\n" || $this->utils->isSpace($ch)) { return $result; } if ($ch === '>') { $result->pos = $pos + 1; $result->str = $this->utils->unescapeAll(substr($str, $start + 1, $pos-($start+1))); $result->ok = true; return $result; } if ($ch === '\\' && $pos + 1 < $max) { $pos += 2; continue; } $pos++; } // no closing '>' return $result; } // this should be ... } else { ... branch $level = 0; while ($pos < $max) { $ch = $str[$pos]; if ($ch === ' ') { break; } // ascii control characters $code = ord($ch); if ($code < 0x20 || $code === 0x7F) { break; } if ($ch === '\\' && $pos + 1 < $max) { $pos += 2; continue; } if ($ch === '(' ) { $level++; } if ($ch === ')' ) { if ($level === 0) { break; } $level--; } $pos++; } if ($start === $pos) { return $result; } if ($level !== 0) { return $result; } $result->str = $this->utils->unescapeAll(substr($str, $start, $pos-$start)); $result->lines = $lines; $result->pos = $pos; $result->ok = true; return $result; }
php
public function parseLinkDestination($str, $pos, $max) { $lines = 0; $start = $pos; $result = new \stdClass(); $result->ok = false; $result->pos = 0; $result->lines = 0; $result->str = ''; if( $pos === $max ) return $result; if ($str[$pos] === '<') { $pos++; while ($pos < $max) { $ch= $str[$pos]; if ($str[$pos] == "\n" || $this->utils->isSpace($ch)) { return $result; } if ($ch === '>') { $result->pos = $pos + 1; $result->str = $this->utils->unescapeAll(substr($str, $start + 1, $pos-($start+1))); $result->ok = true; return $result; } if ($ch === '\\' && $pos + 1 < $max) { $pos += 2; continue; } $pos++; } // no closing '>' return $result; } // this should be ... } else { ... branch $level = 0; while ($pos < $max) { $ch = $str[$pos]; if ($ch === ' ') { break; } // ascii control characters $code = ord($ch); if ($code < 0x20 || $code === 0x7F) { break; } if ($ch === '\\' && $pos + 1 < $max) { $pos += 2; continue; } if ($ch === '(' ) { $level++; } if ($ch === ')' ) { if ($level === 0) { break; } $level--; } $pos++; } if ($start === $pos) { return $result; } if ($level !== 0) { return $result; } $result->str = $this->utils->unescapeAll(substr($str, $start, $pos-$start)); $result->lines = $lines; $result->pos = $pos; $result->ok = true; return $result; }
[ "public", "function", "parseLinkDestination", "(", "$", "str", ",", "$", "pos", ",", "$", "max", ")", "{", "$", "lines", "=", "0", ";", "$", "start", "=", "$", "pos", ";", "$", "result", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "result",...
ParseLinkDestination constructor. @param string $str @param integer $pos @param integer $max @return object
[ "ParseLinkDestination", "constructor", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Helpers/ParseLinkDestination.php#L17-L89
41,627
kaoken/markdown-it-php
src/LinkifyIt/LinkifyIt.php
LinkifyIt.add
public function add($schema, $definition) { if(is_array($definition)) $definition = (object)$definition; $this->__schemas__[$schema] = $definition; $this->compile(); return $this; }
php
public function add($schema, $definition) { if(is_array($definition)) $definition = (object)$definition; $this->__schemas__[$schema] = $definition; $this->compile(); return $this; }
[ "public", "function", "add", "(", "$", "schema", ",", "$", "definition", ")", "{", "if", "(", "is_array", "(", "$", "definition", ")", ")", "$", "definition", "=", "(", "object", ")", "$", "definition", ";", "$", "this", "->", "__schemas__", "[", "$"...
Add new rule definition. See constructor description for details. @param string $schema rule name (fixed pattern prefix) @param string|object $definition schema definition @return $this
[ "Add", "new", "rule", "definition", ".", "See", "constructor", "description", "for", "details", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/LinkifyIt/LinkifyIt.php#L124-L130
41,628
kaoken/markdown-it-php
src/LinkifyIt/LinkifyIt.php
LinkifyIt.set
public function set($options) { $this->__opts__ = $this->assign($this->__opts__, $options); return $this; }
php
public function set($options) { $this->__opts__ = $this->assign($this->__opts__, $options); return $this; }
[ "public", "function", "set", "(", "$", "options", ")", "{", "$", "this", "->", "__opts__", "=", "$", "this", "->", "assign", "(", "$", "this", "->", "__opts__", ",", "$", "options", ")", ";", "return", "$", "this", ";", "}" ]
Set recognition options for links without schema. @param array $options [fuzzyLink|fuzzyEmail|fuzzyIP=> true|false ] @return $this
[ "Set", "recognition", "options", "for", "links", "without", "schema", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/LinkifyIt/LinkifyIt.php#L139-L143
41,629
kaoken/markdown-it-php
src/MarkdownIt/Renderer.php
Renderer.renderAttrs
public function renderAttrs($token) { if (!isset($token->attrs)) return ''; $result = ''; foreach ($token->attrs as &$a) { $result .= ' ' . htmlspecialchars($a[0]) . '="' . htmlspecialchars($a[1]) . '"'; } return $result; }
php
public function renderAttrs($token) { if (!isset($token->attrs)) return ''; $result = ''; foreach ($token->attrs as &$a) { $result .= ' ' . htmlspecialchars($a[0]) . '="' . htmlspecialchars($a[1]) . '"'; } return $result; }
[ "public", "function", "renderAttrs", "(", "$", "token", ")", "{", "if", "(", "!", "isset", "(", "$", "token", "->", "attrs", ")", ")", "return", "''", ";", "$", "result", "=", "''", ";", "foreach", "(", "$", "token", "->", "attrs", "as", "&", "$"...
Render token attributes to string. @param Token $token @return string
[ "Render", "token", "attributes", "to", "string", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Renderer.php#L79-L90
41,630
kaoken/markdown-it-php
src/MarkdownIt/Renderer.php
Renderer.renderInlineAsText
public function renderInlineAsText(array &$tokens, $options, $env) { $result = ''; foreach ( $tokens as &$token) { if ($token->type === 'text') { $result .= $token->content; } else if ($token->type === 'image') { $result .= $this->renderInlineAsText($token->children, $options, $env); } } return $result; }
php
public function renderInlineAsText(array &$tokens, $options, $env) { $result = ''; foreach ( $tokens as &$token) { if ($token->type === 'text') { $result .= $token->content; } else if ($token->type === 'image') { $result .= $this->renderInlineAsText($token->children, $options, $env); } } return $result; }
[ "public", "function", "renderInlineAsText", "(", "array", "&", "$", "tokens", ",", "$", "options", ",", "$", "env", ")", "{", "$", "result", "=", "''", ";", "foreach", "(", "$", "tokens", "as", "&", "$", "token", ")", "{", "if", "(", "$", "token", ...
internal Special kludge for image `alt` attributes to conform CommonMark spec. Don't try to use it! Spec requires to show `alt` content with stripped markup, instead of simple escaping. @param Token[] $tokens list on block tokens to renter @param object $options params of parser instance @param object $env additional data from parsed input (references, for example) @return string
[ "internal", "Special", "kludge", "for", "image", "alt", "attributes", "to", "conform", "CommonMark", "spec", ".", "Don", "t", "try", "to", "use", "it!", "Spec", "requires", "to", "show", "alt", "content", "with", "stripped", "markup", "instead", "of", "simpl...
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Renderer.php#L200-L213
41,631
kaoken/markdown-it-php
src/Punycode/Punycode.php
Punycode.ucs2Encode
public function ucs2Encode($codePoints) { $outStr = ''; foreach ($codePoints as $v) { if( 0x10000 <= $v && $v <= 0x10FFFF) { $v -= 0x10000; $w1 = 0xD800 | ($v >> 10); $w2 = 0xDC00 | ($v & 0x03FF); $outStr .= chr(0xFF & ($w1 >> 8)) . chr(0xFF & $w1); $outStr .= chr(0xFF & ($w2 >> 8)) . chr(0xFF & $w2); }else{ $outStr .= chr(0xFF & ($v >> 8)) . chr(0xFF & $v); } } return $outStr; }
php
public function ucs2Encode($codePoints) { $outStr = ''; foreach ($codePoints as $v) { if( 0x10000 <= $v && $v <= 0x10FFFF) { $v -= 0x10000; $w1 = 0xD800 | ($v >> 10); $w2 = 0xDC00 | ($v & 0x03FF); $outStr .= chr(0xFF & ($w1 >> 8)) . chr(0xFF & $w1); $outStr .= chr(0xFF & ($w2 >> 8)) . chr(0xFF & $w2); }else{ $outStr .= chr(0xFF & ($v >> 8)) . chr(0xFF & $v); } } return $outStr; }
[ "public", "function", "ucs2Encode", "(", "$", "codePoints", ")", "{", "$", "outStr", "=", "''", ";", "foreach", "(", "$", "codePoints", "as", "$", "v", ")", "{", "if", "(", "0x10000", "<=", "$", "v", "&&", "$", "v", "<=", "0x10FFFF", ")", "{", "$...
Creates a string based on an array of numeric code points. @see `punycode->ucs2Decode` @param array $codePoints The array of numeric code points. @returns string The new Unicode string (UCS-2).
[ "Creates", "a", "string", "based", "on", "an", "array", "of", "numeric", "code", "points", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/Punycode/Punycode.php#L122-L137
41,632
kaoken/markdown-it-php
src/Punycode/Punycode.php
Punycode.decode
public function decode($input) { // Don't use UCS-2. $output = []; $inputLength = strlen($input); $i = 0; $n = self::INITIAL_N; $bias = self::INITIAL_BIAS; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. $basic = strrpos($input, self::DELIMITER); if ($basic === false ) { $basic = 0; } for ($j = 0; $j < $basic; ++$j) { // if it's not a basic code point if ( ord($input[$j]) >= 0x80) { $this->error('not-basic'); } $output[] = ord($input[$j]); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for ( $index = $basic > 0 ? $basic + 1 : 0; $index < $inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-$length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. $oldi = $i; for ( $w = 1, $k = self::BASE; /* no condition */; $k += self::BASE) { if ($index >= $inputLength) { $this->error('invalid-input'); } $digit = $this->basicToDigit(ord($input[$index++])); if ($digit >= self::BASE || $digit > floor((self::MAX_INT - $i) / $w)) { $this->error('overflow'); } $i += $digit * $w; $t = $k <= $bias ? self::T_MIN : ($k >= $bias + self::T_MAX ? self::T_MAX : $k - $bias); if ($digit < $t) { break; } $baseMinusT = self::BASE - $t; if ($w > floor(self::MAX_INT / $baseMinusT)) { $this->error('overflow'); } $w *= $baseMinusT; } $out = count($output) + 1; $bias = $this->adapt($i - $oldi, $out, $oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor($i / $out) > self::MAX_INT - $n) { $this->error('overflow'); } $n += floor($i / $out); $i %= $out; // Insert `n` at position `i` of the output. array_splice($output, $i++, 0, $n); } return mb_convert_encoding($this->ucs2Encode($output), "UTF-8", "UTF-16"); }
php
public function decode($input) { // Don't use UCS-2. $output = []; $inputLength = strlen($input); $i = 0; $n = self::INITIAL_N; $bias = self::INITIAL_BIAS; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. $basic = strrpos($input, self::DELIMITER); if ($basic === false ) { $basic = 0; } for ($j = 0; $j < $basic; ++$j) { // if it's not a basic code point if ( ord($input[$j]) >= 0x80) { $this->error('not-basic'); } $output[] = ord($input[$j]); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for ( $index = $basic > 0 ? $basic + 1 : 0; $index < $inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-$length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. $oldi = $i; for ( $w = 1, $k = self::BASE; /* no condition */; $k += self::BASE) { if ($index >= $inputLength) { $this->error('invalid-input'); } $digit = $this->basicToDigit(ord($input[$index++])); if ($digit >= self::BASE || $digit > floor((self::MAX_INT - $i) / $w)) { $this->error('overflow'); } $i += $digit * $w; $t = $k <= $bias ? self::T_MIN : ($k >= $bias + self::T_MAX ? self::T_MAX : $k - $bias); if ($digit < $t) { break; } $baseMinusT = self::BASE - $t; if ($w > floor(self::MAX_INT / $baseMinusT)) { $this->error('overflow'); } $w *= $baseMinusT; } $out = count($output) + 1; $bias = $this->adapt($i - $oldi, $out, $oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor($i / $out) > self::MAX_INT - $n) { $this->error('overflow'); } $n += floor($i / $out); $i %= $out; // Insert `n` at position `i` of the output. array_splice($output, $i++, 0, $n); } return mb_convert_encoding($this->ucs2Encode($output), "UTF-8", "UTF-16"); }
[ "public", "function", "decode", "(", "$", "input", ")", "{", "// Don't use UCS-2.", "$", "output", "=", "[", "]", ";", "$", "inputLength", "=", "strlen", "(", "$", "input", ")", ";", "$", "i", "=", "0", ";", "$", "n", "=", "self", "::", "INITIAL_N"...
Converts a Punycode string of ASCII-only symbols to a string of Unicode symbols. @param string $input The Punycode string of ASCII-only symbols. @returns string The resulting string of Unicode symbols.
[ "Converts", "a", "Punycode", "string", "of", "ASCII", "-", "only", "symbols", "to", "a", "string", "of", "Unicode", "symbols", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/Punycode/Punycode.php#L244-L326
41,633
kaoken/markdown-it-php
src/MarkdownIt/ParserBlock.php
ParserBlock.parse
public function parse($src, $md, $env, &$outTokens) { if (!$src) { return; } $state = new StateBlock($src, $md, $env, $outTokens); $this->tokenize($state, $state->line, $state->lineMax); }
php
public function parse($src, $md, $env, &$outTokens) { if (!$src) { return; } $state = new StateBlock($src, $md, $env, $outTokens); $this->tokenize($state, $state->line, $state->lineMax); }
[ "public", "function", "parse", "(", "$", "src", ",", "$", "md", ",", "$", "env", ",", "&", "$", "outTokens", ")", "{", "if", "(", "!", "$", "src", ")", "{", "return", ";", "}", "$", "state", "=", "new", "StateBlock", "(", "$", "src", ",", "$"...
Process input string and push block tokens into `outTokens` @param string $src @param MarkdownIt $md @param object $env @param $outTokens
[ "Process", "input", "string", "and", "push", "block", "tokens", "into", "outTokens" ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/ParserBlock.php#L126-L133
41,634
kaoken/markdown-it-php
src/MarkdownIt/ParserInline.php
ParserInline.skipToken
public function skipToken(&$state) { $pos = $state->pos; $rules = $this->ruler->getRules(''); $maxNesting = $state->md->options->maxNesting; $cache = &$state->cache; $ok = false; if ( isset($cache[$pos])) { $state->pos = $cache[$pos]; return; } if ($state->level < $maxNesting) { foreach ($rules as &$rule) { // Increment state.level and decrement it later to limit recursion. // It's harmless to do here, because no tokens are created. But ideally, // we'd need a separate private state variable for this purpose. // $state->level++; if( is_array($rule) ) $ok = $rule[0]->{$rule[1]}($state, true); else $ok = $rule($state, true); $state->level--; if ($ok) break; } } else { // Too much nesting, just skip until the end of the paragraph. // // NOTE: this will cause links to behave incorrectly in the following case, // when an amount of `[` is exactly equal to `maxNesting + 1`: // // [[[[[[[[[[[[[[[[[[[[[foo]() // // TODO: remove this workaround when CM standard will allow nested links // (we can replace it by preventing links from being parsed in // validation mode) // $state->pos = $state->posMax; } if (!$ok) { $state->pos++; } $cache[$pos] = $state->pos; }
php
public function skipToken(&$state) { $pos = $state->pos; $rules = $this->ruler->getRules(''); $maxNesting = $state->md->options->maxNesting; $cache = &$state->cache; $ok = false; if ( isset($cache[$pos])) { $state->pos = $cache[$pos]; return; } if ($state->level < $maxNesting) { foreach ($rules as &$rule) { // Increment state.level and decrement it later to limit recursion. // It's harmless to do here, because no tokens are created. But ideally, // we'd need a separate private state variable for this purpose. // $state->level++; if( is_array($rule) ) $ok = $rule[0]->{$rule[1]}($state, true); else $ok = $rule($state, true); $state->level--; if ($ok) break; } } else { // Too much nesting, just skip until the end of the paragraph. // // NOTE: this will cause links to behave incorrectly in the following case, // when an amount of `[` is exactly equal to `maxNesting + 1`: // // [[[[[[[[[[[[[[[[[[[[[foo]() // // TODO: remove this workaround when CM standard will allow nested links // (we can replace it by preventing links from being parsed in // validation mode) // $state->pos = $state->posMax; } if (!$ok) { $state->pos++; } $cache[$pos] = $state->pos; }
[ "public", "function", "skipToken", "(", "&", "$", "state", ")", "{", "$", "pos", "=", "$", "state", "->", "pos", ";", "$", "rules", "=", "$", "this", "->", "ruler", "->", "getRules", "(", "''", ")", ";", "$", "maxNesting", "=", "$", "state", "->"...
returns `true` if any rule reported success @param StateInline $state
[ "returns", "true", "if", "any", "rule", "reported", "success" ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/ParserInline.php#L89-L136
41,635
kaoken/markdown-it-php
src/MarkdownIt/ParserInline.php
ParserInline.parse
public function parse($str, $md, $env, &$outTokens) { $state = new StateInline($str, $md, $env, $outTokens); $this->tokenize($state); $rules = $this->ruler2->getRules(''); foreach ( $rules as &$rule) { if( is_array($rule) ) $rule[0]->{$rule[1]}($state); else $rule($state); } }
php
public function parse($str, $md, $env, &$outTokens) { $state = new StateInline($str, $md, $env, $outTokens); $this->tokenize($state); $rules = $this->ruler2->getRules(''); foreach ( $rules as &$rule) { if( is_array($rule) ) $rule[0]->{$rule[1]}($state); else $rule($state); } }
[ "public", "function", "parse", "(", "$", "str", ",", "$", "md", ",", "$", "env", ",", "&", "$", "outTokens", ")", "{", "$", "state", "=", "new", "StateInline", "(", "$", "str", ",", "$", "md", ",", "$", "env", ",", "$", "outTokens", ")", ";", ...
Process input string and push inline tokens into `outTokens` @param string $str @param MarkdownIt $md @param string $env @param Token[] $outTokens
[ "Process", "input", "string", "and", "push", "inline", "tokens", "into", "outTokens" ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/ParserInline.php#L199-L213
41,636
kaoken/markdown-it-php
src/MDUrl/DecodeTrait.php
DecodeTrait.decode
public function decode($string, $exclude=null) { if ( !is_string( $exclude) ) { $exclude = ';/?:@&=+$,#'; } $cache = $this->getDecodeCache($exclude); return preg_replace_callback("/(%[a-f0-9]{2})+/i", function($seq) use(&$cache) { $result = ''; $seq = $seq[0]; for ($i = 0, $l = strlen($seq); $i < $l; $i += 3) { $b1 = intval(substr($seq, $i + 1, 2), 16); if ($b1 < 0x80) { $result .= $cache[$b1]; continue; } $result .= chr($b1); } return $result; },$string); }
php
public function decode($string, $exclude=null) { if ( !is_string( $exclude) ) { $exclude = ';/?:@&=+$,#'; } $cache = $this->getDecodeCache($exclude); return preg_replace_callback("/(%[a-f0-9]{2})+/i", function($seq) use(&$cache) { $result = ''; $seq = $seq[0]; for ($i = 0, $l = strlen($seq); $i < $l; $i += 3) { $b1 = intval(substr($seq, $i + 1, 2), 16); if ($b1 < 0x80) { $result .= $cache[$b1]; continue; } $result .= chr($b1); } return $result; },$string); }
[ "public", "function", "decode", "(", "$", "string", ",", "$", "exclude", "=", "null", ")", "{", "if", "(", "!", "is_string", "(", "$", "exclude", ")", ")", "{", "$", "exclude", "=", "';/?:@&=+$,#'", ";", "}", "$", "cache", "=", "$", "this", "->", ...
Decode percent-encoded string. @param string $string @param string|null $exclude @return mixed
[ "Decode", "percent", "-", "encoded", "string", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MDUrl/DecodeTrait.php#L54-L76
41,637
kaoken/markdown-it-php
src/MDUrl/EncodeTrait.php
EncodeTrait.&
protected function &getEncodeCache($exclude) { if (array_key_exists($exclude, $this->encodeCache)) { return $this->encodeCache[$exclude]; } $cache = []; for ($i = 0; $i < 128; $i++) { // /^[0-9a-z]$/i if ( $i >= 0x30 && $i <= 0x39 || $i >= 0x41 && $i <= 0x5a || $i >= 0x61 && $i <= 0x7a ) { // always allow unencoded alphanumeric characters $cache[] = chr($i); } else { $cache[] = sprintf("%%%02X",$i); } } for ($i = 0, $l = strlen($exclude); $i < $l; $i++) $cache[ord($exclude[$i])] = $exclude[$i]; $this->encodeCache[$exclude] = $cache; return $cache; }
php
protected function &getEncodeCache($exclude) { if (array_key_exists($exclude, $this->encodeCache)) { return $this->encodeCache[$exclude]; } $cache = []; for ($i = 0; $i < 128; $i++) { // /^[0-9a-z]$/i if ( $i >= 0x30 && $i <= 0x39 || $i >= 0x41 && $i <= 0x5a || $i >= 0x61 && $i <= 0x7a ) { // always allow unencoded alphanumeric characters $cache[] = chr($i); } else { $cache[] = sprintf("%%%02X",$i); } } for ($i = 0, $l = strlen($exclude); $i < $l; $i++) $cache[ord($exclude[$i])] = $exclude[$i]; $this->encodeCache[$exclude] = $cache; return $cache; }
[ "protected", "function", "&", "getEncodeCache", "(", "$", "exclude", ")", "{", "if", "(", "array_key_exists", "(", "$", "exclude", ",", "$", "this", "->", "encodeCache", ")", ")", "{", "return", "$", "this", "->", "encodeCache", "[", "$", "exclude", "]",...
Create a lookup array where anything but characters in `chars` string and alphanumeric chars is percent-encoded. @param string $exclude Ascii character staring @return array
[ "Create", "a", "lookup", "array", "where", "anything", "but", "characters", "in", "chars", "string", "and", "alphanumeric", "chars", "is", "percent", "-", "encoded", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MDUrl/EncodeTrait.php#L33-L56
41,638
kaoken/markdown-it-php
src/MDUrl/EncodeTrait.php
EncodeTrait.encode
public function encode($string, $exclude=null, $keepEscaped=true) { $result = ''; if ( !is_string($exclude) ) { // encode($string, $keepEscaped) $keepEscaped = $exclude; $exclude = $this->defaultChars; } if( !isset($keepEscaped) ) $keepEscaped = true; $cache = $this->getEncodeCache($exclude); for ($i = 0, $l = mb_strlen($string); $i < $l; $i++) { $ch = mb_substr($string,$i,1); $chLen = strlen($ch); if ($keepEscaped && $ch === '%' && $i + 2 < $l) { if (preg_match("/^[0-9a-f]{2}$/i", mb_substr($string, $i + 1, 2))) { $result .= mb_substr($string, $i, 3); $i += 2; continue; } } if ( $chLen === 1 && ($code = ord($ch)) < 128) { $result .= $cache[$code]; continue; } $result .= rawurlencode($ch); } return $result; }
php
public function encode($string, $exclude=null, $keepEscaped=true) { $result = ''; if ( !is_string($exclude) ) { // encode($string, $keepEscaped) $keepEscaped = $exclude; $exclude = $this->defaultChars; } if( !isset($keepEscaped) ) $keepEscaped = true; $cache = $this->getEncodeCache($exclude); for ($i = 0, $l = mb_strlen($string); $i < $l; $i++) { $ch = mb_substr($string,$i,1); $chLen = strlen($ch); if ($keepEscaped && $ch === '%' && $i + 2 < $l) { if (preg_match("/^[0-9a-f]{2}$/i", mb_substr($string, $i + 1, 2))) { $result .= mb_substr($string, $i, 3); $i += 2; continue; } } if ( $chLen === 1 && ($code = ord($ch)) < 128) { $result .= $cache[$code]; continue; } $result .= rawurlencode($ch); } return $result; }
[ "public", "function", "encode", "(", "$", "string", ",", "$", "exclude", "=", "null", ",", "$", "keepEscaped", "=", "true", ")", "{", "$", "result", "=", "''", ";", "if", "(", "!", "is_string", "(", "$", "exclude", ")", ")", "{", "// encode($string, ...
Encode unsafe characters with percent-encoding, skipping already encoded sequences. @param string $string String to encode @param string $exclude List of characters to ignore (in addition to a-zA-Z0-9) @param bool $keepEscaped Don't encode '%' in a correct escape sequence (default: true) @return string
[ "Encode", "unsafe", "characters", "with", "percent", "-", "encoding", "skipping", "already", "encoded", "sequences", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MDUrl/EncodeTrait.php#L67-L100
41,639
kaoken/markdown-it-php
src/MarkdownIt/MarkdownIt.php
MarkdownIt.normalizeLink
public function normalizeLink($url) { if( property_exists($this,'normalizeLink') && is_callable($this->normalizeLink)){ $fn = $this->normalizeLink; return $fn($url); } $parsed = $this->mdurl->parse($url, true); if ($parsed->hostname) { // Encode hostnames in urls like: // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` // // We don't encode unknown schemas, because it's likely that we encode // something we shouldn't (e.g. `skype:name` treated as `skype:host`) // $is = false; foreach (self::RECODE_HOSTNAME_FOR as &$v) { if( ($is = $v === $parsed->protocol) ) break; } if (empty($parsed->protocol) || $is) { try { $parsed->hostname = $this->punycode->toASCII($parsed->hostname); } catch (\Exception $e) { /**/ } } } return $this->mdurl->encode($this->mdurl->format($parsed)); }
php
public function normalizeLink($url) { if( property_exists($this,'normalizeLink') && is_callable($this->normalizeLink)){ $fn = $this->normalizeLink; return $fn($url); } $parsed = $this->mdurl->parse($url, true); if ($parsed->hostname) { // Encode hostnames in urls like: // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` // // We don't encode unknown schemas, because it's likely that we encode // something we shouldn't (e.g. `skype:name` treated as `skype:host`) // $is = false; foreach (self::RECODE_HOSTNAME_FOR as &$v) { if( ($is = $v === $parsed->protocol) ) break; } if (empty($parsed->protocol) || $is) { try { $parsed->hostname = $this->punycode->toASCII($parsed->hostname); } catch (\Exception $e) { /**/ } } } return $this->mdurl->encode($this->mdurl->format($parsed)); }
[ "public", "function", "normalizeLink", "(", "$", "url", ")", "{", "if", "(", "property_exists", "(", "$", "this", ",", "'normalizeLink'", ")", "&&", "is_callable", "(", "$", "this", "->", "normalizeLink", ")", ")", "{", "$", "fn", "=", "$", "this", "->...
Function used to encode link url to a machine-readable format, which includes url-encoding, punycode, etc. @param string $url @return string
[ "Function", "used", "to", "encode", "link", "url", "to", "a", "machine", "-", "readable", "format", "which", "includes", "url", "-", "encoding", "punycode", "etc", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/MarkdownIt.php#L185-L212
41,640
kaoken/markdown-it-php
src/MarkdownIt/MarkdownIt.php
MarkdownIt.enable
public function enable($list, $ignoreInvalid=false) { $result = []; if (!is_array($list)) { $list = [ $list ]; } foreach ([ 'core', 'block', 'inline' ] as &$chain) { if( !property_exists($this,$chain) ) continue; $result = array_merge($result, $this->{$chain}->ruler->enable($list, true)); } $result = array_merge($result, $this->inline->ruler2->enable($list, true) ); $missed = array_filter ($list, function ($name) use(&$result) { return array_search ($name, $result) === false; }); if (count($missed) !== 0 && !$ignoreInvalid) { throw new \Exception('MarkdownIt. Failed to enable unknown rule(s): ' . implode(', ', $missed)); } return $this; }
php
public function enable($list, $ignoreInvalid=false) { $result = []; if (!is_array($list)) { $list = [ $list ]; } foreach ([ 'core', 'block', 'inline' ] as &$chain) { if( !property_exists($this,$chain) ) continue; $result = array_merge($result, $this->{$chain}->ruler->enable($list, true)); } $result = array_merge($result, $this->inline->ruler2->enable($list, true) ); $missed = array_filter ($list, function ($name) use(&$result) { return array_search ($name, $result) === false; }); if (count($missed) !== 0 && !$ignoreInvalid) { throw new \Exception('MarkdownIt. Failed to enable unknown rule(s): ' . implode(', ', $missed)); } return $this; }
[ "public", "function", "enable", "(", "$", "list", ",", "$", "ignoreInvalid", "=", "false", ")", "{", "$", "result", "=", "[", "]", ";", "if", "(", "!", "is_array", "(", "$", "list", ")", ")", "{", "$", "list", "=", "[", "$", "list", "]", ";", ...
chainable Enable list or rules. It will automatically find appropriate components, containing rules with given names. If rule not found, and `ignoreInvalid` not set - throws exception. ##### Example ```PHP $md = new MarkdownIt(); $md->enable(['sub', 'sup']) ->disable('smartquotes'); ``` @param string|array $list rule name or list of rule names to enable @param boolean $ignoreInvalid set `true` to ignore errors when rule not found. @return $this
[ "chainable", "Enable", "list", "or", "rules", ".", "It", "will", "automatically", "find", "appropriate", "components", "containing", "rules", "with", "given", "names", ".", "If", "rule", "not", "found", "and", "ignoreInvalid", "not", "set", "-", "throws", "exc...
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/MarkdownIt.php#L458-L479
41,641
kaoken/markdown-it-php
src/MarkdownIt/Ruler.php
Ruler.at
public function at($name, $entity, $options=null) { $index = $this->__find__($name); if( is_object($options) ) $opt = $options; else $opt = is_array($options) ? (object)$options : new \stdClass(); if ($index === -1) { throw new \Exception('Parser rule not found: ' . $name); } $this->__rules__[$index]->setEntity($entity); $this->__rules__[$index]->alt = isset($opt->alt) ? $opt->alt : []; $this->__cache__ = null; }
php
public function at($name, $entity, $options=null) { $index = $this->__find__($name); if( is_object($options) ) $opt = $options; else $opt = is_array($options) ? (object)$options : new \stdClass(); if ($index === -1) { throw new \Exception('Parser rule not found: ' . $name); } $this->__rules__[$index]->setEntity($entity); $this->__rules__[$index]->alt = isset($opt->alt) ? $opt->alt : []; $this->__cache__ = null; }
[ "public", "function", "at", "(", "$", "name", ",", "$", "entity", ",", "$", "options", "=", "null", ")", "{", "$", "index", "=", "$", "this", "->", "__find__", "(", "$", "name", ")", ";", "if", "(", "is_object", "(", "$", "options", ")", ")", "...
Replace rule by name with new function & options. Throws error if name not found. ##### Options: - __alt__ - array with names of "alternate" chains. ##### Example Replace existing typographer replacement rule with new one: ```PHP class Instance{ public property($state){...} } $md = new Mmarkdown-It(); $md->core->ruler->at('replacements', [new Instance(), 'property']); // or $md->core->ruler->at('replacements', function replace($state) { //... }); ``` @param string $name rule name to replace. @param callable|array $entity new rule function or instance. @param object $options new rule options (not mandatory).
[ "Replace", "rule", "by", "name", "with", "new", "function", "&", "options", ".", "Throws", "error", "if", "name", "not", "found", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Ruler.php#L125-L136
41,642
kaoken/markdown-it-php
src/MarkdownIt/Ruler.php
Ruler.enable
public function enable($list, $ignoreInvalid=false) { if (!is_array($list)) { $list = [ $list ]; } $result = []; // Search by $name and enable foreach ($list as &$name){ $idx = $this->__find__($name); if ($idx < 0) { if ($ignoreInvalid) continue; throw new \Exception("Rules manager: invalid rule name '{$name}''"); } $this->__rules__[$idx]->enabled = true; $result[] = $name; } $this->__cache__ = null; return $result; }
php
public function enable($list, $ignoreInvalid=false) { if (!is_array($list)) { $list = [ $list ]; } $result = []; // Search by $name and enable foreach ($list as &$name){ $idx = $this->__find__($name); if ($idx < 0) { if ($ignoreInvalid) continue; throw new \Exception("Rules manager: invalid rule name '{$name}''"); } $this->__rules__[$idx]->enabled = true; $result[] = $name; } $this->__cache__ = null; return $result; }
[ "public", "function", "enable", "(", "$", "list", ",", "$", "ignoreInvalid", "=", "false", ")", "{", "if", "(", "!", "is_array", "(", "$", "list", ")", ")", "{", "$", "list", "=", "[", "$", "list", "]", ";", "}", "$", "result", "=", "[", "]", ...
Enable rules with given names. If any rule name not found - throw Error. Errors can be disabled by second param. Returns list of found rule names (if no exception happened). See also [[Ruler.disable]], [[Ruler.enableOnly]]. @param string|array $list list of rule names to enable. @param boolean $ignoreInvalid set `true` to ignore errors when $rule not found. @return array
[ "Enable", "rules", "with", "given", "names", ".", "If", "any", "rule", "name", "not", "found", "-", "throw", "Error", ".", "Errors", "can", "be", "disabled", "by", "second", "param", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Ruler.php#L291-L311
41,643
kaoken/markdown-it-php
src/MarkdownIt/Ruler.php
Ruler.enableOnly
public function enableOnly($list, $ignoreInvalid=false) { if (!is_array($list)) { $list = [ $list ]; } foreach ($this->__rules__ as &$rule) { $rule->enabled = false; } $this->enable($list, $ignoreInvalid); }
php
public function enableOnly($list, $ignoreInvalid=false) { if (!is_array($list)) { $list = [ $list ]; } foreach ($this->__rules__ as &$rule) { $rule->enabled = false; } $this->enable($list, $ignoreInvalid); }
[ "public", "function", "enableOnly", "(", "$", "list", ",", "$", "ignoreInvalid", "=", "false", ")", "{", "if", "(", "!", "is_array", "(", "$", "list", ")", ")", "{", "$", "list", "=", "[", "$", "list", "]", ";", "}", "foreach", "(", "$", "this", ...
Enable rules with given names, and disable everything else. If any rule name not found - throw Error. Errors can be disabled by second param. See also [[Ruler.disable]], [[Ruler.enable]]. @param array|string $list list of rule names to enable (whitelist). @param bool $ignoreInvalid set `true` to ignore errors when $rule not found.
[ "Enable", "rules", "with", "given", "names", "and", "disable", "everything", "else", ".", "If", "any", "rule", "name", "not", "found", "-", "throw", "Error", ".", "Errors", "can", "be", "disabled", "by", "second", "param", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Ruler.php#L322-L331
41,644
kaoken/markdown-it-php
src/MarkdownIt/Common/Utils.php
Utils.arrayReplaceAt
public function arrayReplaceAt($src, $pos, $newElements) { if(empty($newElements))$newElements=[]; return array_merge(array_slice($src, 0, $pos), $newElements, array_slice($src, $pos + 1)); }
php
public function arrayReplaceAt($src, $pos, $newElements) { if(empty($newElements))$newElements=[]; return array_merge(array_slice($src, 0, $pos), $newElements, array_slice($src, $pos + 1)); }
[ "public", "function", "arrayReplaceAt", "(", "$", "src", ",", "$", "pos", ",", "$", "newElements", ")", "{", "if", "(", "empty", "(", "$", "newElements", ")", ")", "$", "newElements", "=", "[", "]", ";", "return", "array_merge", "(", "array_slice", "("...
Remove element from array and put another array at those position. Useful for some operations with tokens @param array $src @param integer $pos @param array $newElements @return array
[ "Remove", "element", "from", "array", "and", "put", "another", "array", "at", "those", "position", ".", "Useful", "for", "some", "operations", "with", "tokens" ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Common/Utils.php#L131-L135
41,645
kaoken/markdown-it-php
src/MarkdownIt/Common/Utils.php
Utils.fromCodePoint
public function fromCodePoint($c) { if ($c < 0x7F) // U+0000-U+007F - 1 byte return chr($c); if ($c < 0x7FF) // U+0080-U+07FF - 2 bytes return chr(0xC0 | ($c >> 6)) . chr(0x80 | ($c & 0x3F)); if ($c < 0xFFFF) // U+0800-U+FFFF - 3 bytes return chr(0xE0 | ($c >> 12)) . chr(0x80 | (($c >> 6) & 0x3F)) . chr(0x80 | ($c & 0x3F)); // U+010000-U+10FFFF - 4 bytes return chr(0xF0 | ($c >> 18)) . chr(0x80 | ($c >> 12) & 0x3F) .chr(0x80 | (($c >> 6) & 0x3F)) . chr(0x80 | ($c & 0x3F)); }
php
public function fromCodePoint($c) { if ($c < 0x7F) // U+0000-U+007F - 1 byte return chr($c); if ($c < 0x7FF) // U+0080-U+07FF - 2 bytes return chr(0xC0 | ($c >> 6)) . chr(0x80 | ($c & 0x3F)); if ($c < 0xFFFF) // U+0800-U+FFFF - 3 bytes return chr(0xE0 | ($c >> 12)) . chr(0x80 | (($c >> 6) & 0x3F)) . chr(0x80 | ($c & 0x3F)); // U+010000-U+10FFFF - 4 bytes return chr(0xF0 | ($c >> 18)) . chr(0x80 | ($c >> 12) & 0x3F) .chr(0x80 | (($c >> 6) & 0x3F)) . chr(0x80 | ($c & 0x3F)); }
[ "public", "function", "fromCodePoint", "(", "$", "c", ")", "{", "if", "(", "$", "c", "<", "0x7F", ")", "// U+0000-U+007F - 1 byte", "return", "chr", "(", "$", "c", ")", ";", "if", "(", "$", "c", "<", "0x7FF", ")", "// U+0080-U+07FF - 2 bytes", "return", ...
UTF16 -> UTF8 @param integer $c @return string
[ "UTF16", "-", ">", "UTF8" ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Common/Utils.php#L178-L188
41,646
kaoken/markdown-it-php
src/MarkdownIt/Common/Utils.php
Utils.isMdAsciiPunct
public function isMdAsciiPunct($c) { $code = ord($c); if( ( $code >= 0x21 /* ! */ && $code <= 0x2F /* / */) || ( $code >= 0x3A /* : */ && $code <= 0x40 /* @ */) || ( $code >= 0x5B /* [ */ && $code <= 0x60 /* ` */) || ( $code >= 0x7B /* { */ && $code <= 0x7E /* ~ */) ) return true; return false; }
php
public function isMdAsciiPunct($c) { $code = ord($c); if( ( $code >= 0x21 /* ! */ && $code <= 0x2F /* / */) || ( $code >= 0x3A /* : */ && $code <= 0x40 /* @ */) || ( $code >= 0x5B /* [ */ && $code <= 0x60 /* ` */) || ( $code >= 0x7B /* { */ && $code <= 0x7E /* ~ */) ) return true; return false; }
[ "public", "function", "isMdAsciiPunct", "(", "$", "c", ")", "{", "$", "code", "=", "ord", "(", "$", "c", ")", ";", "if", "(", "(", "$", "code", ">=", "0x21", "/* ! */", "&&", "$", "code", "<=", "0x2F", "/* / */", ")", "||", "(", "$", "code", ">...
Markdown ASCII punctuation characters. !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ @see http://spec.commonmark.org/0.15/#ascii-punctuation-character Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. @param string $c @return bool
[ "Markdown", "ASCII", "punctuation", "characters", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Common/Utils.php#L318-L327
41,647
kaoken/markdown-it-php
src/MarkdownIt/Plugins/MarkdownItForInline.php
MarkdownItForInline.plugin
public function plugin($md, $ruleName, $tokenType, $iteartor) { $scan = function($state) use($md, $ruleName, $tokenType, $iteartor) { for ($blkIdx = count($state->tokens) - 1; $blkIdx >= 0; $blkIdx--) { if ($state->tokens[$blkIdx]->type !== 'inline') { continue; } $inlineTokens = $state->tokens[$blkIdx]->children; for ($i = count($inlineTokens) - 1; $i >= 0; $i--) { if ($inlineTokens[$i]->type !== $tokenType) { continue; } $iteartor($inlineTokens, $i); } } }; $md->core->ruler->push($ruleName, $scan); }
php
public function plugin($md, $ruleName, $tokenType, $iteartor) { $scan = function($state) use($md, $ruleName, $tokenType, $iteartor) { for ($blkIdx = count($state->tokens) - 1; $blkIdx >= 0; $blkIdx--) { if ($state->tokens[$blkIdx]->type !== 'inline') { continue; } $inlineTokens = $state->tokens[$blkIdx]->children; for ($i = count($inlineTokens) - 1; $i >= 0; $i--) { if ($inlineTokens[$i]->type !== $tokenType) { continue; } $iteartor($inlineTokens, $i); } } }; $md->core->ruler->push($ruleName, $scan); }
[ "public", "function", "plugin", "(", "$", "md", ",", "$", "ruleName", ",", "$", "tokenType", ",", "$", "iteartor", ")", "{", "$", "scan", "=", "function", "(", "$", "state", ")", "use", "(", "$", "md", ",", "$", "ruleName", ",", "$", "tokenType", ...
MarkdownItForInline constructor. @param \Kaoken\MarkdownIt\MarkdownIt $md @param string $ruleName @param string $tokenType @param callable $iteartor
[ "MarkdownItForInline", "constructor", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/Plugins/MarkdownItForInline.php#L30-L51
41,648
kaoken/markdown-it-php
src/MarkdownIt/RulesBlock/StateBlock.php
StateBlock.skipSpaces
public function skipSpaces($pos) { for ( $max = strlen ($this->src); $pos < $max; $pos++) { if (!$this->md->utils->isSpace($this->src[$pos])) { break; } } return $pos; }
php
public function skipSpaces($pos) { for ( $max = strlen ($this->src); $pos < $max; $pos++) { if (!$this->md->utils->isSpace($this->src[$pos])) { break; } } return $pos; }
[ "public", "function", "skipSpaces", "(", "$", "pos", ")", "{", "for", "(", "$", "max", "=", "strlen", "(", "$", "this", "->", "src", ")", ";", "$", "pos", "<", "$", "max", ";", "$", "pos", "++", ")", "{", "if", "(", "!", "$", "this", "->", ...
Skip spaces from given position. @param integer $pos @return integer
[ "Skip", "spaces", "from", "given", "position", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/RulesBlock/StateBlock.php#L216-L223
41,649
kaoken/markdown-it-php
src/MarkdownIt/RulesBlock/StateBlock.php
StateBlock.skipSpacesBack
public function skipSpacesBack($pos, $min) { if ($pos <= $min) { return $pos; } while ($pos > $min) { if (!$this->md->utils->isSpace($this->src[--$pos])) { return $pos + 1; } } return $pos; }
php
public function skipSpacesBack($pos, $min) { if ($pos <= $min) { return $pos; } while ($pos > $min) { if (!$this->md->utils->isSpace($this->src[--$pos])) { return $pos + 1; } } return $pos; }
[ "public", "function", "skipSpacesBack", "(", "$", "pos", ",", "$", "min", ")", "{", "if", "(", "$", "pos", "<=", "$", "min", ")", "{", "return", "$", "pos", ";", "}", "while", "(", "$", "pos", ">", "$", "min", ")", "{", "if", "(", "!", "$", ...
Skip spaces from given position in reverse. @param integer $pos @param integer $min @return integer
[ "Skip", "spaces", "from", "given", "position", "in", "reverse", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/RulesBlock/StateBlock.php#L231-L240
41,650
kaoken/markdown-it-php
src/MarkdownIt/RulesBlock/StateBlock.php
StateBlock.skipChars
public function skipChars($pos, $code) { for ($max = strlen ($this->src); $pos < $max; $pos++) { if ($this->src[$pos] !== $code) { break; } } return $pos; }
php
public function skipChars($pos, $code) { for ($max = strlen ($this->src); $pos < $max; $pos++) { if ($this->src[$pos] !== $code) { break; } } return $pos; }
[ "public", "function", "skipChars", "(", "$", "pos", ",", "$", "code", ")", "{", "for", "(", "$", "max", "=", "strlen", "(", "$", "this", "->", "src", ")", ";", "$", "pos", "<", "$", "max", ";", "$", "pos", "++", ")", "{", "if", "(", "$", "t...
Skip char codes from given position @param integer $pos @param string $code @return integer
[ "Skip", "char", "codes", "from", "given", "position" ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/RulesBlock/StateBlock.php#L248-L254
41,651
kaoken/markdown-it-php
src/MarkdownIt/RulesBlock/StateBlock.php
StateBlock.skipCharsBack
public function skipCharsBack($pos, $code, $min) { if ($pos <= $min) { return $pos; } while ($pos > $min) { if ($code !== $this->src[--$pos]) { return $pos + 1; } } return $pos; }
php
public function skipCharsBack($pos, $code, $min) { if ($pos <= $min) { return $pos; } while ($pos > $min) { if ($code !== $this->src[--$pos]) { return $pos + 1; } } return $pos; }
[ "public", "function", "skipCharsBack", "(", "$", "pos", ",", "$", "code", ",", "$", "min", ")", "{", "if", "(", "$", "pos", "<=", "$", "min", ")", "{", "return", "$", "pos", ";", "}", "while", "(", "$", "pos", ">", "$", "min", ")", "{", "if",...
Skip char codes reverse from given position - 1 @param integer $pos @param string $code @param integer $min @return integer
[ "Skip", "char", "codes", "reverse", "from", "given", "position", "-", "1" ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/RulesBlock/StateBlock.php#L263-L271
41,652
kaoken/markdown-it-php
src/MarkdownIt/RulesBlock/StateBlock.php
StateBlock.getLines
public function getLines($begin, $end, $indent, $keepLastLF) { $line = $begin; if ($begin >= $end) { return ''; } $queue =array_fill(0, $end - $begin, ''); for ($i = 0; $line < $end; $line++, $i++) { $lineIndent = 0; $lineStart = $first = $this->bMarks[$line]; if ($line + 1 < $end || $keepLastLF) { // No need for bounds check because we have fake entry on tail. $last = $this->eMarks[$line] + 1; } else { $last = $this->eMarks[$line]; } while ($first < $last && $lineIndent < $indent) { $ch = $this->src[$first]; if ($this->md->utils->isSpace($ch)) { if ($ch === "\t") { $lineIndent += 4 - ($lineIndent + $this->bsCount[$line]) % 4; } else { $lineIndent++; } } else if ($first - $lineStart < $this->tShift[$line]) { // patched tShift masked characters to look like spaces (blockquotes, list markers) $lineIndent++; } else { break; } $first++; } if ($lineIndent > $indent) { // partially expanding tabs in code blocks, e.g '\t\tfoobar' // with indent=2 becomes ' \tfoobar' $queue[$i] = str_repeat(' ', $lineIndent - $indent) . substr($this->src, $first, $last-$first); } else { $queue[$i] = substr($this->src, $first, $last-$first); } } return join('',$queue); }
php
public function getLines($begin, $end, $indent, $keepLastLF) { $line = $begin; if ($begin >= $end) { return ''; } $queue =array_fill(0, $end - $begin, ''); for ($i = 0; $line < $end; $line++, $i++) { $lineIndent = 0; $lineStart = $first = $this->bMarks[$line]; if ($line + 1 < $end || $keepLastLF) { // No need for bounds check because we have fake entry on tail. $last = $this->eMarks[$line] + 1; } else { $last = $this->eMarks[$line]; } while ($first < $last && $lineIndent < $indent) { $ch = $this->src[$first]; if ($this->md->utils->isSpace($ch)) { if ($ch === "\t") { $lineIndent += 4 - ($lineIndent + $this->bsCount[$line]) % 4; } else { $lineIndent++; } } else if ($first - $lineStart < $this->tShift[$line]) { // patched tShift masked characters to look like spaces (blockquotes, list markers) $lineIndent++; } else { break; } $first++; } if ($lineIndent > $indent) { // partially expanding tabs in code blocks, e.g '\t\tfoobar' // with indent=2 becomes ' \tfoobar' $queue[$i] = str_repeat(' ', $lineIndent - $indent) . substr($this->src, $first, $last-$first); } else { $queue[$i] = substr($this->src, $first, $last-$first); } } return join('',$queue); }
[ "public", "function", "getLines", "(", "$", "begin", ",", "$", "end", ",", "$", "indent", ",", "$", "keepLastLF", ")", "{", "$", "line", "=", "$", "begin", ";", "if", "(", "$", "begin", ">=", "$", "end", ")", "{", "return", "''", ";", "}", "$",...
cut lines range from source. @param integer $begin @param integer $end @param integer $indent @param boolean $keepLastLF @return string
[ "cut", "lines", "range", "from", "source", "." ]
ec41aa6d5d700ddeea6819ead10cfbde19d51f8f
https://github.com/kaoken/markdown-it-php/blob/ec41aa6d5d700ddeea6819ead10cfbde19d51f8f/src/MarkdownIt/RulesBlock/StateBlock.php#L281-L332
41,653
boldenamsterdam/htmlcache
src/services/HtmlcacheService.php
HtmlcacheService.checkForCacheFile
public function checkForCacheFile() { // first check if we can create a file if (!$this->canCreateCacheFile()) { return; } $cacheEntry = HtmlCacheCache::findOne(['uri' => $this->uri, 'siteId' => $this->siteId]); // check if cache exists if ($cacheEntry) { $file = $this->getCacheFileName($cacheEntry->uid); if (file_exists($file)) { // load cache - may return false if cache has expired if ($this->loadCache($file)) { return \Craft::$app->end(); } } } // Turn output buffering on ob_start(); }
php
public function checkForCacheFile() { // first check if we can create a file if (!$this->canCreateCacheFile()) { return; } $cacheEntry = HtmlCacheCache::findOne(['uri' => $this->uri, 'siteId' => $this->siteId]); // check if cache exists if ($cacheEntry) { $file = $this->getCacheFileName($cacheEntry->uid); if (file_exists($file)) { // load cache - may return false if cache has expired if ($this->loadCache($file)) { return \Craft::$app->end(); } } } // Turn output buffering on ob_start(); }
[ "public", "function", "checkForCacheFile", "(", ")", "{", "// first check if we can create a file\r", "if", "(", "!", "$", "this", "->", "canCreateCacheFile", "(", ")", ")", "{", "return", ";", "}", "$", "cacheEntry", "=", "HtmlCacheCache", "::", "findOne", "(",...
Check if cache file exists @return void
[ "Check", "if", "cache", "file", "exists" ]
6c9ff585e5fea99929b029c0fdd27ab52619d035
https://github.com/boldenamsterdam/htmlcache/blob/6c9ff585e5fea99929b029c0fdd27ab52619d035/src/services/HtmlcacheService.php#L51-L71
41,654
boldenamsterdam/htmlcache
src/services/HtmlcacheService.php
HtmlcacheService.canCreateCacheFile
public function canCreateCacheFile() { // Skip if we're running in devMode and not in force mode if (\Craft::$app->config->general->devMode === true && $this->settings->forceOn == false) { return false; } // skip if not enabled if ($this->settings->enableGeneral == false) { return false; } // Skip if system is not on and not in force mode if (!\Craft::$app->getIsSystemOn() && $this->settings->forceOn == false) { return false; } // Skip if it's a CP Request if (\Craft::$app->request->getIsCpRequest()) { return false; } // Skip if it's an action Request if (\Craft::$app->request->getIsActionRequest()) { return false; } // Skip if it's a preview request if (\Craft::$app->request->getIsLivePreview()) { return false; } // Skip if it's a post request if (!\Craft::$app->request->getIsGet()) { return false; } // Skip if it's an ajax request if (\Craft::$app->request->getIsAjax()) { return false; } // Skip if route from element api if ($this->isElementApiRoute()) { return false; } // Skip if currently requested URL path is excluded if ($this->isPathExcluded()) { return false; } return true; }
php
public function canCreateCacheFile() { // Skip if we're running in devMode and not in force mode if (\Craft::$app->config->general->devMode === true && $this->settings->forceOn == false) { return false; } // skip if not enabled if ($this->settings->enableGeneral == false) { return false; } // Skip if system is not on and not in force mode if (!\Craft::$app->getIsSystemOn() && $this->settings->forceOn == false) { return false; } // Skip if it's a CP Request if (\Craft::$app->request->getIsCpRequest()) { return false; } // Skip if it's an action Request if (\Craft::$app->request->getIsActionRequest()) { return false; } // Skip if it's a preview request if (\Craft::$app->request->getIsLivePreview()) { return false; } // Skip if it's a post request if (!\Craft::$app->request->getIsGet()) { return false; } // Skip if it's an ajax request if (\Craft::$app->request->getIsAjax()) { return false; } // Skip if route from element api if ($this->isElementApiRoute()) { return false; } // Skip if currently requested URL path is excluded if ($this->isPathExcluded()) { return false; } return true; }
[ "public", "function", "canCreateCacheFile", "(", ")", "{", "// Skip if we're running in devMode and not in force mode\r", "if", "(", "\\", "Craft", "::", "$", "app", "->", "config", "->", "general", "->", "devMode", "===", "true", "&&", "$", "this", "->", "setting...
Check if creation of file is allowed @return boolean
[ "Check", "if", "creation", "of", "file", "is", "allowed" ]
6c9ff585e5fea99929b029c0fdd27ab52619d035
https://github.com/boldenamsterdam/htmlcache/blob/6c9ff585e5fea99929b029c0fdd27ab52619d035/src/services/HtmlcacheService.php#L78-L127
41,655
boldenamsterdam/htmlcache
src/services/HtmlcacheService.php
HtmlcacheService.isElementApiRoute
private function isElementApiRoute() { $plugin = \Craft::$app->getPlugins()->getPlugin('element-api'); if ($plugin) { $elementApiRoutes = $plugin->getSettings()->endpoints; $routes = array_keys($elementApiRoutes); foreach ($routes as $route) { // form the correct expression $route = preg_replace('~\<.*?:(.*?)\>~', '$1', $route); $found = preg_match('~' . $route . '~', $this->uri); if ($found) { return true; } } } return false; }
php
private function isElementApiRoute() { $plugin = \Craft::$app->getPlugins()->getPlugin('element-api'); if ($plugin) { $elementApiRoutes = $plugin->getSettings()->endpoints; $routes = array_keys($elementApiRoutes); foreach ($routes as $route) { // form the correct expression $route = preg_replace('~\<.*?:(.*?)\>~', '$1', $route); $found = preg_match('~' . $route . '~', $this->uri); if ($found) { return true; } } } return false; }
[ "private", "function", "isElementApiRoute", "(", ")", "{", "$", "plugin", "=", "\\", "Craft", "::", "$", "app", "->", "getPlugins", "(", ")", "->", "getPlugin", "(", "'element-api'", ")", ";", "if", "(", "$", "plugin", ")", "{", "$", "elementApiRoutes", ...
Check if route is from element api @return boolean
[ "Check", "if", "route", "is", "from", "element", "api" ]
6c9ff585e5fea99929b029c0fdd27ab52619d035
https://github.com/boldenamsterdam/htmlcache/blob/6c9ff585e5fea99929b029c0fdd27ab52619d035/src/services/HtmlcacheService.php#L134-L150
41,656
boldenamsterdam/htmlcache
src/services/HtmlcacheService.php
HtmlcacheService.isPathExcluded
private function isPathExcluded() { // determine currently requested URL path and the multi-site ID $requestedPath = \Craft::$app->request->getFullPath(); $requestedSiteId = \Craft::$app->getSites()->getCurrentSite()->id; // compare with excluded paths and sites from the settings if (!empty($this->settings->excludedUrlPaths)) { foreach ($this->settings->excludedUrlPaths as $exclude) { $path = reset($exclude); $siteId = intval(next($exclude)); // check if requested path is one of those of the settings if ($requestedPath == $path || preg_match('@' . $path . '@', $requestedPath)) { // and if requested site either corresponds to the exclude setting or if it's unimportant at all if ($requestedSiteId == $siteId || $siteId < 0) { return true; } } } } return false; }
php
private function isPathExcluded() { // determine currently requested URL path and the multi-site ID $requestedPath = \Craft::$app->request->getFullPath(); $requestedSiteId = \Craft::$app->getSites()->getCurrentSite()->id; // compare with excluded paths and sites from the settings if (!empty($this->settings->excludedUrlPaths)) { foreach ($this->settings->excludedUrlPaths as $exclude) { $path = reset($exclude); $siteId = intval(next($exclude)); // check if requested path is one of those of the settings if ($requestedPath == $path || preg_match('@' . $path . '@', $requestedPath)) { // and if requested site either corresponds to the exclude setting or if it's unimportant at all if ($requestedSiteId == $siteId || $siteId < 0) { return true; } } } } return false; }
[ "private", "function", "isPathExcluded", "(", ")", "{", "// determine currently requested URL path and the multi-site ID\r", "$", "requestedPath", "=", "\\", "Craft", "::", "$", "app", "->", "request", "->", "getFullPath", "(", ")", ";", "$", "requestedSiteId", "=", ...
Check if currently requested URL path has been added to list of excluded paths @return bool
[ "Check", "if", "currently", "requested", "URL", "path", "has", "been", "added", "to", "list", "of", "excluded", "paths" ]
6c9ff585e5fea99929b029c0fdd27ab52619d035
https://github.com/boldenamsterdam/htmlcache/blob/6c9ff585e5fea99929b029c0fdd27ab52619d035/src/services/HtmlcacheService.php#L157-L180
41,657
boldenamsterdam/htmlcache
src/services/HtmlcacheService.php
HtmlcacheService.createCacheFile
public function createCacheFile() { // check if valid to create the file if ($this->canCreateCacheFile() && http_response_code() == 200) { $cacheEntry = HtmlCacheCache::findOne(['uri' => $this->uri, 'siteId' => $this->siteId]); // check if entry exists and start capturing content if ($cacheEntry) { $content = ob_get_contents(); if($this->settings->optimizeContent){ $content = implode("\n", array_map('trim', explode("\n", $content))); } $file = $this->getCacheFileName($cacheEntry->uid); $fp = fopen($file, 'w+'); if ($fp) { fwrite($fp, $content); fclose($fp); } else { \Craft::info('HTML Cache could not write cache file "' . $file . '"'); } } else { \Craft::info('HTML Cache could not find cache entry for siteId: "' . $this->siteId . '" and uri: "' . $this->uri . '"'); } } }
php
public function createCacheFile() { // check if valid to create the file if ($this->canCreateCacheFile() && http_response_code() == 200) { $cacheEntry = HtmlCacheCache::findOne(['uri' => $this->uri, 'siteId' => $this->siteId]); // check if entry exists and start capturing content if ($cacheEntry) { $content = ob_get_contents(); if($this->settings->optimizeContent){ $content = implode("\n", array_map('trim', explode("\n", $content))); } $file = $this->getCacheFileName($cacheEntry->uid); $fp = fopen($file, 'w+'); if ($fp) { fwrite($fp, $content); fclose($fp); } else { \Craft::info('HTML Cache could not write cache file "' . $file . '"'); } } else { \Craft::info('HTML Cache could not find cache entry for siteId: "' . $this->siteId . '" and uri: "' . $this->uri . '"'); } } }
[ "public", "function", "createCacheFile", "(", ")", "{", "// check if valid to create the file\r", "if", "(", "$", "this", "->", "canCreateCacheFile", "(", ")", "&&", "http_response_code", "(", ")", "==", "200", ")", "{", "$", "cacheEntry", "=", "HtmlCacheCache", ...
Create the cache file @return void
[ "Create", "the", "cache", "file" ]
6c9ff585e5fea99929b029c0fdd27ab52619d035
https://github.com/boldenamsterdam/htmlcache/blob/6c9ff585e5fea99929b029c0fdd27ab52619d035/src/services/HtmlcacheService.php#L187-L210
41,658
boldenamsterdam/htmlcache
src/services/HtmlcacheService.php
HtmlcacheService.clearCacheFile
public function clearCacheFile($elementId) { // get all possible caches $elements = HtmlCacheElement::findAll(['elementId' => $elementId]); // \craft::Dd($elements); $cacheIds = array_map(function ($el) { return $el->cacheId; }, $elements); // get all possible caches $caches = HtmlCacheCache::findAll(['id' => $cacheIds]); foreach ($caches as $cache) { $file = $this->getCacheFileName($cache->uid); if (file_exists($file)) { @unlink($file); } } // delete caches for related entry HtmlCacheCache::deleteAll(['id' => $cacheIds]); return true; }
php
public function clearCacheFile($elementId) { // get all possible caches $elements = HtmlCacheElement::findAll(['elementId' => $elementId]); // \craft::Dd($elements); $cacheIds = array_map(function ($el) { return $el->cacheId; }, $elements); // get all possible caches $caches = HtmlCacheCache::findAll(['id' => $cacheIds]); foreach ($caches as $cache) { $file = $this->getCacheFileName($cache->uid); if (file_exists($file)) { @unlink($file); } } // delete caches for related entry HtmlCacheCache::deleteAll(['id' => $cacheIds]); return true; }
[ "public", "function", "clearCacheFile", "(", "$", "elementId", ")", "{", "// get all possible caches\r", "$", "elements", "=", "HtmlCacheElement", "::", "findAll", "(", "[", "'elementId'", "=>", "$", "elementId", "]", ")", ";", "// \\craft::Dd($elements);\r", "$", ...
clear cache for given elementId @param integer $elementId @return boolean
[ "clear", "cache", "for", "given", "elementId" ]
6c9ff585e5fea99929b029c0fdd27ab52619d035
https://github.com/boldenamsterdam/htmlcache/blob/6c9ff585e5fea99929b029c0fdd27ab52619d035/src/services/HtmlcacheService.php#L218-L240
41,659
boldenamsterdam/htmlcache
src/services/HtmlcacheService.php
HtmlcacheService.getDirectory
private function getDirectory() { // Fallback to default directory if no storage path defined if (defined('CRAFT_STORAGE_PATH')) { $basePath = CRAFT_STORAGE_PATH; } else { $basePath = CRAFT_BASE_PATH . DIRECTORY_SEPARATOR . 'storage'; } return $basePath . DIRECTORY_SEPARATOR . 'runtime' . DIRECTORY_SEPARATOR . 'htmlcache' . DIRECTORY_SEPARATOR; }
php
private function getDirectory() { // Fallback to default directory if no storage path defined if (defined('CRAFT_STORAGE_PATH')) { $basePath = CRAFT_STORAGE_PATH; } else { $basePath = CRAFT_BASE_PATH . DIRECTORY_SEPARATOR . 'storage'; } return $basePath . DIRECTORY_SEPARATOR . 'runtime' . DIRECTORY_SEPARATOR . 'htmlcache' . DIRECTORY_SEPARATOR; }
[ "private", "function", "getDirectory", "(", ")", "{", "// Fallback to default directory if no storage path defined\r", "if", "(", "defined", "(", "'CRAFT_STORAGE_PATH'", ")", ")", "{", "$", "basePath", "=", "CRAFT_STORAGE_PATH", ";", "}", "else", "{", "$", "basePath",...
Get the directory path @return string
[ "Get", "the", "directory", "path" ]
6c9ff585e5fea99929b029c0fdd27ab52619d035
https://github.com/boldenamsterdam/htmlcache/blob/6c9ff585e5fea99929b029c0fdd27ab52619d035/src/services/HtmlcacheService.php#L269-L279
41,660
boldenamsterdam/htmlcache
src/services/HtmlcacheService.php
HtmlcacheService.loadCache
private function loadCache($file) { if (file_exists($settingsFile = $this->getDirectory() . 'settings.json')) { $settings = json_decode(file_get_contents($settingsFile), true); } elseif (!empty($this->settings->cacheDuration)) { $settings = ['cacheDuration' => $this->settings->cacheDuration]; } else { $settings = ['cacheDuration' => 3600]; } if (time() - ($fmt = filemtime($file)) >= $settings['cacheDuration']) { unlink($file); return false; } \Craft::$app->response->data = file_get_contents($file); return true; }
php
private function loadCache($file) { if (file_exists($settingsFile = $this->getDirectory() . 'settings.json')) { $settings = json_decode(file_get_contents($settingsFile), true); } elseif (!empty($this->settings->cacheDuration)) { $settings = ['cacheDuration' => $this->settings->cacheDuration]; } else { $settings = ['cacheDuration' => 3600]; } if (time() - ($fmt = filemtime($file)) >= $settings['cacheDuration']) { unlink($file); return false; } \Craft::$app->response->data = file_get_contents($file); return true; }
[ "private", "function", "loadCache", "(", "$", "file", ")", "{", "if", "(", "file_exists", "(", "$", "settingsFile", "=", "$", "this", "->", "getDirectory", "(", ")", ".", "'settings.json'", ")", ")", "{", "$", "settings", "=", "json_decode", "(", "file_g...
Check cache and return it if exists @param string $file @return mixed
[ "Check", "cache", "and", "return", "it", "if", "exists" ]
6c9ff585e5fea99929b029c0fdd27ab52619d035
https://github.com/boldenamsterdam/htmlcache/blob/6c9ff585e5fea99929b029c0fdd27ab52619d035/src/services/HtmlcacheService.php#L287-L302
41,661
mister-bk/craft-plugin-mix
src/twigextensions/MixTwigExtension.php
MixTwigExtension.mix
public function mix($file, $tag = false, $inline = false) { if ($tag) { return Mix::$plugin->mix->withTag($file, $inline); } return Mix::$plugin->mix->version($file); }
php
public function mix($file, $tag = false, $inline = false) { if ($tag) { return Mix::$plugin->mix->withTag($file, $inline); } return Mix::$plugin->mix->version($file); }
[ "public", "function", "mix", "(", "$", "file", ",", "$", "tag", "=", "false", ",", "$", "inline", "=", "false", ")", "{", "if", "(", "$", "tag", ")", "{", "return", "Mix", "::", "$", "plugin", "->", "mix", "->", "withTag", "(", "$", "file", ","...
Returns versioned file or the entire tag. @param string $file @param bool $tag (optional) @param bool $inline (optional) @return string
[ "Returns", "versioned", "file", "or", "the", "entire", "tag", "." ]
bf2a66a6a993be46ba43a719971ec99b2d2db827
https://github.com/mister-bk/craft-plugin-mix/blob/bf2a66a6a993be46ba43a719971ec99b2d2db827/src/twigextensions/MixTwigExtension.php#L56-L63
41,662
BeatSwitch/lock
stubs/FalseConditionStub.php
FalseConditionStub.assert
public function assert(Lock $lock, Permission $permission, $action, Resource $resource = null) { return false; }
php
public function assert(Lock $lock, Permission $permission, $action, Resource $resource = null) { return false; }
[ "public", "function", "assert", "(", "Lock", "$", "lock", ",", "Permission", "$", "permission", ",", "$", "action", ",", "Resource", "$", "resource", "=", "null", ")", "{", "return", "false", ";", "}" ]
Assert if the condition is correct @param \BeatSwitch\Lock\Lock $lock @param \BeatSwitch\Lock\Permissions\Permission $permission @param string $action @param \BeatSwitch\Lock\Resources\Resource|null $resource @return bool
[ "Assert", "if", "the", "condition", "is", "correct" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/stubs/FalseConditionStub.php#L20-L23
41,663
BeatSwitch/lock
src/Roles/RoleLock.php
RoleLock.getInheritedRolePermissions
public function getInheritedRolePermissions(Role $role) { $permissions = $this->getPermissionsForRole($role); if ($inheritedRole = $role->getInheritedRole()) { if ($inheritedRole = $this->manager->convertRoleToObject($inheritedRole)) { $permissions = array_merge($permissions, $this->getInheritedRolePermissions($inheritedRole)); } } return $permissions; }
php
public function getInheritedRolePermissions(Role $role) { $permissions = $this->getPermissionsForRole($role); if ($inheritedRole = $role->getInheritedRole()) { if ($inheritedRole = $this->manager->convertRoleToObject($inheritedRole)) { $permissions = array_merge($permissions, $this->getInheritedRolePermissions($inheritedRole)); } } return $permissions; }
[ "public", "function", "getInheritedRolePermissions", "(", "Role", "$", "role", ")", "{", "$", "permissions", "=", "$", "this", "->", "getPermissionsForRole", "(", "$", "role", ")", ";", "if", "(", "$", "inheritedRole", "=", "$", "role", "->", "getInheritedRo...
Returns all the permissions for a role and their inherited roles @param \BeatSwitch\Lock\Roles\Role $role @return \BeatSwitch\Lock\Permissions\Permission[]
[ "Returns", "all", "the", "permissions", "for", "a", "role", "and", "their", "inherited", "roles" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Roles/RoleLock.php#L108-L119
41,664
BeatSwitch/lock
src/Permissions/AbstractPermission.php
AbstractPermission.matchesPermission
public function matchesPermission(Permission $permission) { return ( $this instanceof $permission && $this->action === $permission->getAction() && // Not using matchesAction to avoid the wildcard $this->matchesResource($permission->getResource()) ); }
php
public function matchesPermission(Permission $permission) { return ( $this instanceof $permission && $this->action === $permission->getAction() && // Not using matchesAction to avoid the wildcard $this->matchesResource($permission->getResource()) ); }
[ "public", "function", "matchesPermission", "(", "Permission", "$", "permission", ")", "{", "return", "(", "$", "this", "instanceof", "$", "permission", "&&", "$", "this", "->", "action", "===", "$", "permission", "->", "getAction", "(", ")", "&&", "// Not us...
Determine if a permission exactly matches the current instance @param \BeatSwitch\Lock\Permissions\Permission $permission @return bool
[ "Determine", "if", "a", "permission", "exactly", "matches", "the", "current", "instance" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Permissions/AbstractPermission.php#L43-L50
41,665
BeatSwitch/lock
src/Permissions/AbstractPermission.php
AbstractPermission.resolve
protected function resolve(Lock $lock, $action, Resource $resource = null) { // If no resource was set for this permission we'll only need to check the action. if ($this->resource === null || $this->resource->getResourceType() === null) { return $this->matchesAction($action) && $this->resolveConditions($lock, $action, $resource); } return ( $this->matchesAction($action) && $this->matchesResource($resource) && $this->resolveConditions($lock, $action, $resource) ); }
php
protected function resolve(Lock $lock, $action, Resource $resource = null) { // If no resource was set for this permission we'll only need to check the action. if ($this->resource === null || $this->resource->getResourceType() === null) { return $this->matchesAction($action) && $this->resolveConditions($lock, $action, $resource); } return ( $this->matchesAction($action) && $this->matchesResource($resource) && $this->resolveConditions($lock, $action, $resource) ); }
[ "protected", "function", "resolve", "(", "Lock", "$", "lock", ",", "$", "action", ",", "Resource", "$", "resource", "=", "null", ")", "{", "// If no resource was set for this permission we'll only need to check the action.", "if", "(", "$", "this", "->", "resource", ...
Validate a permission against the given params. @param \BeatSwitch\Lock\Lock $lock @param string $action @param \BeatSwitch\Lock\Resources\Resource|null $resource @return bool
[ "Validate", "a", "permission", "against", "the", "given", "params", "." ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Permissions/AbstractPermission.php#L60-L72
41,666
BeatSwitch/lock
src/Permissions/AbstractPermission.php
AbstractPermission.matchesResource
protected function matchesResource(Resource $resource = null) { // If the resource is null we should only return true if the current resource is also null. if ($resource === null) { return $this->getResource() === null || ( $this->getResourceType() === null && $this->getResourceId() === null ); } // If the permission's resource id is null then all resources with a specific ID are accepted. if ($this->getResourceId() === null) { return $this->getResourceType() === $resource->getResourceType(); } // Otherwise make sure that we're matching a specific resource. return ( $this->getResourceType() === $resource->getResourceType() && $this->getResourceId() === $resource->getResourceId() ); }
php
protected function matchesResource(Resource $resource = null) { // If the resource is null we should only return true if the current resource is also null. if ($resource === null) { return $this->getResource() === null || ( $this->getResourceType() === null && $this->getResourceId() === null ); } // If the permission's resource id is null then all resources with a specific ID are accepted. if ($this->getResourceId() === null) { return $this->getResourceType() === $resource->getResourceType(); } // Otherwise make sure that we're matching a specific resource. return ( $this->getResourceType() === $resource->getResourceType() && $this->getResourceId() === $resource->getResourceId() ); }
[ "protected", "function", "matchesResource", "(", "Resource", "$", "resource", "=", "null", ")", "{", "// If the resource is null we should only return true if the current resource is also null.", "if", "(", "$", "resource", "===", "null", ")", "{", "return", "$", "this", ...
Validate the resource @param \BeatSwitch\Lock\Resources\Resource|null $resource @return bool
[ "Validate", "the", "resource" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Permissions/AbstractPermission.php#L91-L110
41,667
BeatSwitch/lock
src/Permissions/AbstractPermission.php
AbstractPermission.setConditions
protected function setConditions($conditions = []) { if ($conditions instanceof Closure || is_array($conditions)) { $this->conditions = $conditions; } else { $this->conditions = [$conditions]; } }
php
protected function setConditions($conditions = []) { if ($conditions instanceof Closure || is_array($conditions)) { $this->conditions = $conditions; } else { $this->conditions = [$conditions]; } }
[ "protected", "function", "setConditions", "(", "$", "conditions", "=", "[", "]", ")", "{", "if", "(", "$", "conditions", "instanceof", "Closure", "||", "is_array", "(", "$", "conditions", ")", ")", "{", "$", "this", "->", "conditions", "=", "$", "conditi...
Sets the conditions for this permission @param \BeatSwitch\Lock\Permissions\Condition|\BeatSwitch\Lock\Permissions\Condition[]|\Closure $conditions
[ "Sets", "the", "conditions", "for", "this", "permission" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Permissions/AbstractPermission.php#L117-L124
41,668
BeatSwitch/lock
src/Permissions/AbstractPermission.php
AbstractPermission.resolveConditions
protected function resolveConditions(Lock $lock, $action, $resource) { // If the given condition is a closure, execute it. if ($this->conditions instanceof Closure) { return call_user_func($this->conditions, $lock, $this, $action, $resource); } // If the conditions are an array of Condition objects, check them all. foreach ($this->conditions as $condition) { if (! $condition->assert($lock, $this, $action, $resource)) { return false; } } return true; }
php
protected function resolveConditions(Lock $lock, $action, $resource) { // If the given condition is a closure, execute it. if ($this->conditions instanceof Closure) { return call_user_func($this->conditions, $lock, $this, $action, $resource); } // If the conditions are an array of Condition objects, check them all. foreach ($this->conditions as $condition) { if (! $condition->assert($lock, $this, $action, $resource)) { return false; } } return true; }
[ "protected", "function", "resolveConditions", "(", "Lock", "$", "lock", ",", "$", "action", ",", "$", "resource", ")", "{", "// If the given condition is a closure, execute it.", "if", "(", "$", "this", "->", "conditions", "instanceof", "Closure", ")", "{", "retur...
Check all the conditions and make sure they all return true @param \BeatSwitch\Lock\Lock $lock @param string $action @param \BeatSwitch\Lock\Resources\Resource|null $resource @return bool
[ "Check", "all", "the", "conditions", "and", "make", "sure", "they", "all", "return", "true" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Permissions/AbstractPermission.php#L134-L149
41,669
BeatSwitch/lock
src/Manager.php
Manager.makeCallerLockAware
public function makeCallerLockAware(Caller $caller) { $lock = $this->caller($caller); $caller->setLock($lock); return $caller; }
php
public function makeCallerLockAware(Caller $caller) { $lock = $this->caller($caller); $caller->setLock($lock); return $caller; }
[ "public", "function", "makeCallerLockAware", "(", "Caller", "$", "caller", ")", "{", "$", "lock", "=", "$", "this", "->", "caller", "(", "$", "caller", ")", ";", "$", "caller", "->", "setLock", "(", "$", "lock", ")", ";", "return", "$", "caller", ";"...
Sets the lock instance on caller that implements the LockAware trait @param \BeatSwitch\Lock\Callers\Caller $caller @return \BeatSwitch\Lock\Callers\Caller
[ "Sets", "the", "lock", "instance", "on", "caller", "that", "implements", "the", "LockAware", "trait" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Manager.php#L62-L69
41,670
BeatSwitch/lock
src/Manager.php
Manager.makeRoleLockAware
public function makeRoleLockAware($role) { $role = $this->convertRoleToObject($role); $lock = $this->role($role); $role->setLock($lock); return $role; }
php
public function makeRoleLockAware($role) { $role = $this->convertRoleToObject($role); $lock = $this->role($role); $role->setLock($lock); return $role; }
[ "public", "function", "makeRoleLockAware", "(", "$", "role", ")", "{", "$", "role", "=", "$", "this", "->", "convertRoleToObject", "(", "$", "role", ")", ";", "$", "lock", "=", "$", "this", "->", "role", "(", "$", "role", ")", ";", "$", "role", "->...
Sets the lock instance on role that implements the LockAware trait @param \BeatSwitch\Lock\Roles\Role|string $role @return \BeatSwitch\Lock\Roles\Role
[ "Sets", "the", "lock", "instance", "on", "role", "that", "implements", "the", "LockAware", "trait" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Manager.php#L77-L85
41,671
BeatSwitch/lock
src/Manager.php
Manager.setRole
public function setRole($names, $inherit = null) { foreach ((array) $names as $name) { $this->roles[$name] = new SimpleRole($name, $inherit); } }
php
public function setRole($names, $inherit = null) { foreach ((array) $names as $name) { $this->roles[$name] = new SimpleRole($name, $inherit); } }
[ "public", "function", "setRole", "(", "$", "names", ",", "$", "inherit", "=", "null", ")", "{", "foreach", "(", "(", "array", ")", "$", "names", "as", "$", "name", ")", "{", "$", "this", "->", "roles", "[", "$", "name", "]", "=", "new", "SimpleRo...
Add one role to the lock instance @param string|array $names @param string $inherit
[ "Add", "one", "role", "to", "the", "lock", "instance" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Manager.php#L104-L109
41,672
BeatSwitch/lock
src/Manager.php
Manager.findRole
protected function findRole($role) { // Try to see if we have a role registered for the given // key so we can determine the role's inheritances. if (array_key_exists($role, $this->roles)) { return $this->roles[$role]; } // If we couldn't find a registered role for the // given key, just return a new role object. return new SimpleRole($role); }
php
protected function findRole($role) { // Try to see if we have a role registered for the given // key so we can determine the role's inheritances. if (array_key_exists($role, $this->roles)) { return $this->roles[$role]; } // If we couldn't find a registered role for the // given key, just return a new role object. return new SimpleRole($role); }
[ "protected", "function", "findRole", "(", "$", "role", ")", "{", "// Try to see if we have a role registered for the given", "// key so we can determine the role's inheritances.", "if", "(", "array_key_exists", "(", "$", "role", ",", "$", "this", "->", "roles", ")", ")", ...
Find a role in the roles array @param string $role @return \BeatSwitch\Lock\Roles\Role
[ "Find", "a", "role", "in", "the", "roles", "array" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Manager.php#L128-L139
41,673
BeatSwitch/lock
src/Callers/CallerLock.php
CallerLock.getLockInstancesForCallerRoles
protected function getLockInstancesForCallerRoles() { return array_map(function ($role) { return $this->manager->role($role); }, $this->caller->getCallerRoles()); }
php
protected function getLockInstancesForCallerRoles() { return array_map(function ($role) { return $this->manager->role($role); }, $this->caller->getCallerRoles()); }
[ "protected", "function", "getLockInstancesForCallerRoles", "(", ")", "{", "return", "array_map", "(", "function", "(", "$", "role", ")", "{", "return", "$", "this", "->", "manager", "->", "role", "(", "$", "role", ")", ";", "}", ",", "$", "this", "->", ...
Get all the lock instances for all the roles of the current caller @return \BeatSwitch\Lock\Roles\RoleLock[]
[ "Get", "all", "the", "lock", "instances", "for", "all", "the", "roles", "of", "the", "current", "caller" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Callers/CallerLock.php#L103-L108
41,674
BeatSwitch/lock
src/Permissions/PermissionFactory.php
PermissionFactory.createFromData
public static function createFromData($permissions) { return array_map(function ($permission) { if (is_array($permission)) { return PermissionFactory::createFromArray($permission); } else { return PermissionFactory::createFromObject($permission); } }, $permissions); }
php
public static function createFromData($permissions) { return array_map(function ($permission) { if (is_array($permission)) { return PermissionFactory::createFromArray($permission); } else { return PermissionFactory::createFromObject($permission); } }, $permissions); }
[ "public", "static", "function", "createFromData", "(", "$", "permissions", ")", "{", "return", "array_map", "(", "function", "(", "$", "permission", ")", "{", "if", "(", "is_array", "(", "$", "permission", ")", ")", "{", "return", "PermissionFactory", "::", ...
Maps an array of permission data to Permission objects @param array $permissions @return \BeatSwitch\Lock\Permissions\Permission[]
[ "Maps", "an", "array", "of", "permission", "data", "to", "Permission", "objects" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Permissions/PermissionFactory.php#L14-L23
41,675
BeatSwitch/lock
src/Permissions/PermissionFactory.php
PermissionFactory.createFromArray
public static function createFromArray(array $permission) { $type = $permission['type']; // Make sure the id is typecast to an integer. $id = ! is_null($permission['resource_id']) ? (int) $permission['resource_id'] : null; if ($type === Privilege::TYPE) { return new Privilege( $permission['action'], new SimpleResource($permission['resource_type'], $id) ); } elseif ($type === Restriction::TYPE) { return new Restriction( $permission['action'], new SimpleResource($permission['resource_type'], $id) ); } else { throw new InvalidPermissionType("The permission type you provided \"$type\" is incorrect."); } }
php
public static function createFromArray(array $permission) { $type = $permission['type']; // Make sure the id is typecast to an integer. $id = ! is_null($permission['resource_id']) ? (int) $permission['resource_id'] : null; if ($type === Privilege::TYPE) { return new Privilege( $permission['action'], new SimpleResource($permission['resource_type'], $id) ); } elseif ($type === Restriction::TYPE) { return new Restriction( $permission['action'], new SimpleResource($permission['resource_type'], $id) ); } else { throw new InvalidPermissionType("The permission type you provided \"$type\" is incorrect."); } }
[ "public", "static", "function", "createFromArray", "(", "array", "$", "permission", ")", "{", "$", "type", "=", "$", "permission", "[", "'type'", "]", ";", "// Make sure the id is typecast to an integer.", "$", "id", "=", "!", "is_null", "(", "$", "permission", ...
Maps an data array to a permission object @param array $permission @return \BeatSwitch\Lock\Permissions\Permission @throws \BeatSwitch\Lock\Permissions\InvalidPermissionType
[ "Maps", "an", "data", "array", "to", "a", "permission", "object" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Permissions/PermissionFactory.php#L32-L52
41,676
BeatSwitch/lock
src/Permissions/PermissionFactory.php
PermissionFactory.createFromObject
public static function createFromObject($permission) { // Make sure the id is typecast to an integer. $id = ! is_null($permission->resource_id) ? (int) $permission->resource_id : null; if ($permission->type === Privilege::TYPE) { return new Privilege( $permission->action, new SimpleResource($permission->resource_type, $id) ); } elseif ($permission->type === Restriction::TYPE) { return new Restriction( $permission->action, new SimpleResource($permission->resource_type, $id) ); } else { throw new InvalidPermissionType("The permission type you provided \"{$permission->type}\" is incorrect."); } }
php
public static function createFromObject($permission) { // Make sure the id is typecast to an integer. $id = ! is_null($permission->resource_id) ? (int) $permission->resource_id : null; if ($permission->type === Privilege::TYPE) { return new Privilege( $permission->action, new SimpleResource($permission->resource_type, $id) ); } elseif ($permission->type === Restriction::TYPE) { return new Restriction( $permission->action, new SimpleResource($permission->resource_type, $id) ); } else { throw new InvalidPermissionType("The permission type you provided \"{$permission->type}\" is incorrect."); } }
[ "public", "static", "function", "createFromObject", "(", "$", "permission", ")", "{", "// Make sure the id is typecast to an integer.", "$", "id", "=", "!", "is_null", "(", "$", "permission", "->", "resource_id", ")", "?", "(", "int", ")", "$", "permission", "->...
Maps an data object to a permission object @param object $permission @return \BeatSwitch\Lock\Permissions\Permission[] @throws \BeatSwitch\Lock\Permissions\InvalidPermissionType
[ "Maps", "an", "data", "object", "to", "a", "permission", "object" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Permissions/PermissionFactory.php#L61-L79
41,677
BeatSwitch/lock
src/Permissions/Privilege.php
Privilege.isAllowed
public function isAllowed(Lock $lock, $action, Resource $resource = null) { return $this->resolve($lock, $action, $resource); }
php
public function isAllowed(Lock $lock, $action, Resource $resource = null) { return $this->resolve($lock, $action, $resource); }
[ "public", "function", "isAllowed", "(", "Lock", "$", "lock", ",", "$", "action", ",", "Resource", "$", "resource", "=", "null", ")", "{", "return", "$", "this", "->", "resolve", "(", "$", "lock", ",", "$", "action", ",", "$", "resource", ")", ";", ...
Validate a permission against the given params @param \BeatSwitch\Lock\Lock $lock @param string $action @param \BeatSwitch\Lock\Resources\Resource|null $resource @return bool
[ "Validate", "a", "permission", "against", "the", "given", "params" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Permissions/Privilege.php#L23-L26
41,678
BeatSwitch/lock
src/Drivers/ArrayDriver.php
ArrayDriver.storeCallerPermission
public function storeCallerPermission(Caller $caller, Permission $permission) { $this->permissions[$this->getCallerKey($caller)][] = $permission; }
php
public function storeCallerPermission(Caller $caller, Permission $permission) { $this->permissions[$this->getCallerKey($caller)][] = $permission; }
[ "public", "function", "storeCallerPermission", "(", "Caller", "$", "caller", ",", "Permission", "$", "permission", ")", "{", "$", "this", "->", "permissions", "[", "$", "this", "->", "getCallerKey", "(", "$", "caller", ")", "]", "[", "]", "=", "$", "perm...
Stores a new permission into the driver for a caller @param \BeatSwitch\Lock\Callers\Caller $caller @param \BeatSwitch\Lock\Permissions\Permission @return void
[ "Stores", "a", "new", "permission", "into", "the", "driver", "for", "a", "caller" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Drivers/ArrayDriver.php#L40-L43
41,679
BeatSwitch/lock
src/Drivers/ArrayDriver.php
ArrayDriver.removeCallerPermission
public function removeCallerPermission(Caller $caller, Permission $permission) { // Remove permissions which match the action and resource $this->permissions[$this->getCallerKey($caller)] = array_filter( $this->getCallerPermissions($caller), function (Permission $callerPermission) use ($permission) { // Only keep permissions which don't exactly match the one which we're trying to remove. return ! $callerPermission->matchesPermission($permission); } ); }
php
public function removeCallerPermission(Caller $caller, Permission $permission) { // Remove permissions which match the action and resource $this->permissions[$this->getCallerKey($caller)] = array_filter( $this->getCallerPermissions($caller), function (Permission $callerPermission) use ($permission) { // Only keep permissions which don't exactly match the one which we're trying to remove. return ! $callerPermission->matchesPermission($permission); } ); }
[ "public", "function", "removeCallerPermission", "(", "Caller", "$", "caller", ",", "Permission", "$", "permission", ")", "{", "// Remove permissions which match the action and resource", "$", "this", "->", "permissions", "[", "$", "this", "->", "getCallerKey", "(", "$...
Removes a permission from the driver for a caller @param \BeatSwitch\Lock\Callers\Caller $caller @param \BeatSwitch\Lock\Permissions\Permission @return void
[ "Removes", "a", "permission", "from", "the", "driver", "for", "a", "caller" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Drivers/ArrayDriver.php#L52-L62
41,680
BeatSwitch/lock
src/Drivers/ArrayDriver.php
ArrayDriver.hasCallerPermission
public function hasCallerPermission(Caller $caller, Permission $permission) { // Iterate over each permission from the user and check if the permission is in the array. foreach ($this->getCallerPermissions($caller) as $callerPermission) { // If a matching permission was found, immediately break the sequence and return true. if ($callerPermission->matchesPermission($permission)) { return true; } } return false; }
php
public function hasCallerPermission(Caller $caller, Permission $permission) { // Iterate over each permission from the user and check if the permission is in the array. foreach ($this->getCallerPermissions($caller) as $callerPermission) { // If a matching permission was found, immediately break the sequence and return true. if ($callerPermission->matchesPermission($permission)) { return true; } } return false; }
[ "public", "function", "hasCallerPermission", "(", "Caller", "$", "caller", ",", "Permission", "$", "permission", ")", "{", "// Iterate over each permission from the user and check if the permission is in the array.", "foreach", "(", "$", "this", "->", "getCallerPermissions", ...
Checks if a permission is stored for a user @param \BeatSwitch\Lock\Callers\Caller $caller @param \BeatSwitch\Lock\Permissions\Permission @return bool
[ "Checks", "if", "a", "permission", "is", "stored", "for", "a", "user" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Drivers/ArrayDriver.php#L71-L82
41,681
BeatSwitch/lock
src/Lock.php
Lock.allow
public function allow($action, $resource = null, $resourceId = null, $conditions = []) { $actions = (array) $action; $resource = $this->convertResourceToObject($resource, $resourceId); $permissions = $this->getPermissions(); foreach ($actions as $action) { foreach ($permissions as $key => $permission) { if ($permission instanceof Restriction && ! $permission->isAllowed($this, $action, $resource)) { $this->removePermission($permission); unset($permissions[$key]); } } // We'll need to clear any restrictions above $restriction = new Restriction($action, $resource); if ($this->hasPermission($restriction)) { $this->removePermission($restriction); } $this->storePermission(new Privilege($action, $resource, $conditions)); } }
php
public function allow($action, $resource = null, $resourceId = null, $conditions = []) { $actions = (array) $action; $resource = $this->convertResourceToObject($resource, $resourceId); $permissions = $this->getPermissions(); foreach ($actions as $action) { foreach ($permissions as $key => $permission) { if ($permission instanceof Restriction && ! $permission->isAllowed($this, $action, $resource)) { $this->removePermission($permission); unset($permissions[$key]); } } // We'll need to clear any restrictions above $restriction = new Restriction($action, $resource); if ($this->hasPermission($restriction)) { $this->removePermission($restriction); } $this->storePermission(new Privilege($action, $resource, $conditions)); } }
[ "public", "function", "allow", "(", "$", "action", ",", "$", "resource", "=", "null", ",", "$", "resourceId", "=", "null", ",", "$", "conditions", "=", "[", "]", ")", "{", "$", "actions", "=", "(", "array", ")", "$", "action", ";", "$", "resource",...
Give the subject permission to do something @param string|array $action @param string|\BeatSwitch\Lock\Resources\Resource $resource @param int $resourceId @param \BeatSwitch\Lock\Permissions\Condition|\BeatSwitch\Lock\Permissions\Condition[]|\Closure $conditions
[ "Give", "the", "subject", "permission", "to", "do", "something" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Lock.php#L67-L90
41,682
BeatSwitch/lock
src/Lock.php
Lock.deny
public function deny($action, $resource = null, $resourceId = null, $conditions = []) { $actions = (array) $action; $resource = $this->convertResourceToObject($resource, $resourceId); $permissions = $this->getPermissions(); foreach ($actions as $action) { $this->clearPermission($action, $resource, $permissions); $this->storePermission(new Restriction($action, $resource, $conditions)); } }
php
public function deny($action, $resource = null, $resourceId = null, $conditions = []) { $actions = (array) $action; $resource = $this->convertResourceToObject($resource, $resourceId); $permissions = $this->getPermissions(); foreach ($actions as $action) { $this->clearPermission($action, $resource, $permissions); $this->storePermission(new Restriction($action, $resource, $conditions)); } }
[ "public", "function", "deny", "(", "$", "action", ",", "$", "resource", "=", "null", ",", "$", "resourceId", "=", "null", ",", "$", "conditions", "=", "[", "]", ")", "{", "$", "actions", "=", "(", "array", ")", "$", "action", ";", "$", "resource", ...
Deny the subject from doing something @param string|array $action @param string|\BeatSwitch\Lock\Resources\Resource $resource @param int $resourceId @param \BeatSwitch\Lock\Permissions\Condition|\BeatSwitch\Lock\Permissions\Condition[]|\Closure $conditions
[ "Deny", "the", "subject", "from", "doing", "something" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Lock.php#L100-L111
41,683
BeatSwitch/lock
src/Lock.php
Lock.resolveRestrictions
protected function resolveRestrictions($permissions, $action, Resource $resource) { foreach ($permissions as $permission) { // If we've found a matching restriction, return false. if ($permission instanceof Restriction && ! $permission->isAllowed($this, $action, $resource)) { return false; } } return true; }
php
protected function resolveRestrictions($permissions, $action, Resource $resource) { foreach ($permissions as $permission) { // If we've found a matching restriction, return false. if ($permission instanceof Restriction && ! $permission->isAllowed($this, $action, $resource)) { return false; } } return true; }
[ "protected", "function", "resolveRestrictions", "(", "$", "permissions", ",", "$", "action", ",", "Resource", "$", "resource", ")", "{", "foreach", "(", "$", "permissions", "as", "$", "permission", ")", "{", "// If we've found a matching restriction, return false.", ...
Check if the given restrictions prevent the given action and resource to pass @param \BeatSwitch\Lock\Permissions\Permission[] $permissions @param string $action @param \BeatSwitch\Lock\Resources\Resource $resource @return bool
[ "Check", "if", "the", "given", "restrictions", "prevent", "the", "given", "action", "and", "resource", "to", "pass" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Lock.php#L242-L252
41,684
BeatSwitch/lock
src/Lock.php
Lock.resolvePrivileges
protected function resolvePrivileges($permissions, $action, Resource $resource) { // Search for privileges in the permissions. foreach ($permissions as $permission) { // If we've found a valid privilege, return true. if ($permission instanceof Privilege && $permission->isAllowed($this, $action, $resource)) { return true; } } return false; }
php
protected function resolvePrivileges($permissions, $action, Resource $resource) { // Search for privileges in the permissions. foreach ($permissions as $permission) { // If we've found a valid privilege, return true. if ($permission instanceof Privilege && $permission->isAllowed($this, $action, $resource)) { return true; } } return false; }
[ "protected", "function", "resolvePrivileges", "(", "$", "permissions", ",", "$", "action", ",", "Resource", "$", "resource", ")", "{", "// Search for privileges in the permissions.", "foreach", "(", "$", "permissions", "as", "$", "permission", ")", "{", "// If we've...
Check if the given privileges allow the given action and resource to pass @param \BeatSwitch\Lock\Permissions\Permission[] $permissions @param string $action @param \BeatSwitch\Lock\Resources\Resource $resource @return bool
[ "Check", "if", "the", "given", "privileges", "allow", "the", "given", "action", "and", "resource", "to", "pass" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Lock.php#L262-L273
41,685
BeatSwitch/lock
src/Lock.php
Lock.getAliasesForAction
protected function getAliasesForAction($action) { $actions = []; foreach ($this->manager->getAliases() as $aliasName => $alias) { if ($alias->hasAction($action)) { $actions[] = $aliasName; } } return $actions; }
php
protected function getAliasesForAction($action) { $actions = []; foreach ($this->manager->getAliases() as $aliasName => $alias) { if ($alias->hasAction($action)) { $actions[] = $aliasName; } } return $actions; }
[ "protected", "function", "getAliasesForAction", "(", "$", "action", ")", "{", "$", "actions", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "manager", "->", "getAliases", "(", ")", "as", "$", "aliasName", "=>", "$", "alias", ")", "{", "if", ...
Returns all aliases which contain the given action @param string $action @return array
[ "Returns", "all", "aliases", "which", "contain", "the", "given", "action" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Lock.php#L310-L321
41,686
BeatSwitch/lock
src/Lock.php
Lock.convertResourceToObject
protected function convertResourceToObject($resource, $resourceId = null) { return ! $resource instanceof Resource ? new SimpleResource($resource, $resourceId) : $resource; }
php
protected function convertResourceToObject($resource, $resourceId = null) { return ! $resource instanceof Resource ? new SimpleResource($resource, $resourceId) : $resource; }
[ "protected", "function", "convertResourceToObject", "(", "$", "resource", ",", "$", "resourceId", "=", "null", ")", "{", "return", "!", "$", "resource", "instanceof", "Resource", "?", "new", "SimpleResource", "(", "$", "resource", ",", "$", "resourceId", ")", ...
Create a resource value object if a non resource object is passed @param string|\BeatSwitch\Lock\Resources\Resource|null $resource @param int|null $resourceId @return \BeatSwitch\Lock\Resources\Resource
[ "Create", "a", "resource", "value", "object", "if", "a", "non", "resource", "object", "is", "passed" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/Lock.php#L330-L333
41,687
BeatSwitch/lock
src/LockAware.php
LockAware.deny
public function deny($action, $resource = null, $resourceId = null, $conditions = []) { $this->assertLockInstanceIsSet(); $this->lock->deny($action, $resource, $resourceId, $conditions); }
php
public function deny($action, $resource = null, $resourceId = null, $conditions = []) { $this->assertLockInstanceIsSet(); $this->lock->deny($action, $resource, $resourceId, $conditions); }
[ "public", "function", "deny", "(", "$", "action", ",", "$", "resource", "=", "null", ",", "$", "resourceId", "=", "null", ",", "$", "conditions", "=", "[", "]", ")", "{", "$", "this", "->", "assertLockInstanceIsSet", "(", ")", ";", "$", "this", "->",...
Deny a caller from doing something @param string|array $action @param string|\BeatSwitch\Lock\Resources\Resource $resource @param int $resourceId @param \BeatSwitch\Lock\Permissions\Condition|\BeatSwitch\Lock\Permissions\Condition[]|\Closure $conditions
[ "Deny", "a", "caller", "from", "doing", "something" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/LockAware.php#L71-L76
41,688
BeatSwitch/lock
src/LockAware.php
LockAware.setLock
public function setLock(Lock $lock) { // Make sure that the subject from the given lock instance is this object. if ($lock->getSubject() !== $this) { throw new InvalidLockInstance('Invalid Lock instance given for current object.'); } $this->lock = $lock; }
php
public function setLock(Lock $lock) { // Make sure that the subject from the given lock instance is this object. if ($lock->getSubject() !== $this) { throw new InvalidLockInstance('Invalid Lock instance given for current object.'); } $this->lock = $lock; }
[ "public", "function", "setLock", "(", "Lock", "$", "lock", ")", "{", "// Make sure that the subject from the given lock instance is this object.", "if", "(", "$", "lock", "->", "getSubject", "(", ")", "!==", "$", "this", ")", "{", "throw", "new", "InvalidLockInstanc...
Sets the lock instance for this caller @param \BeatSwitch\Lock\Lock $lock @throws \BeatSwitch\Lock\InvalidLockInstance
[ "Sets", "the", "lock", "instance", "for", "this", "caller" ]
b3a47635b06b61915735c8633ad6cee26bf9e7ab
https://github.com/BeatSwitch/lock/blob/b3a47635b06b61915735c8633ad6cee26bf9e7ab/src/LockAware.php#L140-L148
41,689
antkaz/yii2-vue
src/Vue.php
Vue.initClientOptions
protected function initClientOptions() { if (!isset($this->clientOptions['el'])) { $this->clientOptions['el'] = "#{$this->getId()}"; } $this->initData(); $this->initComputed(); $this->initMethods(); }
php
protected function initClientOptions() { if (!isset($this->clientOptions['el'])) { $this->clientOptions['el'] = "#{$this->getId()}"; } $this->initData(); $this->initComputed(); $this->initMethods(); }
[ "protected", "function", "initClientOptions", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "clientOptions", "[", "'el'", "]", ")", ")", "{", "$", "this", "->", "clientOptions", "[", "'el'", "]", "=", "\"#{$this->getId()}\"", ";", "}", ...
Initializes the options for the Vue object
[ "Initializes", "the", "options", "for", "the", "Vue", "object" ]
150deabf6a08961d8876f0eaf55ca53d97badef7
https://github.com/antkaz/yii2-vue/blob/150deabf6a08961d8876f0eaf55ca53d97badef7/src/Vue.php#L92-L101
41,690
antkaz/yii2-vue
src/Vue.php
Vue.initData
protected function initData() { if (empty($this->data)) { return; } if (is_array($this->data) || $this->data instanceof JsExpression) { $this->clientOptions['data'] = $this->data; } elseif (is_string($this->data)) { $this->clientOptions['data'] = new JsExpression($this->data); } else { throw new InvalidConfigException('The "data" option can only be a string or an array'); } }
php
protected function initData() { if (empty($this->data)) { return; } if (is_array($this->data) || $this->data instanceof JsExpression) { $this->clientOptions['data'] = $this->data; } elseif (is_string($this->data)) { $this->clientOptions['data'] = new JsExpression($this->data); } else { throw new InvalidConfigException('The "data" option can only be a string or an array'); } }
[ "protected", "function", "initData", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "data", ")", ")", "{", "return", ";", "}", "if", "(", "is_array", "(", "$", "this", "->", "data", ")", "||", "$", "this", "->", "data", "instanceof", ...
Initializes the data object for the Vue instance @throws InvalidConfigException
[ "Initializes", "the", "data", "object", "for", "the", "Vue", "instance" ]
150deabf6a08961d8876f0eaf55ca53d97badef7
https://github.com/antkaz/yii2-vue/blob/150deabf6a08961d8876f0eaf55ca53d97badef7/src/Vue.php#L108-L121
41,691
antkaz/yii2-vue
src/Vue.php
Vue.initComputed
protected function initComputed() { if (empty($this->computed)) { return; } if (!is_array($this->computed)) { throw new InvalidConfigException('The "computed" option are not an array'); } foreach ($this->computed as $key => $callback) { if (is_array($callback)) { if (isset($callback['get'])) { $function = $callback['get'] instanceof JsExpression ? $callback['get'] : new JsExpression($callback['get']); $this->clientOptions['computed'][$key]['get'] = $function; } if (isset($callback['set'])) { $function = $callback['set'] instanceof JsExpression ? $callback['set'] : new JsExpression($callback['set']); $this->clientOptions['computed'][$key]['set'] = $function; } } else { $function = $callback instanceof JsExpression ? $callback : new JsExpression($callback); $this->clientOptions['computed'][$key] = $function; } } }
php
protected function initComputed() { if (empty($this->computed)) { return; } if (!is_array($this->computed)) { throw new InvalidConfigException('The "computed" option are not an array'); } foreach ($this->computed as $key => $callback) { if (is_array($callback)) { if (isset($callback['get'])) { $function = $callback['get'] instanceof JsExpression ? $callback['get'] : new JsExpression($callback['get']); $this->clientOptions['computed'][$key]['get'] = $function; } if (isset($callback['set'])) { $function = $callback['set'] instanceof JsExpression ? $callback['set'] : new JsExpression($callback['set']); $this->clientOptions['computed'][$key]['set'] = $function; } } else { $function = $callback instanceof JsExpression ? $callback : new JsExpression($callback); $this->clientOptions['computed'][$key] = $function; } } }
[ "protected", "function", "initComputed", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "computed", ")", ")", "{", "return", ";", "}", "if", "(", "!", "is_array", "(", "$", "this", "->", "computed", ")", ")", "{", "throw", "new", "Inval...
Initializes computed to be mixed into the Vue instance. @throws InvalidConfigException
[ "Initializes", "computed", "to", "be", "mixed", "into", "the", "Vue", "instance", "." ]
150deabf6a08961d8876f0eaf55ca53d97badef7
https://github.com/antkaz/yii2-vue/blob/150deabf6a08961d8876f0eaf55ca53d97badef7/src/Vue.php#L128-L153
41,692
antkaz/yii2-vue
src/Vue.php
Vue.initMethods
protected function initMethods() { if (empty($this->methods)) { return; } if (!is_array($this->methods)) { throw new InvalidConfigException('The "methods" option are not an array'); } foreach ($this->methods as $methodName => $handler) { $function = $handler instanceof JsExpression ? $handler : new JsExpression($handler); $this->clientOptions['methods'][$methodName] = $function; } }
php
protected function initMethods() { if (empty($this->methods)) { return; } if (!is_array($this->methods)) { throw new InvalidConfigException('The "methods" option are not an array'); } foreach ($this->methods as $methodName => $handler) { $function = $handler instanceof JsExpression ? $handler : new JsExpression($handler); $this->clientOptions['methods'][$methodName] = $function; } }
[ "protected", "function", "initMethods", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "methods", ")", ")", "{", "return", ";", "}", "if", "(", "!", "is_array", "(", "$", "this", "->", "methods", ")", ")", "{", "throw", "new", "InvalidC...
Initializes methods to be mixed into the Vue instance. @throws InvalidConfigException
[ "Initializes", "methods", "to", "be", "mixed", "into", "the", "Vue", "instance", "." ]
150deabf6a08961d8876f0eaf55ca53d97badef7
https://github.com/antkaz/yii2-vue/blob/150deabf6a08961d8876f0eaf55ca53d97badef7/src/Vue.php#L160-L174
41,693
antkaz/yii2-vue
src/Vue.php
Vue.registerJs
protected function registerJs() { VueAsset::register($this->getView()); $options = Json::htmlEncode($this->clientOptions); $js = "var app = new Vue({$options})"; $this->getView()->registerJs($js, View::POS_END); }
php
protected function registerJs() { VueAsset::register($this->getView()); $options = Json::htmlEncode($this->clientOptions); $js = "var app = new Vue({$options})"; $this->getView()->registerJs($js, View::POS_END); }
[ "protected", "function", "registerJs", "(", ")", "{", "VueAsset", "::", "register", "(", "$", "this", "->", "getView", "(", ")", ")", ";", "$", "options", "=", "Json", "::", "htmlEncode", "(", "$", "this", "->", "clientOptions", ")", ";", "$", "js", ...
Registers a specific asset bundles. @throws \yii\base\InvalidArgumentException
[ "Registers", "a", "specific", "asset", "bundles", "." ]
150deabf6a08961d8876f0eaf55ca53d97badef7
https://github.com/antkaz/yii2-vue/blob/150deabf6a08961d8876f0eaf55ca53d97badef7/src/Vue.php#L180-L187
41,694
romanpitak/PHP-REST-Client
src/Request.php
Request.buildResponse
private function buildResponse() { $curlOptions = $this->getBasicCurlOptions(); $this->addRequestAuth($curlOptions); $this->addRequestHeaders($curlOptions); $this->addRequestMethod($curlOptions); // push options into the resource $curlResource = $this->getCurlResource(); if (!curl_setopt_array($curlResource, $curlOptions)) { throw new RequestException('Invalid cURL options'); } // create response $response = new Response($curlResource); return $response; }
php
private function buildResponse() { $curlOptions = $this->getBasicCurlOptions(); $this->addRequestAuth($curlOptions); $this->addRequestHeaders($curlOptions); $this->addRequestMethod($curlOptions); // push options into the resource $curlResource = $this->getCurlResource(); if (!curl_setopt_array($curlResource, $curlOptions)) { throw new RequestException('Invalid cURL options'); } // create response $response = new Response($curlResource); return $response; }
[ "private", "function", "buildResponse", "(", ")", "{", "$", "curlOptions", "=", "$", "this", "->", "getBasicCurlOptions", "(", ")", ";", "$", "this", "->", "addRequestAuth", "(", "$", "curlOptions", ")", ";", "$", "this", "->", "addRequestHeaders", "(", "$...
Build the response object. Builds the response object based on current request configuration. @return Response @throws RequestException
[ "Build", "the", "response", "object", "." ]
728b6c44040a13daeb8033953f5f3cdd3dde1980
https://github.com/romanpitak/PHP-REST-Client/blob/728b6c44040a13daeb8033953f5f3cdd3dde1980/src/Request.php#L105-L121
41,695
romanpitak/PHP-REST-Client
src/Request.php
Request.getBasicCurlOptions
private function getBasicCurlOptions() { $curlOptions = $this->getOption(self::CURL_OPTIONS_KEY, array()); $curlOptions[CURLOPT_HEADER] = true; $curlOptions[CURLOPT_RETURNTRANSFER] = true; $curlOptions[CURLOPT_USERAGENT] = $this->getOption(self::USER_AGENT_KEY); $curlOptions[CURLOPT_URL] = $this->getOption(self::BASE_URL_KEY); return $curlOptions; }
php
private function getBasicCurlOptions() { $curlOptions = $this->getOption(self::CURL_OPTIONS_KEY, array()); $curlOptions[CURLOPT_HEADER] = true; $curlOptions[CURLOPT_RETURNTRANSFER] = true; $curlOptions[CURLOPT_USERAGENT] = $this->getOption(self::USER_AGENT_KEY); $curlOptions[CURLOPT_URL] = $this->getOption(self::BASE_URL_KEY); return $curlOptions; }
[ "private", "function", "getBasicCurlOptions", "(", ")", "{", "$", "curlOptions", "=", "$", "this", "->", "getOption", "(", "self", "::", "CURL_OPTIONS_KEY", ",", "array", "(", ")", ")", ";", "$", "curlOptions", "[", "CURLOPT_HEADER", "]", "=", "true", ";",...
Create basic curl options @return array Curl options
[ "Create", "basic", "curl", "options" ]
728b6c44040a13daeb8033953f5f3cdd3dde1980
https://github.com/romanpitak/PHP-REST-Client/blob/728b6c44040a13daeb8033953f5f3cdd3dde1980/src/Request.php#L128-L135
41,696
romanpitak/PHP-REST-Client
src/Request.php
Request.addRequestAuth
private function addRequestAuth(&$curlOptions) { $username = $this->getOption(self::USERNAME_KEY); $password = $this->getOption(self::PASSWORD_KEY); if ((!is_null($username)) && (!is_null($password))) { $curlOptions[CURLOPT_USERPWD] = sprintf("%s:%s", $username, $password); } }
php
private function addRequestAuth(&$curlOptions) { $username = $this->getOption(self::USERNAME_KEY); $password = $this->getOption(self::PASSWORD_KEY); if ((!is_null($username)) && (!is_null($password))) { $curlOptions[CURLOPT_USERPWD] = sprintf("%s:%s", $username, $password); } }
[ "private", "function", "addRequestAuth", "(", "&", "$", "curlOptions", ")", "{", "$", "username", "=", "$", "this", "->", "getOption", "(", "self", "::", "USERNAME_KEY", ")", ";", "$", "password", "=", "$", "this", "->", "getOption", "(", "self", "::", ...
Add authentication to curl options @param array &$curlOptions
[ "Add", "authentication", "to", "curl", "options" ]
728b6c44040a13daeb8033953f5f3cdd3dde1980
https://github.com/romanpitak/PHP-REST-Client/blob/728b6c44040a13daeb8033953f5f3cdd3dde1980/src/Request.php#L142-L148
41,697
romanpitak/PHP-REST-Client
src/Request.php
Request.addRequestHeaders
private function addRequestHeaders(&$curlOptions) { // cURL HTTP headers $headers = $this->getOption(self::HEADERS_KEY, array()); // Turn off the Expect header to stop HTTP 100 Continue responses. // Response parsing was not handling these headers. $curlOptions[CURLOPT_HTTPHEADER][] = "Expect:"; if (0 < count($headers)) { $curlOptions[CURLOPT_HTTPHEADER] = array(); foreach ($headers as $key => $value) { $curlOptions[CURLOPT_HTTPHEADER][] = sprintf("%s:%s", $key, $value); } } }
php
private function addRequestHeaders(&$curlOptions) { // cURL HTTP headers $headers = $this->getOption(self::HEADERS_KEY, array()); // Turn off the Expect header to stop HTTP 100 Continue responses. // Response parsing was not handling these headers. $curlOptions[CURLOPT_HTTPHEADER][] = "Expect:"; if (0 < count($headers)) { $curlOptions[CURLOPT_HTTPHEADER] = array(); foreach ($headers as $key => $value) { $curlOptions[CURLOPT_HTTPHEADER][] = sprintf("%s:%s", $key, $value); } } }
[ "private", "function", "addRequestHeaders", "(", "&", "$", "curlOptions", ")", "{", "// cURL HTTP headers", "$", "headers", "=", "$", "this", "->", "getOption", "(", "self", "::", "HEADERS_KEY", ",", "array", "(", ")", ")", ";", "// Turn off the Expect header to...
Add headers to curl options @param array &$curlOptions
[ "Add", "headers", "to", "curl", "options" ]
728b6c44040a13daeb8033953f5f3cdd3dde1980
https://github.com/romanpitak/PHP-REST-Client/blob/728b6c44040a13daeb8033953f5f3cdd3dde1980/src/Request.php#L155-L167
41,698
romanpitak/PHP-REST-Client
src/Request.php
Request.addRequestMethod
private function addRequestMethod(&$curlOptions) { $method = strtoupper($this->getOption(self::METHOD_KEY, 'GET')); switch ($method) { case 'GET': break; case 'POST': $curlOptions[CURLOPT_POST] = true; $curlOptions[CURLOPT_POSTFIELDS] = $this->getOption(self::DATA_KEY, array()); break; default: $curlOptions[CURLOPT_CUSTOMREQUEST] = $method; $curlOptions[CURLOPT_POSTFIELDS] = $this->getOption(self::DATA_KEY, array()); } }
php
private function addRequestMethod(&$curlOptions) { $method = strtoupper($this->getOption(self::METHOD_KEY, 'GET')); switch ($method) { case 'GET': break; case 'POST': $curlOptions[CURLOPT_POST] = true; $curlOptions[CURLOPT_POSTFIELDS] = $this->getOption(self::DATA_KEY, array()); break; default: $curlOptions[CURLOPT_CUSTOMREQUEST] = $method; $curlOptions[CURLOPT_POSTFIELDS] = $this->getOption(self::DATA_KEY, array()); } }
[ "private", "function", "addRequestMethod", "(", "&", "$", "curlOptions", ")", "{", "$", "method", "=", "strtoupper", "(", "$", "this", "->", "getOption", "(", "self", "::", "METHOD_KEY", ",", "'GET'", ")", ")", ";", "switch", "(", "$", "method", ")", "...
Add Method to curl options @param array &$curlOptions
[ "Add", "Method", "to", "curl", "options" ]
728b6c44040a13daeb8033953f5f3cdd3dde1980
https://github.com/romanpitak/PHP-REST-Client/blob/728b6c44040a13daeb8033953f5f3cdd3dde1980/src/Request.php#L174-L187
41,699
grohiro/laravel-camelcase-json
src/CamelCaseJsonResponseFactory.php
CamelCaseJsonResponseFactory.encodeJson
public function encodeJson($value) { if ($value instanceof Arrayable) { return $this->encodeArrayable($value); } else if (is_array($value)) { return $this->encodeArray($value); } else if (is_object($value)) { return $this->encodeArray((array) $value); } else { return $value; } }
php
public function encodeJson($value) { if ($value instanceof Arrayable) { return $this->encodeArrayable($value); } else if (is_array($value)) { return $this->encodeArray($value); } else if (is_object($value)) { return $this->encodeArray((array) $value); } else { return $value; } }
[ "public", "function", "encodeJson", "(", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "Arrayable", ")", "{", "return", "$", "this", "->", "encodeArrayable", "(", "$", "value", ")", ";", "}", "else", "if", "(", "is_array", "(", "$", ...
Encode a value to camelCase JSON
[ "Encode", "a", "value", "to", "camelCase", "JSON" ]
9659d3c418c835864648f3ba1c2c42d2769a543c
https://github.com/grohiro/laravel-camelcase-json/blob/9659d3c418c835864648f3ba1c2c42d2769a543c/src/CamelCaseJsonResponseFactory.php#L26-L37