repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
letsdrink/ouzo | src/Ouzo/Core/Db/ModelQueryBuilder.php | ModelQueryBuilder.update | public function update(array $attributes)
{
$this->query->type = QueryType::$UPDATE;
$this->query->updateAttributes = $attributes;
return QueryExecutor::prepare($this->db, $this->query)->execute();
} | php | public function update(array $attributes)
{
$this->query->type = QueryType::$UPDATE;
$this->query->updateAttributes = $attributes;
return QueryExecutor::prepare($this->db, $this->query)->execute();
} | [
"public",
"function",
"update",
"(",
"array",
"$",
"attributes",
")",
"{",
"$",
"this",
"->",
"query",
"->",
"type",
"=",
"QueryType",
"::",
"$",
"UPDATE",
";",
"$",
"this",
"->",
"query",
"->",
"updateAttributes",
"=",
"$",
"attributes",
";",
"return",
... | Runs an update query against a set of models
@param array $attributes
@return int | [
"Runs",
"an",
"update",
"query",
"against",
"a",
"set",
"of",
"models"
] | 4ab809ce8152dc7ef02c67bd6d42924d5d73631e | https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Db/ModelQueryBuilder.php#L220-L225 | train |
lndj/Lcrawl | src/Traits/Parser.php | Parser.parserSchedule | public function parserSchedule($body)
{
$crawler = new Crawler((string)$body);
$crawler = $crawler->filter('#Table1');
$page = $crawler->children();
//delete line 1、2;
$page = $page->reduce(function (Crawler $node, $i) {
if ($i == 0 || $i == 1) {
return false;
}
});
//to array
$array = $page->each(function (Crawler $node, $i) {
return $node->children()->each(function (Crawler $node, $j) {
$span = (int)$node->attr('rowspan') ?: 0;
return [$node->html(), $span];
});
});
//If there are some classes in the table is in two or more lines,
//insert it into the next lines in $array.
//Thanks for @CheukFung
$line_count = count($array);
$schedule = [];
for ($i = 0; $i < $line_count; $i++) { //lines
for ($j = 0; $j < 9; $j++) { //rows
if (isset($array[$i][$j])) {
$k = $array[$i][$j][1];
while (--$k > 0) { // insert element to next line
//Set the span 0
$array[$i][$j][1] = 0;
$array[$i + $k] = array_merge(
array_slice($array[$i + $k], 0, $j),
[$array[$i][$j]],
array_splice($array[$i + $k], $j)
);
}
}
$schedule[$i][$j] = isset($array[$i][$j][0]) ? $array[$i][$j][0] : '';
}
}
return $schedule;
} | php | public function parserSchedule($body)
{
$crawler = new Crawler((string)$body);
$crawler = $crawler->filter('#Table1');
$page = $crawler->children();
//delete line 1、2;
$page = $page->reduce(function (Crawler $node, $i) {
if ($i == 0 || $i == 1) {
return false;
}
});
//to array
$array = $page->each(function (Crawler $node, $i) {
return $node->children()->each(function (Crawler $node, $j) {
$span = (int)$node->attr('rowspan') ?: 0;
return [$node->html(), $span];
});
});
//If there are some classes in the table is in two or more lines,
//insert it into the next lines in $array.
//Thanks for @CheukFung
$line_count = count($array);
$schedule = [];
for ($i = 0; $i < $line_count; $i++) { //lines
for ($j = 0; $j < 9; $j++) { //rows
if (isset($array[$i][$j])) {
$k = $array[$i][$j][1];
while (--$k > 0) { // insert element to next line
//Set the span 0
$array[$i][$j][1] = 0;
$array[$i + $k] = array_merge(
array_slice($array[$i + $k], 0, $j),
[$array[$i][$j]],
array_splice($array[$i + $k], $j)
);
}
}
$schedule[$i][$j] = isset($array[$i][$j][0]) ? $array[$i][$j][0] : '';
}
}
return $schedule;
} | [
"public",
"function",
"parserSchedule",
"(",
"$",
"body",
")",
"{",
"$",
"crawler",
"=",
"new",
"Crawler",
"(",
"(",
"string",
")",
"$",
"body",
")",
";",
"$",
"crawler",
"=",
"$",
"crawler",
"->",
"filter",
"(",
"'#Table1'",
")",
";",
"$",
"page",
... | Paser the schedule data.
@param Object $body
@return Array | [
"Paser",
"the",
"schedule",
"data",
"."
] | 61adc5d99355155099743b288ea3be52efebb852 | https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Traits/Parser.php#L27-L70 | train |
lndj/Lcrawl | src/Supports/Log.php | Log.info | public static function info($info, $context)
{
self::$logger->pushHandler(new StreamHandler(self::$log_file), Logger::INFO);
return self::$logger->info($info, $context);
} | php | public static function info($info, $context)
{
self::$logger->pushHandler(new StreamHandler(self::$log_file), Logger::INFO);
return self::$logger->info($info, $context);
} | [
"public",
"static",
"function",
"info",
"(",
"$",
"info",
",",
"$",
"context",
")",
"{",
"self",
"::",
"$",
"logger",
"->",
"pushHandler",
"(",
"new",
"StreamHandler",
"(",
"self",
"::",
"$",
"log_file",
")",
",",
"Logger",
"::",
"INFO",
")",
";",
"r... | Info log.
@param $info
@param $context
@return bool | [
"Info",
"log",
"."
] | 61adc5d99355155099743b288ea3be52efebb852 | https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Supports/Log.php#L41-L45 | train |
lndj/Lcrawl | src/Supports/Log.php | Log.debug | public static function debug($message, $context)
{
self::$logger->pushHandler(new StreamHandler(self::$log_file), Logger::DEBUG);
return self::$logger->debug($message, $context);
} | php | public static function debug($message, $context)
{
self::$logger->pushHandler(new StreamHandler(self::$log_file), Logger::DEBUG);
return self::$logger->debug($message, $context);
} | [
"public",
"static",
"function",
"debug",
"(",
"$",
"message",
",",
"$",
"context",
")",
"{",
"self",
"::",
"$",
"logger",
"->",
"pushHandler",
"(",
"new",
"StreamHandler",
"(",
"self",
"::",
"$",
"log_file",
")",
",",
"Logger",
"::",
"DEBUG",
")",
";",... | Debug message.
@param $message
@param $context
@return bool | [
"Debug",
"message",
"."
] | 61adc5d99355155099743b288ea3be52efebb852 | https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Supports/Log.php#L53-L58 | train |
lndj/Lcrawl | src/Lcrawl.php | Lcrawl.getCookie | public function getCookie($forceRefresh = false)
{
$cacheKey = $this->cachePrefix . $this->stu_id;
$cached = $this->getCache()->fetch($cacheKey);
if ($forceRefresh || empty($cached)) {
$jar = $this->login();
//Cache the cookieJar 3000 s.
$this->getCache()->save($cacheKey, serialize($jar), 3000);
return $jar;
}
return unserialize($cached);
} | php | public function getCookie($forceRefresh = false)
{
$cacheKey = $this->cachePrefix . $this->stu_id;
$cached = $this->getCache()->fetch($cacheKey);
if ($forceRefresh || empty($cached)) {
$jar = $this->login();
//Cache the cookieJar 3000 s.
$this->getCache()->save($cacheKey, serialize($jar), 3000);
return $jar;
}
return unserialize($cached);
} | [
"public",
"function",
"getCookie",
"(",
"$",
"forceRefresh",
"=",
"false",
")",
"{",
"$",
"cacheKey",
"=",
"$",
"this",
"->",
"cachePrefix",
".",
"$",
"this",
"->",
"stu_id",
";",
"$",
"cached",
"=",
"$",
"this",
"->",
"getCache",
"(",
")",
"->",
"fe... | Get cookie from cache or login.
@param bool $forceRefresh
@return string | [
"Get",
"cookie",
"from",
"cache",
"or",
"login",
"."
] | 61adc5d99355155099743b288ea3be52efebb852 | https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Lcrawl.php#L111-L122 | train |
lndj/Lcrawl | src/Lcrawl.php | Lcrawl.getAll | public function getAll()
{
$requests = [
'schedule' => $this->buildGetRequest(self::ZF_SCHEDULE_URI, [], $this->headers, true),
'cet' => $this->buildGetRequest(self::ZF_CET_URI, [], $this->headers, true),
'exam' => $this->buildGetRequest(self::ZF_EXAM_URI, [], $this->headers, true),
];
// Wait on all of the requests to complete. Throws a ConnectException
// if any of the requests fail
$results = Promise\unwrap($requests);
// Wait for the requests to complete, even if some of them fail
// $results = Promise\settle($requests)->wait();
//Parser the data we need.
$schedule = $this->parserSchedule($results['schedule']->getBody());
$cet = $this->parserCommonTable($results['cet']->getBody());
$exam = $this->parserCommonTable($results['exam']->getBody());
return compact('schedule', 'cet', 'exam');
} | php | public function getAll()
{
$requests = [
'schedule' => $this->buildGetRequest(self::ZF_SCHEDULE_URI, [], $this->headers, true),
'cet' => $this->buildGetRequest(self::ZF_CET_URI, [], $this->headers, true),
'exam' => $this->buildGetRequest(self::ZF_EXAM_URI, [], $this->headers, true),
];
// Wait on all of the requests to complete. Throws a ConnectException
// if any of the requests fail
$results = Promise\unwrap($requests);
// Wait for the requests to complete, even if some of them fail
// $results = Promise\settle($requests)->wait();
//Parser the data we need.
$schedule = $this->parserSchedule($results['schedule']->getBody());
$cet = $this->parserCommonTable($results['cet']->getBody());
$exam = $this->parserCommonTable($results['exam']->getBody());
return compact('schedule', 'cet', 'exam');
} | [
"public",
"function",
"getAll",
"(",
")",
"{",
"$",
"requests",
"=",
"[",
"'schedule'",
"=>",
"$",
"this",
"->",
"buildGetRequest",
"(",
"self",
"::",
"ZF_SCHEDULE_URI",
",",
"[",
"]",
",",
"$",
"this",
"->",
"headers",
",",
"true",
")",
",",
"'cet'",
... | By Concurrent requests, to get all the data.
@return Array | [
"By",
"Concurrent",
"requests",
"to",
"get",
"all",
"the",
"data",
"."
] | 61adc5d99355155099743b288ea3be52efebb852 | https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Lcrawl.php#L352-L372 | train |
lndj/Lcrawl | src/Lcrawl.php | Lcrawl.getSchedule | public function getSchedule()
{
/**
* Default: get the current term schedule data by GET
* If you want to get the other term's data, use POST
* TODO: use POST to get other term's data
*/
$response = $this->buildGetRequest(self::ZF_SCHEDULE_URI, [], $this->headers);
return $this->parserSchedule($response->getBody());
} | php | public function getSchedule()
{
/**
* Default: get the current term schedule data by GET
* If you want to get the other term's data, use POST
* TODO: use POST to get other term's data
*/
$response = $this->buildGetRequest(self::ZF_SCHEDULE_URI, [], $this->headers);
return $this->parserSchedule($response->getBody());
} | [
"public",
"function",
"getSchedule",
"(",
")",
"{",
"/**\n * Default: get the current term schedule data by GET\n * If you want to get the other term's data, use POST\n * TODO: use POST to get other term's data\n */",
"$",
"response",
"=",
"$",
"this",
"->",
... | Get the schedule data
@return Array | [
"Get",
"the",
"schedule",
"data"
] | 61adc5d99355155099743b288ea3be52efebb852 | https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Lcrawl.php#L404-L413 | train |
lndj/Lcrawl | src/Lcrawl.php | Lcrawl.getCet | public function getCet()
{
$response = $this->buildGetRequest(self::ZF_CET_URI);
return $this->parserCommonTable($response->getBody());
} | php | public function getCet()
{
$response = $this->buildGetRequest(self::ZF_CET_URI);
return $this->parserCommonTable($response->getBody());
} | [
"public",
"function",
"getCet",
"(",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"buildGetRequest",
"(",
"self",
"::",
"ZF_CET_URI",
")",
";",
"return",
"$",
"this",
"->",
"parserCommonTable",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
... | Get the CET data.
@return type|Object | [
"Get",
"the",
"CET",
"data",
"."
] | 61adc5d99355155099743b288ea3be52efebb852 | https://github.com/lndj/Lcrawl/blob/61adc5d99355155099743b288ea3be52efebb852/src/Lcrawl.php#L419-L423 | train |
letsdrink/ouzo | src/Ouzo/Core/Validatable.php | Validatable.validateTrue | public function validateTrue($value, $errorMessage, $errorField = null)
{
if (!$value) {
$this->error($errorMessage);
$this->_errorFields[] = $errorField;
}
} | php | public function validateTrue($value, $errorMessage, $errorField = null)
{
if (!$value) {
$this->error($errorMessage);
$this->_errorFields[] = $errorField;
}
} | [
"public",
"function",
"validateTrue",
"(",
"$",
"value",
",",
"$",
"errorMessage",
",",
"$",
"errorField",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"$",
"errorMessage",
")",
";",
"$",
"this",
"... | Checks whether value is true, if not it saves error
@param $value - value to check whether is true
(values which are considered as TRUE or FALSE are presented here http://php.net/manual/en/types.comparisons.php )
@param $errorMessage - error message
@param null $errorField | [
"Checks",
"whether",
"value",
"is",
"true",
"if",
"not",
"it",
"saves",
"error"
] | 4ab809ce8152dc7ef02c67bd6d42924d5d73631e | https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L88-L94 | train |
letsdrink/ouzo | src/Ouzo/Core/Validatable.php | Validatable.validateUnique | public function validateUnique(array $values, $errorMessage, $errorField = null)
{
if (count($values) != count(array_unique($values))) {
$this->error($errorMessage);
$this->_errorFields[] = $errorField;
}
} | php | public function validateUnique(array $values, $errorMessage, $errorField = null)
{
if (count($values) != count(array_unique($values))) {
$this->error($errorMessage);
$this->_errorFields[] = $errorField;
}
} | [
"public",
"function",
"validateUnique",
"(",
"array",
"$",
"values",
",",
"$",
"errorMessage",
",",
"$",
"errorField",
"=",
"null",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"values",
")",
"!=",
"count",
"(",
"array_unique",
"(",
"$",
"values",
")",
")",... | Checks whether array does not contain duplicate values
@param array $values - array to check
@param $errorMessage - error message
@param null $errorField | [
"Checks",
"whether",
"array",
"does",
"not",
"contain",
"duplicate",
"values"
] | 4ab809ce8152dc7ef02c67bd6d42924d5d73631e | https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L102-L108 | train |
letsdrink/ouzo | src/Ouzo/Core/Validatable.php | Validatable.validateStringMaxLength | public function validateStringMaxLength($value, $maxLength, $errorMessage, $errorField = null)
{
if (strlen($value) > $maxLength) {
$this->error($errorMessage);
$this->_errorFields[] = $errorField;
}
} | php | public function validateStringMaxLength($value, $maxLength, $errorMessage, $errorField = null)
{
if (strlen($value) > $maxLength) {
$this->error($errorMessage);
$this->_errorFields[] = $errorField;
}
} | [
"public",
"function",
"validateStringMaxLength",
"(",
"$",
"value",
",",
"$",
"maxLength",
",",
"$",
"errorMessage",
",",
"$",
"errorField",
"=",
"null",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"value",
")",
">",
"$",
"maxLength",
")",
"{",
"$",
"this... | Checks whether string does not exceed max length
@param string $value - string to check
@param int $maxLength - max length which doesn't cause error
@param $errorMessage - error message
@param null $errorField | [
"Checks",
"whether",
"string",
"does",
"not",
"exceed",
"max",
"length"
] | 4ab809ce8152dc7ef02c67bd6d42924d5d73631e | https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L131-L137 | train |
letsdrink/ouzo | src/Ouzo/Core/Validatable.php | Validatable.error | public function error($error, $code = 0)
{
$this->_errors[] = $error instanceof Error ? $error : new Error($code, $error);
} | php | public function error($error, $code = 0)
{
$this->_errors[] = $error instanceof Error ? $error : new Error($code, $error);
} | [
"public",
"function",
"error",
"(",
"$",
"error",
",",
"$",
"code",
"=",
"0",
")",
"{",
"$",
"this",
"->",
"_errors",
"[",
"]",
"=",
"$",
"error",
"instanceof",
"Error",
"?",
"$",
"error",
":",
"new",
"Error",
"(",
"$",
"code",
",",
"$",
"error",... | Method for adding error manually
@param string|\Ouzo\ExceptionHandling\Error $error - \Ouzo\ExceptionHandling\Error instance or new error message
@param int $code - error code | [
"Method",
"for",
"adding",
"error",
"manually"
] | 4ab809ce8152dc7ef02c67bd6d42924d5d73631e | https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L174-L177 | train |
letsdrink/ouzo | src/Ouzo/Core/Validatable.php | Validatable.errors | public function errors(array $errors, $code = 0)
{
foreach ($errors as $error) {
$this->error($error, $code);
}
} | php | public function errors(array $errors, $code = 0)
{
foreach ($errors as $error) {
$this->error($error, $code);
}
} | [
"public",
"function",
"errors",
"(",
"array",
"$",
"errors",
",",
"$",
"code",
"=",
"0",
")",
"{",
"foreach",
"(",
"$",
"errors",
"as",
"$",
"error",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"$",
"error",
",",
"$",
"code",
")",
";",
"}",
"}"
... | Method for batch adding errors manually
@param array $errors - array of \Ouzo\ExceptionHandling\Error instaces or new error messages
@param int $code | [
"Method",
"for",
"batch",
"adding",
"errors",
"manually"
] | 4ab809ce8152dc7ef02c67bd6d42924d5d73631e | https://github.com/letsdrink/ouzo/blob/4ab809ce8152dc7ef02c67bd6d42924d5d73631e/src/Ouzo/Core/Validatable.php#L184-L189 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Image.php | Image.scaleDimensions | public static function scaleDimensions(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) {
$aspect = $dimensions['height'] / $dimensions['width'];
// Calculate one of the dimensions from the other target dimension,
// ensuring the same aspect ratio as the source dimensions. If one of the
// target dimensions is missing, that is the one that is calculated. If both
// are specified then the dimension calculated is the one that would not be
// calculated to be bigger than its target.
if (($width && !$height) || ($width && $height && $aspect < $height / $width)) {
$height = (int) round($width * $aspect);
}
else {
$width = (int) round($height / $aspect);
}
// Don't upscale if the option isn't enabled.
if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) {
return FALSE;
}
$dimensions['width'] = $width;
$dimensions['height'] = $height;
return TRUE;
} | php | public static function scaleDimensions(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) {
$aspect = $dimensions['height'] / $dimensions['width'];
// Calculate one of the dimensions from the other target dimension,
// ensuring the same aspect ratio as the source dimensions. If one of the
// target dimensions is missing, that is the one that is calculated. If both
// are specified then the dimension calculated is the one that would not be
// calculated to be bigger than its target.
if (($width && !$height) || ($width && $height && $aspect < $height / $width)) {
$height = (int) round($width * $aspect);
}
else {
$width = (int) round($height / $aspect);
}
// Don't upscale if the option isn't enabled.
if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) {
return FALSE;
}
$dimensions['width'] = $width;
$dimensions['height'] = $height;
return TRUE;
} | [
"public",
"static",
"function",
"scaleDimensions",
"(",
"array",
"&",
"$",
"dimensions",
",",
"$",
"width",
"=",
"NULL",
",",
"$",
"height",
"=",
"NULL",
",",
"$",
"upscale",
"=",
"FALSE",
")",
"{",
"$",
"aspect",
"=",
"$",
"dimensions",
"[",
"'height'... | Scales image dimensions while maintaining aspect ratio.
The resulting dimensions can be smaller for one or both target dimensions.
@param array $dimensions
Dimensions to be modified - an array with components width and height, in
pixels.
@param int $width
(optional) The target width, in pixels. If this value is NULL then the
scaling will be based only on the height value.
@param int $height
(optional) The target height, in pixels. If this value is NULL then the
scaling will be based only on the width value.
@param bool $upscale
(optional) Boolean indicating that images smaller than the target
dimensions will be scaled up. This generally results in a low quality
image.
@return bool
TRUE if $dimensions was modified, FALSE otherwise.
@see image_scale() | [
"Scales",
"image",
"dimensions",
"while",
"maintaining",
"aspect",
"ratio",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Image.php#L41-L64 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Color.php | Color.validateHex | public static function validateHex($hex) {
// Must be a string.
$valid = is_string($hex);
// Hash prefix is optional.
$hex = ltrim($hex, '#');
// Must be either RGB or RRGGBB.
$length = Unicode::strlen($hex);
$valid = $valid && ($length === 3 || $length === 6);
// Must be a valid hex value.
$valid = $valid && ctype_xdigit($hex);
return $valid;
} | php | public static function validateHex($hex) {
// Must be a string.
$valid = is_string($hex);
// Hash prefix is optional.
$hex = ltrim($hex, '#');
// Must be either RGB or RRGGBB.
$length = Unicode::strlen($hex);
$valid = $valid && ($length === 3 || $length === 6);
// Must be a valid hex value.
$valid = $valid && ctype_xdigit($hex);
return $valid;
} | [
"public",
"static",
"function",
"validateHex",
"(",
"$",
"hex",
")",
"{",
"// Must be a string.",
"$",
"valid",
"=",
"is_string",
"(",
"$",
"hex",
")",
";",
"// Hash prefix is optional.",
"$",
"hex",
"=",
"ltrim",
"(",
"$",
"hex",
",",
"'#'",
")",
";",
"... | Validates whether a hexadecimal color value is syntactically correct.
@param $hex
The hexadecimal string to validate. May contain a leading '#'. May use
the shorthand notation (e.g., '123' for '112233').
@return bool
TRUE if $hex is valid or FALSE if it is not. | [
"Validates",
"whether",
"a",
"hexadecimal",
"color",
"value",
"is",
"syntactically",
"correct",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Color.php#L25-L36 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Xss.php | Xss.split | protected static function split($string, $html_tags, $class) {
if (substr($string, 0, 1) != '<') {
// We matched a lone ">" character.
return '>';
}
elseif (strlen($string) == 1) {
// We matched a lone "<" character.
return '<';
}
if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)\s*([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
// Seriously malformed.
return '';
}
$slash = trim($matches[1]);
$elem = &$matches[2];
$attrlist = &$matches[3];
$comment = &$matches[4];
if ($comment) {
$elem = '!--';
}
// When in whitelist mode, an element is disallowed when not listed.
if ($class::needsRemoval($html_tags, $elem)) {
return '';
}
if ($comment) {
return $comment;
}
if ($slash != '') {
return "</$elem>";
}
// Is there a closing XHTML slash at the end of the attributes?
$attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
$xhtml_slash = $count ? ' /' : '';
// Clean up attributes.
$attr2 = implode(' ', $class::attributes($attrlist));
$attr2 = preg_replace('/[<>]/', '', $attr2);
$attr2 = strlen($attr2) ? ' ' . $attr2 : '';
return "<$elem$attr2$xhtml_slash>";
} | php | protected static function split($string, $html_tags, $class) {
if (substr($string, 0, 1) != '<') {
// We matched a lone ">" character.
return '>';
}
elseif (strlen($string) == 1) {
// We matched a lone "<" character.
return '<';
}
if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)\s*([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
// Seriously malformed.
return '';
}
$slash = trim($matches[1]);
$elem = &$matches[2];
$attrlist = &$matches[3];
$comment = &$matches[4];
if ($comment) {
$elem = '!--';
}
// When in whitelist mode, an element is disallowed when not listed.
if ($class::needsRemoval($html_tags, $elem)) {
return '';
}
if ($comment) {
return $comment;
}
if ($slash != '') {
return "</$elem>";
}
// Is there a closing XHTML slash at the end of the attributes?
$attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
$xhtml_slash = $count ? ' /' : '';
// Clean up attributes.
$attr2 = implode(' ', $class::attributes($attrlist));
$attr2 = preg_replace('/[<>]/', '', $attr2);
$attr2 = strlen($attr2) ? ' ' . $attr2 : '';
return "<$elem$attr2$xhtml_slash>";
} | [
"protected",
"static",
"function",
"split",
"(",
"$",
"string",
",",
"$",
"html_tags",
",",
"$",
"class",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"string",
",",
"0",
",",
"1",
")",
"!=",
"'<'",
")",
"{",
"// We matched a lone \">\" character.",
"return"... | Processes an HTML tag.
@param string $string
The HTML tag to process.
@param array $html_tags
An array where the keys are the allowed tags and the values are not
used.
@param string $class
The called class. This method is called from an anonymous function which
breaks late static binding. See https://bugs.php.net/bug.php?id=66622 for
more information.
@return string
If the element isn't allowed, an empty string. Otherwise, the cleaned up
version of the HTML element. | [
"Processes",
"an",
"HTML",
"tag",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Xss.php#L147-L193 | train |
aleksip/plugin-data-transform | src/Drupal/Core/Template/AttributeValueBase.php | AttributeValueBase.render | public function render() {
$value = (string) $this;
if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) {
return Html::escape($this->name) . '="' . $value . '"';
}
} | php | public function render() {
$value = (string) $this;
if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) {
return Html::escape($this->name) . '="' . $value . '"';
}
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"value",
"=",
"(",
"string",
")",
"$",
"this",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"value",
")",
"&&",
"static",
"::",
"RENDER_EMPTY_ATTRIBUTE",
"||",
"!",
"empty",
"(",
"$",
"value",
... | Returns a string representation of the attribute.
While __toString only returns the value in a string form, render()
contains the name of the attribute as well.
@return string
The string representation of the attribute. | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"attribute",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/AttributeValueBase.php#L56-L61 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Tags.php | Tags.explode | public static function explode($tags) {
// This regexp allows the following types of user input:
// this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
$regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
preg_match_all($regexp, $tags, $matches);
$typed_tags = array_unique($matches[1]);
$tags = array();
foreach ($typed_tags as $tag) {
// If a user has escaped a term (to demonstrate that it is a group,
// or includes a comma or quote character), we remove the escape
// formatting so to save the term into the database as the user intends.
$tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
if ($tag != "") {
$tags[] = $tag;
}
}
return $tags;
} | php | public static function explode($tags) {
// This regexp allows the following types of user input:
// this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
$regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
preg_match_all($regexp, $tags, $matches);
$typed_tags = array_unique($matches[1]);
$tags = array();
foreach ($typed_tags as $tag) {
// If a user has escaped a term (to demonstrate that it is a group,
// or includes a comma or quote character), we remove the escape
// formatting so to save the term into the database as the user intends.
$tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
if ($tag != "") {
$tags[] = $tag;
}
}
return $tags;
} | [
"public",
"static",
"function",
"explode",
"(",
"$",
"tags",
")",
"{",
"// This regexp allows the following types of user input:",
"// this, \"somecompany, llc\", \"and \"\"this\"\" w,o.rks\", foo bar",
"$",
"regexp",
"=",
"'%(?:^|,\\ *)(\"(?>[^\"]*)(?>\"\"[^\"]* )*\"|(?: [^\",]*))%x'",
... | Explodes a string of tags into an array.
@param string $tags
A string to explode.
@return array
An array of tags. | [
"Explodes",
"a",
"string",
"of",
"tags",
"into",
"an",
"array",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Tags.php#L26-L45 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Tags.php | Tags.encode | public static function encode($tag) {
if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
return '"' . str_replace('"', '""', $tag) . '"';
}
return $tag;
} | php | public static function encode($tag) {
if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
return '"' . str_replace('"', '""', $tag) . '"';
}
return $tag;
} | [
"public",
"static",
"function",
"encode",
"(",
"$",
"tag",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"tag",
",",
"','",
")",
"!==",
"FALSE",
"||",
"strpos",
"(",
"$",
"tag",
",",
"'\"'",
")",
"!==",
"FALSE",
")",
"{",
"return",
"'\"'",
".",
"str_r... | Encodes a tag string, taking care of special cases like commas and quotes.
@param string $tag
A tag string.
@return string
The encoded string. | [
"Encodes",
"a",
"tag",
"string",
"taking",
"care",
"of",
"special",
"cases",
"like",
"commas",
"and",
"quotes",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Tags.php#L56-L61 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Tags.php | Tags.implode | public static function implode($tags) {
$encoded_tags = array();
foreach ($tags as $tag) {
$encoded_tags[] = self::encode($tag);
}
return implode(', ', $encoded_tags);
} | php | public static function implode($tags) {
$encoded_tags = array();
foreach ($tags as $tag) {
$encoded_tags[] = self::encode($tag);
}
return implode(', ', $encoded_tags);
} | [
"public",
"static",
"function",
"implode",
"(",
"$",
"tags",
")",
"{",
"$",
"encoded_tags",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"tags",
"as",
"$",
"tag",
")",
"{",
"$",
"encoded_tags",
"[",
"]",
"=",
"self",
"::",
"encode",
"(",
"$",
... | Implodes an array of tags into a string.
@param array $tags
An array of tags.
@return string
The imploded string. | [
"Implodes",
"an",
"array",
"of",
"tags",
"into",
"a",
"string",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Tags.php#L72-L78 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/UserAgent.php | UserAgent.getBestMatchingLangcode | public static function getBestMatchingLangcode($http_accept_language, $langcodes, $mappings = array()) {
// The Accept-Language header contains information about the language
// preferences configured in the user's user agent / operating system.
// RFC 2616 (section 14.4) defines the Accept-Language header as follows:
// Accept-Language = "Accept-Language" ":"
// 1#( language-range [ ";" "q" "=" qvalue ] )
// language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
// Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
$ua_langcodes = array();
if (preg_match_all('@(?<=[, ]|^)([a-zA-Z-]+|\*)(?:;q=([0-9.]+))?(?:$|\s*,\s*)@', trim($http_accept_language), $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
if ($mappings) {
$langcode = strtolower($match[1]);
foreach ($mappings as $ua_langcode => $standard_langcode) {
if ($langcode == $ua_langcode) {
$match[1] = $standard_langcode;
}
}
}
// We can safely use strtolower() here, tags are ASCII.
// RFC2616 mandates that the decimal part is no more than three digits,
// so we multiply the qvalue by 1000 to avoid floating point
// comparisons.
$langcode = strtolower($match[1]);
$qvalue = isset($match[2]) ? (float) $match[2] : 1;
// Take the highest qvalue for this langcode. Although the request
// supposedly contains unique langcodes, our mapping possibly resolves
// to the same langcode for different qvalues. Keep the highest.
$ua_langcodes[$langcode] = max(
(int) ($qvalue * 1000),
(isset($ua_langcodes[$langcode]) ? $ua_langcodes[$langcode] : 0)
);
}
}
// We should take pristine values from the HTTP headers, but Internet
// Explorer from version 7 sends only specific language tags (eg. fr-CA)
// without the corresponding generic tag (fr) unless explicitly configured.
// In that case, we assume that the lowest value of the specific tags is the
// value of the generic language to be as close to the HTTP 1.1 spec as
// possible.
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and
// http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx
asort($ua_langcodes);
foreach ($ua_langcodes as $langcode => $qvalue) {
// For Chinese languages the generic tag is either zh-hans or zh-hant, so
// we need to handle this separately, we can not split $langcode on the
// first occurrence of '-' otherwise we get a non-existing language zh.
// All other languages use a langcode without a '-', so we can safely
// split on the first occurrence of it.
if (strlen($langcode) > 7 && (substr($langcode, 0, 7) == 'zh-hant' || substr($langcode, 0, 7) == 'zh-hans')) {
$generic_tag = substr($langcode, 0, 7);
}
else {
$generic_tag = strtok($langcode, '-');
}
if (!empty($generic_tag) && !isset($ua_langcodes[$generic_tag])) {
// Add the generic langcode, but make sure it has a lower qvalue as the
// more specific one, so the more specific one gets selected if it's
// defined by both the user agent and us.
$ua_langcodes[$generic_tag] = $qvalue - 0.1;
}
}
// Find the added language with the greatest qvalue, following the rules
// of RFC 2616 (section 14.4). If several languages have the same qvalue,
// prefer the one with the greatest weight.
$best_match_langcode = FALSE;
$max_qvalue = 0;
foreach ($langcodes as $langcode_case_sensitive) {
// Language tags are case insensitive (RFC2616, sec 3.10).
$langcode = strtolower($langcode_case_sensitive);
// If nothing matches below, the default qvalue is the one of the wildcard
// language, if set, or is 0 (which will never match).
$qvalue = isset($ua_langcodes['*']) ? $ua_langcodes['*'] : 0;
// Find the longest possible prefix of the user agent supplied language
// ('the language-range') that matches this site language ('the language
// tag').
$prefix = $langcode;
do {
if (isset($ua_langcodes[$prefix])) {
$qvalue = $ua_langcodes[$prefix];
break;
}
}
while ($prefix = substr($prefix, 0, strrpos($prefix, '-')));
// Find the best match.
if ($qvalue > $max_qvalue) {
$best_match_langcode = $langcode_case_sensitive;
$max_qvalue = $qvalue;
}
}
return $best_match_langcode;
} | php | public static function getBestMatchingLangcode($http_accept_language, $langcodes, $mappings = array()) {
// The Accept-Language header contains information about the language
// preferences configured in the user's user agent / operating system.
// RFC 2616 (section 14.4) defines the Accept-Language header as follows:
// Accept-Language = "Accept-Language" ":"
// 1#( language-range [ ";" "q" "=" qvalue ] )
// language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
// Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
$ua_langcodes = array();
if (preg_match_all('@(?<=[, ]|^)([a-zA-Z-]+|\*)(?:;q=([0-9.]+))?(?:$|\s*,\s*)@', trim($http_accept_language), $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
if ($mappings) {
$langcode = strtolower($match[1]);
foreach ($mappings as $ua_langcode => $standard_langcode) {
if ($langcode == $ua_langcode) {
$match[1] = $standard_langcode;
}
}
}
// We can safely use strtolower() here, tags are ASCII.
// RFC2616 mandates that the decimal part is no more than three digits,
// so we multiply the qvalue by 1000 to avoid floating point
// comparisons.
$langcode = strtolower($match[1]);
$qvalue = isset($match[2]) ? (float) $match[2] : 1;
// Take the highest qvalue for this langcode. Although the request
// supposedly contains unique langcodes, our mapping possibly resolves
// to the same langcode for different qvalues. Keep the highest.
$ua_langcodes[$langcode] = max(
(int) ($qvalue * 1000),
(isset($ua_langcodes[$langcode]) ? $ua_langcodes[$langcode] : 0)
);
}
}
// We should take pristine values from the HTTP headers, but Internet
// Explorer from version 7 sends only specific language tags (eg. fr-CA)
// without the corresponding generic tag (fr) unless explicitly configured.
// In that case, we assume that the lowest value of the specific tags is the
// value of the generic language to be as close to the HTTP 1.1 spec as
// possible.
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and
// http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx
asort($ua_langcodes);
foreach ($ua_langcodes as $langcode => $qvalue) {
// For Chinese languages the generic tag is either zh-hans or zh-hant, so
// we need to handle this separately, we can not split $langcode on the
// first occurrence of '-' otherwise we get a non-existing language zh.
// All other languages use a langcode without a '-', so we can safely
// split on the first occurrence of it.
if (strlen($langcode) > 7 && (substr($langcode, 0, 7) == 'zh-hant' || substr($langcode, 0, 7) == 'zh-hans')) {
$generic_tag = substr($langcode, 0, 7);
}
else {
$generic_tag = strtok($langcode, '-');
}
if (!empty($generic_tag) && !isset($ua_langcodes[$generic_tag])) {
// Add the generic langcode, but make sure it has a lower qvalue as the
// more specific one, so the more specific one gets selected if it's
// defined by both the user agent and us.
$ua_langcodes[$generic_tag] = $qvalue - 0.1;
}
}
// Find the added language with the greatest qvalue, following the rules
// of RFC 2616 (section 14.4). If several languages have the same qvalue,
// prefer the one with the greatest weight.
$best_match_langcode = FALSE;
$max_qvalue = 0;
foreach ($langcodes as $langcode_case_sensitive) {
// Language tags are case insensitive (RFC2616, sec 3.10).
$langcode = strtolower($langcode_case_sensitive);
// If nothing matches below, the default qvalue is the one of the wildcard
// language, if set, or is 0 (which will never match).
$qvalue = isset($ua_langcodes['*']) ? $ua_langcodes['*'] : 0;
// Find the longest possible prefix of the user agent supplied language
// ('the language-range') that matches this site language ('the language
// tag').
$prefix = $langcode;
do {
if (isset($ua_langcodes[$prefix])) {
$qvalue = $ua_langcodes[$prefix];
break;
}
}
while ($prefix = substr($prefix, 0, strrpos($prefix, '-')));
// Find the best match.
if ($qvalue > $max_qvalue) {
$best_match_langcode = $langcode_case_sensitive;
$max_qvalue = $qvalue;
}
}
return $best_match_langcode;
} | [
"public",
"static",
"function",
"getBestMatchingLangcode",
"(",
"$",
"http_accept_language",
",",
"$",
"langcodes",
",",
"$",
"mappings",
"=",
"array",
"(",
")",
")",
"{",
"// The Accept-Language header contains information about the language",
"// preferences configured in t... | Identifies user agent language from the Accept-language HTTP header.
The algorithm works as follows:
- map user agent language codes to available language codes.
- order all user agent language codes by qvalue from high to low.
- add generic user agent language codes if they aren't already specified
but with a slightly lower qvalue.
- find the most specific available language code with the highest qvalue.
- if 2 or more languages are having the same qvalue, respect the order of
them inside the $languages array.
We perform user agent accept-language parsing only if page cache is
disabled, otherwise we would cache a user-specific preference.
@param string $http_accept_language
The value of the "Accept-Language" HTTP header.
@param array $langcodes
An array of available language codes to pick from.
@param array $mappings
(optional) Custom mappings to support user agents that are sending non
standard language codes. No mapping is assumed by default.
@return string
The selected language code or FALSE if no valid language can be
identified. | [
"Identifies",
"user",
"agent",
"language",
"from",
"the",
"Accept",
"-",
"language",
"HTTP",
"header",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UserAgent.php#L44-L141 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Environment.php | Environment.checkMemoryLimit | public static function checkMemoryLimit($required, $memory_limit = NULL) {
if (!isset($memory_limit)) {
$memory_limit = ini_get('memory_limit');
}
// There is sufficient memory if:
// - No memory limit is set.
// - The memory limit is set to unlimited (-1).
// - The memory limit is greater than or equal to the memory required for
// the operation.
return ((!$memory_limit) || ($memory_limit == -1) || (Bytes::toInt($memory_limit) >= Bytes::toInt($required)));
} | php | public static function checkMemoryLimit($required, $memory_limit = NULL) {
if (!isset($memory_limit)) {
$memory_limit = ini_get('memory_limit');
}
// There is sufficient memory if:
// - No memory limit is set.
// - The memory limit is set to unlimited (-1).
// - The memory limit is greater than or equal to the memory required for
// the operation.
return ((!$memory_limit) || ($memory_limit == -1) || (Bytes::toInt($memory_limit) >= Bytes::toInt($required)));
} | [
"public",
"static",
"function",
"checkMemoryLimit",
"(",
"$",
"required",
",",
"$",
"memory_limit",
"=",
"NULL",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"memory_limit",
")",
")",
"{",
"$",
"memory_limit",
"=",
"ini_get",
"(",
"'memory_limit'",
")",
... | Compares the memory required for an operation to the available memory.
@param string $required
The memory required for the operation, expressed as a number of bytes with
optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
9mbytes).
@param $memory_limit
(optional) The memory limit for the operation, expressed as a number of
bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
memory_limit will be used. Defaults to NULL.
@return bool
TRUE if there is sufficient memory to allow the operation, or FALSE
otherwise. | [
"Compares",
"the",
"memory",
"required",
"for",
"an",
"operation",
"to",
"the",
"available",
"memory",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Environment.php#L32-L43 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Unicode.php | Unicode.check | public static function check() {
// Check for mbstring extension.
if (!function_exists('mb_strlen')) {
static::$status = static::STATUS_SINGLEBYTE;
return 'mb_strlen';
}
// Check mbstring configuration.
if (ini_get('mbstring.func_overload') != 0) {
static::$status = static::STATUS_ERROR;
return 'mbstring.func_overload';
}
if (ini_get('mbstring.encoding_translation') != 0) {
static::$status = static::STATUS_ERROR;
return 'mbstring.encoding_translation';
}
// mbstring.http_input and mbstring.http_output are deprecated and empty by
// default in PHP 5.6.
if (version_compare(PHP_VERSION, '5.6.0') == -1) {
if (ini_get('mbstring.http_input') != 'pass') {
static::$status = static::STATUS_ERROR;
return 'mbstring.http_input';
}
if (ini_get('mbstring.http_output') != 'pass') {
static::$status = static::STATUS_ERROR;
return 'mbstring.http_output';
}
}
// Set appropriate configuration.
mb_internal_encoding('utf-8');
mb_language('uni');
static::$status = static::STATUS_MULTIBYTE;
return '';
} | php | public static function check() {
// Check for mbstring extension.
if (!function_exists('mb_strlen')) {
static::$status = static::STATUS_SINGLEBYTE;
return 'mb_strlen';
}
// Check mbstring configuration.
if (ini_get('mbstring.func_overload') != 0) {
static::$status = static::STATUS_ERROR;
return 'mbstring.func_overload';
}
if (ini_get('mbstring.encoding_translation') != 0) {
static::$status = static::STATUS_ERROR;
return 'mbstring.encoding_translation';
}
// mbstring.http_input and mbstring.http_output are deprecated and empty by
// default in PHP 5.6.
if (version_compare(PHP_VERSION, '5.6.0') == -1) {
if (ini_get('mbstring.http_input') != 'pass') {
static::$status = static::STATUS_ERROR;
return 'mbstring.http_input';
}
if (ini_get('mbstring.http_output') != 'pass') {
static::$status = static::STATUS_ERROR;
return 'mbstring.http_output';
}
}
// Set appropriate configuration.
mb_internal_encoding('utf-8');
mb_language('uni');
static::$status = static::STATUS_MULTIBYTE;
return '';
} | [
"public",
"static",
"function",
"check",
"(",
")",
"{",
"// Check for mbstring extension.",
"if",
"(",
"!",
"function_exists",
"(",
"'mb_strlen'",
")",
")",
"{",
"static",
"::",
"$",
"status",
"=",
"static",
"::",
"STATUS_SINGLEBYTE",
";",
"return",
"'mb_strlen'... | Checks for Unicode support in PHP and sets the proper settings if possible.
Because of the need to be able to handle text in various encodings, we do
not support mbstring function overloading. HTTP input/output conversion
must be disabled for similar reasons.
@return string
A string identifier of a failed multibyte extension check, if any.
Otherwise, an empty string. | [
"Checks",
"for",
"Unicode",
"support",
"in",
"PHP",
"and",
"sets",
"the",
"proper",
"settings",
"if",
"possible",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L150-L184 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Unicode.php | Unicode.convertToUtf8 | public static function convertToUtf8($data, $encoding) {
if (function_exists('iconv')) {
return @iconv($encoding, 'utf-8', $data);
}
elseif (function_exists('mb_convert_encoding')) {
return @mb_convert_encoding($data, 'utf-8', $encoding);
}
elseif (function_exists('recode_string')) {
return @recode_string($encoding . '..utf-8', $data);
}
// Cannot convert.
return FALSE;
} | php | public static function convertToUtf8($data, $encoding) {
if (function_exists('iconv')) {
return @iconv($encoding, 'utf-8', $data);
}
elseif (function_exists('mb_convert_encoding')) {
return @mb_convert_encoding($data, 'utf-8', $encoding);
}
elseif (function_exists('recode_string')) {
return @recode_string($encoding . '..utf-8', $data);
}
// Cannot convert.
return FALSE;
} | [
"public",
"static",
"function",
"convertToUtf8",
"(",
"$",
"data",
",",
"$",
"encoding",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'iconv'",
")",
")",
"{",
"return",
"@",
"iconv",
"(",
"$",
"encoding",
",",
"'utf-8'",
",",
"$",
"data",
")",
";",
... | Converts data to UTF-8.
Requires the iconv, GNU recode or mbstring PHP extension.
@param string $data
The data to be converted.
@param string $encoding
The encoding that the data is in.
@return string|bool
Converted data or FALSE. | [
"Converts",
"data",
"to",
"UTF",
"-",
"8",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L231-L243 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Unicode.php | Unicode.truncateBytes | public static function truncateBytes($string, $len) {
if (strlen($string) <= $len) {
return $string;
}
if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
return substr($string, 0, $len);
}
// Scan backwards to beginning of the byte sequence.
while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0);
return substr($string, 0, $len);
} | php | public static function truncateBytes($string, $len) {
if (strlen($string) <= $len) {
return $string;
}
if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
return substr($string, 0, $len);
}
// Scan backwards to beginning of the byte sequence.
while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0);
return substr($string, 0, $len);
} | [
"public",
"static",
"function",
"truncateBytes",
"(",
"$",
"string",
",",
"$",
"len",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"string",
")",
"<=",
"$",
"len",
")",
"{",
"return",
"$",
"string",
";",
"}",
"if",
"(",
"(",
"ord",
"(",
"$",
"string"... | Truncates a UTF-8-encoded string safely to a number of bytes.
If the end position is in the middle of a UTF-8 sequence, it scans backwards
until the beginning of the byte sequence.
Use this function whenever you want to chop off a string at an unsure
location. On the other hand, if you're sure that you're splitting on a
character boundary (e.g. after using strpos() or similar), you can safely
use substr() instead.
@param string $string
The string to truncate.
@param int $len
An upper limit on the returned string length.
@return string
The truncated string. | [
"Truncates",
"a",
"UTF",
"-",
"8",
"-",
"encoded",
"string",
"safely",
"to",
"a",
"number",
"of",
"bytes",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L264-L275 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Unicode.php | Unicode.strtoupper | public static function strtoupper($text) {
if (static::getStatus() == static::STATUS_MULTIBYTE) {
return mb_strtoupper($text);
}
else {
// Use C-locale for ASCII-only uppercase.
$text = strtoupper($text);
// Case flip Latin-1 accented letters.
$text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
return $text;
}
} | php | public static function strtoupper($text) {
if (static::getStatus() == static::STATUS_MULTIBYTE) {
return mb_strtoupper($text);
}
else {
// Use C-locale for ASCII-only uppercase.
$text = strtoupper($text);
// Case flip Latin-1 accented letters.
$text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
return $text;
}
} | [
"public",
"static",
"function",
"strtoupper",
"(",
"$",
"text",
")",
"{",
"if",
"(",
"static",
"::",
"getStatus",
"(",
")",
"==",
"static",
"::",
"STATUS_MULTIBYTE",
")",
"{",
"return",
"mb_strtoupper",
"(",
"$",
"text",
")",
";",
"}",
"else",
"{",
"//... | Converts a UTF-8 string to uppercase.
@param string $text
The string to run the operation on.
@return string
The string in uppercase. | [
"Converts",
"a",
"UTF",
"-",
"8",
"string",
"to",
"uppercase",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L307-L318 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Unicode.php | Unicode.strtolower | public static function strtolower($text) {
if (static::getStatus() == static::STATUS_MULTIBYTE) {
return mb_strtolower($text);
}
else {
// Use C-locale for ASCII-only lowercase.
$text = strtolower($text);
// Case flip Latin-1 accented letters.
$text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
return $text;
}
} | php | public static function strtolower($text) {
if (static::getStatus() == static::STATUS_MULTIBYTE) {
return mb_strtolower($text);
}
else {
// Use C-locale for ASCII-only lowercase.
$text = strtolower($text);
// Case flip Latin-1 accented letters.
$text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
return $text;
}
} | [
"public",
"static",
"function",
"strtolower",
"(",
"$",
"text",
")",
"{",
"if",
"(",
"static",
"::",
"getStatus",
"(",
")",
"==",
"static",
"::",
"STATUS_MULTIBYTE",
")",
"{",
"return",
"mb_strtolower",
"(",
"$",
"text",
")",
";",
"}",
"else",
"{",
"//... | Converts a UTF-8 string to lowercase.
@param string $text
The string to run the operation on.
@return string
The string in lowercase. | [
"Converts",
"a",
"UTF",
"-",
"8",
"string",
"to",
"lowercase",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L329-L340 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Unicode.php | Unicode.ucwords | public static function ucwords($text) {
$regex = '/(^|[' . static::PREG_CLASS_WORD_BOUNDARY . '])([^' . static::PREG_CLASS_WORD_BOUNDARY . '])/u';
return preg_replace_callback($regex, function(array $matches) {
return $matches[1] . Unicode::strtoupper($matches[2]);
}, $text);
} | php | public static function ucwords($text) {
$regex = '/(^|[' . static::PREG_CLASS_WORD_BOUNDARY . '])([^' . static::PREG_CLASS_WORD_BOUNDARY . '])/u';
return preg_replace_callback($regex, function(array $matches) {
return $matches[1] . Unicode::strtoupper($matches[2]);
}, $text);
} | [
"public",
"static",
"function",
"ucwords",
"(",
"$",
"text",
")",
"{",
"$",
"regex",
"=",
"'/(^|['",
".",
"static",
"::",
"PREG_CLASS_WORD_BOUNDARY",
".",
"'])([^'",
".",
"static",
"::",
"PREG_CLASS_WORD_BOUNDARY",
".",
"'])/u'",
";",
"return",
"preg_replace_cal... | Capitalizes the first character of each word in a UTF-8 string.
@param string $text
The text that will be converted.
@return string
The input $text with each word capitalized.
@ingroup php_wrappers | [
"Capitalizes",
"the",
"first",
"character",
"of",
"each",
"word",
"in",
"a",
"UTF",
"-",
"8",
"string",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L382-L387 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Unicode.php | Unicode.substr | public static function substr($text, $start, $length = NULL) {
if (static::getStatus() == static::STATUS_MULTIBYTE) {
return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length);
}
else {
$strlen = strlen($text);
// Find the starting byte offset.
$bytes = 0;
if ($start > 0) {
// Count all the characters except continuation bytes from the start
// until we have found $start characters or the end of the string.
$bytes = -1; $chars = -1;
while ($bytes < $strlen - 1 && $chars < $start) {
$bytes++;
$c = ord($text[$bytes]);
if ($c < 0x80 || $c >= 0xC0) {
$chars++;
}
}
}
elseif ($start < 0) {
// Count all the characters except continuation bytes from the end
// until we have found abs($start) characters.
$start = abs($start);
$bytes = $strlen; $chars = 0;
while ($bytes > 0 && $chars < $start) {
$bytes--;
$c = ord($text[$bytes]);
if ($c < 0x80 || $c >= 0xC0) {
$chars++;
}
}
}
$istart = $bytes;
// Find the ending byte offset.
if ($length === NULL) {
$iend = $strlen;
}
elseif ($length > 0) {
// Count all the characters except continuation bytes from the starting
// index until we have found $length characters or reached the end of
// the string, then backtrace one byte.
$iend = $istart - 1;
$chars = -1;
$last_real = FALSE;
while ($iend < $strlen - 1 && $chars < $length) {
$iend++;
$c = ord($text[$iend]);
$last_real = FALSE;
if ($c < 0x80 || $c >= 0xC0) {
$chars++;
$last_real = TRUE;
}
}
// Backtrace one byte if the last character we found was a real
// character and we don't need it.
if ($last_real && $chars >= $length) {
$iend--;
}
}
elseif ($length < 0) {
// Count all the characters except continuation bytes from the end
// until we have found abs($start) characters, then backtrace one byte.
$length = abs($length);
$iend = $strlen; $chars = 0;
while ($iend > 0 && $chars < $length) {
$iend--;
$c = ord($text[$iend]);
if ($c < 0x80 || $c >= 0xC0) {
$chars++;
}
}
// Backtrace one byte if we are not at the beginning of the string.
if ($iend > 0) {
$iend--;
}
}
else {
// $length == 0, return an empty string.
return '';
}
return substr($text, $istart, max(0, $iend - $istart + 1));
}
} | php | public static function substr($text, $start, $length = NULL) {
if (static::getStatus() == static::STATUS_MULTIBYTE) {
return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length);
}
else {
$strlen = strlen($text);
// Find the starting byte offset.
$bytes = 0;
if ($start > 0) {
// Count all the characters except continuation bytes from the start
// until we have found $start characters or the end of the string.
$bytes = -1; $chars = -1;
while ($bytes < $strlen - 1 && $chars < $start) {
$bytes++;
$c = ord($text[$bytes]);
if ($c < 0x80 || $c >= 0xC0) {
$chars++;
}
}
}
elseif ($start < 0) {
// Count all the characters except continuation bytes from the end
// until we have found abs($start) characters.
$start = abs($start);
$bytes = $strlen; $chars = 0;
while ($bytes > 0 && $chars < $start) {
$bytes--;
$c = ord($text[$bytes]);
if ($c < 0x80 || $c >= 0xC0) {
$chars++;
}
}
}
$istart = $bytes;
// Find the ending byte offset.
if ($length === NULL) {
$iend = $strlen;
}
elseif ($length > 0) {
// Count all the characters except continuation bytes from the starting
// index until we have found $length characters or reached the end of
// the string, then backtrace one byte.
$iend = $istart - 1;
$chars = -1;
$last_real = FALSE;
while ($iend < $strlen - 1 && $chars < $length) {
$iend++;
$c = ord($text[$iend]);
$last_real = FALSE;
if ($c < 0x80 || $c >= 0xC0) {
$chars++;
$last_real = TRUE;
}
}
// Backtrace one byte if the last character we found was a real
// character and we don't need it.
if ($last_real && $chars >= $length) {
$iend--;
}
}
elseif ($length < 0) {
// Count all the characters except continuation bytes from the end
// until we have found abs($start) characters, then backtrace one byte.
$length = abs($length);
$iend = $strlen; $chars = 0;
while ($iend > 0 && $chars < $length) {
$iend--;
$c = ord($text[$iend]);
if ($c < 0x80 || $c >= 0xC0) {
$chars++;
}
}
// Backtrace one byte if we are not at the beginning of the string.
if ($iend > 0) {
$iend--;
}
}
else {
// $length == 0, return an empty string.
return '';
}
return substr($text, $istart, max(0, $iend - $istart + 1));
}
} | [
"public",
"static",
"function",
"substr",
"(",
"$",
"text",
",",
"$",
"start",
",",
"$",
"length",
"=",
"NULL",
")",
"{",
"if",
"(",
"static",
"::",
"getStatus",
"(",
")",
"==",
"static",
"::",
"STATUS_MULTIBYTE",
")",
"{",
"return",
"$",
"length",
"... | Cuts off a piece of a string based on character indices and counts.
Follows the same behavior as PHP's own substr() function. Note that for
cutting off a string at a known character/substring location, the usage of
PHP's normal strpos/substr is safe and much faster.
@param string $text
The input string.
@param int $start
The position at which to start reading.
@param int $length
The number of characters to read.
@return string
The shortened string. | [
"Cuts",
"off",
"a",
"piece",
"of",
"a",
"string",
"based",
"on",
"character",
"indices",
"and",
"counts",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L406-L491 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Unicode.php | Unicode.strpos | public static function strpos($haystack, $needle, $offset = 0) {
if (static::getStatus() == static::STATUS_MULTIBYTE) {
return mb_strpos($haystack, $needle, $offset);
}
else {
// Remove Unicode continuation characters, to be compatible with
// Unicode::strlen() and Unicode::substr().
$haystack = preg_replace("/[\x80-\xBF]/", '', $haystack);
$needle = preg_replace("/[\x80-\xBF]/", '', $needle);
return strpos($haystack, $needle, $offset);
}
} | php | public static function strpos($haystack, $needle, $offset = 0) {
if (static::getStatus() == static::STATUS_MULTIBYTE) {
return mb_strpos($haystack, $needle, $offset);
}
else {
// Remove Unicode continuation characters, to be compatible with
// Unicode::strlen() and Unicode::substr().
$haystack = preg_replace("/[\x80-\xBF]/", '', $haystack);
$needle = preg_replace("/[\x80-\xBF]/", '', $needle);
return strpos($haystack, $needle, $offset);
}
} | [
"public",
"static",
"function",
"strpos",
"(",
"$",
"haystack",
",",
"$",
"needle",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"if",
"(",
"static",
"::",
"getStatus",
"(",
")",
"==",
"static",
"::",
"STATUS_MULTIBYTE",
")",
"{",
"return",
"mb_strpos",
"("... | Finds the position of the first occurrence of a string in another string.
@param string $haystack
The string to search in.
@param string $needle
The string to find in $haystack.
@param int $offset
If specified, start the search at this number of characters from the
beginning (default 0).
@return int|false
The position where $needle occurs in $haystack, always relative to the
beginning (independent of $offset), or FALSE if not found. Note that
a return value of 0 is not the same as FALSE. | [
"Finds",
"the",
"position",
"of",
"the",
"first",
"occurrence",
"of",
"a",
"string",
"in",
"another",
"string",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Unicode.php#L716-L727 | train |
Firehed/u2f-php | src/ECPublicKeyTrait.php | ECPublicKeyTrait.getPublicKeyPem | public function getPublicKeyPem(): string
{
$key = $this->getPublicKeyBinary();
// Described in RFC 5480
// Just use an OID calculator to figure out *that* encoding
$der = hex2bin(
'3059' // SEQUENCE, length 89
.'3013' // SEQUENCE, length 19
.'0607' // OID, length 7
.'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
.'0608' // OID, length 8
.'2a8648ce3d030107' // 1.2.840.10045.3.1.7 = P-256 Curve
.'0342' // BIT STRING, length 66
.'00' // prepend with NUL - pubkey will follow
);
$der .= $key;
$pem = "-----BEGIN PUBLIC KEY-----\r\n";
$pem .= chunk_split(base64_encode($der), 64);
$pem .= "-----END PUBLIC KEY-----";
return $pem;
} | php | public function getPublicKeyPem(): string
{
$key = $this->getPublicKeyBinary();
// Described in RFC 5480
// Just use an OID calculator to figure out *that* encoding
$der = hex2bin(
'3059' // SEQUENCE, length 89
.'3013' // SEQUENCE, length 19
.'0607' // OID, length 7
.'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
.'0608' // OID, length 8
.'2a8648ce3d030107' // 1.2.840.10045.3.1.7 = P-256 Curve
.'0342' // BIT STRING, length 66
.'00' // prepend with NUL - pubkey will follow
);
$der .= $key;
$pem = "-----BEGIN PUBLIC KEY-----\r\n";
$pem .= chunk_split(base64_encode($der), 64);
$pem .= "-----END PUBLIC KEY-----";
return $pem;
} | [
"public",
"function",
"getPublicKeyPem",
"(",
")",
":",
"string",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"getPublicKeyBinary",
"(",
")",
";",
"// Described in RFC 5480",
"// Just use an OID calculator to figure out *that* encoding",
"$",
"der",
"=",
"hex2bin",
"(",
... | public key component | [
"public",
"key",
"component"
] | 65bb799b1f709192ff7fed1af814ca43b03a64c7 | https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/ECPublicKeyTrait.php#L34-L56 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Html.php | Html.getUniqueId | public static function getUniqueId($id) {
// If this is an Ajax request, then content returned by this page request
// will be merged with content already on the base page. The HTML IDs must
// be unique for the fully merged content. Therefore use unique IDs.
if (static::$isAjax) {
return static::getId($id) . '--' . Crypt::randomBytesBase64(8);
}
// @todo Remove all that code once we switch over to random IDs only,
// see https://www.drupal.org/node/1090592.
if (!isset(static::$seenIdsInit)) {
static::$seenIdsInit = array();
}
if (!isset(static::$seenIds)) {
static::$seenIds = static::$seenIdsInit;
}
$id = static::getId($id);
// Ensure IDs are unique by appending a counter after the first occurrence.
// The counter needs to be appended with a delimiter that does not exist in
// the base ID. Requiring a unique delimiter helps ensure that we really do
// return unique IDs and also helps us re-create the $seen_ids array during
// Ajax requests.
if (isset(static::$seenIds[$id])) {
$id = $id . '--' . ++static::$seenIds[$id];
}
else {
static::$seenIds[$id] = 1;
}
return $id;
} | php | public static function getUniqueId($id) {
// If this is an Ajax request, then content returned by this page request
// will be merged with content already on the base page. The HTML IDs must
// be unique for the fully merged content. Therefore use unique IDs.
if (static::$isAjax) {
return static::getId($id) . '--' . Crypt::randomBytesBase64(8);
}
// @todo Remove all that code once we switch over to random IDs only,
// see https://www.drupal.org/node/1090592.
if (!isset(static::$seenIdsInit)) {
static::$seenIdsInit = array();
}
if (!isset(static::$seenIds)) {
static::$seenIds = static::$seenIdsInit;
}
$id = static::getId($id);
// Ensure IDs are unique by appending a counter after the first occurrence.
// The counter needs to be appended with a delimiter that does not exist in
// the base ID. Requiring a unique delimiter helps ensure that we really do
// return unique IDs and also helps us re-create the $seen_ids array during
// Ajax requests.
if (isset(static::$seenIds[$id])) {
$id = $id . '--' . ++static::$seenIds[$id];
}
else {
static::$seenIds[$id] = 1;
}
return $id;
} | [
"public",
"static",
"function",
"getUniqueId",
"(",
"$",
"id",
")",
"{",
"// If this is an Ajax request, then content returned by this page request",
"// will be merged with content already on the base page. The HTML IDs must",
"// be unique for the fully merged content. Therefore use unique I... | Prepares a string for use as a valid HTML ID and guarantees uniqueness.
This function ensures that each passed HTML ID value only exists once on
the page. By tracking the already returned ids, this function enables
forms, blocks, and other content to be output multiple times on the same
page, without breaking (X)HTML validation.
For already existing IDs, a counter is appended to the ID string.
Therefore, JavaScript and CSS code should not rely on any value that was
generated by this function and instead should rely on manually added CSS
classes or similarly reliable constructs.
Two consecutive hyphens separate the counter from the original ID. To
manage uniqueness across multiple Ajax requests on the same page, Ajax
requests POST an array of all IDs currently present on the page, which are
used to prime this function's cache upon first invocation.
To allow reverse-parsing of IDs submitted via Ajax, any multiple
consecutive hyphens in the originally passed $id are replaced with a
single hyphen.
@param string $id
The ID to clean.
@return string
The cleaned ID. | [
"Prepares",
"a",
"string",
"for",
"use",
"as",
"a",
"valid",
"HTML",
"ID",
"and",
"guarantees",
"uniqueness",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Html.php#L154-L185 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Html.php | Html.getId | public static function getId($id) {
$id = str_replace([' ', '_', '[', ']'], ['-', '-', '-', ''], Unicode::strtolower($id));
// As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
// only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
// colons (":"), and periods ("."). We strip out any character not in that
// list. Note that the CSS spec doesn't allow colons or periods in identifiers
// (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
// characters as well.
$id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
// Removing multiple consecutive hyphens.
$id = preg_replace('/\-+/', '-', $id);
return $id;
} | php | public static function getId($id) {
$id = str_replace([' ', '_', '[', ']'], ['-', '-', '-', ''], Unicode::strtolower($id));
// As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
// only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
// colons (":"), and periods ("."). We strip out any character not in that
// list. Note that the CSS spec doesn't allow colons or periods in identifiers
// (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
// characters as well.
$id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
// Removing multiple consecutive hyphens.
$id = preg_replace('/\-+/', '-', $id);
return $id;
} | [
"public",
"static",
"function",
"getId",
"(",
"$",
"id",
")",
"{",
"$",
"id",
"=",
"str_replace",
"(",
"[",
"' '",
",",
"'_'",
",",
"'['",
",",
"']'",
"]",
",",
"[",
"'-'",
",",
"'-'",
",",
"'-'",
",",
"''",
"]",
",",
"Unicode",
"::",
"strtolow... | Prepares a string for use as a valid HTML ID.
Only use this function when you want to intentionally skip the uniqueness
guarantee of self::getUniqueId().
@param string $id
The ID to clean.
@return string
The cleaned ID.
@see self::getUniqueId() | [
"Prepares",
"a",
"string",
"for",
"use",
"as",
"a",
"valid",
"HTML",
"ID",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Html.php#L201-L215 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Html.php | Html.serialize | public static function serialize(\DOMDocument $document) {
$body_node = $document->getElementsByTagName('body')->item(0);
$html = '';
if ($body_node !== NULL) {
foreach ($body_node->getElementsByTagName('script') as $node) {
static::escapeCdataElement($node);
}
foreach ($body_node->getElementsByTagName('style') as $node) {
static::escapeCdataElement($node, '/*', '*/');
}
foreach ($body_node->childNodes as $node) {
$html .= $document->saveXML($node);
}
}
return $html;
} | php | public static function serialize(\DOMDocument $document) {
$body_node = $document->getElementsByTagName('body')->item(0);
$html = '';
if ($body_node !== NULL) {
foreach ($body_node->getElementsByTagName('script') as $node) {
static::escapeCdataElement($node);
}
foreach ($body_node->getElementsByTagName('style') as $node) {
static::escapeCdataElement($node, '/*', '*/');
}
foreach ($body_node->childNodes as $node) {
$html .= $document->saveXML($node);
}
}
return $html;
} | [
"public",
"static",
"function",
"serialize",
"(",
"\\",
"DOMDocument",
"$",
"document",
")",
"{",
"$",
"body_node",
"=",
"$",
"document",
"->",
"getElementsByTagName",
"(",
"'body'",
")",
"->",
"item",
"(",
"0",
")",
";",
"$",
"html",
"=",
"''",
";",
"... | Converts the body of a \DOMDocument back to an HTML snippet.
The function serializes the body part of a \DOMDocument back to an (X)HTML
snippet. The resulting (X)HTML snippet will be properly formatted to be
compatible with HTML user agents.
@param \DOMDocument $document
A \DOMDocument object to serialize, only the tags below the first <body>
node will be converted.
@return string
A valid (X)HTML snippet, as a string. | [
"Converts",
"the",
"body",
"of",
"a",
"\\",
"DOMDocument",
"back",
"to",
"an",
"HTML",
"snippet",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Html.php#L291-L307 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Html.php | Html.escapeCdataElement | public static function escapeCdataElement(\DOMNode $node, $comment_start = '//', $comment_end = '') {
foreach ($node->childNodes as $child_node) {
if ($child_node instanceof \DOMCdataSection) {
$embed_prefix = "\n<!--{$comment_start}--><![CDATA[{$comment_start} ><!--{$comment_end}\n";
$embed_suffix = "\n{$comment_start}--><!]]>{$comment_end}\n";
// Prevent invalid cdata escaping as this would throw a DOM error.
// This is the same behavior as found in libxml2.
// Related W3C standard: http://www.w3.org/TR/REC-xml/#dt-cdsection
// Fix explanation: http://en.wikipedia.org/wiki/CDATA#Nesting
$data = str_replace(']]>', ']]]]><![CDATA[>', $child_node->data);
$fragment = $node->ownerDocument->createDocumentFragment();
$fragment->appendXML($embed_prefix . $data . $embed_suffix);
$node->appendChild($fragment);
$node->removeChild($child_node);
}
}
} | php | public static function escapeCdataElement(\DOMNode $node, $comment_start = '//', $comment_end = '') {
foreach ($node->childNodes as $child_node) {
if ($child_node instanceof \DOMCdataSection) {
$embed_prefix = "\n<!--{$comment_start}--><![CDATA[{$comment_start} ><!--{$comment_end}\n";
$embed_suffix = "\n{$comment_start}--><!]]>{$comment_end}\n";
// Prevent invalid cdata escaping as this would throw a DOM error.
// This is the same behavior as found in libxml2.
// Related W3C standard: http://www.w3.org/TR/REC-xml/#dt-cdsection
// Fix explanation: http://en.wikipedia.org/wiki/CDATA#Nesting
$data = str_replace(']]>', ']]]]><![CDATA[>', $child_node->data);
$fragment = $node->ownerDocument->createDocumentFragment();
$fragment->appendXML($embed_prefix . $data . $embed_suffix);
$node->appendChild($fragment);
$node->removeChild($child_node);
}
}
} | [
"public",
"static",
"function",
"escapeCdataElement",
"(",
"\\",
"DOMNode",
"$",
"node",
",",
"$",
"comment_start",
"=",
"'//'",
",",
"$",
"comment_end",
"=",
"''",
")",
"{",
"foreach",
"(",
"$",
"node",
"->",
"childNodes",
"as",
"$",
"child_node",
")",
... | Adds comments around a <!CDATA section in a \DOMNode.
\DOMDocument::loadHTML() in \Drupal\Component\Utility\Html::load() makes
CDATA sections from the contents of inline script and style tags. This can
cause HTML4 browsers to throw exceptions.
This function attempts to solve the problem by creating a
\DOMDocumentFragment to comment the CDATA tag.
@param \DOMNode $node
The element potentially containing a CDATA node.
@param string $comment_start
(optional) A string to use as a comment start marker to escape the CDATA
declaration. Defaults to '//'.
@param string $comment_end
(optional) A string to use as a comment end marker to escape the CDATA
declaration. Defaults to an empty string. | [
"Adds",
"comments",
"around",
"a",
"<!CDATA",
"section",
"in",
"a",
"\\",
"DOMNode",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Html.php#L328-L346 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Bytes.php | Bytes.toInt | public static function toInt($size) {
// Remove the non-unit characters from the size.
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
// Remove the non-numeric characters from the size.
$size = preg_replace('/[^0-9\.]/', '', $size);
if ($unit) {
// Find the position of the unit in the ordered string which is the power
// of magnitude to multiply a kilobyte by.
return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0])));
}
else {
return round($size);
}
} | php | public static function toInt($size) {
// Remove the non-unit characters from the size.
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
// Remove the non-numeric characters from the size.
$size = preg_replace('/[^0-9\.]/', '', $size);
if ($unit) {
// Find the position of the unit in the ordered string which is the power
// of magnitude to multiply a kilobyte by.
return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0])));
}
else {
return round($size);
}
} | [
"public",
"static",
"function",
"toInt",
"(",
"$",
"size",
")",
"{",
"// Remove the non-unit characters from the size.",
"$",
"unit",
"=",
"preg_replace",
"(",
"'/[^bkmgtpezy]/i'",
",",
"''",
",",
"$",
"size",
")",
";",
"// Remove the non-numeric characters from the siz... | Parses a given byte size.
@param mixed $size
An integer or string size expressed as a number of bytes with optional SI
or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
@return int
An integer representation of the size in bytes. | [
"Parses",
"a",
"given",
"byte",
"size",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Bytes.php#L32-L45 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Random.php | Random.object | public function object($size = 4) {
$object = new \stdClass();
for ($i = 0; $i < $size; $i++) {
$random_key = $this->name();
$random_value = $this->string();
$object->{$random_key} = $random_value;
}
return $object;
} | php | public function object($size = 4) {
$object = new \stdClass();
for ($i = 0; $i < $size; $i++) {
$random_key = $this->name();
$random_value = $this->string();
$object->{$random_key} = $random_value;
}
return $object;
} | [
"public",
"function",
"object",
"(",
"$",
"size",
"=",
"4",
")",
"{",
"$",
"object",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"size",
";",
"$",
"i",
"++",
")",
"{",
"$",
"random_k... | Generates a random PHP object.
@param int $size
The number of random keys to add to the object.
@return \stdClass
The generated object, with the specified number of random keys. Each key
has a random string value. | [
"Generates",
"a",
"random",
"PHP",
"object",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Random.php#L174-L182 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/Random.php | Random.paragraphs | public function paragraphs($paragraph_count = 12) {
$output = '';
for ($i = 1; $i <= $paragraph_count; $i++) {
$output .= $this->sentences(mt_rand(20, 60)) ."\n\n";
}
return $output;
} | php | public function paragraphs($paragraph_count = 12) {
$output = '';
for ($i = 1; $i <= $paragraph_count; $i++) {
$output .= $this->sentences(mt_rand(20, 60)) ."\n\n";
}
return $output;
} | [
"public",
"function",
"paragraphs",
"(",
"$",
"paragraph_count",
"=",
"12",
")",
"{",
"$",
"output",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<=",
"$",
"paragraph_count",
";",
"$",
"i",
"++",
")",
"{",
"$",
"output",
".=",
... | Generate paragraphs separated by double new line.
@param int $paragraph_count
@return string | [
"Generate",
"paragraphs",
"separated",
"by",
"double",
"new",
"line",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/Random.php#L256-L262 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/OpCodeCache.php | OpCodeCache.invalidate | public static function invalidate($pathname) {
clearstatcache(TRUE, $pathname);
// Check if the Zend OPcache is enabled and if so invalidate the file.
if (function_exists('opcache_invalidate')) {
opcache_invalidate($pathname, TRUE);
}
// If apcu extension is enabled in PHP 5.5 or greater it emulates apc.
// This is to provide an easy upgrade path if you are using apc's user
// caching however the emulation does not extend to opcode caching.
// Therefore we need to check if the function exists as well.
if (extension_loaded('apc') && function_exists('apc_delete_file')) {
// apc_delete_file() throws a PHP warning in case the specified file was
// not compiled yet.
// @see http://php.net/manual/en/function.apc-delete-file.php
@apc_delete_file($pathname);
}
} | php | public static function invalidate($pathname) {
clearstatcache(TRUE, $pathname);
// Check if the Zend OPcache is enabled and if so invalidate the file.
if (function_exists('opcache_invalidate')) {
opcache_invalidate($pathname, TRUE);
}
// If apcu extension is enabled in PHP 5.5 or greater it emulates apc.
// This is to provide an easy upgrade path if you are using apc's user
// caching however the emulation does not extend to opcode caching.
// Therefore we need to check if the function exists as well.
if (extension_loaded('apc') && function_exists('apc_delete_file')) {
// apc_delete_file() throws a PHP warning in case the specified file was
// not compiled yet.
// @see http://php.net/manual/en/function.apc-delete-file.php
@apc_delete_file($pathname);
}
} | [
"public",
"static",
"function",
"invalidate",
"(",
"$",
"pathname",
")",
"{",
"clearstatcache",
"(",
"TRUE",
",",
"$",
"pathname",
")",
";",
"// Check if the Zend OPcache is enabled and if so invalidate the file.",
"if",
"(",
"function_exists",
"(",
"'opcache_invalidate'"... | Invalidates a PHP file from a possibly active opcode cache.
In case the opcode cache does not support to invalidate an individual file,
the entire cache will be flushed.
@param string $pathname
The absolute pathname of the PHP file to invalidate. | [
"Invalidates",
"a",
"PHP",
"file",
"from",
"a",
"possibly",
"active",
"opcode",
"cache",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/OpCodeCache.php#L26-L43 | train |
aleksip/plugin-data-transform | src/Drupal/Core/Template/Attribute.php | Attribute.createAttributeValue | protected function createAttributeValue($name, $value) {
// If the value is already an AttributeValueBase object,
// return a new instance of the same class, but with the new name.
if ($value instanceof AttributeValueBase) {
$class = get_class($value);
return new $class($name, $value->value());
}
// An array value or 'class' attribute name are forced to always be an
// AttributeArray value for consistency.
if ($name == 'class' && !is_array($value)) {
// Cast the value to string in case it implements MarkupInterface.
$value = [(string) $value];
}
if (is_array($value)) {
// Cast the value to an array if the value was passed in as a string.
// @todo Decide to fix all the broken instances of class as a string
// in core or cast them.
$value = new AttributeArray($name, $value);
}
elseif (is_bool($value)) {
$value = new AttributeBoolean($name, $value);
}
// As a development aid, we allow the value to be a safe string object.
elseif (SafeMarkup::isSafe($value)) {
// Attributes are not supposed to display HTML markup, so we just convert
// the value to plain text.
$value = PlainTextOutput::renderFromHtml($value);
$value = new AttributeString($name, $value);
}
elseif (!is_object($value)) {
$value = new AttributeString($name, $value);
}
return $value;
} | php | protected function createAttributeValue($name, $value) {
// If the value is already an AttributeValueBase object,
// return a new instance of the same class, but with the new name.
if ($value instanceof AttributeValueBase) {
$class = get_class($value);
return new $class($name, $value->value());
}
// An array value or 'class' attribute name are forced to always be an
// AttributeArray value for consistency.
if ($name == 'class' && !is_array($value)) {
// Cast the value to string in case it implements MarkupInterface.
$value = [(string) $value];
}
if (is_array($value)) {
// Cast the value to an array if the value was passed in as a string.
// @todo Decide to fix all the broken instances of class as a string
// in core or cast them.
$value = new AttributeArray($name, $value);
}
elseif (is_bool($value)) {
$value = new AttributeBoolean($name, $value);
}
// As a development aid, we allow the value to be a safe string object.
elseif (SafeMarkup::isSafe($value)) {
// Attributes are not supposed to display HTML markup, so we just convert
// the value to plain text.
$value = PlainTextOutput::renderFromHtml($value);
$value = new AttributeString($name, $value);
}
elseif (!is_object($value)) {
$value = new AttributeString($name, $value);
}
return $value;
} | [
"protected",
"function",
"createAttributeValue",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"// If the value is already an AttributeValueBase object,",
"// return a new instance of the same class, but with the new name.",
"if",
"(",
"$",
"value",
"instanceof",
"AttributeValue... | Creates the different types of attribute values.
@param string $name
The attribute name.
@param mixed $value
The attribute value.
@return \Drupal\Core\Template\AttributeValueBase
An AttributeValueBase representation of the attribute's value. | [
"Creates",
"the",
"different",
"types",
"of",
"attribute",
"values",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L119-L152 | train |
aleksip/plugin-data-transform | src/Drupal/Core/Template/Attribute.php | Attribute.addClass | public function addClass() {
$args = func_get_args();
if ($args) {
$classes = array();
foreach ($args as $arg) {
// Merge the values passed in from the classes array.
// The argument is cast to an array to support comma separated single
// values or one or more array arguments.
$classes = array_merge($classes, (array) $arg);
}
// Merge if there are values, just add them otherwise.
if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
// Merge the values passed in from the class value array.
$classes = array_merge($this->storage['class']->value(), $classes);
$this->storage['class']->exchangeArray($classes);
}
else {
$this->offsetSet('class', $classes);
}
}
return $this;
} | php | public function addClass() {
$args = func_get_args();
if ($args) {
$classes = array();
foreach ($args as $arg) {
// Merge the values passed in from the classes array.
// The argument is cast to an array to support comma separated single
// values or one or more array arguments.
$classes = array_merge($classes, (array) $arg);
}
// Merge if there are values, just add them otherwise.
if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
// Merge the values passed in from the class value array.
$classes = array_merge($this->storage['class']->value(), $classes);
$this->storage['class']->exchangeArray($classes);
}
else {
$this->offsetSet('class', $classes);
}
}
return $this;
} | [
"public",
"function",
"addClass",
"(",
")",
"{",
"$",
"args",
"=",
"func_get_args",
"(",
")",
";",
"if",
"(",
"$",
"args",
")",
"{",
"$",
"classes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"args",
"as",
"$",
"arg",
")",
"{",
"// Merge t... | Adds classes or merges them on to array of existing CSS classes.
@param string|array ...
CSS classes to add to the class attribute array.
@return $this | [
"Adds",
"classes",
"or",
"merges",
"them",
"on",
"to",
"array",
"of",
"existing",
"CSS",
"classes",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L176-L199 | train |
aleksip/plugin-data-transform | src/Drupal/Core/Template/Attribute.php | Attribute.removeAttribute | public function removeAttribute() {
$args = func_get_args();
foreach ($args as $arg) {
// Support arrays or multiple arguments.
if (is_array($arg)) {
foreach ($arg as $value) {
unset($this->storage[$value]);
}
}
else {
unset($this->storage[$arg]);
}
}
return $this;
} | php | public function removeAttribute() {
$args = func_get_args();
foreach ($args as $arg) {
// Support arrays or multiple arguments.
if (is_array($arg)) {
foreach ($arg as $value) {
unset($this->storage[$value]);
}
}
else {
unset($this->storage[$arg]);
}
}
return $this;
} | [
"public",
"function",
"removeAttribute",
"(",
")",
"{",
"$",
"args",
"=",
"func_get_args",
"(",
")",
";",
"foreach",
"(",
"$",
"args",
"as",
"$",
"arg",
")",
"{",
"// Support arrays or multiple arguments.",
"if",
"(",
"is_array",
"(",
"$",
"arg",
")",
")",... | Removes an attribute from an Attribute object.
@param string|array ...
Attributes to remove from the attribute array.
@return $this | [
"Removes",
"an",
"attribute",
"from",
"an",
"Attribute",
"object",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L225-L240 | train |
aleksip/plugin-data-transform | src/Drupal/Core/Template/Attribute.php | Attribute.removeClass | public function removeClass() {
// With no class attribute, there is no need to remove.
if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
$args = func_get_args();
$classes = array();
foreach ($args as $arg) {
// Merge the values passed in from the classes array.
// The argument is cast to an array to support comma separated single
// values or one or more array arguments.
$classes = array_merge($classes, (array) $arg);
}
// Remove the values passed in from the value array. Use array_values() to
// ensure that the array index remains sequential.
$classes = array_values(array_diff($this->storage['class']->value(), $classes));
$this->storage['class']->exchangeArray($classes);
}
return $this;
} | php | public function removeClass() {
// With no class attribute, there is no need to remove.
if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
$args = func_get_args();
$classes = array();
foreach ($args as $arg) {
// Merge the values passed in from the classes array.
// The argument is cast to an array to support comma separated single
// values or one or more array arguments.
$classes = array_merge($classes, (array) $arg);
}
// Remove the values passed in from the value array. Use array_values() to
// ensure that the array index remains sequential.
$classes = array_values(array_diff($this->storage['class']->value(), $classes));
$this->storage['class']->exchangeArray($classes);
}
return $this;
} | [
"public",
"function",
"removeClass",
"(",
")",
"{",
"// With no class attribute, there is no need to remove.",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"storage",
"[",
"'class'",
"]",
")",
"&&",
"$",
"this",
"->",
"storage",
"[",
"'class'",
"]",
"instanceof",... | Removes argument values from array of existing CSS classes.
@param string|array ...
CSS classes to remove from the class attribute array.
@return $this | [
"Removes",
"argument",
"values",
"from",
"array",
"of",
"existing",
"CSS",
"classes",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L250-L268 | train |
aleksip/plugin-data-transform | src/Drupal/Core/Template/Attribute.php | Attribute.hasClass | public function hasClass($class) {
if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
return in_array($class, $this->storage['class']->value());
}
else {
return FALSE;
}
} | php | public function hasClass($class) {
if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
return in_array($class, $this->storage['class']->value());
}
else {
return FALSE;
}
} | [
"public",
"function",
"hasClass",
"(",
"$",
"class",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"storage",
"[",
"'class'",
"]",
")",
"&&",
"$",
"this",
"->",
"storage",
"[",
"'class'",
"]",
"instanceof",
"AttributeArray",
")",
"{",
"return",... | Checks if the class array has the given CSS class.
@param string $class
The CSS class to check for.
@return bool
Returns TRUE if the class exists, or FALSE otherwise. | [
"Checks",
"if",
"the",
"class",
"array",
"has",
"the",
"given",
"CSS",
"class",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Core/Template/Attribute.php#L279-L286 | train |
Firehed/u2f-php | src/Server.php | Server.register | public function register(RegisterResponse $resp): RegistrationInterface
{
if (!$this->registerRequest) {
throw new BadMethodCallException(
'Before calling register(), provide a RegisterRequest '.
'with setRegisterRequest()'
);
}
$this->validateChallenge($resp->getClientData(), $this->registerRequest);
// Check the Application Parameter?
// https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html#registration-response-message-success
$signed_data = sprintf(
'%s%s%s%s%s',
chr(0),
$this->registerRequest->getApplicationParameter(),
$resp->getClientData()->getChallengeParameter(),
$resp->getKeyHandleBinary(),
$resp->getPublicKeyBinary()
);
$pem = $resp->getAttestationCertificatePem();
if ($this->verifyCA) {
$resp->verifyIssuerAgainstTrustedCAs($this->trustedCAs);
}
// Signature must validate against device issuer's public key
$sig_check = openssl_verify(
$signed_data,
$resp->getSignature(),
$pem,
\OPENSSL_ALGO_SHA256
);
if ($sig_check !== 1) {
throw new SE(SE::SIGNATURE_INVALID);
}
return (new Registration())
->setAttestationCertificate($resp->getAttestationCertificateBinary())
->setCounter(0) // The response does not include this
->setKeyHandle($resp->getKeyHandleBinary())
->setPublicKey($resp->getPublicKeyBinary());
} | php | public function register(RegisterResponse $resp): RegistrationInterface
{
if (!$this->registerRequest) {
throw new BadMethodCallException(
'Before calling register(), provide a RegisterRequest '.
'with setRegisterRequest()'
);
}
$this->validateChallenge($resp->getClientData(), $this->registerRequest);
// Check the Application Parameter?
// https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html#registration-response-message-success
$signed_data = sprintf(
'%s%s%s%s%s',
chr(0),
$this->registerRequest->getApplicationParameter(),
$resp->getClientData()->getChallengeParameter(),
$resp->getKeyHandleBinary(),
$resp->getPublicKeyBinary()
);
$pem = $resp->getAttestationCertificatePem();
if ($this->verifyCA) {
$resp->verifyIssuerAgainstTrustedCAs($this->trustedCAs);
}
// Signature must validate against device issuer's public key
$sig_check = openssl_verify(
$signed_data,
$resp->getSignature(),
$pem,
\OPENSSL_ALGO_SHA256
);
if ($sig_check !== 1) {
throw new SE(SE::SIGNATURE_INVALID);
}
return (new Registration())
->setAttestationCertificate($resp->getAttestationCertificateBinary())
->setCounter(0) // The response does not include this
->setKeyHandle($resp->getKeyHandleBinary())
->setPublicKey($resp->getPublicKeyBinary());
} | [
"public",
"function",
"register",
"(",
"RegisterResponse",
"$",
"resp",
")",
":",
"RegistrationInterface",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"registerRequest",
")",
"{",
"throw",
"new",
"BadMethodCallException",
"(",
"'Before calling register(), provide a Regist... | This method authenticates a RegisterResponse against its corresponding
RegisterRequest by verifying the certificate and signature. If valid, it
returns a registration; if not, a SE will be thrown and attempt to
register the key must be aborted.
@param RegisterResponse $resp The response to verify
@return RegistrationInterface if the response is proven authentic
@throws SE if the response cannot be proven authentic
@throws BadMethodCallException if a precondition is not met | [
"This",
"method",
"authenticates",
"a",
"RegisterResponse",
"against",
"its",
"corresponding",
"RegisterRequest",
"by",
"verifying",
"the",
"certificate",
"and",
"signature",
".",
"If",
"valid",
"it",
"returns",
"a",
"registration",
";",
"if",
"not",
"a",
"SE",
... | 65bb799b1f709192ff7fed1af814ca43b03a64c7 | https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L190-L232 | train |
Firehed/u2f-php | src/Server.php | Server.setTrustedCAs | public function setTrustedCAs(array $CAs): self
{
$this->verifyCA = true;
$this->trustedCAs = $CAs;
return $this;
} | php | public function setTrustedCAs(array $CAs): self
{
$this->verifyCA = true;
$this->trustedCAs = $CAs;
return $this;
} | [
"public",
"function",
"setTrustedCAs",
"(",
"array",
"$",
"CAs",
")",
":",
"self",
"{",
"$",
"this",
"->",
"verifyCA",
"=",
"true",
";",
"$",
"this",
"->",
"trustedCAs",
"=",
"$",
"CAs",
";",
"return",
"$",
"this",
";",
"}"
] | Provides a list of CA certificates for device issuer verification during
registration.
This method or disableCAVerification must be called before register() or
a SecurityException will always be thrown.
@param string[] $CAs A list of file paths to device issuer CA certs
@return self | [
"Provides",
"a",
"list",
"of",
"CA",
"certificates",
"for",
"device",
"issuer",
"verification",
"during",
"registration",
"."
] | 65bb799b1f709192ff7fed1af814ca43b03a64c7 | https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L260-L265 | train |
Firehed/u2f-php | src/Server.php | Server.setRegistrations | public function setRegistrations(array $registrations): self
{
array_map(function (Registration $r) {
}, $registrations); // type check
$this->registrations = $registrations;
return $this;
} | php | public function setRegistrations(array $registrations): self
{
array_map(function (Registration $r) {
}, $registrations); // type check
$this->registrations = $registrations;
return $this;
} | [
"public",
"function",
"setRegistrations",
"(",
"array",
"$",
"registrations",
")",
":",
"self",
"{",
"array_map",
"(",
"function",
"(",
"Registration",
"$",
"r",
")",
"{",
"}",
",",
"$",
"registrations",
")",
";",
"// type check",
"$",
"this",
"->",
"regis... | Provide a user's existing registration to be used during
authentication
@param RegistrationInterface[] $registrations
@return self | [
"Provide",
"a",
"user",
"s",
"existing",
"registration",
"to",
"be",
"used",
"during",
"authentication"
] | 65bb799b1f709192ff7fed1af814ca43b03a64c7 | https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L287-L293 | train |
Firehed/u2f-php | src/Server.php | Server.generateSignRequest | public function generateSignRequest(RegistrationInterface $reg): SignRequest
{
return (new SignRequest())
->setAppId($this->getAppId())
->setChallenge($this->generateChallenge())
->setKeyHandle($reg->getKeyHandleBinary());
} | php | public function generateSignRequest(RegistrationInterface $reg): SignRequest
{
return (new SignRequest())
->setAppId($this->getAppId())
->setChallenge($this->generateChallenge())
->setKeyHandle($reg->getKeyHandleBinary());
} | [
"public",
"function",
"generateSignRequest",
"(",
"RegistrationInterface",
"$",
"reg",
")",
":",
"SignRequest",
"{",
"return",
"(",
"new",
"SignRequest",
"(",
")",
")",
"->",
"setAppId",
"(",
"$",
"this",
"->",
"getAppId",
"(",
")",
")",
"->",
"setChallenge"... | Creates a new SignRequest for an existing registration for an
authenticating user, used by the `u2f.sign` API.
@param RegistrationInterface $reg one of the user's existing Registrations
@return SignRequest | [
"Creates",
"a",
"new",
"SignRequest",
"for",
"an",
"existing",
"registration",
"for",
"an",
"authenticating",
"user",
"used",
"by",
"the",
"u2f",
".",
"sign",
"API",
"."
] | 65bb799b1f709192ff7fed1af814ca43b03a64c7 | https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L331-L337 | train |
Firehed/u2f-php | src/Server.php | Server.findObjectWithKeyHandle | private function findObjectWithKeyHandle(
array $objects,
string $keyHandle
) {
foreach ($objects as $object) {
if (hash_equals($object->getKeyHandleBinary(), $keyHandle)) {
return $object;
}
}
return null;
} | php | private function findObjectWithKeyHandle(
array $objects,
string $keyHandle
) {
foreach ($objects as $object) {
if (hash_equals($object->getKeyHandleBinary(), $keyHandle)) {
return $object;
}
}
return null;
} | [
"private",
"function",
"findObjectWithKeyHandle",
"(",
"array",
"$",
"objects",
",",
"string",
"$",
"keyHandle",
")",
"{",
"foreach",
"(",
"$",
"objects",
"as",
"$",
"object",
")",
"{",
"if",
"(",
"hash_equals",
"(",
"$",
"object",
"->",
"getKeyHandleBinary"... | Searches through the provided array of objects, and looks for a matching
key handle value. If one is found, it is returned; if not, this returns
null.
TODO: create and implement a HasKeyHandle interface of sorts to type
this better
@param array $objects haystack to search
@param string $keyHandle key handle to find in haystack
@return mixed element from haystack
@return null if no element matches | [
"Searches",
"through",
"the",
"provided",
"array",
"of",
"objects",
"and",
"looks",
"for",
"a",
"matching",
"key",
"handle",
"value",
".",
"If",
"one",
"is",
"found",
"it",
"is",
"returned",
";",
"if",
"not",
"this",
"returns",
"null",
"."
] | 65bb799b1f709192ff7fed1af814ca43b03a64c7 | https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L362-L372 | train |
Firehed/u2f-php | src/Server.php | Server.validateChallenge | private function validateChallenge(
ChallengeProvider $from,
ChallengeProvider $to
): bool {
// Note: strictly speaking, this shouldn't even be targetable as
// a timing attack. However, this opts to be proactive, and also
// ensures that no weird PHP-isms in string handling cause mismatched
// values to validate.
if (!hash_equals($from->getChallenge(), $to->getChallenge())) {
throw new SE(SE::CHALLENGE_MISMATCH);
}
// TOOD: generate and compare timestamps
return true;
} | php | private function validateChallenge(
ChallengeProvider $from,
ChallengeProvider $to
): bool {
// Note: strictly speaking, this shouldn't even be targetable as
// a timing attack. However, this opts to be proactive, and also
// ensures that no weird PHP-isms in string handling cause mismatched
// values to validate.
if (!hash_equals($from->getChallenge(), $to->getChallenge())) {
throw new SE(SE::CHALLENGE_MISMATCH);
}
// TOOD: generate and compare timestamps
return true;
} | [
"private",
"function",
"validateChallenge",
"(",
"ChallengeProvider",
"$",
"from",
",",
"ChallengeProvider",
"$",
"to",
")",
":",
"bool",
"{",
"// Note: strictly speaking, this shouldn't even be targetable as",
"// a timing attack. However, this opts to be proactive, and also",
"//... | Compares the Challenge value from a known source against the
user-provided value. A mismatch will throw a SE. Future
versions may also enforce a timing window.
@param ChallengeProvider $from source of known challenge
@param ChallengeProvider $to user-provided value
@return true on success
@throws SE on failure | [
"Compares",
"the",
"Challenge",
"value",
"from",
"a",
"known",
"source",
"against",
"the",
"user",
"-",
"provided",
"value",
".",
"A",
"mismatch",
"will",
"throw",
"a",
"SE",
".",
"Future",
"versions",
"may",
"also",
"enforce",
"a",
"timing",
"window",
"."... | 65bb799b1f709192ff7fed1af814ca43b03a64c7 | https://github.com/Firehed/u2f-php/blob/65bb799b1f709192ff7fed1af814ca43b03a64c7/src/Server.php#L395-L408 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/UrlHelper.php | UrlHelper.filterQueryParameters | public static function filterQueryParameters(array $query, array $exclude = array(), $parent = '') {
// If $exclude is empty, there is nothing to filter.
if (empty($exclude)) {
return $query;
}
elseif (!$parent) {
$exclude = array_flip($exclude);
}
$params = array();
foreach ($query as $key => $value) {
$string_key = ($parent ? $parent . '[' . $key . ']' : $key);
if (isset($exclude[$string_key])) {
continue;
}
if (is_array($value)) {
$params[$key] = static::filterQueryParameters($value, $exclude, $string_key);
}
else {
$params[$key] = $value;
}
}
return $params;
} | php | public static function filterQueryParameters(array $query, array $exclude = array(), $parent = '') {
// If $exclude is empty, there is nothing to filter.
if (empty($exclude)) {
return $query;
}
elseif (!$parent) {
$exclude = array_flip($exclude);
}
$params = array();
foreach ($query as $key => $value) {
$string_key = ($parent ? $parent . '[' . $key . ']' : $key);
if (isset($exclude[$string_key])) {
continue;
}
if (is_array($value)) {
$params[$key] = static::filterQueryParameters($value, $exclude, $string_key);
}
else {
$params[$key] = $value;
}
}
return $params;
} | [
"public",
"static",
"function",
"filterQueryParameters",
"(",
"array",
"$",
"query",
",",
"array",
"$",
"exclude",
"=",
"array",
"(",
")",
",",
"$",
"parent",
"=",
"''",
")",
"{",
"// If $exclude is empty, there is nothing to filter.",
"if",
"(",
"empty",
"(",
... | Filters a URL query parameter array to remove unwanted elements.
@param array $query
An array to be processed.
@param array $exclude
(optional) A list of $query array keys to remove. Use "parent[child]" to
exclude nested items.
@param string $parent
Internal use only. Used to build the $query array key for nested items.
@return
An array containing query parameters. | [
"Filters",
"a",
"URL",
"query",
"parameter",
"array",
"to",
"remove",
"unwanted",
"elements",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L87-L112 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/UrlHelper.php | UrlHelper.parse | public static function parse($url) {
$options = array(
'path' => NULL,
'query' => array(),
'fragment' => '',
);
// External URLs: not using parse_url() here, so we do not have to rebuild
// the scheme, host, and path without having any use for it.
if (strpos($url, '://') !== FALSE) {
// Split off everything before the query string into 'path'.
$parts = explode('?', $url);
// Don't support URLs without a path, like 'http://'.
list(, $path) = explode('://', $parts[0], 2);
if ($path != '') {
$options['path'] = $parts[0];
}
// If there is a query string, transform it into keyed query parameters.
if (isset($parts[1])) {
$query_parts = explode('#', $parts[1]);
parse_str($query_parts[0], $options['query']);
// Take over the fragment, if there is any.
if (isset($query_parts[1])) {
$options['fragment'] = $query_parts[1];
}
}
}
// Internal URLs.
else {
// parse_url() does not support relative URLs, so make it absolute. E.g. the
// relative URL "foo/bar:1" isn't properly parsed.
$parts = parse_url('http://example.com/' . $url);
// Strip the leading slash that was just added.
$options['path'] = substr($parts['path'], 1);
if (isset($parts['query'])) {
parse_str($parts['query'], $options['query']);
}
if (isset($parts['fragment'])) {
$options['fragment'] = $parts['fragment'];
}
}
return $options;
} | php | public static function parse($url) {
$options = array(
'path' => NULL,
'query' => array(),
'fragment' => '',
);
// External URLs: not using parse_url() here, so we do not have to rebuild
// the scheme, host, and path without having any use for it.
if (strpos($url, '://') !== FALSE) {
// Split off everything before the query string into 'path'.
$parts = explode('?', $url);
// Don't support URLs without a path, like 'http://'.
list(, $path) = explode('://', $parts[0], 2);
if ($path != '') {
$options['path'] = $parts[0];
}
// If there is a query string, transform it into keyed query parameters.
if (isset($parts[1])) {
$query_parts = explode('#', $parts[1]);
parse_str($query_parts[0], $options['query']);
// Take over the fragment, if there is any.
if (isset($query_parts[1])) {
$options['fragment'] = $query_parts[1];
}
}
}
// Internal URLs.
else {
// parse_url() does not support relative URLs, so make it absolute. E.g. the
// relative URL "foo/bar:1" isn't properly parsed.
$parts = parse_url('http://example.com/' . $url);
// Strip the leading slash that was just added.
$options['path'] = substr($parts['path'], 1);
if (isset($parts['query'])) {
parse_str($parts['query'], $options['query']);
}
if (isset($parts['fragment'])) {
$options['fragment'] = $parts['fragment'];
}
}
return $options;
} | [
"public",
"static",
"function",
"parse",
"(",
"$",
"url",
")",
"{",
"$",
"options",
"=",
"array",
"(",
"'path'",
"=>",
"NULL",
",",
"'query'",
"=>",
"array",
"(",
")",
",",
"'fragment'",
"=>",
"''",
",",
")",
";",
"// External URLs: not using parse_url() h... | Parses a URL string into its path, query, and fragment components.
This function splits both internal paths like @code node?b=c#d @endcode and
external URLs like @code https://example.com/a?b=c#d @endcode into their
component parts. See
@link http://tools.ietf.org/html/rfc3986#section-3 RFC 3986 @endlink for an
explanation of what the component parts are.
Note that, unlike the RFC, when passed an external URL, this function
groups the scheme, authority, and path together into the path component.
@param string $url
The internal path or external URL string to parse.
@return array
An associative array containing:
- path: The path component of $url. If $url is an external URL, this
includes the scheme, authority, and path.
- query: An array of query parameters from $url, if they exist.
- fragment: The fragment component from $url, if it exists.
@see \Drupal\Core\Utility\LinkGenerator
@see http://tools.ietf.org/html/rfc3986
@ingroup php_wrappers | [
"Parses",
"a",
"URL",
"string",
"into",
"its",
"path",
"query",
"and",
"fragment",
"components",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L141-L185 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/UrlHelper.php | UrlHelper.externalIsLocal | public static function externalIsLocal($url, $base_url) {
$url_parts = parse_url($url);
$base_parts = parse_url($base_url);
if (empty($base_parts['host']) || empty($url_parts['host'])) {
throw new \InvalidArgumentException('A path was passed when a fully qualified domain was expected.');
}
if (!isset($url_parts['path']) || !isset($base_parts['path'])) {
return (!isset($base_parts['path']) || $base_parts['path'] == '/')
&& ($url_parts['host'] == $base_parts['host']);
}
else {
// When comparing base paths, we need a trailing slash to make sure a
// partial URL match isn't occurring. Since base_path() always returns
// with a trailing slash, we don't need to add the trailing slash here.
return ($url_parts['host'] == $base_parts['host'] && stripos($url_parts['path'], $base_parts['path']) === 0);
}
} | php | public static function externalIsLocal($url, $base_url) {
$url_parts = parse_url($url);
$base_parts = parse_url($base_url);
if (empty($base_parts['host']) || empty($url_parts['host'])) {
throw new \InvalidArgumentException('A path was passed when a fully qualified domain was expected.');
}
if (!isset($url_parts['path']) || !isset($base_parts['path'])) {
return (!isset($base_parts['path']) || $base_parts['path'] == '/')
&& ($url_parts['host'] == $base_parts['host']);
}
else {
// When comparing base paths, we need a trailing slash to make sure a
// partial URL match isn't occurring. Since base_path() always returns
// with a trailing slash, we don't need to add the trailing slash here.
return ($url_parts['host'] == $base_parts['host'] && stripos($url_parts['path'], $base_parts['path']) === 0);
}
} | [
"public",
"static",
"function",
"externalIsLocal",
"(",
"$",
"url",
",",
"$",
"base_url",
")",
"{",
"$",
"url_parts",
"=",
"parse_url",
"(",
"$",
"url",
")",
";",
"$",
"base_parts",
"=",
"parse_url",
"(",
"$",
"base_url",
")",
";",
"if",
"(",
"empty",
... | Determines if an external URL points to this installation.
@param string $url
A string containing an external URL, such as "http://example.com/foo".
@param string $base_url
The base URL string to check against, such as "http://example.com/"
@return bool
TRUE if the URL has the same domain and base path.
@throws \InvalidArgumentException
Exception thrown when a either $url or $bath_url are not fully qualified. | [
"Determines",
"if",
"an",
"external",
"URL",
"points",
"to",
"this",
"installation",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L242-L260 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/UrlHelper.php | UrlHelper.filterBadProtocol | public static function filterBadProtocol($string) {
// Get the plain text representation of the attribute value (i.e. its
// meaning).
$string = Html::decodeEntities($string);
return Html::escape(static::stripDangerousProtocols($string));
} | php | public static function filterBadProtocol($string) {
// Get the plain text representation of the attribute value (i.e. its
// meaning).
$string = Html::decodeEntities($string);
return Html::escape(static::stripDangerousProtocols($string));
} | [
"public",
"static",
"function",
"filterBadProtocol",
"(",
"$",
"string",
")",
"{",
"// Get the plain text representation of the attribute value (i.e. its",
"// meaning).",
"$",
"string",
"=",
"Html",
"::",
"decodeEntities",
"(",
"$",
"string",
")",
";",
"return",
"Html"... | Processes an HTML attribute value and strips dangerous protocols from URLs.
@param string $string
The string with the attribute value.
@return string
Cleaned up and HTML-escaped version of $string. | [
"Processes",
"an",
"HTML",
"attribute",
"value",
"and",
"strips",
"dangerous",
"protocols",
"from",
"URLs",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L271-L276 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/UrlHelper.php | UrlHelper.isValid | public static function isValid($url, $absolute = FALSE) {
if ($absolute) {
return (bool) preg_match("
/^ # Start at the beginning of the text
(?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
(?: # Userinfo (optional) which is typically
(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
)?
(?:
(?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
)
(?::[0-9]+)? # Server port number (optional)
(?:[\/|\?]
(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
*)?
$/xi", $url);
}
else {
return (bool) preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
}
} | php | public static function isValid($url, $absolute = FALSE) {
if ($absolute) {
return (bool) preg_match("
/^ # Start at the beginning of the text
(?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
(?: # Userinfo (optional) which is typically
(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
)?
(?:
(?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
)
(?::[0-9]+)? # Server port number (optional)
(?:[\/|\?]
(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
*)?
$/xi", $url);
}
else {
return (bool) preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
}
} | [
"public",
"static",
"function",
"isValid",
"(",
"$",
"url",
",",
"$",
"absolute",
"=",
"FALSE",
")",
"{",
"if",
"(",
"$",
"absolute",
")",
"{",
"return",
"(",
"bool",
")",
"preg_match",
"(",
"\"\n /^ # St... | Verifies the syntax of the given URL.
This function should only be used on actual URLs. It should not be used for
Drupal menu paths, which can contain arbitrary characters.
Valid values per RFC 3986.
@param string $url
The URL to verify.
@param bool $absolute
Whether the URL is absolute (beginning with a scheme such as "http:").
@return bool
TRUE if the URL is in a valid format, FALSE otherwise. | [
"Verifies",
"the",
"syntax",
"of",
"the",
"given",
"URL",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/UrlHelper.php#L380-L402 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Render/MarkupTrait.php | MarkupTrait.create | public static function create($string) {
if ($string instanceof MarkupInterface) {
return $string;
}
$string = (string) $string;
if ($string === '') {
return '';
}
$safe_string = new static();
$safe_string->string = $string;
return $safe_string;
} | php | public static function create($string) {
if ($string instanceof MarkupInterface) {
return $string;
}
$string = (string) $string;
if ($string === '') {
return '';
}
$safe_string = new static();
$safe_string->string = $string;
return $safe_string;
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"$",
"string",
"instanceof",
"MarkupInterface",
")",
"{",
"return",
"$",
"string",
";",
"}",
"$",
"string",
"=",
"(",
"string",
")",
"$",
"string",
";",
"if",
"(",
"$"... | Creates a Markup object if necessary.
If $string is equal to a blank string then it is not necessary to create a
Markup object. If $string is an object that implements MarkupInterface it
is returned unchanged.
@param mixed $string
The string to mark as safe. This value will be cast to a string.
@return string|\Drupal\Component\Render\MarkupInterface
A safe string. | [
"Creates",
"a",
"Markup",
"object",
"if",
"necessary",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Render/MarkupTrait.php#L39-L50 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Render/FormattableMarkup.php | FormattableMarkup.placeholderFormat | protected static function placeholderFormat($string, array $args) {
// Transform arguments before inserting them.
foreach ($args as $key => $value) {
switch ($key[0]) {
case '@':
// Escape if the value is not an object from a class that implements
// \Drupal\Component\Render\MarkupInterface, for example strings will
// be escaped.
// \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe() may
// return TRUE for content that is safe within HTML fragments, but not
// within other contexts, so this placeholder type must not be used
// within HTML attributes, JavaScript, or CSS.
$args[$key] = static::placeholderEscape($value);
break;
case ':':
// Strip URL protocols that can be XSS vectors.
$value = UrlHelper::stripDangerousProtocols($value);
// Escape unconditionally, without checking
// \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe(). This
// forces characters that are unsafe for use in an "href" HTML
// attribute to be encoded. If a caller wants to pass a value that is
// extracted from HTML and therefore is already HTML encoded, it must
// invoke
// \Drupal\Component\Render\OutputStrategyInterface::renderFromHtml()
// on it prior to passing it in as a placeholder value of this type.
// @todo Add some advice and stronger warnings.
// https://www.drupal.org/node/2569041.
$args[$key] = Html::escape($value);
break;
case '%':
// Similarly to @, escape non-safe values. Also, add wrapping markup
// in order to render as a placeholder. Not for use within attributes,
// per the warning above about
// \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe() and also
// due to the wrapping markup.
$args[$key] = '<em class="placeholder">' . static::placeholderEscape($value) . '</em>';
break;
default:
// We do not trigger an error for placeholder that start with an
// alphabetic character.
if (!ctype_alpha($key[0])) {
// We trigger an error as we may want to introduce new placeholders
// in the future without breaking backward compatibility.
trigger_error('Invalid placeholder (' . $key . ') in string: ' . $string, E_USER_ERROR);
}
break;
}
}
return strtr($string, $args);
} | php | protected static function placeholderFormat($string, array $args) {
// Transform arguments before inserting them.
foreach ($args as $key => $value) {
switch ($key[0]) {
case '@':
// Escape if the value is not an object from a class that implements
// \Drupal\Component\Render\MarkupInterface, for example strings will
// be escaped.
// \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe() may
// return TRUE for content that is safe within HTML fragments, but not
// within other contexts, so this placeholder type must not be used
// within HTML attributes, JavaScript, or CSS.
$args[$key] = static::placeholderEscape($value);
break;
case ':':
// Strip URL protocols that can be XSS vectors.
$value = UrlHelper::stripDangerousProtocols($value);
// Escape unconditionally, without checking
// \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe(). This
// forces characters that are unsafe for use in an "href" HTML
// attribute to be encoded. If a caller wants to pass a value that is
// extracted from HTML and therefore is already HTML encoded, it must
// invoke
// \Drupal\Component\Render\OutputStrategyInterface::renderFromHtml()
// on it prior to passing it in as a placeholder value of this type.
// @todo Add some advice and stronger warnings.
// https://www.drupal.org/node/2569041.
$args[$key] = Html::escape($value);
break;
case '%':
// Similarly to @, escape non-safe values. Also, add wrapping markup
// in order to render as a placeholder. Not for use within attributes,
// per the warning above about
// \Drupal\Component\Utility\SafeMarkup\SafeMarkup::isSafe() and also
// due to the wrapping markup.
$args[$key] = '<em class="placeholder">' . static::placeholderEscape($value) . '</em>';
break;
default:
// We do not trigger an error for placeholder that start with an
// alphabetic character.
if (!ctype_alpha($key[0])) {
// We trigger an error as we may want to introduce new placeholders
// in the future without breaking backward compatibility.
trigger_error('Invalid placeholder (' . $key . ') in string: ' . $string, E_USER_ERROR);
}
break;
}
}
return strtr($string, $args);
} | [
"protected",
"static",
"function",
"placeholderFormat",
"(",
"$",
"string",
",",
"array",
"$",
"args",
")",
"{",
"// Transform arguments before inserting them.",
"foreach",
"(",
"$",
"args",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"switch",
"(",
"$",
... | Replaces placeholders in a string with values.
@param string $string
A string containing placeholders. The string itself is expected to be
safe and correct HTML. Any unsafe content must be in $args and
inserted via placeholders.
@param array $args
An associative array of replacements. Each array key should be the same
as a placeholder in $string. The corresponding value should be a string
or an object that implements
\Drupal\Component\Render\MarkupInterface. The value replaces the
placeholder in $string. Sanitization and formatting will be done before
replacement. The type of sanitization and formatting depends on the first
character of the key:
- @variable: When the placeholder replacement value is:
- A string, the replaced value in the returned string will be sanitized
using \Drupal\Component\Utility\Html::escape().
- A MarkupInterface object, the replaced value in the returned string
will not be sanitized.
- A MarkupInterface object cast to a string, the replaced value in the
returned string be forcibly sanitized using
\Drupal\Component\Utility\Html::escape().
@code
$this->placeholderFormat('This will force HTML-escaping of the replacement value: @text', ['@text' => (string) $safe_string_interface_object));
@endcode
Use this placeholder as the default choice for anything displayed on
the site, but not within HTML attributes, JavaScript, or CSS. Doing so
is a security risk.
- %variable: Use when the replacement value is to be wrapped in <em>
tags.
A call like:
@code
$string = "%output_text";
$arguments = ['output_text' => 'text output here.'];
$this->placeholderFormat($string, $arguments);
@endcode
makes the following HTML code:
@code
<em class="placeholder">text output here.</em>
@endcode
As with @variable, do not use this within HTML attributes, JavaScript,
or CSS. Doing so is a security risk.
- :variable: Return value is escaped with
\Drupal\Component\Utility\Html::escape() and filtered for dangerous
protocols using UrlHelper::stripDangerousProtocols(). Use this when
using the "href" attribute, ensuring the attribute value is always
wrapped in quotes:
@code
// Secure (with quotes):
$this->placeholderFormat('<a href=":url">@variable</a>', [':url' => $url, @variable => $variable]);
// Insecure (without quotes):
$this->placeholderFormat('<a href=:url>@variable</a>', [':url' => $url, @variable => $variable]);
@endcode
When ":variable" comes from arbitrary user input, the result is secure,
but not guaranteed to be a valid URL (which means the resulting output
could fail HTML validation). To guarantee a valid URL, use
Url::fromUri($user_input)->toString() (which either throws an exception
or returns a well-formed URL) before passing the result into a
":variable" placeholder.
@return string
A formatted HTML string with the placeholders replaced.
@ingroup sanitization
@see \Drupal\Core\StringTranslation\TranslatableMarkup
@see \Drupal\Core\StringTranslation\PluralTranslatableMarkup
@see \Drupal\Component\Utility\Html::escape()
@see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
@see \Drupal\Core\Url::fromUri() | [
"Replaces",
"placeholders",
"in",
"a",
"string",
"with",
"values",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Render/FormattableMarkup.php#L194-L247 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Render/FormattableMarkup.php | FormattableMarkup.placeholderEscape | protected static function placeholderEscape($value) {
return SafeMarkup::isSafe($value) ? (string) $value : Html::escape($value);
} | php | protected static function placeholderEscape($value) {
return SafeMarkup::isSafe($value) ? (string) $value : Html::escape($value);
} | [
"protected",
"static",
"function",
"placeholderEscape",
"(",
"$",
"value",
")",
"{",
"return",
"SafeMarkup",
"::",
"isSafe",
"(",
"$",
"value",
")",
"?",
"(",
"string",
")",
"$",
"value",
":",
"Html",
"::",
"escape",
"(",
"$",
"value",
")",
";",
"}"
] | Escapes a placeholder replacement value if needed.
@param string|\Drupal\Component\Render\MarkupInterface $value
A placeholder replacement value.
@return string
The properly escaped replacement value. | [
"Escapes",
"a",
"placeholder",
"replacement",
"value",
"if",
"needed",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Render/FormattableMarkup.php#L258-L260 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/ArgumentsResolver.php | ArgumentsResolver.getArgument | protected function getArgument(\ReflectionParameter $parameter) {
$parameter_type_hint = $parameter->getClass();
$parameter_name = $parameter->getName();
// If the argument exists and is NULL, return it, regardless of
// parameter type hint.
if (!isset($this->objects[$parameter_name]) && array_key_exists($parameter_name, $this->objects)) {
return NULL;
}
if ($parameter_type_hint) {
// If the argument exists and complies with the type hint, return it.
if (isset($this->objects[$parameter_name]) && is_object($this->objects[$parameter_name]) && $parameter_type_hint->isInstance($this->objects[$parameter_name])) {
return $this->objects[$parameter_name];
}
// Otherwise, resolve wildcard arguments by type matching.
foreach ($this->wildcards as $wildcard) {
if ($parameter_type_hint->isInstance($wildcard)) {
return $wildcard;
}
}
}
elseif (isset($this->scalars[$parameter_name])) {
return $this->scalars[$parameter_name];
}
// If the callable provides a default value, use it.
if ($parameter->isDefaultValueAvailable()) {
return $parameter->getDefaultValue();
}
// Can't resolve it: call a method that throws an exception or can be
// overridden to do something else.
return $this->handleUnresolvedArgument($parameter);
} | php | protected function getArgument(\ReflectionParameter $parameter) {
$parameter_type_hint = $parameter->getClass();
$parameter_name = $parameter->getName();
// If the argument exists and is NULL, return it, regardless of
// parameter type hint.
if (!isset($this->objects[$parameter_name]) && array_key_exists($parameter_name, $this->objects)) {
return NULL;
}
if ($parameter_type_hint) {
// If the argument exists and complies with the type hint, return it.
if (isset($this->objects[$parameter_name]) && is_object($this->objects[$parameter_name]) && $parameter_type_hint->isInstance($this->objects[$parameter_name])) {
return $this->objects[$parameter_name];
}
// Otherwise, resolve wildcard arguments by type matching.
foreach ($this->wildcards as $wildcard) {
if ($parameter_type_hint->isInstance($wildcard)) {
return $wildcard;
}
}
}
elseif (isset($this->scalars[$parameter_name])) {
return $this->scalars[$parameter_name];
}
// If the callable provides a default value, use it.
if ($parameter->isDefaultValueAvailable()) {
return $parameter->getDefaultValue();
}
// Can't resolve it: call a method that throws an exception or can be
// overridden to do something else.
return $this->handleUnresolvedArgument($parameter);
} | [
"protected",
"function",
"getArgument",
"(",
"\\",
"ReflectionParameter",
"$",
"parameter",
")",
"{",
"$",
"parameter_type_hint",
"=",
"$",
"parameter",
"->",
"getClass",
"(",
")",
";",
"$",
"parameter_name",
"=",
"$",
"parameter",
"->",
"getName",
"(",
")",
... | Gets the argument value for a parameter.
@param \ReflectionParameter $parameter
The parameter of a callable to get the value for.
@return mixed
The value of the requested parameter value.
@throws \RuntimeException
Thrown when there is a missing parameter. | [
"Gets",
"the",
"argument",
"value",
"for",
"a",
"parameter",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/ArgumentsResolver.php#L76-L110 | train |
aleksip/plugin-data-transform | src/Drupal/Component/Utility/SortArray.php | SortArray.sortByKeyString | public static function sortByKeyString($a, $b, $key) {
$a_title = (is_array($a) && isset($a[$key])) ? $a[$key] : '';
$b_title = (is_array($b) && isset($b[$key])) ? $b[$key] : '';
return strnatcasecmp($a_title, $b_title);
} | php | public static function sortByKeyString($a, $b, $key) {
$a_title = (is_array($a) && isset($a[$key])) ? $a[$key] : '';
$b_title = (is_array($b) && isset($b[$key])) ? $b[$key] : '';
return strnatcasecmp($a_title, $b_title);
} | [
"public",
"static",
"function",
"sortByKeyString",
"(",
"$",
"a",
",",
"$",
"b",
",",
"$",
"key",
")",
"{",
"$",
"a_title",
"=",
"(",
"is_array",
"(",
"$",
"a",
")",
"&&",
"isset",
"(",
"$",
"a",
"[",
"$",
"key",
"]",
")",
")",
"?",
"$",
"a",... | Sorts a string 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",
"a",
"string",
"array",
"item",
"by",
"an",
"arbitrary",
"key",
"."
] | 7fc113993903b7d64dfd98bc32f5450e164313a7 | https://github.com/aleksip/plugin-data-transform/blob/7fc113993903b7d64dfd98bc32f5450e164313a7/src/Drupal/Component/Utility/SortArray.php#L106-L111 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.