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 |
---|---|---|---|---|---|---|---|---|---|---|---|
webmozart/json
|
src/JsonEncoder.php
|
JsonEncoder.encode
|
public function encode($data, $schema = null)
{
if (null !== $schema) {
$errors = $this->validator->validate($data, $schema);
if (count($errors) > 0) {
throw ValidationFailedException::fromErrors($errors);
}
}
$options = 0;
if (self::JSON_OBJECT === $this->arrayEncoding) {
$options |= JSON_FORCE_OBJECT;
}
if (self::JSON_NUMBER === $this->numericEncoding) {
$options |= JSON_NUMERIC_CHECK;
}
if ($this->gtLtEscaped) {
$options |= JSON_HEX_TAG;
}
if ($this->ampersandEscaped) {
$options |= JSON_HEX_AMP;
}
if ($this->singleQuoteEscaped) {
$options |= JSON_HEX_APOS;
}
if ($this->doubleQuoteEscaped) {
$options |= JSON_HEX_QUOT;
}
if (PHP_VERSION_ID >= 50400) {
if (!$this->slashEscaped) {
$options |= JSON_UNESCAPED_SLASHES;
}
if (!$this->unicodeEscaped) {
$options |= JSON_UNESCAPED_UNICODE;
}
if ($this->prettyPrinting) {
$options |= JSON_PRETTY_PRINT;
}
}
if (PHP_VERSION_ID < 71000) {
// PHP before 7.1 decodes empty properties as "_empty_". Make
// sure the encoding of these properties works again.
if (is_object($data) && isset($data->{'_empty_'})) {
$data = (array) $data;
}
if (is_array($data) && isset($data['_empty_'])) {
// Maintain key order
$keys = array_keys($data);
$keys[array_search('_empty_', $keys, true)] = '';
$data = array_combine($keys, $data);
}
}
if (PHP_VERSION_ID >= 50500) {
$maxDepth = $this->maxDepth;
// We subtract 1 from the max depth to make JsonDecoder and
// JsonEncoder consistent. json_encode() and json_decode() behave
// differently for their depth values. See the test cases for
// examples.
// HHVM does not have this inconsistency.
if (!defined('HHVM_VERSION')) {
--$maxDepth;
}
$encoded = json_encode($data, $options, $maxDepth);
} else {
$encoded = json_encode($data, $options);
}
if (PHP_VERSION_ID < 50400 && !$this->slashEscaped) {
// PHP below 5.4 does not allow to turn off slash escaping. Let's
// unescape slashes manually.
$encoded = str_replace('\\/', '/', $encoded);
}
if (JSON_ERROR_NONE !== json_last_error()) {
throw new EncodingFailedException(sprintf(
'The data could not be encoded as JSON: %s',
JsonError::getLastErrorMessage()
), json_last_error());
}
if ($this->terminatedWithLineFeed) {
$encoded .= "\n";
}
return $encoded;
}
|
php
|
public function encode($data, $schema = null)
{
if (null !== $schema) {
$errors = $this->validator->validate($data, $schema);
if (count($errors) > 0) {
throw ValidationFailedException::fromErrors($errors);
}
}
$options = 0;
if (self::JSON_OBJECT === $this->arrayEncoding) {
$options |= JSON_FORCE_OBJECT;
}
if (self::JSON_NUMBER === $this->numericEncoding) {
$options |= JSON_NUMERIC_CHECK;
}
if ($this->gtLtEscaped) {
$options |= JSON_HEX_TAG;
}
if ($this->ampersandEscaped) {
$options |= JSON_HEX_AMP;
}
if ($this->singleQuoteEscaped) {
$options |= JSON_HEX_APOS;
}
if ($this->doubleQuoteEscaped) {
$options |= JSON_HEX_QUOT;
}
if (PHP_VERSION_ID >= 50400) {
if (!$this->slashEscaped) {
$options |= JSON_UNESCAPED_SLASHES;
}
if (!$this->unicodeEscaped) {
$options |= JSON_UNESCAPED_UNICODE;
}
if ($this->prettyPrinting) {
$options |= JSON_PRETTY_PRINT;
}
}
if (PHP_VERSION_ID < 71000) {
// PHP before 7.1 decodes empty properties as "_empty_". Make
// sure the encoding of these properties works again.
if (is_object($data) && isset($data->{'_empty_'})) {
$data = (array) $data;
}
if (is_array($data) && isset($data['_empty_'])) {
// Maintain key order
$keys = array_keys($data);
$keys[array_search('_empty_', $keys, true)] = '';
$data = array_combine($keys, $data);
}
}
if (PHP_VERSION_ID >= 50500) {
$maxDepth = $this->maxDepth;
// We subtract 1 from the max depth to make JsonDecoder and
// JsonEncoder consistent. json_encode() and json_decode() behave
// differently for their depth values. See the test cases for
// examples.
// HHVM does not have this inconsistency.
if (!defined('HHVM_VERSION')) {
--$maxDepth;
}
$encoded = json_encode($data, $options, $maxDepth);
} else {
$encoded = json_encode($data, $options);
}
if (PHP_VERSION_ID < 50400 && !$this->slashEscaped) {
// PHP below 5.4 does not allow to turn off slash escaping. Let's
// unescape slashes manually.
$encoded = str_replace('\\/', '/', $encoded);
}
if (JSON_ERROR_NONE !== json_last_error()) {
throw new EncodingFailedException(sprintf(
'The data could not be encoded as JSON: %s',
JsonError::getLastErrorMessage()
), json_last_error());
}
if ($this->terminatedWithLineFeed) {
$encoded .= "\n";
}
return $encoded;
}
|
[
"public",
"function",
"encode",
"(",
"$",
"data",
",",
"$",
"schema",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"schema",
")",
"{",
"$",
"errors",
"=",
"$",
"this",
"->",
"validator",
"->",
"validate",
"(",
"$",
"data",
",",
"$",
"schema",
")",
";",
"if",
"(",
"count",
"(",
"$",
"errors",
")",
">",
"0",
")",
"{",
"throw",
"ValidationFailedException",
"::",
"fromErrors",
"(",
"$",
"errors",
")",
";",
"}",
"}",
"$",
"options",
"=",
"0",
";",
"if",
"(",
"self",
"::",
"JSON_OBJECT",
"===",
"$",
"this",
"->",
"arrayEncoding",
")",
"{",
"$",
"options",
"|=",
"JSON_FORCE_OBJECT",
";",
"}",
"if",
"(",
"self",
"::",
"JSON_NUMBER",
"===",
"$",
"this",
"->",
"numericEncoding",
")",
"{",
"$",
"options",
"|=",
"JSON_NUMERIC_CHECK",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"gtLtEscaped",
")",
"{",
"$",
"options",
"|=",
"JSON_HEX_TAG",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"ampersandEscaped",
")",
"{",
"$",
"options",
"|=",
"JSON_HEX_AMP",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"singleQuoteEscaped",
")",
"{",
"$",
"options",
"|=",
"JSON_HEX_APOS",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"doubleQuoteEscaped",
")",
"{",
"$",
"options",
"|=",
"JSON_HEX_QUOT",
";",
"}",
"if",
"(",
"PHP_VERSION_ID",
">=",
"50400",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"slashEscaped",
")",
"{",
"$",
"options",
"|=",
"JSON_UNESCAPED_SLASHES",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"unicodeEscaped",
")",
"{",
"$",
"options",
"|=",
"JSON_UNESCAPED_UNICODE",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"prettyPrinting",
")",
"{",
"$",
"options",
"|=",
"JSON_PRETTY_PRINT",
";",
"}",
"}",
"if",
"(",
"PHP_VERSION_ID",
"<",
"71000",
")",
"{",
"// PHP before 7.1 decodes empty properties as \"_empty_\". Make",
"// sure the encoding of these properties works again.",
"if",
"(",
"is_object",
"(",
"$",
"data",
")",
"&&",
"isset",
"(",
"$",
"data",
"->",
"{",
"'_empty_'",
"}",
")",
")",
"{",
"$",
"data",
"=",
"(",
"array",
")",
"$",
"data",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
"&&",
"isset",
"(",
"$",
"data",
"[",
"'_empty_'",
"]",
")",
")",
"{",
"// Maintain key order",
"$",
"keys",
"=",
"array_keys",
"(",
"$",
"data",
")",
";",
"$",
"keys",
"[",
"array_search",
"(",
"'_empty_'",
",",
"$",
"keys",
",",
"true",
")",
"]",
"=",
"''",
";",
"$",
"data",
"=",
"array_combine",
"(",
"$",
"keys",
",",
"$",
"data",
")",
";",
"}",
"}",
"if",
"(",
"PHP_VERSION_ID",
">=",
"50500",
")",
"{",
"$",
"maxDepth",
"=",
"$",
"this",
"->",
"maxDepth",
";",
"// We subtract 1 from the max depth to make JsonDecoder and",
"// JsonEncoder consistent. json_encode() and json_decode() behave",
"// differently for their depth values. See the test cases for",
"// examples.",
"// HHVM does not have this inconsistency.",
"if",
"(",
"!",
"defined",
"(",
"'HHVM_VERSION'",
")",
")",
"{",
"--",
"$",
"maxDepth",
";",
"}",
"$",
"encoded",
"=",
"json_encode",
"(",
"$",
"data",
",",
"$",
"options",
",",
"$",
"maxDepth",
")",
";",
"}",
"else",
"{",
"$",
"encoded",
"=",
"json_encode",
"(",
"$",
"data",
",",
"$",
"options",
")",
";",
"}",
"if",
"(",
"PHP_VERSION_ID",
"<",
"50400",
"&&",
"!",
"$",
"this",
"->",
"slashEscaped",
")",
"{",
"// PHP below 5.4 does not allow to turn off slash escaping. Let's",
"// unescape slashes manually.",
"$",
"encoded",
"=",
"str_replace",
"(",
"'\\\\/'",
",",
"'/'",
",",
"$",
"encoded",
")",
";",
"}",
"if",
"(",
"JSON_ERROR_NONE",
"!==",
"json_last_error",
"(",
")",
")",
"{",
"throw",
"new",
"EncodingFailedException",
"(",
"sprintf",
"(",
"'The data could not be encoded as JSON: %s'",
",",
"JsonError",
"::",
"getLastErrorMessage",
"(",
")",
")",
",",
"json_last_error",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"terminatedWithLineFeed",
")",
"{",
"$",
"encoded",
".=",
"\"\\n\"",
";",
"}",
"return",
"$",
"encoded",
";",
"}"
] |
Encodes data as JSON.
If a schema is passed, the value is validated against that schema before
encoding. The schema may be passed as file path or as object returned
from `JsonDecoder::decodeFile($schemaFile)`.
You can adjust the decoding with the various setters in this class.
@param mixed $data The data to encode
@param string|object $schema The schema file or object
@return string The JSON string
@throws EncodingFailedException If the data could not be encoded
@throws ValidationFailedException If the data fails schema validation
@throws InvalidSchemaException If the schema is invalid
|
[
"Encodes",
"data",
"as",
"JSON",
"."
] |
d823428254474fc26aa499aebbda1315e2fedf3a
|
https://github.com/webmozart/json/blob/d823428254474fc26aa499aebbda1315e2fedf3a/src/JsonEncoder.php#L131-L231
|
train
|
webmozart/json
|
src/JsonEncoder.php
|
JsonEncoder.encodeFile
|
public function encodeFile($data, $path, $schema = null)
{
if (!file_exists($dir = dirname($path))) {
mkdir($dir, 0777, true);
}
try {
// Right now, it's sufficient to just write the file. In the future,
// this will diff existing files with the given data and only do
// in-place modifications where necessary.
$content = $this->encode($data, $schema);
} catch (EncodingFailedException $e) {
// Add the file name to the exception
throw new EncodingFailedException(sprintf(
'An error happened while encoding %s: %s',
$path,
$e->getMessage()
), $e->getCode(), $e);
} catch (ValidationFailedException $e) {
// Add the file name to the exception
throw new ValidationFailedException(sprintf(
"Validation failed while encoding %s:\n%s",
$path,
$e->getErrorsAsString()
), $e->getErrors(), $e->getCode(), $e);
} catch (InvalidSchemaException $e) {
// Add the file name to the exception
throw new InvalidSchemaException(sprintf(
'An error happened while encoding %s: %s',
$path,
$e->getMessage()
), $e->getCode(), $e);
}
$errorMessage = null;
$errorCode = 0;
set_error_handler(function ($errno, $errstr) use (&$errorMessage, &$errorCode) {
$errorMessage = $errstr;
$errorCode = $errno;
});
file_put_contents($path, $content);
restore_error_handler();
if (null !== $errorMessage) {
if (false !== $pos = strpos($errorMessage, '): ')) {
// cut "file_put_contents(%path%):" to make message more readable
$errorMessage = substr($errorMessage, $pos + 3);
}
throw new IOException(sprintf(
'Could not write %s: %s (%s)',
$path,
$errorMessage,
$errorCode
), $errorCode);
}
}
|
php
|
public function encodeFile($data, $path, $schema = null)
{
if (!file_exists($dir = dirname($path))) {
mkdir($dir, 0777, true);
}
try {
// Right now, it's sufficient to just write the file. In the future,
// this will diff existing files with the given data and only do
// in-place modifications where necessary.
$content = $this->encode($data, $schema);
} catch (EncodingFailedException $e) {
// Add the file name to the exception
throw new EncodingFailedException(sprintf(
'An error happened while encoding %s: %s',
$path,
$e->getMessage()
), $e->getCode(), $e);
} catch (ValidationFailedException $e) {
// Add the file name to the exception
throw new ValidationFailedException(sprintf(
"Validation failed while encoding %s:\n%s",
$path,
$e->getErrorsAsString()
), $e->getErrors(), $e->getCode(), $e);
} catch (InvalidSchemaException $e) {
// Add the file name to the exception
throw new InvalidSchemaException(sprintf(
'An error happened while encoding %s: %s',
$path,
$e->getMessage()
), $e->getCode(), $e);
}
$errorMessage = null;
$errorCode = 0;
set_error_handler(function ($errno, $errstr) use (&$errorMessage, &$errorCode) {
$errorMessage = $errstr;
$errorCode = $errno;
});
file_put_contents($path, $content);
restore_error_handler();
if (null !== $errorMessage) {
if (false !== $pos = strpos($errorMessage, '): ')) {
// cut "file_put_contents(%path%):" to make message more readable
$errorMessage = substr($errorMessage, $pos + 3);
}
throw new IOException(sprintf(
'Could not write %s: %s (%s)',
$path,
$errorMessage,
$errorCode
), $errorCode);
}
}
|
[
"public",
"function",
"encodeFile",
"(",
"$",
"data",
",",
"$",
"path",
",",
"$",
"schema",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"dir",
"=",
"dirname",
"(",
"$",
"path",
")",
")",
")",
"{",
"mkdir",
"(",
"$",
"dir",
",",
"0777",
",",
"true",
")",
";",
"}",
"try",
"{",
"// Right now, it's sufficient to just write the file. In the future,",
"// this will diff existing files with the given data and only do",
"// in-place modifications where necessary.",
"$",
"content",
"=",
"$",
"this",
"->",
"encode",
"(",
"$",
"data",
",",
"$",
"schema",
")",
";",
"}",
"catch",
"(",
"EncodingFailedException",
"$",
"e",
")",
"{",
"// Add the file name to the exception",
"throw",
"new",
"EncodingFailedException",
"(",
"sprintf",
"(",
"'An error happened while encoding %s: %s'",
",",
"$",
"path",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
",",
"$",
"e",
"->",
"getCode",
"(",
")",
",",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"ValidationFailedException",
"$",
"e",
")",
"{",
"// Add the file name to the exception",
"throw",
"new",
"ValidationFailedException",
"(",
"sprintf",
"(",
"\"Validation failed while encoding %s:\\n%s\"",
",",
"$",
"path",
",",
"$",
"e",
"->",
"getErrorsAsString",
"(",
")",
")",
",",
"$",
"e",
"->",
"getErrors",
"(",
")",
",",
"$",
"e",
"->",
"getCode",
"(",
")",
",",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"InvalidSchemaException",
"$",
"e",
")",
"{",
"// Add the file name to the exception",
"throw",
"new",
"InvalidSchemaException",
"(",
"sprintf",
"(",
"'An error happened while encoding %s: %s'",
",",
"$",
"path",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
",",
"$",
"e",
"->",
"getCode",
"(",
")",
",",
"$",
"e",
")",
";",
"}",
"$",
"errorMessage",
"=",
"null",
";",
"$",
"errorCode",
"=",
"0",
";",
"set_error_handler",
"(",
"function",
"(",
"$",
"errno",
",",
"$",
"errstr",
")",
"use",
"(",
"&",
"$",
"errorMessage",
",",
"&",
"$",
"errorCode",
")",
"{",
"$",
"errorMessage",
"=",
"$",
"errstr",
";",
"$",
"errorCode",
"=",
"$",
"errno",
";",
"}",
")",
";",
"file_put_contents",
"(",
"$",
"path",
",",
"$",
"content",
")",
";",
"restore_error_handler",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"errorMessage",
")",
"{",
"if",
"(",
"false",
"!==",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"errorMessage",
",",
"'): '",
")",
")",
"{",
"// cut \"file_put_contents(%path%):\" to make message more readable",
"$",
"errorMessage",
"=",
"substr",
"(",
"$",
"errorMessage",
",",
"$",
"pos",
"+",
"3",
")",
";",
"}",
"throw",
"new",
"IOException",
"(",
"sprintf",
"(",
"'Could not write %s: %s (%s)'",
",",
"$",
"path",
",",
"$",
"errorMessage",
",",
"$",
"errorCode",
")",
",",
"$",
"errorCode",
")",
";",
"}",
"}"
] |
Encodes data into a JSON file.
@param mixed $data The data to encode
@param string $path The path where the JSON file will be stored
@param string|object $schema The schema file or object
@throws EncodingFailedException If the data could not be encoded
@throws ValidationFailedException If the data fails schema validation
@throws InvalidSchemaException If the schema is invalid
@see encode
|
[
"Encodes",
"data",
"into",
"a",
"JSON",
"file",
"."
] |
d823428254474fc26aa499aebbda1315e2fedf3a
|
https://github.com/webmozart/json/blob/d823428254474fc26aa499aebbda1315e2fedf3a/src/JsonEncoder.php#L246-L305
|
train
|
webmozart/json
|
src/JsonEncoder.php
|
JsonEncoder.setArrayEncoding
|
public function setArrayEncoding($encoding)
{
if (self::JSON_ARRAY !== $encoding && self::JSON_OBJECT !== $encoding) {
throw new \InvalidArgumentException(sprintf(
'Expected JsonEncoder::JSON_ARRAY or JsonEncoder::JSON_OBJECT. '.
'Got: %s',
$encoding
));
}
$this->arrayEncoding = $encoding;
}
|
php
|
public function setArrayEncoding($encoding)
{
if (self::JSON_ARRAY !== $encoding && self::JSON_OBJECT !== $encoding) {
throw new \InvalidArgumentException(sprintf(
'Expected JsonEncoder::JSON_ARRAY or JsonEncoder::JSON_OBJECT. '.
'Got: %s',
$encoding
));
}
$this->arrayEncoding = $encoding;
}
|
[
"public",
"function",
"setArrayEncoding",
"(",
"$",
"encoding",
")",
"{",
"if",
"(",
"self",
"::",
"JSON_ARRAY",
"!==",
"$",
"encoding",
"&&",
"self",
"::",
"JSON_OBJECT",
"!==",
"$",
"encoding",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Expected JsonEncoder::JSON_ARRAY or JsonEncoder::JSON_OBJECT. '",
".",
"'Got: %s'",
",",
"$",
"encoding",
")",
")",
";",
"}",
"$",
"this",
"->",
"arrayEncoding",
"=",
"$",
"encoding",
";",
"}"
] |
Sets the encoding of non-associative arrays.
By default, non-associative arrays are decoded as JSON arrays.
@param int $encoding One of the constants {@link JSON_OBJECT} and {@link JSON_ARRAY}
@throws \InvalidArgumentException If the passed encoding is invalid
|
[
"Sets",
"the",
"encoding",
"of",
"non",
"-",
"associative",
"arrays",
"."
] |
d823428254474fc26aa499aebbda1315e2fedf3a
|
https://github.com/webmozart/json/blob/d823428254474fc26aa499aebbda1315e2fedf3a/src/JsonEncoder.php#L326-L337
|
train
|
webmozart/json
|
src/JsonEncoder.php
|
JsonEncoder.setNumericEncoding
|
public function setNumericEncoding($encoding)
{
if (self::JSON_NUMBER !== $encoding && self::JSON_STRING !== $encoding) {
throw new \InvalidArgumentException(sprintf(
'Expected JsonEncoder::JSON_NUMBER or JsonEncoder::JSON_STRING. '.
'Got: %s',
$encoding
));
}
$this->numericEncoding = $encoding;
}
|
php
|
public function setNumericEncoding($encoding)
{
if (self::JSON_NUMBER !== $encoding && self::JSON_STRING !== $encoding) {
throw new \InvalidArgumentException(sprintf(
'Expected JsonEncoder::JSON_NUMBER or JsonEncoder::JSON_STRING. '.
'Got: %s',
$encoding
));
}
$this->numericEncoding = $encoding;
}
|
[
"public",
"function",
"setNumericEncoding",
"(",
"$",
"encoding",
")",
"{",
"if",
"(",
"self",
"::",
"JSON_NUMBER",
"!==",
"$",
"encoding",
"&&",
"self",
"::",
"JSON_STRING",
"!==",
"$",
"encoding",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Expected JsonEncoder::JSON_NUMBER or JsonEncoder::JSON_STRING. '",
".",
"'Got: %s'",
",",
"$",
"encoding",
")",
")",
";",
"}",
"$",
"this",
"->",
"numericEncoding",
"=",
"$",
"encoding",
";",
"}"
] |
Sets the encoding of numeric strings.
By default, non-associative arrays are decoded as JSON strings.
@param int $encoding One of the constants {@link JSON_STRING} and {@link JSON_NUMBER}
@throws \InvalidArgumentException If the passed encoding is invalid
|
[
"Sets",
"the",
"encoding",
"of",
"numeric",
"strings",
"."
] |
d823428254474fc26aa499aebbda1315e2fedf3a
|
https://github.com/webmozart/json/blob/d823428254474fc26aa499aebbda1315e2fedf3a/src/JsonEncoder.php#L358-L369
|
train
|
Art4/json-api-client
|
src/V1/ResourceCollection.php
|
ResourceCollection.parseResource
|
private function parseResource($data)
{
if (! is_object($data)) {
throw new ValidationException('Resources inside a collection MUST be objects, "' . gettype($data) . '" given.');
}
$object_vars = get_object_vars($data);
// the 2 properties must be type and id
// or the 3 properties must be type, id and meta
if (count($object_vars) === 2 or (count($object_vars) === 3 and property_exists($data, 'meta'))) {
$resource = $this->create('ResourceIdentifier', $data);
} else {
$resource = $this->create('ResourceItem', $data);
}
return $resource;
}
|
php
|
private function parseResource($data)
{
if (! is_object($data)) {
throw new ValidationException('Resources inside a collection MUST be objects, "' . gettype($data) . '" given.');
}
$object_vars = get_object_vars($data);
// the 2 properties must be type and id
// or the 3 properties must be type, id and meta
if (count($object_vars) === 2 or (count($object_vars) === 3 and property_exists($data, 'meta'))) {
$resource = $this->create('ResourceIdentifier', $data);
} else {
$resource = $this->create('ResourceItem', $data);
}
return $resource;
}
|
[
"private",
"function",
"parseResource",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"'Resources inside a collection MUST be objects, \"'",
".",
"gettype",
"(",
"$",
"data",
")",
".",
"'\" given.'",
")",
";",
"}",
"$",
"object_vars",
"=",
"get_object_vars",
"(",
"$",
"data",
")",
";",
"// the 2 properties must be type and id",
"// or the 3 properties must be type, id and meta",
"if",
"(",
"count",
"(",
"$",
"object_vars",
")",
"===",
"2",
"or",
"(",
"count",
"(",
"$",
"object_vars",
")",
"===",
"3",
"and",
"property_exists",
"(",
"$",
"data",
",",
"'meta'",
")",
")",
")",
"{",
"$",
"resource",
"=",
"$",
"this",
"->",
"create",
"(",
"'ResourceIdentifier'",
",",
"$",
"data",
")",
";",
"}",
"else",
"{",
"$",
"resource",
"=",
"$",
"this",
"->",
"create",
"(",
"'ResourceItem'",
",",
"$",
"data",
")",
";",
"}",
"return",
"$",
"resource",
";",
"}"
] |
Generate a new resource from an object
@param object $data The resource data
@return ElementInterface The resource
|
[
"Generate",
"a",
"new",
"resource",
"from",
"an",
"object"
] |
2e4148f73966fdc815b6406a3779ef3bb046e1a4
|
https://github.com/Art4/json-api-client/blob/2e4148f73966fdc815b6406a3779ef3bb046e1a4/src/V1/ResourceCollection.php#L76-L93
|
train
|
Art4/json-api-client
|
src/V1/Document.php
|
Document.parseData
|
private function parseData($data)
{
if ($data === null) {
return $this->create('ResourceNull', $data);
}
if (is_array($data)) {
return $this->create('ResourceCollection', $data);
}
if (! is_object($data)) {
throw new ValidationException('Data value has to be null or an object, "' . gettype($data) . '" given.');
}
$object_keys = array_keys(get_object_vars($data));
sort($object_keys);
// the properties must be type and id or
// the 3 properties must be type, id and meta
if ($object_keys === ['id', 'type'] or $object_keys === ['id', 'meta', 'type']) {
$resource = $this->create('ResourceIdentifier', $data);
} else {
// #Workaround: preset `data` with null, so ResourceItem can distinguish his parent between Document and ResourceCollection
$this->set('data', null);
$resource = $this->create('ResourceItem', $data);
}
return $resource;
}
|
php
|
private function parseData($data)
{
if ($data === null) {
return $this->create('ResourceNull', $data);
}
if (is_array($data)) {
return $this->create('ResourceCollection', $data);
}
if (! is_object($data)) {
throw new ValidationException('Data value has to be null or an object, "' . gettype($data) . '" given.');
}
$object_keys = array_keys(get_object_vars($data));
sort($object_keys);
// the properties must be type and id or
// the 3 properties must be type, id and meta
if ($object_keys === ['id', 'type'] or $object_keys === ['id', 'meta', 'type']) {
$resource = $this->create('ResourceIdentifier', $data);
} else {
// #Workaround: preset `data` with null, so ResourceItem can distinguish his parent between Document and ResourceCollection
$this->set('data', null);
$resource = $this->create('ResourceItem', $data);
}
return $resource;
}
|
[
"private",
"function",
"parseData",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"data",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"create",
"(",
"'ResourceNull'",
",",
"$",
"data",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"return",
"$",
"this",
"->",
"create",
"(",
"'ResourceCollection'",
",",
"$",
"data",
")",
";",
"}",
"if",
"(",
"!",
"is_object",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"'Data value has to be null or an object, \"'",
".",
"gettype",
"(",
"$",
"data",
")",
".",
"'\" given.'",
")",
";",
"}",
"$",
"object_keys",
"=",
"array_keys",
"(",
"get_object_vars",
"(",
"$",
"data",
")",
")",
";",
"sort",
"(",
"$",
"object_keys",
")",
";",
"// the properties must be type and id or",
"// the 3 properties must be type, id and meta",
"if",
"(",
"$",
"object_keys",
"===",
"[",
"'id'",
",",
"'type'",
"]",
"or",
"$",
"object_keys",
"===",
"[",
"'id'",
",",
"'meta'",
",",
"'type'",
"]",
")",
"{",
"$",
"resource",
"=",
"$",
"this",
"->",
"create",
"(",
"'ResourceIdentifier'",
",",
"$",
"data",
")",
";",
"}",
"else",
"{",
"// #Workaround: preset `data` with null, so ResourceItem can distinguish his parent between Document and ResourceCollection",
"$",
"this",
"->",
"set",
"(",
"'data'",
",",
"null",
")",
";",
"$",
"resource",
"=",
"$",
"this",
"->",
"create",
"(",
"'ResourceItem'",
",",
"$",
"data",
")",
";",
"}",
"return",
"$",
"resource",
";",
"}"
] |
Parse the data value
@param null|object $data Data value
@throws ValidationException If $data isn't null or an object
@return Accessable The parsed data
|
[
"Parse",
"the",
"data",
"value"
] |
2e4148f73966fdc815b6406a3779ef3bb046e1a4
|
https://github.com/Art4/json-api-client/blob/2e4148f73966fdc815b6406a3779ef3bb046e1a4/src/V1/Document.php#L109-L137
|
train
|
Art4/json-api-client
|
src/Serializer/ArraySerializer.php
|
ArraySerializer.serialize
|
public function serialize(Accessable $data)
{
$fullArray = (bool) $this->config['recursive'];
if (
$data instanceof ResourceNull
or $data instanceof ResourceNullInterface // #TODO Don't use ResourceNullInterface anymore
) {
return null;
}
$array = [];
foreach ($data->getKeys() as $key) {
$value = $data->get($key);
if ($fullArray) {
$array[$key] = $this->objectTransform($value);
} else {
$array[$key] = $value;
}
}
return $array;
}
|
php
|
public function serialize(Accessable $data)
{
$fullArray = (bool) $this->config['recursive'];
if (
$data instanceof ResourceNull
or $data instanceof ResourceNullInterface // #TODO Don't use ResourceNullInterface anymore
) {
return null;
}
$array = [];
foreach ($data->getKeys() as $key) {
$value = $data->get($key);
if ($fullArray) {
$array[$key] = $this->objectTransform($value);
} else {
$array[$key] = $value;
}
}
return $array;
}
|
[
"public",
"function",
"serialize",
"(",
"Accessable",
"$",
"data",
")",
"{",
"$",
"fullArray",
"=",
"(",
"bool",
")",
"$",
"this",
"->",
"config",
"[",
"'recursive'",
"]",
";",
"if",
"(",
"$",
"data",
"instanceof",
"ResourceNull",
"or",
"$",
"data",
"instanceof",
"ResourceNullInterface",
"// #TODO Don't use ResourceNullInterface anymore",
")",
"{",
"return",
"null",
";",
"}",
"$",
"array",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"->",
"getKeys",
"(",
")",
"as",
"$",
"key",
")",
"{",
"$",
"value",
"=",
"$",
"data",
"->",
"get",
"(",
"$",
"key",
")",
";",
"if",
"(",
"$",
"fullArray",
")",
"{",
"$",
"array",
"[",
"$",
"key",
"]",
"=",
"$",
"this",
"->",
"objectTransform",
"(",
"$",
"value",
")",
";",
"}",
"else",
"{",
"$",
"array",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"return",
"$",
"array",
";",
"}"
] |
Convert data in an array
@param Art4\JsonApiClient\Accessable $data The data for serialization
@return array
|
[
"Convert",
"data",
"in",
"an",
"array"
] |
2e4148f73966fdc815b6406a3779ef3bb046e1a4
|
https://github.com/Art4/json-api-client/blob/2e4148f73966fdc815b6406a3779ef3bb046e1a4/src/Serializer/ArraySerializer.php#L53-L77
|
train
|
Art4/json-api-client
|
src/Serializer/ArraySerializer.php
|
ArraySerializer.objectTransform
|
private function objectTransform($val)
{
if (! is_object($val)) {
return $val;
} elseif ($val instanceof Accessable) {
return $this->serialize($val);
} else {
// Fallback for stdClass objects
return json_decode(json_encode($val), true);
}
}
|
php
|
private function objectTransform($val)
{
if (! is_object($val)) {
return $val;
} elseif ($val instanceof Accessable) {
return $this->serialize($val);
} else {
// Fallback for stdClass objects
return json_decode(json_encode($val), true);
}
}
|
[
"private",
"function",
"objectTransform",
"(",
"$",
"val",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"val",
")",
")",
"{",
"return",
"$",
"val",
";",
"}",
"elseif",
"(",
"$",
"val",
"instanceof",
"Accessable",
")",
"{",
"return",
"$",
"this",
"->",
"serialize",
"(",
"$",
"val",
")",
";",
"}",
"else",
"{",
"// Fallback for stdClass objects",
"return",
"json_decode",
"(",
"json_encode",
"(",
"$",
"val",
")",
",",
"true",
")",
";",
"}",
"}"
] |
Transforms objects to arrays
@param $val
@return mixed
|
[
"Transforms",
"objects",
"to",
"arrays"
] |
2e4148f73966fdc815b6406a3779ef3bb046e1a4
|
https://github.com/Art4/json-api-client/blob/2e4148f73966fdc815b6406a3779ef3bb046e1a4/src/Serializer/ArraySerializer.php#L86-L96
|
train
|
Art4/json-api-client
|
src/Helper/AccessableTrait.php
|
AccessableTrait.has
|
public function has($key)
{
$key = $this->parseKey($key);
$string = $key->shift();
$key->next();
if ($key->count() === 0) {
return array_key_exists($string, $this->data);
}
if (! array_key_exists($string, $this->data)) {
return false;
}
$value = $this->getValue($string);
// #TODO Handle other objects and arrays
if (! $value instanceof Accessable) {
//throw new AccessException('The existance for the key "' . $key->raw . '" could\'nt be checked.');
return false;
}
return $value->has($key);
}
|
php
|
public function has($key)
{
$key = $this->parseKey($key);
$string = $key->shift();
$key->next();
if ($key->count() === 0) {
return array_key_exists($string, $this->data);
}
if (! array_key_exists($string, $this->data)) {
return false;
}
$value = $this->getValue($string);
// #TODO Handle other objects and arrays
if (! $value instanceof Accessable) {
//throw new AccessException('The existance for the key "' . $key->raw . '" could\'nt be checked.');
return false;
}
return $value->has($key);
}
|
[
"public",
"function",
"has",
"(",
"$",
"key",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"parseKey",
"(",
"$",
"key",
")",
";",
"$",
"string",
"=",
"$",
"key",
"->",
"shift",
"(",
")",
";",
"$",
"key",
"->",
"next",
"(",
")",
";",
"if",
"(",
"$",
"key",
"->",
"count",
"(",
")",
"===",
"0",
")",
"{",
"return",
"array_key_exists",
"(",
"$",
"string",
",",
"$",
"this",
"->",
"data",
")",
";",
"}",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"string",
",",
"$",
"this",
"->",
"data",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"value",
"=",
"$",
"this",
"->",
"getValue",
"(",
"$",
"string",
")",
";",
"// #TODO Handle other objects and arrays",
"if",
"(",
"!",
"$",
"value",
"instanceof",
"Accessable",
")",
"{",
"//throw new AccessException('The existance for the key \"' . $key->raw . '\" could\\'nt be checked.');",
"return",
"false",
";",
"}",
"return",
"$",
"value",
"->",
"has",
"(",
"$",
"key",
")",
";",
"}"
] |
Check if a value exists
@param mixed $key The key
@return bool
|
[
"Check",
"if",
"a",
"value",
"exists"
] |
2e4148f73966fdc815b6406a3779ef3bb046e1a4
|
https://github.com/Art4/json-api-client/blob/2e4148f73966fdc815b6406a3779ef3bb046e1a4/src/Helper/AccessableTrait.php#L74-L98
|
train
|
Art4/json-api-client
|
src/Helper/AccessableTrait.php
|
AccessableTrait.get
|
public function get($key)
{
$key = $this->parseKey($key);
$string = $key->shift();
$key->next();
$value = $this->getValue($string);
if ($key->count() === 0) {
return $value;
}
// #TODO Handle other objects and arrays
if (! $value instanceof Accessable) {
throw new AccessException('Could not get the value for the key "' . $key->raw . '".');
}
return $value->get($key);
}
|
php
|
public function get($key)
{
$key = $this->parseKey($key);
$string = $key->shift();
$key->next();
$value = $this->getValue($string);
if ($key->count() === 0) {
return $value;
}
// #TODO Handle other objects and arrays
if (! $value instanceof Accessable) {
throw new AccessException('Could not get the value for the key "' . $key->raw . '".');
}
return $value->get($key);
}
|
[
"public",
"function",
"get",
"(",
"$",
"key",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"parseKey",
"(",
"$",
"key",
")",
";",
"$",
"string",
"=",
"$",
"key",
"->",
"shift",
"(",
")",
";",
"$",
"key",
"->",
"next",
"(",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"getValue",
"(",
"$",
"string",
")",
";",
"if",
"(",
"$",
"key",
"->",
"count",
"(",
")",
"===",
"0",
")",
"{",
"return",
"$",
"value",
";",
"}",
"// #TODO Handle other objects and arrays",
"if",
"(",
"!",
"$",
"value",
"instanceof",
"Accessable",
")",
"{",
"throw",
"new",
"AccessException",
"(",
"'Could not get the value for the key \"'",
".",
"$",
"key",
"->",
"raw",
".",
"'\".'",
")",
";",
"}",
"return",
"$",
"value",
"->",
"get",
"(",
"$",
"key",
")",
";",
"}"
] |
Get a value by a key
@param mixed $key The key
@return mixed
|
[
"Get",
"a",
"value",
"by",
"a",
"key"
] |
2e4148f73966fdc815b6406a3779ef3bb046e1a4
|
https://github.com/Art4/json-api-client/blob/2e4148f73966fdc815b6406a3779ef3bb046e1a4/src/Helper/AccessableTrait.php#L107-L126
|
train
|
Art4/json-api-client
|
src/Helper/AccessableTrait.php
|
AccessableTrait.getValue
|
private function getValue($key)
{
if (array_key_exists($key, $this->data)) {
return $this->data[$key];
}
throw new AccessException('Could not get the value for the key "' . $key . '".');
}
|
php
|
private function getValue($key)
{
if (array_key_exists($key, $this->data)) {
return $this->data[$key];
}
throw new AccessException('Could not get the value for the key "' . $key . '".');
}
|
[
"private",
"function",
"getValue",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"data",
")",
")",
"{",
"return",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
";",
"}",
"throw",
"new",
"AccessException",
"(",
"'Could not get the value for the key \"'",
".",
"$",
"key",
".",
"'\".'",
")",
";",
"}"
] |
Get a value by the key
@param string $key The key of the value
@return mixed The value
|
[
"Get",
"a",
"value",
"by",
"the",
"key"
] |
2e4148f73966fdc815b6406a3779ef3bb046e1a4
|
https://github.com/Art4/json-api-client/blob/2e4148f73966fdc815b6406a3779ef3bb046e1a4/src/Helper/AccessableTrait.php#L135-L142
|
train
|
Art4/json-api-client
|
src/Helper/AccessableTrait.php
|
AccessableTrait.parseKey
|
private function parseKey($key)
{
if (is_object($key) and $key instanceof AccessKey) {
return $key;
}
$key = AccessKey::create($key);
return $key;
}
|
php
|
private function parseKey($key)
{
if (is_object($key) and $key instanceof AccessKey) {
return $key;
}
$key = AccessKey::create($key);
return $key;
}
|
[
"private",
"function",
"parseKey",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"key",
")",
"and",
"$",
"key",
"instanceof",
"AccessKey",
")",
"{",
"return",
"$",
"key",
";",
"}",
"$",
"key",
"=",
"AccessKey",
"::",
"create",
"(",
"$",
"key",
")",
";",
"return",
"$",
"key",
";",
"}"
] |
Parse a dot.notated.key to an object
@param string|AccessKey $key The key
@return AccessKey The parsed key
|
[
"Parse",
"a",
"dot",
".",
"notated",
".",
"key",
"to",
"an",
"object"
] |
2e4148f73966fdc815b6406a3779ef3bb046e1a4
|
https://github.com/Art4/json-api-client/blob/2e4148f73966fdc815b6406a3779ef3bb046e1a4/src/Helper/AccessableTrait.php#L151-L160
|
train
|
Art4/json-api-client
|
src/Helper/AccessKey.php
|
AccessKey.create
|
public static function create($key)
{
// Ignore arrays and objects
if (is_object($key) or is_array($key)) {
$key = '';
}
$key_string = strval($key);
$key = new self;
$key->raw = $key_string;
$keys = explode('.', $key_string);
foreach ($keys as $value) {
$key->push($value);
}
$key->rewind();
return $key;
}
|
php
|
public static function create($key)
{
// Ignore arrays and objects
if (is_object($key) or is_array($key)) {
$key = '';
}
$key_string = strval($key);
$key = new self;
$key->raw = $key_string;
$keys = explode('.', $key_string);
foreach ($keys as $value) {
$key->push($value);
}
$key->rewind();
return $key;
}
|
[
"public",
"static",
"function",
"create",
"(",
"$",
"key",
")",
"{",
"// Ignore arrays and objects",
"if",
"(",
"is_object",
"(",
"$",
"key",
")",
"or",
"is_array",
"(",
"$",
"key",
")",
")",
"{",
"$",
"key",
"=",
"''",
";",
"}",
"$",
"key_string",
"=",
"strval",
"(",
"$",
"key",
")",
";",
"$",
"key",
"=",
"new",
"self",
";",
"$",
"key",
"->",
"raw",
"=",
"$",
"key_string",
";",
"$",
"keys",
"=",
"explode",
"(",
"'.'",
",",
"$",
"key_string",
")",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"value",
")",
"{",
"$",
"key",
"->",
"push",
"(",
"$",
"value",
")",
";",
"}",
"$",
"key",
"->",
"rewind",
"(",
")",
";",
"return",
"$",
"key",
";",
"}"
] |
Transforms the Key to a string
@param mixed $key
@return string
|
[
"Transforms",
"the",
"Key",
"to",
"a",
"string"
] |
2e4148f73966fdc815b6406a3779ef3bb046e1a4
|
https://github.com/Art4/json-api-client/blob/2e4148f73966fdc815b6406a3779ef3bb046e1a4/src/Helper/AccessKey.php#L38-L59
|
train
|
notamedia/yii2-sentry
|
src/SentryTarget.php
|
SentryTarget.runExtraCallback
|
public function runExtraCallback($text, $data)
{
if (is_callable($this->extraCallback)) {
$data['extra'] = call_user_func($this->extraCallback, $text, $data['extra'] ? $data['extra'] : []);
}
return $data;
}
|
php
|
public function runExtraCallback($text, $data)
{
if (is_callable($this->extraCallback)) {
$data['extra'] = call_user_func($this->extraCallback, $text, $data['extra'] ? $data['extra'] : []);
}
return $data;
}
|
[
"public",
"function",
"runExtraCallback",
"(",
"$",
"text",
",",
"$",
"data",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"extraCallback",
")",
")",
"{",
"$",
"data",
"[",
"'extra'",
"]",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"extraCallback",
",",
"$",
"text",
",",
"$",
"data",
"[",
"'extra'",
"]",
"?",
"$",
"data",
"[",
"'extra'",
"]",
":",
"[",
"]",
")",
";",
"}",
"return",
"$",
"data",
";",
"}"
] |
Calls the extra callback if it exists
@param $text
@param $data
@return array
|
[
"Calls",
"the",
"extra",
"callback",
"if",
"it",
"exists"
] |
b096576dcd01e4063aa1643115b35e18cd35d538
|
https://github.com/notamedia/yii2-sentry/blob/b096576dcd01e4063aa1643115b35e18cd35d538/src/SentryTarget.php#L112-L119
|
train
|
notamedia/yii2-sentry
|
src/SentryTarget.php
|
SentryTarget.getLevelName
|
public static function getLevelName($level)
{
static $levels = [
Logger::LEVEL_ERROR => 'error',
Logger::LEVEL_WARNING => 'warning',
Logger::LEVEL_INFO => 'info',
Logger::LEVEL_TRACE => 'debug',
Logger::LEVEL_PROFILE_BEGIN => 'debug',
Logger::LEVEL_PROFILE_END => 'debug',
];
return isset($levels[$level]) ? $levels[$level] : 'error';
}
|
php
|
public static function getLevelName($level)
{
static $levels = [
Logger::LEVEL_ERROR => 'error',
Logger::LEVEL_WARNING => 'warning',
Logger::LEVEL_INFO => 'info',
Logger::LEVEL_TRACE => 'debug',
Logger::LEVEL_PROFILE_BEGIN => 'debug',
Logger::LEVEL_PROFILE_END => 'debug',
];
return isset($levels[$level]) ? $levels[$level] : 'error';
}
|
[
"public",
"static",
"function",
"getLevelName",
"(",
"$",
"level",
")",
"{",
"static",
"$",
"levels",
"=",
"[",
"Logger",
"::",
"LEVEL_ERROR",
"=>",
"'error'",
",",
"Logger",
"::",
"LEVEL_WARNING",
"=>",
"'warning'",
",",
"Logger",
"::",
"LEVEL_INFO",
"=>",
"'info'",
",",
"Logger",
"::",
"LEVEL_TRACE",
"=>",
"'debug'",
",",
"Logger",
"::",
"LEVEL_PROFILE_BEGIN",
"=>",
"'debug'",
",",
"Logger",
"::",
"LEVEL_PROFILE_END",
"=>",
"'debug'",
",",
"]",
";",
"return",
"isset",
"(",
"$",
"levels",
"[",
"$",
"level",
"]",
")",
"?",
"$",
"levels",
"[",
"$",
"level",
"]",
":",
"'error'",
";",
"}"
] |
Returns the text display of the specified level for the Sentry.
@param integer $level The message level, e.g. [[LEVEL_ERROR]], [[LEVEL_WARNING]].
@return string
|
[
"Returns",
"the",
"text",
"display",
"of",
"the",
"specified",
"level",
"for",
"the",
"Sentry",
"."
] |
b096576dcd01e4063aa1643115b35e18cd35d538
|
https://github.com/notamedia/yii2-sentry/blob/b096576dcd01e4063aa1643115b35e18cd35d538/src/SentryTarget.php#L127-L139
|
train
|
amphp/artax
|
lib/HttpTunneler.php
|
HttpTunneler.tunnel
|
public function tunnel(ClientSocket $socket, string $authority): Promise {
return call(function () use ($socket, $authority) {
$parser = new Parser(null);
$parser->enqueueResponseMethodMatch("CONNECT");
try {
yield $socket->write("CONNECT {$authority} HTTP/1.1\r\n\r\n");
} catch (StreamException $e) {
new SocketException(
'Proxy CONNECT failed: Socket went away while writing tunneling request',
0,
$e
);
}
try {
while (null !== $chunk = yield $socket->read()) {
if (!$response = $parser->parse($chunk)) {
continue;
}
if ($response["status"] === 200) {
// Tunnel connected! We're finished \o/ #WinningAtLife #DealWithIt
\stream_context_set_option($socket->getResource(), 'artax*', 'is_tunneled', true);
return $socket->getResource();
}
throw new HttpException(\sprintf(
'Proxy CONNECT failed: Unexpected response status received from proxy: %d',
$response["status"]
));
}
} catch (ParseException $e) {
throw new HttpException(
'Proxy CONNECT failed: Malformed HTTP response received from proxy while establishing tunnel',
0,
$e
);
} catch (StreamException $e) {
// fall through
}
throw new SocketException(
'Proxy CONNECT failed: Socket went away while awaiting tunneling response',
0,
$e ?? null
);
});
}
|
php
|
public function tunnel(ClientSocket $socket, string $authority): Promise {
return call(function () use ($socket, $authority) {
$parser = new Parser(null);
$parser->enqueueResponseMethodMatch("CONNECT");
try {
yield $socket->write("CONNECT {$authority} HTTP/1.1\r\n\r\n");
} catch (StreamException $e) {
new SocketException(
'Proxy CONNECT failed: Socket went away while writing tunneling request',
0,
$e
);
}
try {
while (null !== $chunk = yield $socket->read()) {
if (!$response = $parser->parse($chunk)) {
continue;
}
if ($response["status"] === 200) {
// Tunnel connected! We're finished \o/ #WinningAtLife #DealWithIt
\stream_context_set_option($socket->getResource(), 'artax*', 'is_tunneled', true);
return $socket->getResource();
}
throw new HttpException(\sprintf(
'Proxy CONNECT failed: Unexpected response status received from proxy: %d',
$response["status"]
));
}
} catch (ParseException $e) {
throw new HttpException(
'Proxy CONNECT failed: Malformed HTTP response received from proxy while establishing tunnel',
0,
$e
);
} catch (StreamException $e) {
// fall through
}
throw new SocketException(
'Proxy CONNECT failed: Socket went away while awaiting tunneling response',
0,
$e ?? null
);
});
}
|
[
"public",
"function",
"tunnel",
"(",
"ClientSocket",
"$",
"socket",
",",
"string",
"$",
"authority",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"socket",
",",
"$",
"authority",
")",
"{",
"$",
"parser",
"=",
"new",
"Parser",
"(",
"null",
")",
";",
"$",
"parser",
"->",
"enqueueResponseMethodMatch",
"(",
"\"CONNECT\"",
")",
";",
"try",
"{",
"yield",
"$",
"socket",
"->",
"write",
"(",
"\"CONNECT {$authority} HTTP/1.1\\r\\n\\r\\n\"",
")",
";",
"}",
"catch",
"(",
"StreamException",
"$",
"e",
")",
"{",
"new",
"SocketException",
"(",
"'Proxy CONNECT failed: Socket went away while writing tunneling request'",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"try",
"{",
"while",
"(",
"null",
"!==",
"$",
"chunk",
"=",
"yield",
"$",
"socket",
"->",
"read",
"(",
")",
")",
"{",
"if",
"(",
"!",
"$",
"response",
"=",
"$",
"parser",
"->",
"parse",
"(",
"$",
"chunk",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"response",
"[",
"\"status\"",
"]",
"===",
"200",
")",
"{",
"// Tunnel connected! We're finished \\o/ #WinningAtLife #DealWithIt",
"\\",
"stream_context_set_option",
"(",
"$",
"socket",
"->",
"getResource",
"(",
")",
",",
"'artax*'",
",",
"'is_tunneled'",
",",
"true",
")",
";",
"return",
"$",
"socket",
"->",
"getResource",
"(",
")",
";",
"}",
"throw",
"new",
"HttpException",
"(",
"\\",
"sprintf",
"(",
"'Proxy CONNECT failed: Unexpected response status received from proxy: %d'",
",",
"$",
"response",
"[",
"\"status\"",
"]",
")",
")",
";",
"}",
"}",
"catch",
"(",
"ParseException",
"$",
"e",
")",
"{",
"throw",
"new",
"HttpException",
"(",
"'Proxy CONNECT failed: Malformed HTTP response received from proxy while establishing tunnel'",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"StreamException",
"$",
"e",
")",
"{",
"// fall through",
"}",
"throw",
"new",
"SocketException",
"(",
"'Proxy CONNECT failed: Socket went away while awaiting tunneling response'",
",",
"0",
",",
"$",
"e",
"??",
"null",
")",
";",
"}",
")",
";",
"}"
] |
Establish an HTTP tunnel to the specified authority over this socket.
@param ClientSocket $socket
@param string $authority
@return Promise
|
[
"Establish",
"an",
"HTTP",
"tunnel",
"to",
"the",
"specified",
"authority",
"over",
"this",
"socket",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/HttpTunneler.php#L20-L68
|
train
|
amphp/artax
|
lib/Cookie/ArrayCookieJar.php
|
ArrayCookieJar.store
|
public function store(Cookie $cookie) {
$this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
}
|
php
|
public function store(Cookie $cookie) {
$this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
}
|
[
"public",
"function",
"store",
"(",
"Cookie",
"$",
"cookie",
")",
"{",
"$",
"this",
"->",
"cookies",
"[",
"$",
"cookie",
"->",
"getDomain",
"(",
")",
"]",
"[",
"$",
"cookie",
"->",
"getPath",
"(",
")",
"]",
"[",
"$",
"cookie",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"cookie",
";",
"}"
] |
Store a cookie.
@param Cookie $cookie
@return void
|
[
"Store",
"a",
"cookie",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/Cookie/ArrayCookieJar.php#L15-L17
|
train
|
amphp/artax
|
lib/Cookie/ArrayCookieJar.php
|
ArrayCookieJar.remove
|
public function remove(Cookie $cookie) {
unset($this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()]);
}
|
php
|
public function remove(Cookie $cookie) {
unset($this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()]);
}
|
[
"public",
"function",
"remove",
"(",
"Cookie",
"$",
"cookie",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"cookies",
"[",
"$",
"cookie",
"->",
"getDomain",
"(",
")",
"]",
"[",
"$",
"cookie",
"->",
"getPath",
"(",
")",
"]",
"[",
"$",
"cookie",
"->",
"getName",
"(",
")",
"]",
")",
";",
"}"
] |
Remove a specific cookie from the storage.
@param Cookie $cookie
|
[
"Remove",
"a",
"specific",
"cookie",
"from",
"the",
"storage",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/Cookie/ArrayCookieJar.php#L24-L26
|
train
|
amphp/artax
|
lib/Cookie/ArrayCookieJar.php
|
ArrayCookieJar.get
|
public function get(string $domain, string $path = '', string $name = null): array {
$this->clearExpiredCookies();
$path = $path === "" ? "/" : $path;
$domain = \strtolower($domain);
$matches = [];
foreach ($this->cookies as $cookieDomain => $domainCookies) {
if (!$this->matchesDomain($domain, $cookieDomain)) {
continue;
}
foreach ($domainCookies as $cookiePath => $pathCookies) {
if (!$this->matchesPath($path, $cookiePath)) {
continue;
}
foreach ($pathCookies as $cookieName => $cookie) {
if (!isset($name) || $name === $cookieName) {
$matches[] = $cookie;
}
}
}
}
return $matches;
}
|
php
|
public function get(string $domain, string $path = '', string $name = null): array {
$this->clearExpiredCookies();
$path = $path === "" ? "/" : $path;
$domain = \strtolower($domain);
$matches = [];
foreach ($this->cookies as $cookieDomain => $domainCookies) {
if (!$this->matchesDomain($domain, $cookieDomain)) {
continue;
}
foreach ($domainCookies as $cookiePath => $pathCookies) {
if (!$this->matchesPath($path, $cookiePath)) {
continue;
}
foreach ($pathCookies as $cookieName => $cookie) {
if (!isset($name) || $name === $cookieName) {
$matches[] = $cookie;
}
}
}
}
return $matches;
}
|
[
"public",
"function",
"get",
"(",
"string",
"$",
"domain",
",",
"string",
"$",
"path",
"=",
"''",
",",
"string",
"$",
"name",
"=",
"null",
")",
":",
"array",
"{",
"$",
"this",
"->",
"clearExpiredCookies",
"(",
")",
";",
"$",
"path",
"=",
"$",
"path",
"===",
"\"\"",
"?",
"\"/\"",
":",
"$",
"path",
";",
"$",
"domain",
"=",
"\\",
"strtolower",
"(",
"$",
"domain",
")",
";",
"$",
"matches",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"cookies",
"as",
"$",
"cookieDomain",
"=>",
"$",
"domainCookies",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"matchesDomain",
"(",
"$",
"domain",
",",
"$",
"cookieDomain",
")",
")",
"{",
"continue",
";",
"}",
"foreach",
"(",
"$",
"domainCookies",
"as",
"$",
"cookiePath",
"=>",
"$",
"pathCookies",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"matchesPath",
"(",
"$",
"path",
",",
"$",
"cookiePath",
")",
")",
"{",
"continue",
";",
"}",
"foreach",
"(",
"$",
"pathCookies",
"as",
"$",
"cookieName",
"=>",
"$",
"cookie",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"name",
")",
"||",
"$",
"name",
"===",
"$",
"cookieName",
")",
"{",
"$",
"matches",
"[",
"]",
"=",
"$",
"cookie",
";",
"}",
"}",
"}",
"}",
"return",
"$",
"matches",
";",
"}"
] |
Retrieve all cookies matching the specified constraints.
@param string $domain
@param string $path
@param string $name
@return array Returns an array (possibly empty) of all cookie matches.
|
[
"Retrieve",
"all",
"cookies",
"matching",
"the",
"specified",
"constraints",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/Cookie/ArrayCookieJar.php#L53-L80
|
train
|
amphp/artax
|
lib/TlsInfo.php
|
TlsInfo.fromMetaData
|
public static function fromMetaData(array $cryptoInfo, array $tlsContext): TlsInfo {
return new self(
$cryptoInfo["protocol"],
$cryptoInfo["cipher_name"],
$cryptoInfo["cipher_bits"],
$cryptoInfo["cipher_version"],
array_merge([$tlsContext["peer_certificate"]] ?: [], $tlsContext["peer_certificate_chain"] ?? [])
);
}
|
php
|
public static function fromMetaData(array $cryptoInfo, array $tlsContext): TlsInfo {
return new self(
$cryptoInfo["protocol"],
$cryptoInfo["cipher_name"],
$cryptoInfo["cipher_bits"],
$cryptoInfo["cipher_version"],
array_merge([$tlsContext["peer_certificate"]] ?: [], $tlsContext["peer_certificate_chain"] ?? [])
);
}
|
[
"public",
"static",
"function",
"fromMetaData",
"(",
"array",
"$",
"cryptoInfo",
",",
"array",
"$",
"tlsContext",
")",
":",
"TlsInfo",
"{",
"return",
"new",
"self",
"(",
"$",
"cryptoInfo",
"[",
"\"protocol\"",
"]",
",",
"$",
"cryptoInfo",
"[",
"\"cipher_name\"",
"]",
",",
"$",
"cryptoInfo",
"[",
"\"cipher_bits\"",
"]",
",",
"$",
"cryptoInfo",
"[",
"\"cipher_version\"",
"]",
",",
"array_merge",
"(",
"[",
"$",
"tlsContext",
"[",
"\"peer_certificate\"",
"]",
"]",
"?",
":",
"[",
"]",
",",
"$",
"tlsContext",
"[",
"\"peer_certificate_chain\"",
"]",
"??",
"[",
"]",
")",
")",
";",
"}"
] |
Constructs a new instance from PHP's internal info.
Always pass the info as obtained from PHP as this method might extract additional fields in the future.
@param array $cryptoInfo Crypto info obtained via `stream_get_meta_data($socket->getResource())["crypto"]`.
@param array $tlsContext Context obtained via `stream_context_get_options($socket->getResource())["ssl"])`.
@return TlsInfo
|
[
"Constructs",
"a",
"new",
"instance",
"from",
"PHP",
"s",
"internal",
"info",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/TlsInfo.php#L36-L44
|
train
|
amphp/artax
|
lib/FormBody.php
|
FormBody.addField
|
public function addField(string $name, string $value, string $contentType = 'text/plain') {
$this->fields[] = [$name, $value, $contentType, null];
$this->resetCache();
}
|
php
|
public function addField(string $name, string $value, string $contentType = 'text/plain') {
$this->fields[] = [$name, $value, $contentType, null];
$this->resetCache();
}
|
[
"public",
"function",
"addField",
"(",
"string",
"$",
"name",
",",
"string",
"$",
"value",
",",
"string",
"$",
"contentType",
"=",
"'text/plain'",
")",
"{",
"$",
"this",
"->",
"fields",
"[",
"]",
"=",
"[",
"$",
"name",
",",
"$",
"value",
",",
"$",
"contentType",
",",
"null",
"]",
";",
"$",
"this",
"->",
"resetCache",
"(",
")",
";",
"}"
] |
Add a data field to the form entity body.
@param string $name
@param string $value
@param string $contentType
|
[
"Add",
"a",
"data",
"field",
"to",
"the",
"form",
"entity",
"body",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/FormBody.php#L36-L39
|
train
|
amphp/artax
|
lib/FormBody.php
|
FormBody.addFields
|
public function addFields(array $data, string $contentType = 'text/plain') {
foreach ($data as $key => $value) {
$this->addField($key, $value, $contentType);
}
}
|
php
|
public function addFields(array $data, string $contentType = 'text/plain') {
foreach ($data as $key => $value) {
$this->addField($key, $value, $contentType);
}
}
|
[
"public",
"function",
"addFields",
"(",
"array",
"$",
"data",
",",
"string",
"$",
"contentType",
"=",
"'text/plain'",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"addField",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"contentType",
")",
";",
"}",
"}"
] |
Add each element of a associative array as a data field to the form entity body.
@param array $data
@param string $contentType
|
[
"Add",
"each",
"element",
"of",
"a",
"associative",
"array",
"as",
"a",
"data",
"field",
"to",
"the",
"form",
"entity",
"body",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/FormBody.php#L47-L51
|
train
|
amphp/artax
|
lib/FormBody.php
|
FormBody.addFile
|
public function addFile(string $name, string $filePath, string $contentType = 'application/octet-stream') {
$fileName = \basename($filePath);
$this->fields[] = [$name, new FileBody($filePath), $contentType, $fileName];
$this->isMultipart = true;
$this->resetCache();
}
|
php
|
public function addFile(string $name, string $filePath, string $contentType = 'application/octet-stream') {
$fileName = \basename($filePath);
$this->fields[] = [$name, new FileBody($filePath), $contentType, $fileName];
$this->isMultipart = true;
$this->resetCache();
}
|
[
"public",
"function",
"addFile",
"(",
"string",
"$",
"name",
",",
"string",
"$",
"filePath",
",",
"string",
"$",
"contentType",
"=",
"'application/octet-stream'",
")",
"{",
"$",
"fileName",
"=",
"\\",
"basename",
"(",
"$",
"filePath",
")",
";",
"$",
"this",
"->",
"fields",
"[",
"]",
"=",
"[",
"$",
"name",
",",
"new",
"FileBody",
"(",
"$",
"filePath",
")",
",",
"$",
"contentType",
",",
"$",
"fileName",
"]",
";",
"$",
"this",
"->",
"isMultipart",
"=",
"true",
";",
"$",
"this",
"->",
"resetCache",
"(",
")",
";",
"}"
] |
Add a file field to the form entity body.
@param string $name
@param string $filePath
@param string $contentType
|
[
"Add",
"a",
"file",
"field",
"to",
"the",
"form",
"entity",
"body",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/FormBody.php#L60-L65
|
train
|
amphp/artax
|
lib/FormBody.php
|
FormBody.addFiles
|
public function addFiles(array $data, string $contentType = 'application/octet-stream') {
foreach ($data as $key => $value) {
$this->addFile($key, $value, $contentType);
}
}
|
php
|
public function addFiles(array $data, string $contentType = 'application/octet-stream') {
foreach ($data as $key => $value) {
$this->addFile($key, $value, $contentType);
}
}
|
[
"public",
"function",
"addFiles",
"(",
"array",
"$",
"data",
",",
"string",
"$",
"contentType",
"=",
"'application/octet-stream'",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"addFile",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"contentType",
")",
";",
"}",
"}"
] |
Add each element of a associative array as a file field to the form entity body.
@param array $data
@param string $contentType
|
[
"Add",
"each",
"element",
"of",
"a",
"associative",
"array",
"as",
"a",
"file",
"field",
"to",
"the",
"form",
"entity",
"body",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/FormBody.php#L73-L77
|
train
|
amphp/artax
|
lib/DefaultClient.php
|
DefaultClient.assignRedirectRefererHeader
|
private function assignRedirectRefererHeader(Request $request, string $refererUri, string $newUri): Request {
$refererIsEncrypted = (\stripos($refererUri, 'https') === 0);
$destinationIsEncrypted = (\stripos($newUri, 'https') === 0);
if (!$refererIsEncrypted || $destinationIsEncrypted) {
return $request->withHeader('Referer', $refererUri);
}
return $request->withoutHeader('Referer');
}
|
php
|
private function assignRedirectRefererHeader(Request $request, string $refererUri, string $newUri): Request {
$refererIsEncrypted = (\stripos($refererUri, 'https') === 0);
$destinationIsEncrypted = (\stripos($newUri, 'https') === 0);
if (!$refererIsEncrypted || $destinationIsEncrypted) {
return $request->withHeader('Referer', $refererUri);
}
return $request->withoutHeader('Referer');
}
|
[
"private",
"function",
"assignRedirectRefererHeader",
"(",
"Request",
"$",
"request",
",",
"string",
"$",
"refererUri",
",",
"string",
"$",
"newUri",
")",
":",
"Request",
"{",
"$",
"refererIsEncrypted",
"=",
"(",
"\\",
"stripos",
"(",
"$",
"refererUri",
",",
"'https'",
")",
"===",
"0",
")",
";",
"$",
"destinationIsEncrypted",
"=",
"(",
"\\",
"stripos",
"(",
"$",
"newUri",
",",
"'https'",
")",
"===",
"0",
")",
";",
"if",
"(",
"!",
"$",
"refererIsEncrypted",
"||",
"$",
"destinationIsEncrypted",
")",
"{",
"return",
"$",
"request",
"->",
"withHeader",
"(",
"'Referer'",
",",
"$",
"refererUri",
")",
";",
"}",
"return",
"$",
"request",
"->",
"withoutHeader",
"(",
"'Referer'",
")",
";",
"}"
] |
Clients must not add a Referer header when leaving an unencrypted resource and redirecting to an encrypted
resource.
@param Request $request
@param string $refererUri
@param string $newUri
@return Request
@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3
|
[
"Clients",
"must",
"not",
"add",
"a",
"Referer",
"header",
"when",
"leaving",
"an",
"unencrypted",
"resource",
"and",
"redirecting",
"to",
"an",
"encrypted",
"resource",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/DefaultClient.php#L950-L959
|
train
|
amphp/artax
|
lib/DefaultClient.php
|
DefaultClient.setOption
|
public function setOption(string $option, $value) {
$this->validateOption($option, $value);
$this->options[$option] = $value;
}
|
php
|
public function setOption(string $option, $value) {
$this->validateOption($option, $value);
$this->options[$option] = $value;
}
|
[
"public",
"function",
"setOption",
"(",
"string",
"$",
"option",
",",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"validateOption",
"(",
"$",
"option",
",",
"$",
"value",
")",
";",
"$",
"this",
"->",
"options",
"[",
"$",
"option",
"]",
"=",
"$",
"value",
";",
"}"
] |
Set an option.
@param string $option A Client option constant
@param mixed $value The option value to assign
@throws \Error On unknown option key or invalid value.
|
[
"Set",
"an",
"option",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/DefaultClient.php#L1023-L1026
|
train
|
amphp/artax
|
lib/Request.php
|
Request.withProtocolVersions
|
public function withProtocolVersions(array $versions): self {
$versions = \array_unique($versions);
if (empty($versions)) {
throw new \Error("Empty array of protocol versions provided, must not be empty.");
}
foreach ($versions as $version) {
if (!\in_array($version, ["1.0", "1.1", "2.0"], true)) {
throw new \Error(
"Invalid HTTP protocol version: " . $version
);
}
}
if ($this->protocolVersions === $versions) {
return $this;
}
$clone = clone $this;
$clone->protocolVersions = $versions;
return $clone;
}
|
php
|
public function withProtocolVersions(array $versions): self {
$versions = \array_unique($versions);
if (empty($versions)) {
throw new \Error("Empty array of protocol versions provided, must not be empty.");
}
foreach ($versions as $version) {
if (!\in_array($version, ["1.0", "1.1", "2.0"], true)) {
throw new \Error(
"Invalid HTTP protocol version: " . $version
);
}
}
if ($this->protocolVersions === $versions) {
return $this;
}
$clone = clone $this;
$clone->protocolVersions = $versions;
return $clone;
}
|
[
"public",
"function",
"withProtocolVersions",
"(",
"array",
"$",
"versions",
")",
":",
"self",
"{",
"$",
"versions",
"=",
"\\",
"array_unique",
"(",
"$",
"versions",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"versions",
")",
")",
"{",
"throw",
"new",
"\\",
"Error",
"(",
"\"Empty array of protocol versions provided, must not be empty.\"",
")",
";",
"}",
"foreach",
"(",
"$",
"versions",
"as",
"$",
"version",
")",
"{",
"if",
"(",
"!",
"\\",
"in_array",
"(",
"$",
"version",
",",
"[",
"\"1.0\"",
",",
"\"1.1\"",
",",
"\"2.0\"",
"]",
",",
"true",
")",
")",
"{",
"throw",
"new",
"\\",
"Error",
"(",
"\"Invalid HTTP protocol version: \"",
".",
"$",
"version",
")",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"protocolVersions",
"===",
"$",
"versions",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"clone",
"=",
"clone",
"$",
"this",
";",
"$",
"clone",
"->",
"protocolVersions",
"=",
"$",
"versions",
";",
"return",
"$",
"clone",
";",
"}"
] |
Assign the requests's acceptable HTTP protocol versions.
The HTTP client might choose any of these.
@param string[] $versions
@return Request
|
[
"Assign",
"the",
"requests",
"s",
"acceptable",
"HTTP",
"protocol",
"versions",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/Request.php#L51-L74
|
train
|
amphp/artax
|
lib/Request.php
|
Request.withMethod
|
public function withMethod(string $method): self {
if ($this->method === $method) {
return $this;
}
$clone = clone $this;
$clone->method = $method;
return $clone;
}
|
php
|
public function withMethod(string $method): self {
if ($this->method === $method) {
return $this;
}
$clone = clone $this;
$clone->method = $method;
return $clone;
}
|
[
"public",
"function",
"withMethod",
"(",
"string",
"$",
"method",
")",
":",
"self",
"{",
"if",
"(",
"$",
"this",
"->",
"method",
"===",
"$",
"method",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"clone",
"=",
"clone",
"$",
"this",
";",
"$",
"clone",
"->",
"method",
"=",
"$",
"method",
";",
"return",
"$",
"clone",
";",
"}"
] |
Specify the request's HTTP method verb.
@param string $method
@return Request
|
[
"Specify",
"the",
"request",
"s",
"HTTP",
"method",
"verb",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/Request.php#L92-L101
|
train
|
amphp/artax
|
lib/Request.php
|
Request.withHeader
|
public function withHeader(string $field, string $value): self {
$field = \trim($field);
$lower = \strtolower($field);
$clone = clone $this;
$clone->headers[$lower] = [\trim($value)];
$clone->headerCaseMap[$lower] = $field;
return $clone;
}
|
php
|
public function withHeader(string $field, string $value): self {
$field = \trim($field);
$lower = \strtolower($field);
$clone = clone $this;
$clone->headers[$lower] = [\trim($value)];
$clone->headerCaseMap[$lower] = $field;
return $clone;
}
|
[
"public",
"function",
"withHeader",
"(",
"string",
"$",
"field",
",",
"string",
"$",
"value",
")",
":",
"self",
"{",
"$",
"field",
"=",
"\\",
"trim",
"(",
"$",
"field",
")",
";",
"$",
"lower",
"=",
"\\",
"strtolower",
"(",
"$",
"field",
")",
";",
"$",
"clone",
"=",
"clone",
"$",
"this",
";",
"$",
"clone",
"->",
"headers",
"[",
"$",
"lower",
"]",
"=",
"[",
"\\",
"trim",
"(",
"$",
"value",
")",
"]",
";",
"$",
"clone",
"->",
"headerCaseMap",
"[",
"$",
"lower",
"]",
"=",
"$",
"field",
";",
"return",
"$",
"clone",
";",
"}"
] |
Assign a value for the specified header field by replacing any existing values for that field.
@param string $field Header name.
@param string $value Header value.
@return Request
|
[
"Assign",
"a",
"value",
"for",
"the",
"specified",
"header",
"field",
"by",
"replacing",
"any",
"existing",
"values",
"for",
"that",
"field",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/Request.php#L174-L184
|
train
|
amphp/artax
|
lib/Request.php
|
Request.getHeaders
|
public function getHeaders(bool $originalCase = false): array {
if (!$originalCase) {
return $this->headers;
}
$headers = [];
foreach ($this->headers as $header => $values) {
$headers[$this->headerCaseMap[$header]] = $values;
}
return $headers;
}
|
php
|
public function getHeaders(bool $originalCase = false): array {
if (!$originalCase) {
return $this->headers;
}
$headers = [];
foreach ($this->headers as $header => $values) {
$headers[$this->headerCaseMap[$header]] = $values;
}
return $headers;
}
|
[
"public",
"function",
"getHeaders",
"(",
"bool",
"$",
"originalCase",
"=",
"false",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"originalCase",
")",
"{",
"return",
"$",
"this",
"->",
"headers",
";",
"}",
"$",
"headers",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"headers",
"as",
"$",
"header",
"=>",
"$",
"values",
")",
"{",
"$",
"headers",
"[",
"$",
"this",
"->",
"headerCaseMap",
"[",
"$",
"header",
"]",
"]",
"=",
"$",
"values",
";",
"}",
"return",
"$",
"headers",
";",
"}"
] |
Retrieve an associative array of headers matching field names to an array of field values.
@param bool $originalCase If true, headers are returned in the case of the last set header with that name.
@return array
|
[
"Retrieve",
"an",
"associative",
"array",
"of",
"headers",
"matching",
"field",
"names",
"to",
"an",
"array",
"of",
"field",
"values",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/Request.php#L259-L271
|
train
|
amphp/artax
|
lib/Request.php
|
Request.withoutHeader
|
public function withoutHeader(string $field): self {
$lower = \strtolower($field);
$clone = clone $this;
unset(
$clone->headerCaseMap[$lower],
$clone->headers[$lower]
);
return $clone;
}
|
php
|
public function withoutHeader(string $field): self {
$lower = \strtolower($field);
$clone = clone $this;
unset(
$clone->headerCaseMap[$lower],
$clone->headers[$lower]
);
return $clone;
}
|
[
"public",
"function",
"withoutHeader",
"(",
"string",
"$",
"field",
")",
":",
"self",
"{",
"$",
"lower",
"=",
"\\",
"strtolower",
"(",
"$",
"field",
")",
";",
"$",
"clone",
"=",
"clone",
"$",
"this",
";",
"unset",
"(",
"$",
"clone",
"->",
"headerCaseMap",
"[",
"$",
"lower",
"]",
",",
"$",
"clone",
"->",
"headers",
"[",
"$",
"lower",
"]",
")",
";",
"return",
"$",
"clone",
";",
"}"
] |
Remove the specified header field from the message.
@param string $field Header name.
@return Request
|
[
"Remove",
"the",
"specified",
"header",
"field",
"from",
"the",
"message",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/Request.php#L280-L291
|
train
|
amphp/artax
|
lib/Request.php
|
Request.withBody
|
public function withBody($body): self {
$clone = clone $this;
if ($body === null) {
$clone->body = new StringBody("");
} elseif (\is_scalar($body)) {
$clone->body = new StringBody((string) $body);
} elseif ($body instanceof RequestBody) {
$clone->body = $body;
} else {
throw new \TypeError("Invalid body type: " . gettype($body));
}
return $clone;
}
|
php
|
public function withBody($body): self {
$clone = clone $this;
if ($body === null) {
$clone->body = new StringBody("");
} elseif (\is_scalar($body)) {
$clone->body = new StringBody((string) $body);
} elseif ($body instanceof RequestBody) {
$clone->body = $body;
} else {
throw new \TypeError("Invalid body type: " . gettype($body));
}
return $clone;
}
|
[
"public",
"function",
"withBody",
"(",
"$",
"body",
")",
":",
"self",
"{",
"$",
"clone",
"=",
"clone",
"$",
"this",
";",
"if",
"(",
"$",
"body",
"===",
"null",
")",
"{",
"$",
"clone",
"->",
"body",
"=",
"new",
"StringBody",
"(",
"\"\"",
")",
";",
"}",
"elseif",
"(",
"\\",
"is_scalar",
"(",
"$",
"body",
")",
")",
"{",
"$",
"clone",
"->",
"body",
"=",
"new",
"StringBody",
"(",
"(",
"string",
")",
"$",
"body",
")",
";",
"}",
"elseif",
"(",
"$",
"body",
"instanceof",
"RequestBody",
")",
"{",
"$",
"clone",
"->",
"body",
"=",
"$",
"body",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"TypeError",
"(",
"\"Invalid body type: \"",
".",
"gettype",
"(",
"$",
"body",
")",
")",
";",
"}",
"return",
"$",
"clone",
";",
"}"
] |
Assign the message entity body.
@param mixed $body
@return Request
|
[
"Assign",
"the",
"message",
"entity",
"body",
"."
] |
3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f
|
https://github.com/amphp/artax/blob/3b3c7b58cfccf2af53ac437a5140c970bf4e5d5f/lib/Request.php#L309-L323
|
train
|
seboettg/citeproc-php
|
src/Seboettg/CiteProc/Util/CiteProcHelper.php
|
CiteProcHelper.applyAdditionMarkupFunction
|
public static function applyAdditionMarkupFunction($dataItem, $valueToRender, $renderedText)
{
$markupExtension = CiteProc::getContext()->getMarkupExtension();
if (array_key_exists($valueToRender, $markupExtension)) {
$function = $markupExtension[$valueToRender];
if (is_callable($function)) {
$renderedText = $function($dataItem, $renderedText);
}
} else if (array_key_exists($mode = CiteProc::getContext()->getMode(), $markupExtension)) {
if (array_key_exists($valueToRender, $markupExtension[$mode])) {
$function = CiteProc::getContext()->getMarkupExtension()[$mode][$valueToRender];
if (is_callable($function)) {
$renderedText = $function($dataItem, $renderedText);
}
}
}
return $renderedText;
}
|
php
|
public static function applyAdditionMarkupFunction($dataItem, $valueToRender, $renderedText)
{
$markupExtension = CiteProc::getContext()->getMarkupExtension();
if (array_key_exists($valueToRender, $markupExtension)) {
$function = $markupExtension[$valueToRender];
if (is_callable($function)) {
$renderedText = $function($dataItem, $renderedText);
}
} else if (array_key_exists($mode = CiteProc::getContext()->getMode(), $markupExtension)) {
if (array_key_exists($valueToRender, $markupExtension[$mode])) {
$function = CiteProc::getContext()->getMarkupExtension()[$mode][$valueToRender];
if (is_callable($function)) {
$renderedText = $function($dataItem, $renderedText);
}
}
}
return $renderedText;
}
|
[
"public",
"static",
"function",
"applyAdditionMarkupFunction",
"(",
"$",
"dataItem",
",",
"$",
"valueToRender",
",",
"$",
"renderedText",
")",
"{",
"$",
"markupExtension",
"=",
"CiteProc",
"::",
"getContext",
"(",
")",
"->",
"getMarkupExtension",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"valueToRender",
",",
"$",
"markupExtension",
")",
")",
"{",
"$",
"function",
"=",
"$",
"markupExtension",
"[",
"$",
"valueToRender",
"]",
";",
"if",
"(",
"is_callable",
"(",
"$",
"function",
")",
")",
"{",
"$",
"renderedText",
"=",
"$",
"function",
"(",
"$",
"dataItem",
",",
"$",
"renderedText",
")",
";",
"}",
"}",
"else",
"if",
"(",
"array_key_exists",
"(",
"$",
"mode",
"=",
"CiteProc",
"::",
"getContext",
"(",
")",
"->",
"getMode",
"(",
")",
",",
"$",
"markupExtension",
")",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"valueToRender",
",",
"$",
"markupExtension",
"[",
"$",
"mode",
"]",
")",
")",
"{",
"$",
"function",
"=",
"CiteProc",
"::",
"getContext",
"(",
")",
"->",
"getMarkupExtension",
"(",
")",
"[",
"$",
"mode",
"]",
"[",
"$",
"valueToRender",
"]",
";",
"if",
"(",
"is_callable",
"(",
"$",
"function",
")",
")",
"{",
"$",
"renderedText",
"=",
"$",
"function",
"(",
"$",
"dataItem",
",",
"$",
"renderedText",
")",
";",
"}",
"}",
"}",
"return",
"$",
"renderedText",
";",
"}"
] |
Applies additional functions for markup extension
@param \stdClass $dataItem the actual item
@param string $valueToRender value the has to apply on
@param string $renderedText actual by citeproc rendered text
@return string
|
[
"Applies",
"additional",
"functions",
"for",
"markup",
"extension"
] |
795c6a4cfb070137df1f7bb7832c4cff2bf40a38
|
https://github.com/seboettg/citeproc-php/blob/795c6a4cfb070137df1f7bb7832c4cff2bf40a38/src/Seboettg/CiteProc/Util/CiteProcHelper.php#L25-L42
|
train
|
seboettg/citeproc-php
|
src/Seboettg/CiteProc/StyleSheet.php
|
StyleSheet.loadLocales
|
public static function loadLocales($langKey)
{
$data = null;
$localesPath = self::vendorPath() . "/citation-style-language/locales/";
$localeFile = $localesPath . "locales-" . $langKey . '.xml';
if (file_exists($localeFile)) {
$data = file_get_contents($localeFile);
} else {
$metadata = self::loadLocalesMetadata();
if (!empty($metadata->{'primary-dialects'}->{$langKey})) {
$data = file_get_contents($localesPath . "locales-" . $metadata->{'primary-dialects'}->{$langKey} . '.xml');
}
}
return $data;
}
|
php
|
public static function loadLocales($langKey)
{
$data = null;
$localesPath = self::vendorPath() . "/citation-style-language/locales/";
$localeFile = $localesPath . "locales-" . $langKey . '.xml';
if (file_exists($localeFile)) {
$data = file_get_contents($localeFile);
} else {
$metadata = self::loadLocalesMetadata();
if (!empty($metadata->{'primary-dialects'}->{$langKey})) {
$data = file_get_contents($localesPath . "locales-" . $metadata->{'primary-dialects'}->{$langKey} . '.xml');
}
}
return $data;
}
|
[
"public",
"static",
"function",
"loadLocales",
"(",
"$",
"langKey",
")",
"{",
"$",
"data",
"=",
"null",
";",
"$",
"localesPath",
"=",
"self",
"::",
"vendorPath",
"(",
")",
".",
"\"/citation-style-language/locales/\"",
";",
"$",
"localeFile",
"=",
"$",
"localesPath",
".",
"\"locales-\"",
".",
"$",
"langKey",
".",
"'.xml'",
";",
"if",
"(",
"file_exists",
"(",
"$",
"localeFile",
")",
")",
"{",
"$",
"data",
"=",
"file_get_contents",
"(",
"$",
"localeFile",
")",
";",
"}",
"else",
"{",
"$",
"metadata",
"=",
"self",
"::",
"loadLocalesMetadata",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"metadata",
"->",
"{",
"'primary-dialects'",
"}",
"->",
"{",
"$",
"langKey",
"}",
")",
")",
"{",
"$",
"data",
"=",
"file_get_contents",
"(",
"$",
"localesPath",
".",
"\"locales-\"",
".",
"$",
"metadata",
"->",
"{",
"'primary-dialects'",
"}",
"->",
"{",
"$",
"langKey",
"}",
".",
"'.xml'",
")",
";",
"}",
"}",
"return",
"$",
"data",
";",
"}"
] |
Loads xml formatted locales of given language key
@param string $langKey e.g. "en-US", or "de-CH"
@return string
@throws CiteProcException
|
[
"Loads",
"xml",
"formatted",
"locales",
"of",
"given",
"language",
"key"
] |
795c6a4cfb070137df1f7bb7832c4cff2bf40a38
|
https://github.com/seboettg/citeproc-php/blob/795c6a4cfb070137df1f7bb7832c4cff2bf40a38/src/Seboettg/CiteProc/StyleSheet.php#L48-L63
|
train
|
seboettg/citeproc-php
|
src/Seboettg/CiteProc/Style/Sort/Sort.php
|
Sort.sort
|
public function sort(&$data)
{
if (is_array($data)) {
$data = new DataList($data);
}
$dataToSort = $data->toArray();
try {
$data->replace($this->performSort(0, $dataToSort));
} catch (CiteProcException $e) {
//nothing to do, because $data is passed by referenced
}
}
|
php
|
public function sort(&$data)
{
if (is_array($data)) {
$data = new DataList($data);
}
$dataToSort = $data->toArray();
try {
$data->replace($this->performSort(0, $dataToSort));
} catch (CiteProcException $e) {
//nothing to do, because $data is passed by referenced
}
}
|
[
"public",
"function",
"sort",
"(",
"&",
"$",
"data",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"$",
"data",
"=",
"new",
"DataList",
"(",
"$",
"data",
")",
";",
"}",
"$",
"dataToSort",
"=",
"$",
"data",
"->",
"toArray",
"(",
")",
";",
"try",
"{",
"$",
"data",
"->",
"replace",
"(",
"$",
"this",
"->",
"performSort",
"(",
"0",
",",
"$",
"dataToSort",
")",
")",
";",
"}",
"catch",
"(",
"CiteProcException",
"$",
"e",
")",
"{",
"//nothing to do, because $data is passed by referenced",
"}",
"}"
] |
Function in order to sort a set of csl items by one or multiple sort keys.
Sort keys are evaluated in sequence. A primary sort is performed on all items using the first sort key.
A secondary sort, using the second sort key, is applied to items sharing the first sort key value. A tertiary
sort, using the third sort key, is applied to items sharing the first and second sort key values. Sorting
continues until either the order of all items is fixed, or until the sort keys are exhausted. Items with an
empty sort key value are placed at the end of the sort, both for ascending and descending sorts.
@param DataList|array $data reference
|
[
"Function",
"in",
"order",
"to",
"sort",
"a",
"set",
"of",
"csl",
"items",
"by",
"one",
"or",
"multiple",
"sort",
"keys",
".",
"Sort",
"keys",
"are",
"evaluated",
"in",
"sequence",
".",
"A",
"primary",
"sort",
"is",
"performed",
"on",
"all",
"items",
"using",
"the",
"first",
"sort",
"key",
".",
"A",
"secondary",
"sort",
"using",
"the",
"second",
"sort",
"key",
"is",
"applied",
"to",
"items",
"sharing",
"the",
"first",
"sort",
"key",
"value",
".",
"A",
"tertiary",
"sort",
"using",
"the",
"third",
"sort",
"key",
"is",
"applied",
"to",
"items",
"sharing",
"the",
"first",
"and",
"second",
"sort",
"key",
"values",
".",
"Sorting",
"continues",
"until",
"either",
"the",
"order",
"of",
"all",
"items",
"is",
"fixed",
"or",
"until",
"the",
"sort",
"keys",
"are",
"exhausted",
".",
"Items",
"with",
"an",
"empty",
"sort",
"key",
"value",
"are",
"placed",
"at",
"the",
"end",
"of",
"the",
"sort",
"both",
"for",
"ascending",
"and",
"descending",
"sorts",
"."
] |
795c6a4cfb070137df1f7bb7832c4cff2bf40a38
|
https://github.com/seboettg/citeproc-php/blob/795c6a4cfb070137df1f7bb7832c4cff2bf40a38/src/Seboettg/CiteProc/Style/Sort/Sort.php#L67-L78
|
train
|
seboettg/citeproc-php
|
src/Seboettg/CiteProc/Util/DateHelper.php
|
DateHelper.getSortKeyDate
|
public static function getSortKeyDate($dataItem, $key)
{
$variable = $variable = $key->getVariable();
$part = $key->getRangePart();
if (count($dataItem->{$variable}->{'date-parts'}) > 1) {
//Date range
$datePart = $dataItem->{$variable}->{'date-parts'}[$part];
$sortKey = self::serializeDate($datePart);
if ($key->getSort() === "descending" && $part === 0 ||
$key->getSort() === "ascending" && $part === 1) {
$sortKey .= "-";
}
} else {
if (!isset($dataItem->{$variable}->{'date-parts'})) {
$dateParts = self::parseDateParts($dataItem->{$variable});
} else {
$dateParts = $dataItem->{$variable}->{'date-parts'}[0];
}
$sortKey = self::serializeDate($dateParts);
}
return $sortKey;
}
|
php
|
public static function getSortKeyDate($dataItem, $key)
{
$variable = $variable = $key->getVariable();
$part = $key->getRangePart();
if (count($dataItem->{$variable}->{'date-parts'}) > 1) {
//Date range
$datePart = $dataItem->{$variable}->{'date-parts'}[$part];
$sortKey = self::serializeDate($datePart);
if ($key->getSort() === "descending" && $part === 0 ||
$key->getSort() === "ascending" && $part === 1) {
$sortKey .= "-";
}
} else {
if (!isset($dataItem->{$variable}->{'date-parts'})) {
$dateParts = self::parseDateParts($dataItem->{$variable});
} else {
$dateParts = $dataItem->{$variable}->{'date-parts'}[0];
}
$sortKey = self::serializeDate($dateParts);
}
return $sortKey;
}
|
[
"public",
"static",
"function",
"getSortKeyDate",
"(",
"$",
"dataItem",
",",
"$",
"key",
")",
"{",
"$",
"variable",
"=",
"$",
"variable",
"=",
"$",
"key",
"->",
"getVariable",
"(",
")",
";",
"$",
"part",
"=",
"$",
"key",
"->",
"getRangePart",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"dataItem",
"->",
"{",
"$",
"variable",
"}",
"->",
"{",
"'date-parts'",
"}",
")",
">",
"1",
")",
"{",
"//Date range",
"$",
"datePart",
"=",
"$",
"dataItem",
"->",
"{",
"$",
"variable",
"}",
"->",
"{",
"'date-parts'",
"}",
"[",
"$",
"part",
"]",
";",
"$",
"sortKey",
"=",
"self",
"::",
"serializeDate",
"(",
"$",
"datePart",
")",
";",
"if",
"(",
"$",
"key",
"->",
"getSort",
"(",
")",
"===",
"\"descending\"",
"&&",
"$",
"part",
"===",
"0",
"||",
"$",
"key",
"->",
"getSort",
"(",
")",
"===",
"\"ascending\"",
"&&",
"$",
"part",
"===",
"1",
")",
"{",
"$",
"sortKey",
".=",
"\"-\"",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"dataItem",
"->",
"{",
"$",
"variable",
"}",
"->",
"{",
"'date-parts'",
"}",
")",
")",
"{",
"$",
"dateParts",
"=",
"self",
"::",
"parseDateParts",
"(",
"$",
"dataItem",
"->",
"{",
"$",
"variable",
"}",
")",
";",
"}",
"else",
"{",
"$",
"dateParts",
"=",
"$",
"dataItem",
"->",
"{",
"$",
"variable",
"}",
"->",
"{",
"'date-parts'",
"}",
"[",
"0",
"]",
";",
"}",
"$",
"sortKey",
"=",
"self",
"::",
"serializeDate",
"(",
"$",
"dateParts",
")",
";",
"}",
"return",
"$",
"sortKey",
";",
"}"
] |
creates sort key for variables containing date and date ranges
@param array $dataItem
@param Key $key
@return string
@throws CiteProcException
|
[
"creates",
"sort",
"key",
"for",
"variables",
"containing",
"date",
"and",
"date",
"ranges"
] |
795c6a4cfb070137df1f7bb7832c4cff2bf40a38
|
https://github.com/seboettg/citeproc-php/blob/795c6a4cfb070137df1f7bb7832c4cff2bf40a38/src/Seboettg/CiteProc/Util/DateHelper.php#L73-L95
|
train
|
seboettg/citeproc-php
|
src/Seboettg/CiteProc/CiteProc.php
|
CiteProc.init
|
public function init($citationAsArray = false)
{
self::$context = new Context($this);
self::$context->setLocale(new Locale\Locale($this->lang)); //init locale
self::$context->setCitationsAsArray($citationAsArray);
// set markup extensions
self::$context->setMarkupExtension($this->markupExtension);
$this->styleSheetXml = new SimpleXMLElement($this->styleSheet);
$this->parse($this->styleSheetXml);
}
|
php
|
public function init($citationAsArray = false)
{
self::$context = new Context($this);
self::$context->setLocale(new Locale\Locale($this->lang)); //init locale
self::$context->setCitationsAsArray($citationAsArray);
// set markup extensions
self::$context->setMarkupExtension($this->markupExtension);
$this->styleSheetXml = new SimpleXMLElement($this->styleSheet);
$this->parse($this->styleSheetXml);
}
|
[
"public",
"function",
"init",
"(",
"$",
"citationAsArray",
"=",
"false",
")",
"{",
"self",
"::",
"$",
"context",
"=",
"new",
"Context",
"(",
"$",
"this",
")",
";",
"self",
"::",
"$",
"context",
"->",
"setLocale",
"(",
"new",
"Locale",
"\\",
"Locale",
"(",
"$",
"this",
"->",
"lang",
")",
")",
";",
"//init locale",
"self",
"::",
"$",
"context",
"->",
"setCitationsAsArray",
"(",
"$",
"citationAsArray",
")",
";",
"// set markup extensions",
"self",
"::",
"$",
"context",
"->",
"setMarkupExtension",
"(",
"$",
"this",
"->",
"markupExtension",
")",
";",
"$",
"this",
"->",
"styleSheetXml",
"=",
"new",
"SimpleXMLElement",
"(",
"$",
"this",
"->",
"styleSheet",
")",
";",
"$",
"this",
"->",
"parse",
"(",
"$",
"this",
"->",
"styleSheetXml",
")",
";",
"}"
] |
initializes CiteProc and start parsing XML stylesheet
@param bool $citationAsArray
@throws CiteProcException
|
[
"initializes",
"CiteProc",
"and",
"start",
"parsing",
"XML",
"stylesheet"
] |
795c6a4cfb070137df1f7bb7832c4cff2bf40a38
|
https://github.com/seboettg/citeproc-php/blob/795c6a4cfb070137df1f7bb7832c4cff2bf40a38/src/Seboettg/CiteProc/CiteProc.php#L206-L215
|
train
|
seboettg/citeproc-php
|
src/Seboettg/CiteProc/Styles/Css/CssStyle.php
|
CssStyle.init
|
private function init()
{
$lineSpacing = $this->bibliographyOptions->getLineSpacing();
$entrySpacing = $this->bibliographyOptions->getEntrySpacing();
$hangingIndent = $this->bibliographyOptions->getHangingIndent();
if ($lineSpacing || $entrySpacing || $hangingIndent) {
$rule = $this->cssRules->getRule(".csl-entry");
if (!empty($lineSpacing)) {
$rule->addDirective("line-height", intval($lineSpacing) . "em");
}
if (!empty($entrySpacing)) {
$rule->addDirective("margin-bottom", intval($entrySpacing) . "em");
}
if (!empty($hangingIndent)) {
$rule->addDirective("padding-left", "2em");
$rule->addDirective("text-indent", "-2em");
}
}
if ("flush" === $this->bibliographyOptions->getSecondFieldAlign()) {
$rule = $this->cssRules->getRule(".csl-left-margin");
$rule->addDirective("display", "block");
$rule->addDirective("float", "left");
$rule = $this->cssRules->getRule(".csl-right-inline");
$rule->addDirective("margin-left", "35px");
}
}
|
php
|
private function init()
{
$lineSpacing = $this->bibliographyOptions->getLineSpacing();
$entrySpacing = $this->bibliographyOptions->getEntrySpacing();
$hangingIndent = $this->bibliographyOptions->getHangingIndent();
if ($lineSpacing || $entrySpacing || $hangingIndent) {
$rule = $this->cssRules->getRule(".csl-entry");
if (!empty($lineSpacing)) {
$rule->addDirective("line-height", intval($lineSpacing) . "em");
}
if (!empty($entrySpacing)) {
$rule->addDirective("margin-bottom", intval($entrySpacing) . "em");
}
if (!empty($hangingIndent)) {
$rule->addDirective("padding-left", "2em");
$rule->addDirective("text-indent", "-2em");
}
}
if ("flush" === $this->bibliographyOptions->getSecondFieldAlign()) {
$rule = $this->cssRules->getRule(".csl-left-margin");
$rule->addDirective("display", "block");
$rule->addDirective("float", "left");
$rule = $this->cssRules->getRule(".csl-right-inline");
$rule->addDirective("margin-left", "35px");
}
}
|
[
"private",
"function",
"init",
"(",
")",
"{",
"$",
"lineSpacing",
"=",
"$",
"this",
"->",
"bibliographyOptions",
"->",
"getLineSpacing",
"(",
")",
";",
"$",
"entrySpacing",
"=",
"$",
"this",
"->",
"bibliographyOptions",
"->",
"getEntrySpacing",
"(",
")",
";",
"$",
"hangingIndent",
"=",
"$",
"this",
"->",
"bibliographyOptions",
"->",
"getHangingIndent",
"(",
")",
";",
"if",
"(",
"$",
"lineSpacing",
"||",
"$",
"entrySpacing",
"||",
"$",
"hangingIndent",
")",
"{",
"$",
"rule",
"=",
"$",
"this",
"->",
"cssRules",
"->",
"getRule",
"(",
"\".csl-entry\"",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"lineSpacing",
")",
")",
"{",
"$",
"rule",
"->",
"addDirective",
"(",
"\"line-height\"",
",",
"intval",
"(",
"$",
"lineSpacing",
")",
".",
"\"em\"",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"entrySpacing",
")",
")",
"{",
"$",
"rule",
"->",
"addDirective",
"(",
"\"margin-bottom\"",
",",
"intval",
"(",
"$",
"entrySpacing",
")",
".",
"\"em\"",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"hangingIndent",
")",
")",
"{",
"$",
"rule",
"->",
"addDirective",
"(",
"\"padding-left\"",
",",
"\"2em\"",
")",
";",
"$",
"rule",
"->",
"addDirective",
"(",
"\"text-indent\"",
",",
"\"-2em\"",
")",
";",
"}",
"}",
"if",
"(",
"\"flush\"",
"===",
"$",
"this",
"->",
"bibliographyOptions",
"->",
"getSecondFieldAlign",
"(",
")",
")",
"{",
"$",
"rule",
"=",
"$",
"this",
"->",
"cssRules",
"->",
"getRule",
"(",
"\".csl-left-margin\"",
")",
";",
"$",
"rule",
"->",
"addDirective",
"(",
"\"display\"",
",",
"\"block\"",
")",
";",
"$",
"rule",
"->",
"addDirective",
"(",
"\"float\"",
",",
"\"left\"",
")",
";",
"$",
"rule",
"=",
"$",
"this",
"->",
"cssRules",
"->",
"getRule",
"(",
"\".csl-right-inline\"",
")",
";",
"$",
"rule",
"->",
"addDirective",
"(",
"\"margin-left\"",
",",
"\"35px\"",
")",
";",
"}",
"}"
] |
initialize CSS rules
|
[
"initialize",
"CSS",
"rules"
] |
795c6a4cfb070137df1f7bb7832c4cff2bf40a38
|
https://github.com/seboettg/citeproc-php/blob/795c6a4cfb070137df1f7bb7832c4cff2bf40a38/src/Seboettg/CiteProc/Styles/Css/CssStyle.php#L54-L84
|
train
|
UseMuffin/Footprint
|
src/Model/Behavior/FootprintBehavior.php
|
FootprintBehavior.dispatch
|
public function dispatch(Event $event, $data, ArrayObject $options)
{
$eventName = $event->getName();
if (empty($this->_config['events'][$eventName])) {
return;
}
$fields = $this->_config['events'][$eventName];
if ($data instanceof EntityInterface) {
$this->_injectEntity($data, $options, $fields);
return;
}
if ($data instanceof Query) {
$this->_injectConditions($data, $options, $fields);
return;
}
throw new InvalidArgumentException(sprintf(
'Event "%s" is not supported.',
$eventName
));
}
|
php
|
public function dispatch(Event $event, $data, ArrayObject $options)
{
$eventName = $event->getName();
if (empty($this->_config['events'][$eventName])) {
return;
}
$fields = $this->_config['events'][$eventName];
if ($data instanceof EntityInterface) {
$this->_injectEntity($data, $options, $fields);
return;
}
if ($data instanceof Query) {
$this->_injectConditions($data, $options, $fields);
return;
}
throw new InvalidArgumentException(sprintf(
'Event "%s" is not supported.',
$eventName
));
}
|
[
"public",
"function",
"dispatch",
"(",
"Event",
"$",
"event",
",",
"$",
"data",
",",
"ArrayObject",
"$",
"options",
")",
"{",
"$",
"eventName",
"=",
"$",
"event",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"_config",
"[",
"'events'",
"]",
"[",
"$",
"eventName",
"]",
")",
")",
"{",
"return",
";",
"}",
"$",
"fields",
"=",
"$",
"this",
"->",
"_config",
"[",
"'events'",
"]",
"[",
"$",
"eventName",
"]",
";",
"if",
"(",
"$",
"data",
"instanceof",
"EntityInterface",
")",
"{",
"$",
"this",
"->",
"_injectEntity",
"(",
"$",
"data",
",",
"$",
"options",
",",
"$",
"fields",
")",
";",
"return",
";",
"}",
"if",
"(",
"$",
"data",
"instanceof",
"Query",
")",
"{",
"$",
"this",
"->",
"_injectConditions",
"(",
"$",
"data",
",",
"$",
"options",
",",
"$",
"fields",
")",
";",
"return",
";",
"}",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Event \"%s\" is not supported.'",
",",
"$",
"eventName",
")",
")",
";",
"}"
] |
Dispatch an event to the corresponding function.
Called by the event manager as per list provided by implementedEvents().
@param \Cake\Event\Event $event Event.
@param \Cake\ORM\Query|\Cake\Datasource\EntityInterface $data Query or Entity.
@param \ArrayObject $options Options.
@return void
@throws \InvalidArgumentException If method is called with an unsupported event.
|
[
"Dispatch",
"an",
"event",
"to",
"the",
"corresponding",
"function",
"."
] |
8bbb49ac3baac4e6896e2410af07ef77f5d8d459
|
https://github.com/UseMuffin/Footprint/blob/8bbb49ac3baac4e6896e2410af07ef77f5d8d459/src/Model/Behavior/FootprintBehavior.php#L94-L119
|
train
|
UseMuffin/Footprint
|
src/Model/Behavior/FootprintBehavior.php
|
FootprintBehavior._injectConditions
|
protected function _injectConditions(Query $query, ArrayObject $options, array $fields)
{
foreach (array_keys($fields) as $field) {
$path = $this->getConfig('propertiesMap.' . $field);
$check = false;
$query->traverseExpressions(function ($expression) use (&$check, $field, $query) {
if ($expression instanceof IdentifierExpression) {
!$check && $check = $expression->getIdentifier() === $field;
return;
}
$alias = $this->_table->aliasField($field);
!$check && $check = preg_match(
'/^' . $alias . '/',
$expression->sql($query->getValueBinder())
);
});
if (!$check && $value = Hash::get((array)$options, $path)) {
$query->where([$this->_table->aliasField($field) => $value]);
}
}
}
|
php
|
protected function _injectConditions(Query $query, ArrayObject $options, array $fields)
{
foreach (array_keys($fields) as $field) {
$path = $this->getConfig('propertiesMap.' . $field);
$check = false;
$query->traverseExpressions(function ($expression) use (&$check, $field, $query) {
if ($expression instanceof IdentifierExpression) {
!$check && $check = $expression->getIdentifier() === $field;
return;
}
$alias = $this->_table->aliasField($field);
!$check && $check = preg_match(
'/^' . $alias . '/',
$expression->sql($query->getValueBinder())
);
});
if (!$check && $value = Hash::get((array)$options, $path)) {
$query->where([$this->_table->aliasField($field) => $value]);
}
}
}
|
[
"protected",
"function",
"_injectConditions",
"(",
"Query",
"$",
"query",
",",
"ArrayObject",
"$",
"options",
",",
"array",
"$",
"fields",
")",
"{",
"foreach",
"(",
"array_keys",
"(",
"$",
"fields",
")",
"as",
"$",
"field",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'propertiesMap.'",
".",
"$",
"field",
")",
";",
"$",
"check",
"=",
"false",
";",
"$",
"query",
"->",
"traverseExpressions",
"(",
"function",
"(",
"$",
"expression",
")",
"use",
"(",
"&",
"$",
"check",
",",
"$",
"field",
",",
"$",
"query",
")",
"{",
"if",
"(",
"$",
"expression",
"instanceof",
"IdentifierExpression",
")",
"{",
"!",
"$",
"check",
"&&",
"$",
"check",
"=",
"$",
"expression",
"->",
"getIdentifier",
"(",
")",
"===",
"$",
"field",
";",
"return",
";",
"}",
"$",
"alias",
"=",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"field",
")",
";",
"!",
"$",
"check",
"&&",
"$",
"check",
"=",
"preg_match",
"(",
"'/^'",
".",
"$",
"alias",
".",
"'/'",
",",
"$",
"expression",
"->",
"sql",
"(",
"$",
"query",
"->",
"getValueBinder",
"(",
")",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"$",
"check",
"&&",
"$",
"value",
"=",
"Hash",
"::",
"get",
"(",
"(",
"array",
")",
"$",
"options",
",",
"$",
"path",
")",
")",
"{",
"$",
"query",
"->",
"where",
"(",
"[",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"field",
")",
"=>",
"$",
"value",
"]",
")",
";",
"}",
"}",
"}"
] |
Injects configured fields into finder conditions.
@param \Cake\ORM\Query $query Query.
@param \ArrayObject $options Options.
@param array $fields Field configuration.
@return void
|
[
"Injects",
"configured",
"fields",
"into",
"finder",
"conditions",
"."
] |
8bbb49ac3baac4e6896e2410af07ef77f5d8d459
|
https://github.com/UseMuffin/Footprint/blob/8bbb49ac3baac4e6896e2410af07ef77f5d8d459/src/Model/Behavior/FootprintBehavior.php#L129-L152
|
train
|
UseMuffin/Footprint
|
src/Model/Behavior/FootprintBehavior.php
|
FootprintBehavior._injectEntity
|
protected function _injectEntity(EntityInterface $entity, ArrayObject $options, array $fields)
{
$new = $entity->isNew() !== false;
foreach ($fields as $field => $when) {
if (!in_array($when, ['always', 'new', 'existing'])) {
throw new UnexpectedValueException(sprintf(
'When should be one of "always", "new" or "existing". The passed value "%s" is invalid',
$when
));
}
if ($entity->isDirty($field)) {
continue;
}
if ($when === 'always' ||
($when === 'new' && $new) ||
($when === 'existing' && !$new)
) {
$entity->set(
$field,
Hash::get(
$options,
$this->getConfig('propertiesMap.' . $field)
)
);
}
}
}
|
php
|
protected function _injectEntity(EntityInterface $entity, ArrayObject $options, array $fields)
{
$new = $entity->isNew() !== false;
foreach ($fields as $field => $when) {
if (!in_array($when, ['always', 'new', 'existing'])) {
throw new UnexpectedValueException(sprintf(
'When should be one of "always", "new" or "existing". The passed value "%s" is invalid',
$when
));
}
if ($entity->isDirty($field)) {
continue;
}
if ($when === 'always' ||
($when === 'new' && $new) ||
($when === 'existing' && !$new)
) {
$entity->set(
$field,
Hash::get(
$options,
$this->getConfig('propertiesMap.' . $field)
)
);
}
}
}
|
[
"protected",
"function",
"_injectEntity",
"(",
"EntityInterface",
"$",
"entity",
",",
"ArrayObject",
"$",
"options",
",",
"array",
"$",
"fields",
")",
"{",
"$",
"new",
"=",
"$",
"entity",
"->",
"isNew",
"(",
")",
"!==",
"false",
";",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"field",
"=>",
"$",
"when",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"when",
",",
"[",
"'always'",
",",
"'new'",
",",
"'existing'",
"]",
")",
")",
"{",
"throw",
"new",
"UnexpectedValueException",
"(",
"sprintf",
"(",
"'When should be one of \"always\", \"new\" or \"existing\". The passed value \"%s\" is invalid'",
",",
"$",
"when",
")",
")",
";",
"}",
"if",
"(",
"$",
"entity",
"->",
"isDirty",
"(",
"$",
"field",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"when",
"===",
"'always'",
"||",
"(",
"$",
"when",
"===",
"'new'",
"&&",
"$",
"new",
")",
"||",
"(",
"$",
"when",
"===",
"'existing'",
"&&",
"!",
"$",
"new",
")",
")",
"{",
"$",
"entity",
"->",
"set",
"(",
"$",
"field",
",",
"Hash",
"::",
"get",
"(",
"$",
"options",
",",
"$",
"this",
"->",
"getConfig",
"(",
"'propertiesMap.'",
".",
"$",
"field",
")",
")",
")",
";",
"}",
"}",
"}"
] |
Injects configured field values into entity if those fields are not dirty.
@param \Cake\Datasource\EntityInterface $entity Entity.
@param \ArrayObject $options Options.
@param array $fields Field configuration.
@return void
|
[
"Injects",
"configured",
"field",
"values",
"into",
"entity",
"if",
"those",
"fields",
"are",
"not",
"dirty",
"."
] |
8bbb49ac3baac4e6896e2410af07ef77f5d8d459
|
https://github.com/UseMuffin/Footprint/blob/8bbb49ac3baac4e6896e2410af07ef77f5d8d459/src/Model/Behavior/FootprintBehavior.php#L162-L191
|
train
|
UseMuffin/Footprint
|
src/Auth/FootprintAwareTrait.php
|
FootprintAwareTrait.footprint
|
public function footprint(Event $event)
{
if (!$this->_listener) {
$this->_listener = new FootprintListener($this->_getCurrentUser());
}
if ($event->getName() === 'Auth.afterIdentify') {
$this->_listener->setUser($this->_getCurrentUser($event->getData(0)));
return;
}
$event->getSubject()->getEventManager()->on($this->_listener);
}
|
php
|
public function footprint(Event $event)
{
if (!$this->_listener) {
$this->_listener = new FootprintListener($this->_getCurrentUser());
}
if ($event->getName() === 'Auth.afterIdentify') {
$this->_listener->setUser($this->_getCurrentUser($event->getData(0)));
return;
}
$event->getSubject()->getEventManager()->on($this->_listener);
}
|
[
"public",
"function",
"footprint",
"(",
"Event",
"$",
"event",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_listener",
")",
"{",
"$",
"this",
"->",
"_listener",
"=",
"new",
"FootprintListener",
"(",
"$",
"this",
"->",
"_getCurrentUser",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"event",
"->",
"getName",
"(",
")",
"===",
"'Auth.afterIdentify'",
")",
"{",
"$",
"this",
"->",
"_listener",
"->",
"setUser",
"(",
"$",
"this",
"->",
"_getCurrentUser",
"(",
"$",
"event",
"->",
"getData",
"(",
"0",
")",
")",
")",
";",
"return",
";",
"}",
"$",
"event",
"->",
"getSubject",
"(",
")",
"->",
"getEventManager",
"(",
")",
"->",
"on",
"(",
"$",
"this",
"->",
"_listener",
")",
";",
"}"
] |
Try and attach footprint listener to models.
It also passing the user record to footprint listener after user is
identified by AuthComponent.
@param \Cake\Event\Event $event Event.
@return void
|
[
"Try",
"and",
"attach",
"footprint",
"listener",
"to",
"models",
"."
] |
8bbb49ac3baac4e6896e2410af07ef77f5d8d459
|
https://github.com/UseMuffin/Footprint/blob/8bbb49ac3baac4e6896e2410af07ef77f5d8d459/src/Auth/FootprintAwareTrait.php#L54-L67
|
train
|
UseMuffin/Footprint
|
src/Auth/FootprintAwareTrait.php
|
FootprintAwareTrait._circumventEventManager
|
protected function _circumventEventManager($method, $args = [])
{
EventManager::instance()->off('Model.initialize', [$this, 'footprint']);
$result = call_user_func_array([TableRegistry::get($this->_userModel), $method], $args);
EventManager::instance()->on('Model.initialize', [$this, 'footprint']);
return $result;
}
|
php
|
protected function _circumventEventManager($method, $args = [])
{
EventManager::instance()->off('Model.initialize', [$this, 'footprint']);
$result = call_user_func_array([TableRegistry::get($this->_userModel), $method], $args);
EventManager::instance()->on('Model.initialize', [$this, 'footprint']);
return $result;
}
|
[
"protected",
"function",
"_circumventEventManager",
"(",
"$",
"method",
",",
"$",
"args",
"=",
"[",
"]",
")",
"{",
"EventManager",
"::",
"instance",
"(",
")",
"->",
"off",
"(",
"'Model.initialize'",
",",
"[",
"$",
"this",
",",
"'footprint'",
"]",
")",
";",
"$",
"result",
"=",
"call_user_func_array",
"(",
"[",
"TableRegistry",
"::",
"get",
"(",
"$",
"this",
"->",
"_userModel",
")",
",",
"$",
"method",
"]",
",",
"$",
"args",
")",
";",
"EventManager",
"::",
"instance",
"(",
")",
"->",
"on",
"(",
"'Model.initialize'",
",",
"[",
"$",
"this",
",",
"'footprint'",
"]",
")",
";",
"return",
"$",
"result",
";",
"}"
] |
Temporarily disable the listener on `Model.initialize` when trying to
fetch instantiate the table and avoid an infinite loop.
@param string $method Method name.
@param array $args Arguments to pass to the method.
@return \Cake\ORM\Table The users table.
|
[
"Temporarily",
"disable",
"the",
"listener",
"on",
"Model",
".",
"initialize",
"when",
"trying",
"to",
"fetch",
"instantiate",
"the",
"table",
"and",
"avoid",
"an",
"infinite",
"loop",
"."
] |
8bbb49ac3baac4e6896e2410af07ef77f5d8d459
|
https://github.com/UseMuffin/Footprint/blob/8bbb49ac3baac4e6896e2410af07ef77f5d8d459/src/Auth/FootprintAwareTrait.php#L135-L142
|
train
|
UseMuffin/Footprint
|
src/Event/FootprintListener.php
|
FootprintListener.handleEvent
|
public function handleEvent(Event $event, $ormObject, $options)
{
$key = $this->getConfig('optionKey');
if (empty($options[$key]) && !empty($this->_currentUser)) {
$options[$key] = $this->_currentUser;
}
}
|
php
|
public function handleEvent(Event $event, $ormObject, $options)
{
$key = $this->getConfig('optionKey');
if (empty($options[$key]) && !empty($this->_currentUser)) {
$options[$key] = $this->_currentUser;
}
}
|
[
"public",
"function",
"handleEvent",
"(",
"Event",
"$",
"event",
",",
"$",
"ormObject",
",",
"$",
"options",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'optionKey'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"options",
"[",
"$",
"key",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"this",
"->",
"_currentUser",
")",
")",
"{",
"$",
"options",
"[",
"$",
"key",
"]",
"=",
"$",
"this",
"->",
"_currentUser",
";",
"}",
"}"
] |
Universal callback.
@param \Cake\Event\Event $event Event.
@param mixed $ormObject Query or Entity.
@param \ArrayObject $options Options.
@return void
|
[
"Universal",
"callback",
"."
] |
8bbb49ac3baac4e6896e2410af07ef77f5d8d459
|
https://github.com/UseMuffin/Footprint/blob/8bbb49ac3baac4e6896e2410af07ef77f5d8d459/src/Event/FootprintListener.php#L78-L84
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/Dispatcher.php
|
Dispatcher.switchMode
|
public function switchMode( $mode ) {
$this->mode = $mode;
$this->handler = $this->dispatchTable[$mode];
return $this->handler;
}
|
php
|
public function switchMode( $mode ) {
$this->mode = $mode;
$this->handler = $this->dispatchTable[$mode];
return $this->handler;
}
|
[
"public",
"function",
"switchMode",
"(",
"$",
"mode",
")",
"{",
"$",
"this",
"->",
"mode",
"=",
"$",
"mode",
";",
"$",
"this",
"->",
"handler",
"=",
"$",
"this",
"->",
"dispatchTable",
"[",
"$",
"mode",
"]",
";",
"return",
"$",
"this",
"->",
"handler",
";",
"}"
] |
Switch the insertion mode, and return the new handler
@param int $mode
@return InsertionMode
|
[
"Switch",
"the",
"insertion",
"mode",
"and",
"return",
"the",
"new",
"handler"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/Dispatcher.php#L139-L143
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/Dispatcher.php
|
Dispatcher.switchAndSave
|
public function switchAndSave( $mode ) {
$this->originalMode = $this->mode;
$this->mode = $mode;
$this->handler = $this->dispatchTable[$mode];
return $this->handler;
}
|
php
|
public function switchAndSave( $mode ) {
$this->originalMode = $this->mode;
$this->mode = $mode;
$this->handler = $this->dispatchTable[$mode];
return $this->handler;
}
|
[
"public",
"function",
"switchAndSave",
"(",
"$",
"mode",
")",
"{",
"$",
"this",
"->",
"originalMode",
"=",
"$",
"this",
"->",
"mode",
";",
"$",
"this",
"->",
"mode",
"=",
"$",
"mode",
";",
"$",
"this",
"->",
"handler",
"=",
"$",
"this",
"->",
"dispatchTable",
"[",
"$",
"mode",
"]",
";",
"return",
"$",
"this",
"->",
"handler",
";",
"}"
] |
Let the original insertion mode be the current insertion mode, and
switch the insertion mode to some new value. Return the new handler.
@param int $mode
@return InsertionMode
|
[
"Let",
"the",
"original",
"insertion",
"mode",
"be",
"the",
"current",
"insertion",
"mode",
"and",
"switch",
"the",
"insertion",
"mode",
"to",
"some",
"new",
"value",
".",
"Return",
"the",
"new",
"handler",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/Dispatcher.php#L152-L157
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/Dispatcher.php
|
Dispatcher.restoreMode
|
public function restoreMode() {
if ( $this->originalMode === null ) {
throw new TreeBuilderError( "original insertion mode is not set" );
}
$mode = $this->mode = $this->originalMode;
$this->originalMode = null;
$this->handler = $this->dispatchTable[$mode];
return $this->handler;
}
|
php
|
public function restoreMode() {
if ( $this->originalMode === null ) {
throw new TreeBuilderError( "original insertion mode is not set" );
}
$mode = $this->mode = $this->originalMode;
$this->originalMode = null;
$this->handler = $this->dispatchTable[$mode];
return $this->handler;
}
|
[
"public",
"function",
"restoreMode",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"originalMode",
"===",
"null",
")",
"{",
"throw",
"new",
"TreeBuilderError",
"(",
"\"original insertion mode is not set\"",
")",
";",
"}",
"$",
"mode",
"=",
"$",
"this",
"->",
"mode",
"=",
"$",
"this",
"->",
"originalMode",
";",
"$",
"this",
"->",
"originalMode",
"=",
"null",
";",
"$",
"this",
"->",
"handler",
"=",
"$",
"this",
"->",
"dispatchTable",
"[",
"$",
"mode",
"]",
";",
"return",
"$",
"this",
"->",
"handler",
";",
"}"
] |
Switch the insertion mode to the original insertion mode and return the
new handler.
@return InsertionMode
|
[
"Switch",
"the",
"insertion",
"mode",
"to",
"the",
"original",
"insertion",
"mode",
"and",
"return",
"the",
"new",
"handler",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/Dispatcher.php#L165-L173
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/Dispatcher.php
|
Dispatcher.isInTableMode
|
public function isInTableMode() {
static $tableModes = [
self::IN_TABLE => true,
self::IN_CAPTION => true,
self::IN_TABLE_BODY => true,
self::IN_ROW => true,
self::IN_CELL => true ];
return isset( $tableModes[$this->mode] );
}
|
php
|
public function isInTableMode() {
static $tableModes = [
self::IN_TABLE => true,
self::IN_CAPTION => true,
self::IN_TABLE_BODY => true,
self::IN_ROW => true,
self::IN_CELL => true ];
return isset( $tableModes[$this->mode] );
}
|
[
"public",
"function",
"isInTableMode",
"(",
")",
"{",
"static",
"$",
"tableModes",
"=",
"[",
"self",
"::",
"IN_TABLE",
"=>",
"true",
",",
"self",
"::",
"IN_CAPTION",
"=>",
"true",
",",
"self",
"::",
"IN_TABLE_BODY",
"=>",
"true",
",",
"self",
"::",
"IN_ROW",
"=>",
"true",
",",
"self",
"::",
"IN_CELL",
"=>",
"true",
"]",
";",
"return",
"isset",
"(",
"$",
"tableModes",
"[",
"$",
"this",
"->",
"mode",
"]",
")",
";",
"}"
] |
True if we are in a table mode, for the purposes of switching to
IN_SELECT_IN_TABLE as opposed to IN_SELECT.
@return bool
|
[
"True",
"if",
"we",
"are",
"in",
"a",
"table",
"mode",
"for",
"the",
"purposes",
"of",
"switching",
"to",
"IN_SELECT_IN_TABLE",
"as",
"opposed",
"to",
"IN_SELECT",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/Dispatcher.php#L193-L201
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/Dispatcher.php
|
Dispatcher.getAppropriateMode
|
protected function getAppropriateMode() {
$builder = $this->builder;
$stack = $builder->stack;
$last = false;
$node = $stack->current;
for ( $idx = $stack->length() - 1; $idx >= 0; $idx-- ) {
$node = $stack->item( $idx );
if ( $idx === 0 ) {
$last = true;
if ( $builder->isFragment ) {
$node = $builder->fragmentContext;
}
}
switch ( $node->htmlName ) {
case 'select':
if ( $last ) {
return self::IN_SELECT;
}
for ( $ancestorIdx = $idx - 1; $ancestorIdx >= 1; $ancestorIdx-- ) {
$ancestor = $stack->item( $ancestorIdx );
if ( $ancestor->htmlName === 'template' ) {
return self::IN_SELECT;
} elseif ( $ancestor->htmlName === 'table' ) {
return self::IN_SELECT_IN_TABLE;
}
}
return self::IN_SELECT;
case 'td':
case 'th':
if ( !$last ) {
return self::IN_CELL;
}
break;
case 'tr':
return self::IN_ROW;
case 'tbody':
case 'thead':
case 'tfoot':
return self::IN_TABLE_BODY;
case 'caption':
return self::IN_CAPTION;
case 'colgroup':
return self::IN_COLUMN_GROUP;
case 'table':
return self::IN_TABLE;
case 'template':
return $this->templateModeStack->current;
case 'head':
if ( $last ) {
return self::IN_BODY;
} else {
return self::IN_HEAD;
}
case 'body':
return self::IN_BODY;
case 'frameset':
return self::IN_FRAMESET;
case 'html':
if ( $builder->headElement === null ) {
return self::BEFORE_HEAD;
} else {
return self::AFTER_HEAD;
}
}
}
return self::IN_BODY;
}
|
php
|
protected function getAppropriateMode() {
$builder = $this->builder;
$stack = $builder->stack;
$last = false;
$node = $stack->current;
for ( $idx = $stack->length() - 1; $idx >= 0; $idx-- ) {
$node = $stack->item( $idx );
if ( $idx === 0 ) {
$last = true;
if ( $builder->isFragment ) {
$node = $builder->fragmentContext;
}
}
switch ( $node->htmlName ) {
case 'select':
if ( $last ) {
return self::IN_SELECT;
}
for ( $ancestorIdx = $idx - 1; $ancestorIdx >= 1; $ancestorIdx-- ) {
$ancestor = $stack->item( $ancestorIdx );
if ( $ancestor->htmlName === 'template' ) {
return self::IN_SELECT;
} elseif ( $ancestor->htmlName === 'table' ) {
return self::IN_SELECT_IN_TABLE;
}
}
return self::IN_SELECT;
case 'td':
case 'th':
if ( !$last ) {
return self::IN_CELL;
}
break;
case 'tr':
return self::IN_ROW;
case 'tbody':
case 'thead':
case 'tfoot':
return self::IN_TABLE_BODY;
case 'caption':
return self::IN_CAPTION;
case 'colgroup':
return self::IN_COLUMN_GROUP;
case 'table':
return self::IN_TABLE;
case 'template':
return $this->templateModeStack->current;
case 'head':
if ( $last ) {
return self::IN_BODY;
} else {
return self::IN_HEAD;
}
case 'body':
return self::IN_BODY;
case 'frameset':
return self::IN_FRAMESET;
case 'html':
if ( $builder->headElement === null ) {
return self::BEFORE_HEAD;
} else {
return self::AFTER_HEAD;
}
}
}
return self::IN_BODY;
}
|
[
"protected",
"function",
"getAppropriateMode",
"(",
")",
"{",
"$",
"builder",
"=",
"$",
"this",
"->",
"builder",
";",
"$",
"stack",
"=",
"$",
"builder",
"->",
"stack",
";",
"$",
"last",
"=",
"false",
";",
"$",
"node",
"=",
"$",
"stack",
"->",
"current",
";",
"for",
"(",
"$",
"idx",
"=",
"$",
"stack",
"->",
"length",
"(",
")",
"-",
"1",
";",
"$",
"idx",
">=",
"0",
";",
"$",
"idx",
"--",
")",
"{",
"$",
"node",
"=",
"$",
"stack",
"->",
"item",
"(",
"$",
"idx",
")",
";",
"if",
"(",
"$",
"idx",
"===",
"0",
")",
"{",
"$",
"last",
"=",
"true",
";",
"if",
"(",
"$",
"builder",
"->",
"isFragment",
")",
"{",
"$",
"node",
"=",
"$",
"builder",
"->",
"fragmentContext",
";",
"}",
"}",
"switch",
"(",
"$",
"node",
"->",
"htmlName",
")",
"{",
"case",
"'select'",
":",
"if",
"(",
"$",
"last",
")",
"{",
"return",
"self",
"::",
"IN_SELECT",
";",
"}",
"for",
"(",
"$",
"ancestorIdx",
"=",
"$",
"idx",
"-",
"1",
";",
"$",
"ancestorIdx",
">=",
"1",
";",
"$",
"ancestorIdx",
"--",
")",
"{",
"$",
"ancestor",
"=",
"$",
"stack",
"->",
"item",
"(",
"$",
"ancestorIdx",
")",
";",
"if",
"(",
"$",
"ancestor",
"->",
"htmlName",
"===",
"'template'",
")",
"{",
"return",
"self",
"::",
"IN_SELECT",
";",
"}",
"elseif",
"(",
"$",
"ancestor",
"->",
"htmlName",
"===",
"'table'",
")",
"{",
"return",
"self",
"::",
"IN_SELECT_IN_TABLE",
";",
"}",
"}",
"return",
"self",
"::",
"IN_SELECT",
";",
"case",
"'td'",
":",
"case",
"'th'",
":",
"if",
"(",
"!",
"$",
"last",
")",
"{",
"return",
"self",
"::",
"IN_CELL",
";",
"}",
"break",
";",
"case",
"'tr'",
":",
"return",
"self",
"::",
"IN_ROW",
";",
"case",
"'tbody'",
":",
"case",
"'thead'",
":",
"case",
"'tfoot'",
":",
"return",
"self",
"::",
"IN_TABLE_BODY",
";",
"case",
"'caption'",
":",
"return",
"self",
"::",
"IN_CAPTION",
";",
"case",
"'colgroup'",
":",
"return",
"self",
"::",
"IN_COLUMN_GROUP",
";",
"case",
"'table'",
":",
"return",
"self",
"::",
"IN_TABLE",
";",
"case",
"'template'",
":",
"return",
"$",
"this",
"->",
"templateModeStack",
"->",
"current",
";",
"case",
"'head'",
":",
"if",
"(",
"$",
"last",
")",
"{",
"return",
"self",
"::",
"IN_BODY",
";",
"}",
"else",
"{",
"return",
"self",
"::",
"IN_HEAD",
";",
"}",
"case",
"'body'",
":",
"return",
"self",
"::",
"IN_BODY",
";",
"case",
"'frameset'",
":",
"return",
"self",
"::",
"IN_FRAMESET",
";",
"case",
"'html'",
":",
"if",
"(",
"$",
"builder",
"->",
"headElement",
"===",
"null",
")",
"{",
"return",
"self",
"::",
"BEFORE_HEAD",
";",
"}",
"else",
"{",
"return",
"self",
"::",
"AFTER_HEAD",
";",
"}",
"}",
"}",
"return",
"self",
"::",
"IN_BODY",
";",
"}"
] |
Get the insertion mode index which is switched to when we reset the
insertion mode appropriately.
@return int
|
[
"Get",
"the",
"insertion",
"mode",
"index",
"which",
"is",
"switched",
"to",
"when",
"we",
"reset",
"the",
"insertion",
"mode",
"appropriately",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/Dispatcher.php#L218-L297
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/Dispatcher.php
|
Dispatcher.dispatcherCurrentNode
|
protected function dispatcherCurrentNode() {
$current = $this->builder->stack->current;
if ( $current && $current->stackIndex === 0 && $this->builder->isFragment ) {
return $this->builder->fragmentContext;
} else {
return $current;
}
}
|
php
|
protected function dispatcherCurrentNode() {
$current = $this->builder->stack->current;
if ( $current && $current->stackIndex === 0 && $this->builder->isFragment ) {
return $this->builder->fragmentContext;
} else {
return $current;
}
}
|
[
"protected",
"function",
"dispatcherCurrentNode",
"(",
")",
"{",
"$",
"current",
"=",
"$",
"this",
"->",
"builder",
"->",
"stack",
"->",
"current",
";",
"if",
"(",
"$",
"current",
"&&",
"$",
"current",
"->",
"stackIndex",
"===",
"0",
"&&",
"$",
"this",
"->",
"builder",
"->",
"isFragment",
")",
"{",
"return",
"$",
"this",
"->",
"builder",
"->",
"fragmentContext",
";",
"}",
"else",
"{",
"return",
"$",
"current",
";",
"}",
"}"
] |
If the stack of open elements is empty, return null, otherwise return
the adjusted current node.
@return Element|null
|
[
"If",
"the",
"stack",
"of",
"open",
"elements",
"is",
"empty",
"return",
"null",
"otherwise",
"return",
"the",
"adjusted",
"current",
"node",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/Dispatcher.php#L304-L311
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.execute
|
public function execute( $options = [] ) {
if ( isset( $options['state'] ) ) {
$this->state = $options['state'];
} else {
$this->state = self::STATE_START;
}
if ( isset( $options['fragmentNamespace'] ) ) {
$this->setFragmentContext( $options['fragmentNamespace'], $options['fragmentName'] );
} else {
$this->fragmentNamespace = null;
$this->fragmentName = null;
}
$this->appropriateEndTag = isset( $options['appropriateEndTag'] ) ?
$options['appropriateEndTag'] : null;
$this->preprocess();
$this->listener->startDocument( $this, $this->fragmentNamespace, $this->fragmentName );
$this->executeInternal( true );
}
|
php
|
public function execute( $options = [] ) {
if ( isset( $options['state'] ) ) {
$this->state = $options['state'];
} else {
$this->state = self::STATE_START;
}
if ( isset( $options['fragmentNamespace'] ) ) {
$this->setFragmentContext( $options['fragmentNamespace'], $options['fragmentName'] );
} else {
$this->fragmentNamespace = null;
$this->fragmentName = null;
}
$this->appropriateEndTag = isset( $options['appropriateEndTag'] ) ?
$options['appropriateEndTag'] : null;
$this->preprocess();
$this->listener->startDocument( $this, $this->fragmentNamespace, $this->fragmentName );
$this->executeInternal( true );
}
|
[
"public",
"function",
"execute",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'state'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"state",
"=",
"$",
"options",
"[",
"'state'",
"]",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"state",
"=",
"self",
"::",
"STATE_START",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'fragmentNamespace'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"setFragmentContext",
"(",
"$",
"options",
"[",
"'fragmentNamespace'",
"]",
",",
"$",
"options",
"[",
"'fragmentName'",
"]",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"fragmentNamespace",
"=",
"null",
";",
"$",
"this",
"->",
"fragmentName",
"=",
"null",
";",
"}",
"$",
"this",
"->",
"appropriateEndTag",
"=",
"isset",
"(",
"$",
"options",
"[",
"'appropriateEndTag'",
"]",
")",
"?",
"$",
"options",
"[",
"'appropriateEndTag'",
"]",
":",
"null",
";",
"$",
"this",
"->",
"preprocess",
"(",
")",
";",
"$",
"this",
"->",
"listener",
"->",
"startDocument",
"(",
"$",
"this",
",",
"$",
"this",
"->",
"fragmentNamespace",
",",
"$",
"this",
"->",
"fragmentName",
")",
";",
"$",
"this",
"->",
"executeInternal",
"(",
"true",
")",
";",
"}"
] |
Run the tokenizer on the whole input stream. This is the normal entry point.
@param array $options An associative array of options:
- state : One of the STATE_* constants, a state in which to start.
- appropriateEndTag : The "appropriate end tag", which needs to be set
if entering one of the raw text states.
- fragmentNamespace : The fragment namespace
- fragmentName : The fragment tag name
|
[
"Run",
"the",
"tokenizer",
"on",
"the",
"whole",
"input",
"stream",
".",
"This",
"is",
"the",
"normal",
"entry",
"point",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L150-L169
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.setFragmentContext
|
public function setFragmentContext( $namespace, $tagName ) {
$this->fragmentNamespace = $namespace;
$this->fragmentName = $tagName;
if ( strval( $namespace ) !== '' && $namespace !== HTMLData::NS_HTML ) {
return;
}
switch ( $tagName ) {
case 'title':
case 'textarea':
$this->state = self::STATE_RCDATA;
break;
case 'style':
case 'xmp':
case 'iframe':
case 'noembed':
case 'noframes':
$this->state = self::STATE_RAWTEXT;
break;
case 'script':
$this->state = self::STATE_SCRIPT_DATA;
break;
case 'noscript':
if ( $this->scriptingFlag ) {
$this->state = self::STATE_RAWTEXT;
}
break;
case 'plaintext':
$this->state = self::STATE_PLAINTEXT;
break;
}
}
|
php
|
public function setFragmentContext( $namespace, $tagName ) {
$this->fragmentNamespace = $namespace;
$this->fragmentName = $tagName;
if ( strval( $namespace ) !== '' && $namespace !== HTMLData::NS_HTML ) {
return;
}
switch ( $tagName ) {
case 'title':
case 'textarea':
$this->state = self::STATE_RCDATA;
break;
case 'style':
case 'xmp':
case 'iframe':
case 'noembed':
case 'noframes':
$this->state = self::STATE_RAWTEXT;
break;
case 'script':
$this->state = self::STATE_SCRIPT_DATA;
break;
case 'noscript':
if ( $this->scriptingFlag ) {
$this->state = self::STATE_RAWTEXT;
}
break;
case 'plaintext':
$this->state = self::STATE_PLAINTEXT;
break;
}
}
|
[
"public",
"function",
"setFragmentContext",
"(",
"$",
"namespace",
",",
"$",
"tagName",
")",
"{",
"$",
"this",
"->",
"fragmentNamespace",
"=",
"$",
"namespace",
";",
"$",
"this",
"->",
"fragmentName",
"=",
"$",
"tagName",
";",
"if",
"(",
"strval",
"(",
"$",
"namespace",
")",
"!==",
"''",
"&&",
"$",
"namespace",
"!==",
"HTMLData",
"::",
"NS_HTML",
")",
"{",
"return",
";",
"}",
"switch",
"(",
"$",
"tagName",
")",
"{",
"case",
"'title'",
":",
"case",
"'textarea'",
":",
"$",
"this",
"->",
"state",
"=",
"self",
"::",
"STATE_RCDATA",
";",
"break",
";",
"case",
"'style'",
":",
"case",
"'xmp'",
":",
"case",
"'iframe'",
":",
"case",
"'noembed'",
":",
"case",
"'noframes'",
":",
"$",
"this",
"->",
"state",
"=",
"self",
"::",
"STATE_RAWTEXT",
";",
"break",
";",
"case",
"'script'",
":",
"$",
"this",
"->",
"state",
"=",
"self",
"::",
"STATE_SCRIPT_DATA",
";",
"break",
";",
"case",
"'noscript'",
":",
"if",
"(",
"$",
"this",
"->",
"scriptingFlag",
")",
"{",
"$",
"this",
"->",
"state",
"=",
"self",
"::",
"STATE_RAWTEXT",
";",
"}",
"break",
";",
"case",
"'plaintext'",
":",
"$",
"this",
"->",
"state",
"=",
"self",
"::",
"STATE_PLAINTEXT",
";",
"break",
";",
"}",
"}"
] |
Initialize the tokenizer for fragment parsing
@param string $namespace The namespace of the context element
@param string $tagName The name of the context element
|
[
"Initialize",
"the",
"tokenizer",
"for",
"fragment",
"parsing"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L200-L236
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.preprocess
|
protected function preprocess() {
if ( $this->preprocessed || $this->skipPreprocess ) {
return;
}
// Normalize line endings
if ( strcspn( $this->text, "\r" ) !== strlen( $this->text ) ) {
$this->text = preg_replace( '/\r\n?/', "\n", $this->text );
$this->length = strlen( $this->text );
}
// Raise parse errors for any control characters
static $re;
if ( $re === null ) {
// Note that we deliberately do not use the 'u' flag on the
// regexp below, as that bypasses the PCRE JIT. Instead we
// rewrite character classes containing codepoints which
// require more than one UTF-8 byte as alternations.
$re = '/[' .
// "C0 controls" (u0000 - u001F) but not
// "ASCII whitespace" (u0009, u000A, u000C, u000D, u0020) or
// NULL (u0000)
// https://infra.spec.whatwg.org/#c0-control
// https://infra.spec.whatwg.org/#ascii-whitespace
'\x{0001}-\x{0008}' .
'\x{000B}' .
'\x{000E}-\x{001F}' .
// "Controls" other than C0 controls (u007F - u009F)
// https://infra.spec.whatwg.org/#control
'\x{007F}]|' .
// (We can't use character classes above u007F)
"\u{0080}|\u{0081}|\u{0082}|\u{0083}|" .
"\u{0084}|\u{0085}|\u{0086}|\u{0087}|" .
"\u{0088}|\u{0089}|\u{008A}|\u{008B}|" .
"\u{008C}|\u{008D}|\u{008E}|\u{008F}|" .
"\u{0090}|\u{0091}|\u{0092}|\u{0093}|" .
"\u{0094}|\u{0095}|\u{0096}|\u{0097}|" .
"\u{0098}|\u{0099}|\u{009A}|\u{009B}|" .
"\u{009C}|\u{009D}|\u{009E}|\u{009F}|" .
// HTML spec calls these "noncharacters"
// https://infra.spec.whatwg.org/#noncharacter
"\u{FDD0}|\u{FDD1}|\u{FDD2}|\u{FDD3}|" .
"\u{FDD4}|\u{FDD5}|\u{FDD6}|\u{FDD7}|" .
"\u{FDD8}|\u{FDD9}|\u{FDDA}|\u{FDDB}|" .
"\u{FDDC}|\u{FDDD}|\u{FDDE}|\u{FDDF}|" .
"\u{FDE0}|\u{FDE1}|\u{FDE2}|\u{FDE3}|" .
"\u{FDE4}|\u{FDE5}|\u{FDE6}|\u{FDE7}|" .
"\u{FDE8}|\u{FDE9}|\u{FDEA}|\u{FDEB}|" .
"\u{FDEC}|\u{FDED}|\u{FDEE}|\u{FDEF}|" .
"\u{FFFE}|\u{FFFF}|" .
"\u{1FFFE}|\u{1FFFF}|" .
"\u{2FFFE}|\u{2FFFF}|" .
"\u{3FFFE}|\u{3FFFF}|" .
"\u{4FFFE}|\u{4FFFF}|" .
"\u{5FFFE}|\u{5FFFF}|" .
"\u{6FFFE}|\u{6FFFF}|" .
"\u{7FFFE}|\u{7FFFF}|" .
"\u{8FFFE}|\u{8FFFF}|" .
"\u{9FFFE}|\u{9FFFF}|" .
"\u{AFFFE}|\u{AFFFF}|" .
"\u{BFFFE}|\u{BFFFF}|" .
"\u{CFFFE}|\u{CFFFF}|" .
"\u{DFFFE}|\u{DFFFF}|" .
"\u{EFFFE}|\u{EFFFF}|" .
"\u{FFFFE}|\u{FFFFF}|" .
"\u{10FFFE}|\u{10FFFF}/S";
}
if ( !$this->ignoreErrors ) {
$pos = 0;
while ( $pos < $this->length ) {
$count = preg_match( $re, $this->text, $m, PREG_OFFSET_CAPTURE, $pos );
if ( $count === false ) {
$this->throwPregError();
} elseif ( !$count ) {
break;
}
$pos = $m[0][1];
$this->error( "disallowed control character", $pos );
$pos += strlen( $m[0][0] );
}
}
}
|
php
|
protected function preprocess() {
if ( $this->preprocessed || $this->skipPreprocess ) {
return;
}
// Normalize line endings
if ( strcspn( $this->text, "\r" ) !== strlen( $this->text ) ) {
$this->text = preg_replace( '/\r\n?/', "\n", $this->text );
$this->length = strlen( $this->text );
}
// Raise parse errors for any control characters
static $re;
if ( $re === null ) {
// Note that we deliberately do not use the 'u' flag on the
// regexp below, as that bypasses the PCRE JIT. Instead we
// rewrite character classes containing codepoints which
// require more than one UTF-8 byte as alternations.
$re = '/[' .
// "C0 controls" (u0000 - u001F) but not
// "ASCII whitespace" (u0009, u000A, u000C, u000D, u0020) or
// NULL (u0000)
// https://infra.spec.whatwg.org/#c0-control
// https://infra.spec.whatwg.org/#ascii-whitespace
'\x{0001}-\x{0008}' .
'\x{000B}' .
'\x{000E}-\x{001F}' .
// "Controls" other than C0 controls (u007F - u009F)
// https://infra.spec.whatwg.org/#control
'\x{007F}]|' .
// (We can't use character classes above u007F)
"\u{0080}|\u{0081}|\u{0082}|\u{0083}|" .
"\u{0084}|\u{0085}|\u{0086}|\u{0087}|" .
"\u{0088}|\u{0089}|\u{008A}|\u{008B}|" .
"\u{008C}|\u{008D}|\u{008E}|\u{008F}|" .
"\u{0090}|\u{0091}|\u{0092}|\u{0093}|" .
"\u{0094}|\u{0095}|\u{0096}|\u{0097}|" .
"\u{0098}|\u{0099}|\u{009A}|\u{009B}|" .
"\u{009C}|\u{009D}|\u{009E}|\u{009F}|" .
// HTML spec calls these "noncharacters"
// https://infra.spec.whatwg.org/#noncharacter
"\u{FDD0}|\u{FDD1}|\u{FDD2}|\u{FDD3}|" .
"\u{FDD4}|\u{FDD5}|\u{FDD6}|\u{FDD7}|" .
"\u{FDD8}|\u{FDD9}|\u{FDDA}|\u{FDDB}|" .
"\u{FDDC}|\u{FDDD}|\u{FDDE}|\u{FDDF}|" .
"\u{FDE0}|\u{FDE1}|\u{FDE2}|\u{FDE3}|" .
"\u{FDE4}|\u{FDE5}|\u{FDE6}|\u{FDE7}|" .
"\u{FDE8}|\u{FDE9}|\u{FDEA}|\u{FDEB}|" .
"\u{FDEC}|\u{FDED}|\u{FDEE}|\u{FDEF}|" .
"\u{FFFE}|\u{FFFF}|" .
"\u{1FFFE}|\u{1FFFF}|" .
"\u{2FFFE}|\u{2FFFF}|" .
"\u{3FFFE}|\u{3FFFF}|" .
"\u{4FFFE}|\u{4FFFF}|" .
"\u{5FFFE}|\u{5FFFF}|" .
"\u{6FFFE}|\u{6FFFF}|" .
"\u{7FFFE}|\u{7FFFF}|" .
"\u{8FFFE}|\u{8FFFF}|" .
"\u{9FFFE}|\u{9FFFF}|" .
"\u{AFFFE}|\u{AFFFF}|" .
"\u{BFFFE}|\u{BFFFF}|" .
"\u{CFFFE}|\u{CFFFF}|" .
"\u{DFFFE}|\u{DFFFF}|" .
"\u{EFFFE}|\u{EFFFF}|" .
"\u{FFFFE}|\u{FFFFF}|" .
"\u{10FFFE}|\u{10FFFF}/S";
}
if ( !$this->ignoreErrors ) {
$pos = 0;
while ( $pos < $this->length ) {
$count = preg_match( $re, $this->text, $m, PREG_OFFSET_CAPTURE, $pos );
if ( $count === false ) {
$this->throwPregError();
} elseif ( !$count ) {
break;
}
$pos = $m[0][1];
$this->error( "disallowed control character", $pos );
$pos += strlen( $m[0][0] );
}
}
}
|
[
"protected",
"function",
"preprocess",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"preprocessed",
"||",
"$",
"this",
"->",
"skipPreprocess",
")",
"{",
"return",
";",
"}",
"// Normalize line endings",
"if",
"(",
"strcspn",
"(",
"$",
"this",
"->",
"text",
",",
"\"\\r\"",
")",
"!==",
"strlen",
"(",
"$",
"this",
"->",
"text",
")",
")",
"{",
"$",
"this",
"->",
"text",
"=",
"preg_replace",
"(",
"'/\\r\\n?/'",
",",
"\"\\n\"",
",",
"$",
"this",
"->",
"text",
")",
";",
"$",
"this",
"->",
"length",
"=",
"strlen",
"(",
"$",
"this",
"->",
"text",
")",
";",
"}",
"// Raise parse errors for any control characters",
"static",
"$",
"re",
";",
"if",
"(",
"$",
"re",
"===",
"null",
")",
"{",
"// Note that we deliberately do not use the 'u' flag on the",
"// regexp below, as that bypasses the PCRE JIT. Instead we",
"// rewrite character classes containing codepoints which",
"// require more than one UTF-8 byte as alternations.",
"$",
"re",
"=",
"'/['",
".",
"// \"C0 controls\" (u0000 - u001F) but not",
"// \"ASCII whitespace\" (u0009, u000A, u000C, u000D, u0020) or",
"// NULL (u0000)",
"// https://infra.spec.whatwg.org/#c0-control",
"// https://infra.spec.whatwg.org/#ascii-whitespace",
"'\\x{0001}-\\x{0008}'",
".",
"'\\x{000B}'",
".",
"'\\x{000E}-\\x{001F}'",
".",
"// \"Controls\" other than C0 controls (u007F - u009F)",
"// https://infra.spec.whatwg.org/#control",
"'\\x{007F}]|'",
".",
"// (We can't use character classes above u007F)",
"\"\\u{0080}|\\u{0081}|\\u{0082}|\\u{0083}|\"",
".",
"\"\\u{0084}|\\u{0085}|\\u{0086}|\\u{0087}|\"",
".",
"\"\\u{0088}|\\u{0089}|\\u{008A}|\\u{008B}|\"",
".",
"\"\\u{008C}|\\u{008D}|\\u{008E}|\\u{008F}|\"",
".",
"\"\\u{0090}|\\u{0091}|\\u{0092}|\\u{0093}|\"",
".",
"\"\\u{0094}|\\u{0095}|\\u{0096}|\\u{0097}|\"",
".",
"\"\\u{0098}|\\u{0099}|\\u{009A}|\\u{009B}|\"",
".",
"\"\\u{009C}|\\u{009D}|\\u{009E}|\\u{009F}|\"",
".",
"// HTML spec calls these \"noncharacters\"",
"// https://infra.spec.whatwg.org/#noncharacter",
"\"\\u{FDD0}|\\u{FDD1}|\\u{FDD2}|\\u{FDD3}|\"",
".",
"\"\\u{FDD4}|\\u{FDD5}|\\u{FDD6}|\\u{FDD7}|\"",
".",
"\"\\u{FDD8}|\\u{FDD9}|\\u{FDDA}|\\u{FDDB}|\"",
".",
"\"\\u{FDDC}|\\u{FDDD}|\\u{FDDE}|\\u{FDDF}|\"",
".",
"\"\\u{FDE0}|\\u{FDE1}|\\u{FDE2}|\\u{FDE3}|\"",
".",
"\"\\u{FDE4}|\\u{FDE5}|\\u{FDE6}|\\u{FDE7}|\"",
".",
"\"\\u{FDE8}|\\u{FDE9}|\\u{FDEA}|\\u{FDEB}|\"",
".",
"\"\\u{FDEC}|\\u{FDED}|\\u{FDEE}|\\u{FDEF}|\"",
".",
"\"\\u{FFFE}|\\u{FFFF}|\"",
".",
"\"\\u{1FFFE}|\\u{1FFFF}|\"",
".",
"\"\\u{2FFFE}|\\u{2FFFF}|\"",
".",
"\"\\u{3FFFE}|\\u{3FFFF}|\"",
".",
"\"\\u{4FFFE}|\\u{4FFFF}|\"",
".",
"\"\\u{5FFFE}|\\u{5FFFF}|\"",
".",
"\"\\u{6FFFE}|\\u{6FFFF}|\"",
".",
"\"\\u{7FFFE}|\\u{7FFFF}|\"",
".",
"\"\\u{8FFFE}|\\u{8FFFF}|\"",
".",
"\"\\u{9FFFE}|\\u{9FFFF}|\"",
".",
"\"\\u{AFFFE}|\\u{AFFFF}|\"",
".",
"\"\\u{BFFFE}|\\u{BFFFF}|\"",
".",
"\"\\u{CFFFE}|\\u{CFFFF}|\"",
".",
"\"\\u{DFFFE}|\\u{DFFFF}|\"",
".",
"\"\\u{EFFFE}|\\u{EFFFF}|\"",
".",
"\"\\u{FFFFE}|\\u{FFFFF}|\"",
".",
"\"\\u{10FFFE}|\\u{10FFFF}/S\"",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"ignoreErrors",
")",
"{",
"$",
"pos",
"=",
"0",
";",
"while",
"(",
"$",
"pos",
"<",
"$",
"this",
"->",
"length",
")",
"{",
"$",
"count",
"=",
"preg_match",
"(",
"$",
"re",
",",
"$",
"this",
"->",
"text",
",",
"$",
"m",
",",
"PREG_OFFSET_CAPTURE",
",",
"$",
"pos",
")",
";",
"if",
"(",
"$",
"count",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"throwPregError",
"(",
")",
";",
"}",
"elseif",
"(",
"!",
"$",
"count",
")",
"{",
"break",
";",
"}",
"$",
"pos",
"=",
"$",
"m",
"[",
"0",
"]",
"[",
"1",
"]",
";",
"$",
"this",
"->",
"error",
"(",
"\"disallowed control character\"",
",",
"$",
"pos",
")",
";",
"$",
"pos",
"+=",
"strlen",
"(",
"$",
"m",
"[",
"0",
"]",
"[",
"0",
"]",
")",
";",
"}",
"}",
"}"
] |
Preprocess the input text, if it hasn't been done already.
|
[
"Preprocess",
"the",
"input",
"text",
"if",
"it",
"hasn",
"t",
"been",
"done",
"already",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L265-L346
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.interpretCommentMatches
|
protected function interpretCommentMatches( $m ) {
$outerStart = $m[0][1];
$outerLength = strlen( $m[0][0] );
$innerStart = $outerStart + strlen( '<!--' );
$innerLength = isset( $m[self::MD_COMMENT_INNER] ) ? strlen( $m[self::MD_COMMENT_INNER][0] ) : 0;
$contents = $innerLength ? $m[self::MD_COMMENT_INNER][0] : '';
if ( $m[0][0] === '<!-->' || $m[0][0] === '<!--->' ) {
// These are special cases in the comment start state
$this->error( 'not enough dashes in empty comment', $outerStart );
$this->listener->comment( '', $outerStart, $outerLength );
return;
}
if ( !$this->ignoreNulls ) {
$contents = $this->handleNulls( $contents, $innerStart );
}
$close = $m[self::MD_COMMENT_END][0];
$closePos = $m[self::MD_COMMENT_END][1];
if ( !$this->ignoreErrors ) {
if ( $close === '--!>' ) {
$this->error( 'invalid comment end bang', $closePos );
} elseif ( $close === '-' || $close === '--' || $close === '--!' ) {
$this->error( 'EOF part way through comment close', $closePos );
} elseif ( $close === '' ) {
$this->error( 'EOF in comment', $closePos );
}
$dashSearchLength = $innerLength;
while ( $dashSearchLength > 0 && $contents[$dashSearchLength - 1] === '-' ) {
$this->error( 'invalid extra dash at comment end',
$innerStart + $dashSearchLength - 1 );
$dashSearchLength--;
}
$offset = 0;
while ( $offset !== false && $offset < $dashSearchLength ) {
$offset = strpos( $contents, '--', $offset );
if ( $offset !== false ) {
$this->error( 'bare "--" found in comment', $innerStart + $offset );
$offset += 2;
}
}
}
$this->listener->comment( $contents, $outerStart, $outerLength );
}
|
php
|
protected function interpretCommentMatches( $m ) {
$outerStart = $m[0][1];
$outerLength = strlen( $m[0][0] );
$innerStart = $outerStart + strlen( '<!--' );
$innerLength = isset( $m[self::MD_COMMENT_INNER] ) ? strlen( $m[self::MD_COMMENT_INNER][0] ) : 0;
$contents = $innerLength ? $m[self::MD_COMMENT_INNER][0] : '';
if ( $m[0][0] === '<!-->' || $m[0][0] === '<!--->' ) {
// These are special cases in the comment start state
$this->error( 'not enough dashes in empty comment', $outerStart );
$this->listener->comment( '', $outerStart, $outerLength );
return;
}
if ( !$this->ignoreNulls ) {
$contents = $this->handleNulls( $contents, $innerStart );
}
$close = $m[self::MD_COMMENT_END][0];
$closePos = $m[self::MD_COMMENT_END][1];
if ( !$this->ignoreErrors ) {
if ( $close === '--!>' ) {
$this->error( 'invalid comment end bang', $closePos );
} elseif ( $close === '-' || $close === '--' || $close === '--!' ) {
$this->error( 'EOF part way through comment close', $closePos );
} elseif ( $close === '' ) {
$this->error( 'EOF in comment', $closePos );
}
$dashSearchLength = $innerLength;
while ( $dashSearchLength > 0 && $contents[$dashSearchLength - 1] === '-' ) {
$this->error( 'invalid extra dash at comment end',
$innerStart + $dashSearchLength - 1 );
$dashSearchLength--;
}
$offset = 0;
while ( $offset !== false && $offset < $dashSearchLength ) {
$offset = strpos( $contents, '--', $offset );
if ( $offset !== false ) {
$this->error( 'bare "--" found in comment', $innerStart + $offset );
$offset += 2;
}
}
}
$this->listener->comment( $contents, $outerStart, $outerLength );
}
|
[
"protected",
"function",
"interpretCommentMatches",
"(",
"$",
"m",
")",
"{",
"$",
"outerStart",
"=",
"$",
"m",
"[",
"0",
"]",
"[",
"1",
"]",
";",
"$",
"outerLength",
"=",
"strlen",
"(",
"$",
"m",
"[",
"0",
"]",
"[",
"0",
"]",
")",
";",
"$",
"innerStart",
"=",
"$",
"outerStart",
"+",
"strlen",
"(",
"'<!--'",
")",
";",
"$",
"innerLength",
"=",
"isset",
"(",
"$",
"m",
"[",
"self",
"::",
"MD_COMMENT_INNER",
"]",
")",
"?",
"strlen",
"(",
"$",
"m",
"[",
"self",
"::",
"MD_COMMENT_INNER",
"]",
"[",
"0",
"]",
")",
":",
"0",
";",
"$",
"contents",
"=",
"$",
"innerLength",
"?",
"$",
"m",
"[",
"self",
"::",
"MD_COMMENT_INNER",
"]",
"[",
"0",
"]",
":",
"''",
";",
"if",
"(",
"$",
"m",
"[",
"0",
"]",
"[",
"0",
"]",
"===",
"'<!-->'",
"||",
"$",
"m",
"[",
"0",
"]",
"[",
"0",
"]",
"===",
"'<!--->'",
")",
"{",
"// These are special cases in the comment start state",
"$",
"this",
"->",
"error",
"(",
"'not enough dashes in empty comment'",
",",
"$",
"outerStart",
")",
";",
"$",
"this",
"->",
"listener",
"->",
"comment",
"(",
"''",
",",
"$",
"outerStart",
",",
"$",
"outerLength",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"ignoreNulls",
")",
"{",
"$",
"contents",
"=",
"$",
"this",
"->",
"handleNulls",
"(",
"$",
"contents",
",",
"$",
"innerStart",
")",
";",
"}",
"$",
"close",
"=",
"$",
"m",
"[",
"self",
"::",
"MD_COMMENT_END",
"]",
"[",
"0",
"]",
";",
"$",
"closePos",
"=",
"$",
"m",
"[",
"self",
"::",
"MD_COMMENT_END",
"]",
"[",
"1",
"]",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"ignoreErrors",
")",
"{",
"if",
"(",
"$",
"close",
"===",
"'--!>'",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"'invalid comment end bang'",
",",
"$",
"closePos",
")",
";",
"}",
"elseif",
"(",
"$",
"close",
"===",
"'-'",
"||",
"$",
"close",
"===",
"'--'",
"||",
"$",
"close",
"===",
"'--!'",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"'EOF part way through comment close'",
",",
"$",
"closePos",
")",
";",
"}",
"elseif",
"(",
"$",
"close",
"===",
"''",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"'EOF in comment'",
",",
"$",
"closePos",
")",
";",
"}",
"$",
"dashSearchLength",
"=",
"$",
"innerLength",
";",
"while",
"(",
"$",
"dashSearchLength",
">",
"0",
"&&",
"$",
"contents",
"[",
"$",
"dashSearchLength",
"-",
"1",
"]",
"===",
"'-'",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"'invalid extra dash at comment end'",
",",
"$",
"innerStart",
"+",
"$",
"dashSearchLength",
"-",
"1",
")",
";",
"$",
"dashSearchLength",
"--",
";",
"}",
"$",
"offset",
"=",
"0",
";",
"while",
"(",
"$",
"offset",
"!==",
"false",
"&&",
"$",
"offset",
"<",
"$",
"dashSearchLength",
")",
"{",
"$",
"offset",
"=",
"strpos",
"(",
"$",
"contents",
",",
"'--'",
",",
"$",
"offset",
")",
";",
"if",
"(",
"$",
"offset",
"!==",
"false",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"'bare \"--\" found in comment'",
",",
"$",
"innerStart",
"+",
"$",
"offset",
")",
";",
"$",
"offset",
"+=",
"2",
";",
"}",
"}",
"}",
"$",
"this",
"->",
"listener",
"->",
"comment",
"(",
"$",
"contents",
",",
"$",
"outerStart",
",",
"$",
"outerLength",
")",
";",
"}"
] |
Interpret the data state match results for a detected comment, and emit
events as appropriate.
@param array $m The match array
|
[
"Interpret",
"the",
"data",
"state",
"match",
"results",
"for",
"a",
"detected",
"comment",
"and",
"emit",
"events",
"as",
"appropriate",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L674-L721
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.handleNulls
|
protected function handleNulls( $text, $sourcePos ) {
if ( $this->ignoreNulls ) {
return $text;
}
if ( !$this->ignoreErrors ) {
$offset = 0;
while ( true ) {
$nullPos = strpos( $text, "\0", $offset );
if ( $nullPos === false ) {
break;
}
$this->error( "replaced null character", $sourcePos + $nullPos );
if ( $nullPos < strlen( $text ) - 1 ) {
$offset = $nullPos + 1;
} else {
break;
}
}
}
return str_replace( "\0", self::REPLACEMENT_CHAR, $text );
}
|
php
|
protected function handleNulls( $text, $sourcePos ) {
if ( $this->ignoreNulls ) {
return $text;
}
if ( !$this->ignoreErrors ) {
$offset = 0;
while ( true ) {
$nullPos = strpos( $text, "\0", $offset );
if ( $nullPos === false ) {
break;
}
$this->error( "replaced null character", $sourcePos + $nullPos );
if ( $nullPos < strlen( $text ) - 1 ) {
$offset = $nullPos + 1;
} else {
break;
}
}
}
return str_replace( "\0", self::REPLACEMENT_CHAR, $text );
}
|
[
"protected",
"function",
"handleNulls",
"(",
"$",
"text",
",",
"$",
"sourcePos",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"ignoreNulls",
")",
"{",
"return",
"$",
"text",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"ignoreErrors",
")",
"{",
"$",
"offset",
"=",
"0",
";",
"while",
"(",
"true",
")",
"{",
"$",
"nullPos",
"=",
"strpos",
"(",
"$",
"text",
",",
"\"\\0\"",
",",
"$",
"offset",
")",
";",
"if",
"(",
"$",
"nullPos",
"===",
"false",
")",
"{",
"break",
";",
"}",
"$",
"this",
"->",
"error",
"(",
"\"replaced null character\"",
",",
"$",
"sourcePos",
"+",
"$",
"nullPos",
")",
";",
"if",
"(",
"$",
"nullPos",
"<",
"strlen",
"(",
"$",
"text",
")",
"-",
"1",
")",
"{",
"$",
"offset",
"=",
"$",
"nullPos",
"+",
"1",
";",
"}",
"else",
"{",
"break",
";",
"}",
"}",
"}",
"return",
"str_replace",
"(",
"\"\\0\"",
",",
"self",
"::",
"REPLACEMENT_CHAR",
",",
"$",
"text",
")",
";",
"}"
] |
Generic helper for all those points in the spec where U+0000 needs to be
replaced with U+FFFD with a parse error issued.
@param string $text The text to be converted
@param int $sourcePos The input byte offset from which $text was
extracted, for error position reporting.
@return string The converted text
|
[
"Generic",
"helper",
"for",
"all",
"those",
"points",
"in",
"the",
"spec",
"where",
"U",
"+",
"0000",
"needs",
"to",
"be",
"replaced",
"with",
"U",
"+",
"FFFD",
"with",
"a",
"parse",
"error",
"issued",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L853-L873
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.handleAsciiErrors
|
protected function handleAsciiErrors( $mask, $text, $offset, $length, $sourcePos ) {
while ( $length > 0 ) {
$validLength = strcspn( $text, $mask, $offset, $length );
$offset += $validLength;
$length -= $validLength;
if ( $length <= 0 ) {
break;
}
$char = $text[$offset];
$codepoint = ord( $char );
if ( $codepoint < 0x20 || $codepoint >= 0x7f ) {
$this->error( sprintf( 'unexpected U+00%02X', $codepoint ), $offset + $sourcePos );
} else {
$this->error( "unexpected \"$char\"", $offset + $sourcePos );
}
$offset++;
$length--;
}
}
|
php
|
protected function handleAsciiErrors( $mask, $text, $offset, $length, $sourcePos ) {
while ( $length > 0 ) {
$validLength = strcspn( $text, $mask, $offset, $length );
$offset += $validLength;
$length -= $validLength;
if ( $length <= 0 ) {
break;
}
$char = $text[$offset];
$codepoint = ord( $char );
if ( $codepoint < 0x20 || $codepoint >= 0x7f ) {
$this->error( sprintf( 'unexpected U+00%02X', $codepoint ), $offset + $sourcePos );
} else {
$this->error( "unexpected \"$char\"", $offset + $sourcePos );
}
$offset++;
$length--;
}
}
|
[
"protected",
"function",
"handleAsciiErrors",
"(",
"$",
"mask",
",",
"$",
"text",
",",
"$",
"offset",
",",
"$",
"length",
",",
"$",
"sourcePos",
")",
"{",
"while",
"(",
"$",
"length",
">",
"0",
")",
"{",
"$",
"validLength",
"=",
"strcspn",
"(",
"$",
"text",
",",
"$",
"mask",
",",
"$",
"offset",
",",
"$",
"length",
")",
";",
"$",
"offset",
"+=",
"$",
"validLength",
";",
"$",
"length",
"-=",
"$",
"validLength",
";",
"if",
"(",
"$",
"length",
"<=",
"0",
")",
"{",
"break",
";",
"}",
"$",
"char",
"=",
"$",
"text",
"[",
"$",
"offset",
"]",
";",
"$",
"codepoint",
"=",
"ord",
"(",
"$",
"char",
")",
";",
"if",
"(",
"$",
"codepoint",
"<",
"0x20",
"||",
"$",
"codepoint",
">=",
"0x7f",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"sprintf",
"(",
"'unexpected U+00%02X'",
",",
"$",
"codepoint",
")",
",",
"$",
"offset",
"+",
"$",
"sourcePos",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"error",
"(",
"\"unexpected \\\"$char\\\"\"",
",",
"$",
"offset",
"+",
"$",
"sourcePos",
")",
";",
"}",
"$",
"offset",
"++",
";",
"$",
"length",
"--",
";",
"}",
"}"
] |
Generic helper for points in the spec which say that an error should
be issued when certain ASCII characters are seen, with no other action
taken.
@param string $mask Mask for strcspn
@param string $text The input text
@param int $offset The start of the range within $text to search
@param int $length The length of the range within $text to search
@param int $sourcePos The offset within the input text corresponding
to $text, for error position reporting.
|
[
"Generic",
"helper",
"for",
"points",
"in",
"the",
"spec",
"which",
"say",
"that",
"an",
"error",
"should",
"be",
"issued",
"when",
"certain",
"ASCII",
"characters",
"are",
"seen",
"with",
"no",
"other",
"action",
"taken",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L887-L905
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.emitDataRange
|
protected function emitDataRange( $pos, $length, $isSimple = false, $hasSimpleRefs = false ) {
if ( $length === 0 ) {
return;
}
if ( $this->ignoreCharRefs && $this->ignoreNulls && $this->ignoreErrors ) {
// Pretend this data range doesn't contain < \0 or &
$isSimple = true;
}
if ( $isSimple ) {
$this->listener->characters( $this->text, $pos, $length, $pos, $length );
} else {
if ( !$this->ignoreErrors ) {
// Any bare "<" in a data state text node is a parse error.
// Uniquely to the data state, nulls are just flagged as errors
// and passed through, they are not replaced.
$this->handleAsciiErrors( "<\0", $this->text, $pos, $length, 0 );
}
$text = substr( $this->text, $pos, $length );
if ( $hasSimpleRefs ) {
$text = strtr( $text, self::$commonEntities );
} else {
$text = $this->handleCharRefs( $text, $pos );
}
$this->listener->characters( $text, 0, strlen( $text ), $pos, $length );
}
}
|
php
|
protected function emitDataRange( $pos, $length, $isSimple = false, $hasSimpleRefs = false ) {
if ( $length === 0 ) {
return;
}
if ( $this->ignoreCharRefs && $this->ignoreNulls && $this->ignoreErrors ) {
// Pretend this data range doesn't contain < \0 or &
$isSimple = true;
}
if ( $isSimple ) {
$this->listener->characters( $this->text, $pos, $length, $pos, $length );
} else {
if ( !$this->ignoreErrors ) {
// Any bare "<" in a data state text node is a parse error.
// Uniquely to the data state, nulls are just flagged as errors
// and passed through, they are not replaced.
$this->handleAsciiErrors( "<\0", $this->text, $pos, $length, 0 );
}
$text = substr( $this->text, $pos, $length );
if ( $hasSimpleRefs ) {
$text = strtr( $text, self::$commonEntities );
} else {
$text = $this->handleCharRefs( $text, $pos );
}
$this->listener->characters( $text, 0, strlen( $text ), $pos, $length );
}
}
|
[
"protected",
"function",
"emitDataRange",
"(",
"$",
"pos",
",",
"$",
"length",
",",
"$",
"isSimple",
"=",
"false",
",",
"$",
"hasSimpleRefs",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"ignoreCharRefs",
"&&",
"$",
"this",
"->",
"ignoreNulls",
"&&",
"$",
"this",
"->",
"ignoreErrors",
")",
"{",
"// Pretend this data range doesn't contain < \\0 or &",
"$",
"isSimple",
"=",
"true",
";",
"}",
"if",
"(",
"$",
"isSimple",
")",
"{",
"$",
"this",
"->",
"listener",
"->",
"characters",
"(",
"$",
"this",
"->",
"text",
",",
"$",
"pos",
",",
"$",
"length",
",",
"$",
"pos",
",",
"$",
"length",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"ignoreErrors",
")",
"{",
"// Any bare \"<\" in a data state text node is a parse error.",
"// Uniquely to the data state, nulls are just flagged as errors",
"// and passed through, they are not replaced.",
"$",
"this",
"->",
"handleAsciiErrors",
"(",
"\"<\\0\"",
",",
"$",
"this",
"->",
"text",
",",
"$",
"pos",
",",
"$",
"length",
",",
"0",
")",
";",
"}",
"$",
"text",
"=",
"substr",
"(",
"$",
"this",
"->",
"text",
",",
"$",
"pos",
",",
"$",
"length",
")",
";",
"if",
"(",
"$",
"hasSimpleRefs",
")",
"{",
"$",
"text",
"=",
"strtr",
"(",
"$",
"text",
",",
"self",
"::",
"$",
"commonEntities",
")",
";",
"}",
"else",
"{",
"$",
"text",
"=",
"$",
"this",
"->",
"handleCharRefs",
"(",
"$",
"text",
",",
"$",
"pos",
")",
";",
"}",
"$",
"this",
"->",
"listener",
"->",
"characters",
"(",
"$",
"text",
",",
"0",
",",
"strlen",
"(",
"$",
"text",
")",
",",
"$",
"pos",
",",
"$",
"length",
")",
";",
"}",
"}"
] |
Emit a range of the input text as a character token, and emit related
errors, with validity rules as per the data state.
@param int $pos Offset within the input text
@param int $length The length of the range
@param bool $isSimple True if you know that the data range does not
contain < \0 or &; false is safe if you're not sure
@param bool $hasSimpleRefs True if you know that any character
references are semicolon terminated and in the list of $commonEntities;
false is safe if you're not sure
|
[
"Emit",
"a",
"range",
"of",
"the",
"input",
"text",
"as",
"a",
"character",
"token",
"and",
"emit",
"related",
"errors",
"with",
"validity",
"rules",
"as",
"per",
"the",
"data",
"state",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L1095-L1121
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.emitCdataRange
|
protected function emitCdataRange( $innerPos, $innerLength, $outerPos, $outerLength ) {
$this->listener->characters( $this->text, $innerPos, $innerLength,
$outerPos, $outerLength );
}
|
php
|
protected function emitCdataRange( $innerPos, $innerLength, $outerPos, $outerLength ) {
$this->listener->characters( $this->text, $innerPos, $innerLength,
$outerPos, $outerLength );
}
|
[
"protected",
"function",
"emitCdataRange",
"(",
"$",
"innerPos",
",",
"$",
"innerLength",
",",
"$",
"outerPos",
",",
"$",
"outerLength",
")",
"{",
"$",
"this",
"->",
"listener",
"->",
"characters",
"(",
"$",
"this",
"->",
"text",
",",
"$",
"innerPos",
",",
"$",
"innerLength",
",",
"$",
"outerPos",
",",
"$",
"outerLength",
")",
";",
"}"
] |
Emit a range of characters from the input text, with validity rules as
per the CDATA section state.
@param int $innerPos The position after the <![CDATA[
@param int $innerLength The length of the string not including the terminating ]]>
@param int $outerPos The position of the start of the <!CDATA[
@param int $outerLength The length of the whole input region being emitted
|
[
"Emit",
"a",
"range",
"of",
"characters",
"from",
"the",
"input",
"text",
"with",
"validity",
"rules",
"as",
"per",
"the",
"CDATA",
"section",
"state",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L1132-L1135
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.emitRawTextRange
|
protected function emitRawTextRange( $ignoreCharRefs, $pos, $length ) {
if ( $length === 0 ) {
return;
}
$ignoreCharRefs = $ignoreCharRefs || $this->ignoreCharRefs;
if ( $ignoreCharRefs && $this->ignoreNulls ) {
$this->listener->characters( $this->text, $pos, $length, $pos, $length );
} else {
$text = substr( $this->text, $pos, $length );
if ( !$ignoreCharRefs ) {
$text = $this->handleCharRefs( $text, $pos );
}
$text = $this->handleNulls( $text, $pos );
$this->listener->characters( $text, 0, strlen( $text ), $pos, $length );
}
}
|
php
|
protected function emitRawTextRange( $ignoreCharRefs, $pos, $length ) {
if ( $length === 0 ) {
return;
}
$ignoreCharRefs = $ignoreCharRefs || $this->ignoreCharRefs;
if ( $ignoreCharRefs && $this->ignoreNulls ) {
$this->listener->characters( $this->text, $pos, $length, $pos, $length );
} else {
$text = substr( $this->text, $pos, $length );
if ( !$ignoreCharRefs ) {
$text = $this->handleCharRefs( $text, $pos );
}
$text = $this->handleNulls( $text, $pos );
$this->listener->characters( $text, 0, strlen( $text ), $pos, $length );
}
}
|
[
"protected",
"function",
"emitRawTextRange",
"(",
"$",
"ignoreCharRefs",
",",
"$",
"pos",
",",
"$",
"length",
")",
"{",
"if",
"(",
"$",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"$",
"ignoreCharRefs",
"=",
"$",
"ignoreCharRefs",
"||",
"$",
"this",
"->",
"ignoreCharRefs",
";",
"if",
"(",
"$",
"ignoreCharRefs",
"&&",
"$",
"this",
"->",
"ignoreNulls",
")",
"{",
"$",
"this",
"->",
"listener",
"->",
"characters",
"(",
"$",
"this",
"->",
"text",
",",
"$",
"pos",
",",
"$",
"length",
",",
"$",
"pos",
",",
"$",
"length",
")",
";",
"}",
"else",
"{",
"$",
"text",
"=",
"substr",
"(",
"$",
"this",
"->",
"text",
",",
"$",
"pos",
",",
"$",
"length",
")",
";",
"if",
"(",
"!",
"$",
"ignoreCharRefs",
")",
"{",
"$",
"text",
"=",
"$",
"this",
"->",
"handleCharRefs",
"(",
"$",
"text",
",",
"$",
"pos",
")",
";",
"}",
"$",
"text",
"=",
"$",
"this",
"->",
"handleNulls",
"(",
"$",
"text",
",",
"$",
"pos",
")",
";",
"$",
"this",
"->",
"listener",
"->",
"characters",
"(",
"$",
"text",
",",
"0",
",",
"strlen",
"(",
"$",
"text",
")",
",",
"$",
"pos",
",",
"$",
"length",
")",
";",
"}",
"}"
] |
Emit a range of characters from the input text, either from RCDATA,
RAWTEXT, script data or PLAINTEXT. The only difference between these
states is whether or not character references are expanded, so we take
that as a parameter.
@param bool $ignoreCharRefs
@param int $pos The input position
@param int $length The length of the range to be emitted
|
[
"Emit",
"a",
"range",
"of",
"characters",
"from",
"the",
"input",
"text",
"either",
"from",
"RCDATA",
"RAWTEXT",
"script",
"data",
"or",
"PLAINTEXT",
".",
"The",
"only",
"difference",
"between",
"these",
"states",
"is",
"whether",
"or",
"not",
"character",
"references",
"are",
"expanded",
"so",
"we",
"take",
"that",
"as",
"a",
"parameter",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L1147-L1162
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.textElementState
|
protected function textElementState( $ignoreCharRefs ) {
if ( $this->appropriateEndTag === null ) {
$this->emitRawTextRange( $ignoreCharRefs, $this->pos, $this->length - $this->pos );
$this->pos = $this->length;
return self::STATE_EOF;
}
$re = "~</
{$this->appropriateEndTag}
# Assert that the end tag name state is exited appropriately,
# since the anything else case leads to the tag being treated as
# a literal
(?=[\t\n\f />])
~ix";
do {
$count = preg_match( $re, $this->text, $m, PREG_OFFSET_CAPTURE, $this->pos );
if ( $count === false ) {
$this->throwPregError();
} elseif ( !$count ) {
// Text runs to end
$this->emitRawTextRange( $ignoreCharRefs, $this->pos, $this->length - $this->pos );
$this->pos = $this->length;
return self::STATE_EOF;
}
$startPos = $m[0][1];
// Emit text before tag
$this->emitRawTextRange( $ignoreCharRefs, $this->pos, $startPos - $this->pos );
$matchLength = strlen( $m[0][0] );
$this->pos = $startPos + $matchLength;
$nextState = $this->handleAttribsAndClose( self::STATE_RCDATA,
$this->appropriateEndTag, true, $startPos );
} while ( $nextState === self::STATE_RCDATA );
return $nextState;
}
|
php
|
protected function textElementState( $ignoreCharRefs ) {
if ( $this->appropriateEndTag === null ) {
$this->emitRawTextRange( $ignoreCharRefs, $this->pos, $this->length - $this->pos );
$this->pos = $this->length;
return self::STATE_EOF;
}
$re = "~</
{$this->appropriateEndTag}
# Assert that the end tag name state is exited appropriately,
# since the anything else case leads to the tag being treated as
# a literal
(?=[\t\n\f />])
~ix";
do {
$count = preg_match( $re, $this->text, $m, PREG_OFFSET_CAPTURE, $this->pos );
if ( $count === false ) {
$this->throwPregError();
} elseif ( !$count ) {
// Text runs to end
$this->emitRawTextRange( $ignoreCharRefs, $this->pos, $this->length - $this->pos );
$this->pos = $this->length;
return self::STATE_EOF;
}
$startPos = $m[0][1];
// Emit text before tag
$this->emitRawTextRange( $ignoreCharRefs, $this->pos, $startPos - $this->pos );
$matchLength = strlen( $m[0][0] );
$this->pos = $startPos + $matchLength;
$nextState = $this->handleAttribsAndClose( self::STATE_RCDATA,
$this->appropriateEndTag, true, $startPos );
} while ( $nextState === self::STATE_RCDATA );
return $nextState;
}
|
[
"protected",
"function",
"textElementState",
"(",
"$",
"ignoreCharRefs",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"appropriateEndTag",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"emitRawTextRange",
"(",
"$",
"ignoreCharRefs",
",",
"$",
"this",
"->",
"pos",
",",
"$",
"this",
"->",
"length",
"-",
"$",
"this",
"->",
"pos",
")",
";",
"$",
"this",
"->",
"pos",
"=",
"$",
"this",
"->",
"length",
";",
"return",
"self",
"::",
"STATE_EOF",
";",
"}",
"$",
"re",
"=",
"\"~</\n\t\t\t{$this->appropriateEndTag}\n\t\t\t# Assert that the end tag name state is exited appropriately,\n\t\t\t# since the anything else case leads to the tag being treated as\n\t\t\t# a literal\n\t\t\t(?=[\\t\\n\\f />])\n\t\t\t~ix\"",
";",
"do",
"{",
"$",
"count",
"=",
"preg_match",
"(",
"$",
"re",
",",
"$",
"this",
"->",
"text",
",",
"$",
"m",
",",
"PREG_OFFSET_CAPTURE",
",",
"$",
"this",
"->",
"pos",
")",
";",
"if",
"(",
"$",
"count",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"throwPregError",
"(",
")",
";",
"}",
"elseif",
"(",
"!",
"$",
"count",
")",
"{",
"// Text runs to end",
"$",
"this",
"->",
"emitRawTextRange",
"(",
"$",
"ignoreCharRefs",
",",
"$",
"this",
"->",
"pos",
",",
"$",
"this",
"->",
"length",
"-",
"$",
"this",
"->",
"pos",
")",
";",
"$",
"this",
"->",
"pos",
"=",
"$",
"this",
"->",
"length",
";",
"return",
"self",
"::",
"STATE_EOF",
";",
"}",
"$",
"startPos",
"=",
"$",
"m",
"[",
"0",
"]",
"[",
"1",
"]",
";",
"// Emit text before tag",
"$",
"this",
"->",
"emitRawTextRange",
"(",
"$",
"ignoreCharRefs",
",",
"$",
"this",
"->",
"pos",
",",
"$",
"startPos",
"-",
"$",
"this",
"->",
"pos",
")",
";",
"$",
"matchLength",
"=",
"strlen",
"(",
"$",
"m",
"[",
"0",
"]",
"[",
"0",
"]",
")",
";",
"$",
"this",
"->",
"pos",
"=",
"$",
"startPos",
"+",
"$",
"matchLength",
";",
"$",
"nextState",
"=",
"$",
"this",
"->",
"handleAttribsAndClose",
"(",
"self",
"::",
"STATE_RCDATA",
",",
"$",
"this",
"->",
"appropriateEndTag",
",",
"true",
",",
"$",
"startPos",
")",
";",
"}",
"while",
"(",
"$",
"nextState",
"===",
"self",
"::",
"STATE_RCDATA",
")",
";",
"return",
"$",
"nextState",
";",
"}"
] |
The entry point for the RCDATA and RAWTEXT states.
@param bool $ignoreCharRefs True to ignore character references regardless
of configuration, false to respect the configuration.
@return int The next state index
|
[
"The",
"entry",
"point",
"for",
"the",
"RCDATA",
"and",
"RAWTEXT",
"states",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L1170-L1207
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.handleAttribsAndClose
|
protected function handleAttribsAndClose( $state, $tagName, $isEndTag, $startPos ) {
$attribStartPos = $this->pos;
$attribs = $this->consumeAttribs();
$pos = $this->pos;
// Literal characters are emitted on EOF or "anything else" from the
// end tag substates of the text states.
// (spec ref 8.2.4 sections 11-19, 25-27)
$isDataState = $state === self::STATE_DATA;
$isLiteral = $attribStartPos === $pos && !$isDataState;
if ( $pos >= $this->length ) {
$this->error( 'unexpected end of file inside tag' );
if ( $isLiteral ) {
$this->listener->characters( $this->text,
$startPos, $this->length - $startPos,
$startPos, $this->length - $startPos );
}
return self::STATE_EOF;
}
if ( $isEndTag && !$this->ignoreErrors && $attribs->count() ) {
$this->error( 'end tag has an attribute' );
}
if ( $this->text[$pos] === '/' && $this->text[$pos + 1] === '>' ) {
$pos += 2;
$selfClose = true;
} elseif ( $this->text[$pos] === '>' ) {
$pos++;
$selfClose = false;
} elseif ( $isLiteral ) {
$this->listener->characters( $this->text,
$startPos, $attribStartPos - $startPos,
$startPos, $attribStartPos - $startPos );
return $state;
} else {
$this->fatal( 'failed to find an already-matched ">"' );
}
$this->pos = $pos;
if ( $isEndTag ) {
if ( $selfClose ) {
$this->error( 'self-closing end tag' );
}
$this->listener->endTag( $tagName, $startPos, $pos - $startPos );
} else {
$this->listener->startTag( $tagName, $attribs, $selfClose,
$startPos, $pos - $startPos );
}
return self::STATE_DATA;
}
|
php
|
protected function handleAttribsAndClose( $state, $tagName, $isEndTag, $startPos ) {
$attribStartPos = $this->pos;
$attribs = $this->consumeAttribs();
$pos = $this->pos;
// Literal characters are emitted on EOF or "anything else" from the
// end tag substates of the text states.
// (spec ref 8.2.4 sections 11-19, 25-27)
$isDataState = $state === self::STATE_DATA;
$isLiteral = $attribStartPos === $pos && !$isDataState;
if ( $pos >= $this->length ) {
$this->error( 'unexpected end of file inside tag' );
if ( $isLiteral ) {
$this->listener->characters( $this->text,
$startPos, $this->length - $startPos,
$startPos, $this->length - $startPos );
}
return self::STATE_EOF;
}
if ( $isEndTag && !$this->ignoreErrors && $attribs->count() ) {
$this->error( 'end tag has an attribute' );
}
if ( $this->text[$pos] === '/' && $this->text[$pos + 1] === '>' ) {
$pos += 2;
$selfClose = true;
} elseif ( $this->text[$pos] === '>' ) {
$pos++;
$selfClose = false;
} elseif ( $isLiteral ) {
$this->listener->characters( $this->text,
$startPos, $attribStartPos - $startPos,
$startPos, $attribStartPos - $startPos );
return $state;
} else {
$this->fatal( 'failed to find an already-matched ">"' );
}
$this->pos = $pos;
if ( $isEndTag ) {
if ( $selfClose ) {
$this->error( 'self-closing end tag' );
}
$this->listener->endTag( $tagName, $startPos, $pos - $startPos );
} else {
$this->listener->startTag( $tagName, $attribs, $selfClose,
$startPos, $pos - $startPos );
}
return self::STATE_DATA;
}
|
[
"protected",
"function",
"handleAttribsAndClose",
"(",
"$",
"state",
",",
"$",
"tagName",
",",
"$",
"isEndTag",
",",
"$",
"startPos",
")",
"{",
"$",
"attribStartPos",
"=",
"$",
"this",
"->",
"pos",
";",
"$",
"attribs",
"=",
"$",
"this",
"->",
"consumeAttribs",
"(",
")",
";",
"$",
"pos",
"=",
"$",
"this",
"->",
"pos",
";",
"// Literal characters are emitted on EOF or \"anything else\" from the",
"// end tag substates of the text states.",
"// (spec ref 8.2.4 sections 11-19, 25-27)",
"$",
"isDataState",
"=",
"$",
"state",
"===",
"self",
"::",
"STATE_DATA",
";",
"$",
"isLiteral",
"=",
"$",
"attribStartPos",
"===",
"$",
"pos",
"&&",
"!",
"$",
"isDataState",
";",
"if",
"(",
"$",
"pos",
">=",
"$",
"this",
"->",
"length",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"'unexpected end of file inside tag'",
")",
";",
"if",
"(",
"$",
"isLiteral",
")",
"{",
"$",
"this",
"->",
"listener",
"->",
"characters",
"(",
"$",
"this",
"->",
"text",
",",
"$",
"startPos",
",",
"$",
"this",
"->",
"length",
"-",
"$",
"startPos",
",",
"$",
"startPos",
",",
"$",
"this",
"->",
"length",
"-",
"$",
"startPos",
")",
";",
"}",
"return",
"self",
"::",
"STATE_EOF",
";",
"}",
"if",
"(",
"$",
"isEndTag",
"&&",
"!",
"$",
"this",
"->",
"ignoreErrors",
"&&",
"$",
"attribs",
"->",
"count",
"(",
")",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"'end tag has an attribute'",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"text",
"[",
"$",
"pos",
"]",
"===",
"'/'",
"&&",
"$",
"this",
"->",
"text",
"[",
"$",
"pos",
"+",
"1",
"]",
"===",
"'>'",
")",
"{",
"$",
"pos",
"+=",
"2",
";",
"$",
"selfClose",
"=",
"true",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"text",
"[",
"$",
"pos",
"]",
"===",
"'>'",
")",
"{",
"$",
"pos",
"++",
";",
"$",
"selfClose",
"=",
"false",
";",
"}",
"elseif",
"(",
"$",
"isLiteral",
")",
"{",
"$",
"this",
"->",
"listener",
"->",
"characters",
"(",
"$",
"this",
"->",
"text",
",",
"$",
"startPos",
",",
"$",
"attribStartPos",
"-",
"$",
"startPos",
",",
"$",
"startPos",
",",
"$",
"attribStartPos",
"-",
"$",
"startPos",
")",
";",
"return",
"$",
"state",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"fatal",
"(",
"'failed to find an already-matched \">\"'",
")",
";",
"}",
"$",
"this",
"->",
"pos",
"=",
"$",
"pos",
";",
"if",
"(",
"$",
"isEndTag",
")",
"{",
"if",
"(",
"$",
"selfClose",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"'self-closing end tag'",
")",
";",
"}",
"$",
"this",
"->",
"listener",
"->",
"endTag",
"(",
"$",
"tagName",
",",
"$",
"startPos",
",",
"$",
"pos",
"-",
"$",
"startPos",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"listener",
"->",
"startTag",
"(",
"$",
"tagName",
",",
"$",
"attribs",
",",
"$",
"selfClose",
",",
"$",
"startPos",
",",
"$",
"pos",
"-",
"$",
"startPos",
")",
";",
"}",
"return",
"self",
"::",
"STATE_DATA",
";",
"}"
] |
Consume attributes, and the closing bracket which follows attributes.
Emit the appropriate tag event, or in the case of broken attributes in
text states, emit characters.
@param int $state The current state
@param string $tagName The normalized tag name
@param bool $isEndTag True if this is an end tag, false if it is a start tag
@param int $startPos The input position of the start of the current tag.
@return int The next state
|
[
"Consume",
"attributes",
"and",
"the",
"closing",
"bracket",
"which",
"follows",
"attributes",
".",
"Emit",
"the",
"appropriate",
"tag",
"event",
"or",
"in",
"the",
"case",
"of",
"broken",
"attributes",
"in",
"text",
"states",
"emit",
"characters",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L1416-L1465
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.plaintextState
|
protected function plaintextState() {
$this->emitRawTextRange( true, $this->pos, $this->length - $this->pos );
return self::STATE_EOF;
}
|
php
|
protected function plaintextState() {
$this->emitRawTextRange( true, $this->pos, $this->length - $this->pos );
return self::STATE_EOF;
}
|
[
"protected",
"function",
"plaintextState",
"(",
")",
"{",
"$",
"this",
"->",
"emitRawTextRange",
"(",
"true",
",",
"$",
"this",
"->",
"pos",
",",
"$",
"this",
"->",
"length",
"-",
"$",
"this",
"->",
"pos",
")",
";",
"return",
"self",
"::",
"STATE_EOF",
";",
"}"
] |
Process input text in the PLAINTEXT state
@return int The next state index
|
[
"Process",
"input",
"text",
"in",
"the",
"PLAINTEXT",
"state"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L1471-L1474
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.scriptDataState
|
protected function scriptDataState() {
if ( $this->appropriateEndTag === null ) {
$this->pos = $this->length;
return self::STATE_EOF;
}
$re = <<<REGEX
~
(?: # Outer loop start
# Script data state
# Stop iteration if we previously matched an appropriate end tag.
# This is a conditional subpattern: if capture 1 previously
# matched, then run the pattern /$./ which always fails.
(?(1) $. )
.*?
(?:
$ |
(
</ {$this->appropriateEndTag}
# If we hit the "anything else" case in the script data
# end tag name state, don't exit
(?= [\t\n\f />] )
) | # 1. Appropriate end tag
<!--
# Script data escaped dash dash state
# Hyphens at this point are consumed without a state transition
# and so are not part of a comment-end.
-*+
(?: # Inner loop start
# Script data escaped state
.*?
(?:
$ |
# Stop at, but do not consume, comment-close or end tag.
# This causes the inner loop to exit, since restarting the
# inner loop at this input position will cause the loop
# body to match zero characters. Repeating a zero-character
# match causes the repeat to terminate.
(?= --> ) |
(?= </ {$this->appropriateEndTag} [\t\n\f />] ) |
<script [\t\n\f />]
# Script data double escaped state
.*?
(?:
$ |
# Stop at, but do not consume, comment-close
(?= --> ) |
</script [\t\n\f />]
)
)
)*
# Consume the comment close which exited the inner loop, if any
(?: --> )?
)
)*+
~xsiA
REGEX;
do {
$count = preg_match( $re, $this->text, $m, 0, $this->pos );
if ( $count === false ) {
$this->throwPregError();
} elseif ( !$count ) {
$this->fatal( 'unexpected regex failure: this pattern can match zero characters' );
}
$startPos = $this->pos;
$matchLength = strlen( $m[0] );
$endTagLength = isset( $m[1] ) ? strlen( $m[1] ) : 0;
$textLength = $matchLength - $endTagLength;
$this->emitRawTextRange( true, $startPos, $textLength );
$this->pos = $startPos + $matchLength;
$tagStartPos = $startPos + $textLength;
if ( $endTagLength ) {
$nextState = $this->handleAttribsAndClose( self::STATE_SCRIPT_DATA,
$this->appropriateEndTag, true, $tagStartPos );
} else {
$nextState = self::STATE_EOF;
}
} while ( $nextState === self::STATE_SCRIPT_DATA );
return $nextState;
}
|
php
|
protected function scriptDataState() {
if ( $this->appropriateEndTag === null ) {
$this->pos = $this->length;
return self::STATE_EOF;
}
$re = <<<REGEX
~
(?: # Outer loop start
# Script data state
# Stop iteration if we previously matched an appropriate end tag.
# This is a conditional subpattern: if capture 1 previously
# matched, then run the pattern /$./ which always fails.
(?(1) $. )
.*?
(?:
$ |
(
</ {$this->appropriateEndTag}
# If we hit the "anything else" case in the script data
# end tag name state, don't exit
(?= [\t\n\f />] )
) | # 1. Appropriate end tag
<!--
# Script data escaped dash dash state
# Hyphens at this point are consumed without a state transition
# and so are not part of a comment-end.
-*+
(?: # Inner loop start
# Script data escaped state
.*?
(?:
$ |
# Stop at, but do not consume, comment-close or end tag.
# This causes the inner loop to exit, since restarting the
# inner loop at this input position will cause the loop
# body to match zero characters. Repeating a zero-character
# match causes the repeat to terminate.
(?= --> ) |
(?= </ {$this->appropriateEndTag} [\t\n\f />] ) |
<script [\t\n\f />]
# Script data double escaped state
.*?
(?:
$ |
# Stop at, but do not consume, comment-close
(?= --> ) |
</script [\t\n\f />]
)
)
)*
# Consume the comment close which exited the inner loop, if any
(?: --> )?
)
)*+
~xsiA
REGEX;
do {
$count = preg_match( $re, $this->text, $m, 0, $this->pos );
if ( $count === false ) {
$this->throwPregError();
} elseif ( !$count ) {
$this->fatal( 'unexpected regex failure: this pattern can match zero characters' );
}
$startPos = $this->pos;
$matchLength = strlen( $m[0] );
$endTagLength = isset( $m[1] ) ? strlen( $m[1] ) : 0;
$textLength = $matchLength - $endTagLength;
$this->emitRawTextRange( true, $startPos, $textLength );
$this->pos = $startPos + $matchLength;
$tagStartPos = $startPos + $textLength;
if ( $endTagLength ) {
$nextState = $this->handleAttribsAndClose( self::STATE_SCRIPT_DATA,
$this->appropriateEndTag, true, $tagStartPos );
} else {
$nextState = self::STATE_EOF;
}
} while ( $nextState === self::STATE_SCRIPT_DATA );
return $nextState;
}
|
[
"protected",
"function",
"scriptDataState",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"appropriateEndTag",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"pos",
"=",
"$",
"this",
"->",
"length",
";",
"return",
"self",
"::",
"STATE_EOF",
";",
"}",
"$",
"re",
"=",
" <<<REGEX\n~\n\t\t\t(?: # Outer loop start\n\t\t\t\t# Script data state\n\t\t\t\t# Stop iteration if we previously matched an appropriate end tag.\n\t\t\t\t# This is a conditional subpattern: if capture 1 previously\n\t\t\t\t# matched, then run the pattern /$./ which always fails.\n\t\t\t\t(?(1) $. )\n\t\t\t\t.*?\n\t\t\t\t(?:\n\t\t\t\t\t$ |\n\t\t\t\t\t(\n\t\t\t\t\t\t</ {$this->appropriateEndTag}\n\t\t\t\t\t\t# If we hit the \"anything else\" case in the script data\n\t\t\t\t\t\t# end tag name state, don't exit\n\t\t\t\t\t\t(?= [\\t\\n\\f />] )\n\t\t\t\t\t) | # 1. Appropriate end tag\n\t\t\t\t\t<!--\n\t\t\t\t\t# Script data escaped dash dash state\n\t\t\t\t\t# Hyphens at this point are consumed without a state transition\n\t\t\t\t\t# and so are not part of a comment-end.\n\t\t\t\t\t-*+\n\n\t\t\t\t\t(?: # Inner loop start\n\t\t\t\t\t\t# Script data escaped state\n\t\t\t\t\t\t.*?\n\t\t\t\t\t\t(?:\n\t\t\t\t\t\t\t$ |\n\t\t\t\t\t\t\t# Stop at, but do not consume, comment-close or end tag.\n\t\t\t\t\t\t\t# This causes the inner loop to exit, since restarting the\n\t\t\t\t\t\t\t# inner loop at this input position will cause the loop\n\t\t\t\t\t\t\t# body to match zero characters. Repeating a zero-character\n\t\t\t\t\t\t\t# match causes the repeat to terminate.\n\t\t\t\t\t\t\t(?= --> ) |\n\t\t\t\t\t\t\t(?= </ {$this->appropriateEndTag} [\\t\\n\\f />] ) |\n\t\t\t\t\t\t\t<script [\\t\\n\\f />]\n\t\t\t\t\t\t\t# Script data double escaped state\n\t\t\t\t\t\t\t.*?\n\t\t\t\t\t\t\t(?:\n\t\t\t\t\t\t\t\t$ |\n\t\t\t\t\t\t\t\t# Stop at, but do not consume, comment-close\n\t\t\t\t\t\t\t\t(?= --> ) |\n\t\t\t\t\t\t\t\t</script [\\t\\n\\f />]\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t)*\n\n\n\t\t\t\t\t# Consume the comment close which exited the inner loop, if any\n\t\t\t\t\t(?: --> )?\n\t\t\t\t)\n\t\t\t)*+\n\t\t\t~xsiA\nREGEX",
";",
"do",
"{",
"$",
"count",
"=",
"preg_match",
"(",
"$",
"re",
",",
"$",
"this",
"->",
"text",
",",
"$",
"m",
",",
"0",
",",
"$",
"this",
"->",
"pos",
")",
";",
"if",
"(",
"$",
"count",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"throwPregError",
"(",
")",
";",
"}",
"elseif",
"(",
"!",
"$",
"count",
")",
"{",
"$",
"this",
"->",
"fatal",
"(",
"'unexpected regex failure: this pattern can match zero characters'",
")",
";",
"}",
"$",
"startPos",
"=",
"$",
"this",
"->",
"pos",
";",
"$",
"matchLength",
"=",
"strlen",
"(",
"$",
"m",
"[",
"0",
"]",
")",
";",
"$",
"endTagLength",
"=",
"isset",
"(",
"$",
"m",
"[",
"1",
"]",
")",
"?",
"strlen",
"(",
"$",
"m",
"[",
"1",
"]",
")",
":",
"0",
";",
"$",
"textLength",
"=",
"$",
"matchLength",
"-",
"$",
"endTagLength",
";",
"$",
"this",
"->",
"emitRawTextRange",
"(",
"true",
",",
"$",
"startPos",
",",
"$",
"textLength",
")",
";",
"$",
"this",
"->",
"pos",
"=",
"$",
"startPos",
"+",
"$",
"matchLength",
";",
"$",
"tagStartPos",
"=",
"$",
"startPos",
"+",
"$",
"textLength",
";",
"if",
"(",
"$",
"endTagLength",
")",
"{",
"$",
"nextState",
"=",
"$",
"this",
"->",
"handleAttribsAndClose",
"(",
"self",
"::",
"STATE_SCRIPT_DATA",
",",
"$",
"this",
"->",
"appropriateEndTag",
",",
"true",
",",
"$",
"tagStartPos",
")",
";",
"}",
"else",
"{",
"$",
"nextState",
"=",
"self",
"::",
"STATE_EOF",
";",
"}",
"}",
"while",
"(",
"$",
"nextState",
"===",
"self",
"::",
"STATE_SCRIPT_DATA",
")",
";",
"return",
"$",
"nextState",
";",
"}"
] |
Process input text in the script data state
@return int The next state index
|
[
"Process",
"input",
"text",
"in",
"the",
"script",
"data",
"state"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L1480-L1565
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/Tokenizer.php
|
Tokenizer.error
|
protected function error( $text, $pos = null ) {
if ( !$this->ignoreErrors ) {
if ( $pos === null ) {
$pos = $this->pos;
}
$this->listener->error( $text, $pos );
}
}
|
php
|
protected function error( $text, $pos = null ) {
if ( !$this->ignoreErrors ) {
if ( $pos === null ) {
$pos = $this->pos;
}
$this->listener->error( $text, $pos );
}
}
|
[
"protected",
"function",
"error",
"(",
"$",
"text",
",",
"$",
"pos",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"ignoreErrors",
")",
"{",
"if",
"(",
"$",
"pos",
"===",
"null",
")",
"{",
"$",
"pos",
"=",
"$",
"this",
"->",
"pos",
";",
"}",
"$",
"this",
"->",
"listener",
"->",
"error",
"(",
"$",
"text",
",",
"$",
"pos",
")",
";",
"}",
"}"
] |
Emit a parse error event.
@param string $text The error message
@param int|null $pos The error position, or null to use the current position
|
[
"Emit",
"a",
"parse",
"error",
"event",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/Tokenizer.php#L1572-L1579
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/InTableText.php
|
InTableText.processPendingCharacters
|
protected function processPendingCharacters() {
$builder = $this->builder;
$allSpace = true;
foreach ( $builder->pendingTableCharacters as $token ) {
list( $text, $start, $length, $sourceStart, $sourceLength ) = $token;
if ( strspn( $text, "\t\n\f\r ", $start, $length ) !== $length ) {
$allSpace = false;
}
}
if ( $allSpace ) {
foreach ( $builder->pendingTableCharacters as $token ) {
list( $text, $start, $length, $sourceStart, $sourceLength ) = $token;
$builder->insertCharacters( $text, $start, $length, $sourceStart, $sourceLength );
}
} else {
$builder->fosterParenting = true;
foreach ( $builder->pendingTableCharacters as $token ) {
list( $text, $start, $length, $sourceStart, $sourceLength ) = $token;
$builder->error( 'invalid characters in table text, fostering', $sourceStart );
$this->dispatcher->inBody->characters( $text, $start, $length,
$sourceStart, $sourceLength );
}
$builder->fosterParenting = false;
}
}
|
php
|
protected function processPendingCharacters() {
$builder = $this->builder;
$allSpace = true;
foreach ( $builder->pendingTableCharacters as $token ) {
list( $text, $start, $length, $sourceStart, $sourceLength ) = $token;
if ( strspn( $text, "\t\n\f\r ", $start, $length ) !== $length ) {
$allSpace = false;
}
}
if ( $allSpace ) {
foreach ( $builder->pendingTableCharacters as $token ) {
list( $text, $start, $length, $sourceStart, $sourceLength ) = $token;
$builder->insertCharacters( $text, $start, $length, $sourceStart, $sourceLength );
}
} else {
$builder->fosterParenting = true;
foreach ( $builder->pendingTableCharacters as $token ) {
list( $text, $start, $length, $sourceStart, $sourceLength ) = $token;
$builder->error( 'invalid characters in table text, fostering', $sourceStart );
$this->dispatcher->inBody->characters( $text, $start, $length,
$sourceStart, $sourceLength );
}
$builder->fosterParenting = false;
}
}
|
[
"protected",
"function",
"processPendingCharacters",
"(",
")",
"{",
"$",
"builder",
"=",
"$",
"this",
"->",
"builder",
";",
"$",
"allSpace",
"=",
"true",
";",
"foreach",
"(",
"$",
"builder",
"->",
"pendingTableCharacters",
"as",
"$",
"token",
")",
"{",
"list",
"(",
"$",
"text",
",",
"$",
"start",
",",
"$",
"length",
",",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
"=",
"$",
"token",
";",
"if",
"(",
"strspn",
"(",
"$",
"text",
",",
"\"\\t\\n\\f\\r \"",
",",
"$",
"start",
",",
"$",
"length",
")",
"!==",
"$",
"length",
")",
"{",
"$",
"allSpace",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"$",
"allSpace",
")",
"{",
"foreach",
"(",
"$",
"builder",
"->",
"pendingTableCharacters",
"as",
"$",
"token",
")",
"{",
"list",
"(",
"$",
"text",
",",
"$",
"start",
",",
"$",
"length",
",",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
"=",
"$",
"token",
";",
"$",
"builder",
"->",
"insertCharacters",
"(",
"$",
"text",
",",
"$",
"start",
",",
"$",
"length",
",",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
";",
"}",
"}",
"else",
"{",
"$",
"builder",
"->",
"fosterParenting",
"=",
"true",
";",
"foreach",
"(",
"$",
"builder",
"->",
"pendingTableCharacters",
"as",
"$",
"token",
")",
"{",
"list",
"(",
"$",
"text",
",",
"$",
"start",
",",
"$",
"length",
",",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
"=",
"$",
"token",
";",
"$",
"builder",
"->",
"error",
"(",
"'invalid characters in table text, fostering'",
",",
"$",
"sourceStart",
")",
";",
"$",
"this",
"->",
"dispatcher",
"->",
"inBody",
"->",
"characters",
"(",
"$",
"text",
",",
"$",
"start",
",",
"$",
"length",
",",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
";",
"}",
"$",
"builder",
"->",
"fosterParenting",
"=",
"false",
";",
"}",
"}"
] |
Common code for the "anything else" case. Process the pending table
character tokens.
|
[
"Common",
"code",
"for",
"the",
"anything",
"else",
"case",
".",
"Process",
"the",
"pending",
"table",
"character",
"tokens",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/InTableText.php#L58-L82
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/TraceFormatter.php
|
TraceFormatter.getDebugTag
|
public static function getDebugTag( $element ) {
if ( !$element ) {
return '';
} elseif ( $element instanceof Element || $element instanceof SerializerNode ) {
return $element->getDebugTag();
} else {
return get_class( $element ) . '#' . substr( md5( spl_object_hash( $element ) ), 0, 8 );
}
}
|
php
|
public static function getDebugTag( $element ) {
if ( !$element ) {
return '';
} elseif ( $element instanceof Element || $element instanceof SerializerNode ) {
return $element->getDebugTag();
} else {
return get_class( $element ) . '#' . substr( md5( spl_object_hash( $element ) ), 0, 8 );
}
}
|
[
"public",
"static",
"function",
"getDebugTag",
"(",
"$",
"element",
")",
"{",
"if",
"(",
"!",
"$",
"element",
")",
"{",
"return",
"''",
";",
"}",
"elseif",
"(",
"$",
"element",
"instanceof",
"Element",
"||",
"$",
"element",
"instanceof",
"SerializerNode",
")",
"{",
"return",
"$",
"element",
"->",
"getDebugTag",
"(",
")",
";",
"}",
"else",
"{",
"return",
"get_class",
"(",
"$",
"element",
")",
".",
"'#'",
".",
"substr",
"(",
"md5",
"(",
"spl_object_hash",
"(",
"$",
"element",
")",
")",
",",
"0",
",",
"8",
")",
";",
"}",
"}"
] |
Get a debug tag for an element or null
@param Element|SerializerNode|null $element
@return string
|
[
"Get",
"a",
"debug",
"tag",
"for",
"an",
"element",
"or",
"null"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/TraceFormatter.php#L18-L26
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/TraceFormatter.php
|
TraceFormatter.getPrepositionName
|
public static function getPrepositionName( $prep ) {
$names = [
TreeBuilder::BEFORE => 'before',
TreeBuilder::UNDER => 'under',
TreeBuilder::ROOT => 'under root'
];
return isset( $names[$prep] ) ? $names[$prep] : '???';
}
|
php
|
public static function getPrepositionName( $prep ) {
$names = [
TreeBuilder::BEFORE => 'before',
TreeBuilder::UNDER => 'under',
TreeBuilder::ROOT => 'under root'
];
return isset( $names[$prep] ) ? $names[$prep] : '???';
}
|
[
"public",
"static",
"function",
"getPrepositionName",
"(",
"$",
"prep",
")",
"{",
"$",
"names",
"=",
"[",
"TreeBuilder",
"::",
"BEFORE",
"=>",
"'before'",
",",
"TreeBuilder",
"::",
"UNDER",
"=>",
"'under'",
",",
"TreeBuilder",
"::",
"ROOT",
"=>",
"'under root'",
"]",
";",
"return",
"isset",
"(",
"$",
"names",
"[",
"$",
"prep",
"]",
")",
"?",
"$",
"names",
"[",
"$",
"prep",
"]",
":",
"'???'",
";",
"}"
] |
Get a readable version of the TreeBuilder preposition constants
@param int $prep
@return string
|
[
"Get",
"a",
"readable",
"version",
"of",
"the",
"TreeBuilder",
"preposition",
"constants"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/TraceFormatter.php#L46-L53
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/ActiveFormattingElements.php
|
ActiveFormattingElements.insertMarker
|
public function insertMarker() {
$elt = new Marker( 'marker' );
if ( $this->tail ) {
$this->tail->nextAFE = $elt;
$elt->prevAFE = $this->tail;
} else {
$this->head = $elt;
}
$this->tail = $elt;
$this->noahTableStack[] = [];
}
|
php
|
public function insertMarker() {
$elt = new Marker( 'marker' );
if ( $this->tail ) {
$this->tail->nextAFE = $elt;
$elt->prevAFE = $this->tail;
} else {
$this->head = $elt;
}
$this->tail = $elt;
$this->noahTableStack[] = [];
}
|
[
"public",
"function",
"insertMarker",
"(",
")",
"{",
"$",
"elt",
"=",
"new",
"Marker",
"(",
"'marker'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"tail",
")",
"{",
"$",
"this",
"->",
"tail",
"->",
"nextAFE",
"=",
"$",
"elt",
";",
"$",
"elt",
"->",
"prevAFE",
"=",
"$",
"this",
"->",
"tail",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"head",
"=",
"$",
"elt",
";",
"}",
"$",
"this",
"->",
"tail",
"=",
"$",
"elt",
";",
"$",
"this",
"->",
"noahTableStack",
"[",
"]",
"=",
"[",
"]",
";",
"}"
] |
Insert a marker
|
[
"Insert",
"a",
"marker"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/ActiveFormattingElements.php#L50-L60
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/ActiveFormattingElements.php
|
ActiveFormattingElements.push
|
public function push( Element $elt ) {
// Must not be in the list already
if ( $elt->prevAFE !== null || $this->head === $elt ) {
throw new \Exception( 'Cannot insert a node into the AFE list twice' );
}
// "Noah's Ark clause" -- if there are already three copies of
// this element before we encounter a marker, then drop the last
// one.
$noahKey = $elt->getNoahKey();
$table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
if ( !isset( $table[$noahKey] ) ) {
$table[$noahKey] = $elt;
} else {
$count = 1;
$head = $tail = $table[$noahKey];
while ( $tail->nextNoah ) {
$tail = $tail->nextNoah;
$count++;
}
if ( $count >= 3 ) {
$this->remove( $head );
}
$tail->nextNoah = $elt;
}
// Add to the main AFE list
if ( $this->tail ) {
$this->tail->nextAFE = $elt;
$elt->prevAFE = $this->tail;
} else {
$this->head = $elt;
}
$this->tail = $elt;
}
|
php
|
public function push( Element $elt ) {
// Must not be in the list already
if ( $elt->prevAFE !== null || $this->head === $elt ) {
throw new \Exception( 'Cannot insert a node into the AFE list twice' );
}
// "Noah's Ark clause" -- if there are already three copies of
// this element before we encounter a marker, then drop the last
// one.
$noahKey = $elt->getNoahKey();
$table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
if ( !isset( $table[$noahKey] ) ) {
$table[$noahKey] = $elt;
} else {
$count = 1;
$head = $tail = $table[$noahKey];
while ( $tail->nextNoah ) {
$tail = $tail->nextNoah;
$count++;
}
if ( $count >= 3 ) {
$this->remove( $head );
}
$tail->nextNoah = $elt;
}
// Add to the main AFE list
if ( $this->tail ) {
$this->tail->nextAFE = $elt;
$elt->prevAFE = $this->tail;
} else {
$this->head = $elt;
}
$this->tail = $elt;
}
|
[
"public",
"function",
"push",
"(",
"Element",
"$",
"elt",
")",
"{",
"// Must not be in the list already",
"if",
"(",
"$",
"elt",
"->",
"prevAFE",
"!==",
"null",
"||",
"$",
"this",
"->",
"head",
"===",
"$",
"elt",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Cannot insert a node into the AFE list twice'",
")",
";",
"}",
"// \"Noah's Ark clause\" -- if there are already three copies of",
"// this element before we encounter a marker, then drop the last",
"// one.",
"$",
"noahKey",
"=",
"$",
"elt",
"->",
"getNoahKey",
"(",
")",
";",
"$",
"table",
"=",
"&",
"$",
"this",
"->",
"noahTableStack",
"[",
"count",
"(",
"$",
"this",
"->",
"noahTableStack",
")",
"-",
"1",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"table",
"[",
"$",
"noahKey",
"]",
")",
")",
"{",
"$",
"table",
"[",
"$",
"noahKey",
"]",
"=",
"$",
"elt",
";",
"}",
"else",
"{",
"$",
"count",
"=",
"1",
";",
"$",
"head",
"=",
"$",
"tail",
"=",
"$",
"table",
"[",
"$",
"noahKey",
"]",
";",
"while",
"(",
"$",
"tail",
"->",
"nextNoah",
")",
"{",
"$",
"tail",
"=",
"$",
"tail",
"->",
"nextNoah",
";",
"$",
"count",
"++",
";",
"}",
"if",
"(",
"$",
"count",
">=",
"3",
")",
"{",
"$",
"this",
"->",
"remove",
"(",
"$",
"head",
")",
";",
"}",
"$",
"tail",
"->",
"nextNoah",
"=",
"$",
"elt",
";",
"}",
"// Add to the main AFE list",
"if",
"(",
"$",
"this",
"->",
"tail",
")",
"{",
"$",
"this",
"->",
"tail",
"->",
"nextAFE",
"=",
"$",
"elt",
";",
"$",
"elt",
"->",
"prevAFE",
"=",
"$",
"this",
"->",
"tail",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"head",
"=",
"$",
"elt",
";",
"}",
"$",
"this",
"->",
"tail",
"=",
"$",
"elt",
";",
"}"
] |
Follow the steps required when the spec requires us to "push onto the
list of active formatting elements".
@param Element $elt
|
[
"Follow",
"the",
"steps",
"required",
"when",
"the",
"spec",
"requires",
"us",
"to",
"push",
"onto",
"the",
"list",
"of",
"active",
"formatting",
"elements",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/ActiveFormattingElements.php#L67-L100
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/ActiveFormattingElements.php
|
ActiveFormattingElements.clearToMarker
|
public function clearToMarker() {
// Iterate back through the list starting from the tail
$tail = $this->tail;
while ( $tail && !( $tail instanceof Marker ) ) {
// Unlink the element
$prev = $tail->prevAFE;
$tail->prevAFE = null;
if ( $prev ) {
$prev->nextAFE = null;
}
$tail->nextNoah = null;
$tail = $prev;
}
// If we finished on a marker, unlink it and pop it off the Noah table stack
if ( $tail ) {
$prev = $tail->prevAFE;
if ( $prev ) {
$prev->nextAFE = null;
}
$tail = $prev;
array_pop( $this->noahTableStack );
} else {
// No marker: wipe the top-level Noah table (which is the only one)
$this->noahTableStack[0] = [];
}
// If we removed all the elements, clear the head pointer
if ( !$tail ) {
$this->head = null;
}
$this->tail = $tail;
}
|
php
|
public function clearToMarker() {
// Iterate back through the list starting from the tail
$tail = $this->tail;
while ( $tail && !( $tail instanceof Marker ) ) {
// Unlink the element
$prev = $tail->prevAFE;
$tail->prevAFE = null;
if ( $prev ) {
$prev->nextAFE = null;
}
$tail->nextNoah = null;
$tail = $prev;
}
// If we finished on a marker, unlink it and pop it off the Noah table stack
if ( $tail ) {
$prev = $tail->prevAFE;
if ( $prev ) {
$prev->nextAFE = null;
}
$tail = $prev;
array_pop( $this->noahTableStack );
} else {
// No marker: wipe the top-level Noah table (which is the only one)
$this->noahTableStack[0] = [];
}
// If we removed all the elements, clear the head pointer
if ( !$tail ) {
$this->head = null;
}
$this->tail = $tail;
}
|
[
"public",
"function",
"clearToMarker",
"(",
")",
"{",
"// Iterate back through the list starting from the tail",
"$",
"tail",
"=",
"$",
"this",
"->",
"tail",
";",
"while",
"(",
"$",
"tail",
"&&",
"!",
"(",
"$",
"tail",
"instanceof",
"Marker",
")",
")",
"{",
"// Unlink the element",
"$",
"prev",
"=",
"$",
"tail",
"->",
"prevAFE",
";",
"$",
"tail",
"->",
"prevAFE",
"=",
"null",
";",
"if",
"(",
"$",
"prev",
")",
"{",
"$",
"prev",
"->",
"nextAFE",
"=",
"null",
";",
"}",
"$",
"tail",
"->",
"nextNoah",
"=",
"null",
";",
"$",
"tail",
"=",
"$",
"prev",
";",
"}",
"// If we finished on a marker, unlink it and pop it off the Noah table stack",
"if",
"(",
"$",
"tail",
")",
"{",
"$",
"prev",
"=",
"$",
"tail",
"->",
"prevAFE",
";",
"if",
"(",
"$",
"prev",
")",
"{",
"$",
"prev",
"->",
"nextAFE",
"=",
"null",
";",
"}",
"$",
"tail",
"=",
"$",
"prev",
";",
"array_pop",
"(",
"$",
"this",
"->",
"noahTableStack",
")",
";",
"}",
"else",
"{",
"// No marker: wipe the top-level Noah table (which is the only one)",
"$",
"this",
"->",
"noahTableStack",
"[",
"0",
"]",
"=",
"[",
"]",
";",
"}",
"// If we removed all the elements, clear the head pointer",
"if",
"(",
"!",
"$",
"tail",
")",
"{",
"$",
"this",
"->",
"head",
"=",
"null",
";",
"}",
"$",
"this",
"->",
"tail",
"=",
"$",
"tail",
";",
"}"
] |
Follow the steps required when the spec asks us to "clear the list of
active formatting elements up to the last marker".
|
[
"Follow",
"the",
"steps",
"required",
"when",
"the",
"spec",
"asks",
"us",
"to",
"clear",
"the",
"list",
"of",
"active",
"formatting",
"elements",
"up",
"to",
"the",
"last",
"marker",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/ActiveFormattingElements.php#L106-L136
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/ActiveFormattingElements.php
|
ActiveFormattingElements.addToNoahList
|
private function addToNoahList( Element $elt ) {
$noahKey = $elt->getNoahKey();
$table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
if ( !isset( $table[$noahKey] ) ) {
$table[$noahKey] = $elt;
} else {
$tail = $table[$noahKey];
while ( $tail->nextNoah ) {
$tail = $tail->nextNoah;
}
$tail->nextNoah = $elt;
}
}
|
php
|
private function addToNoahList( Element $elt ) {
$noahKey = $elt->getNoahKey();
$table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
if ( !isset( $table[$noahKey] ) ) {
$table[$noahKey] = $elt;
} else {
$tail = $table[$noahKey];
while ( $tail->nextNoah ) {
$tail = $tail->nextNoah;
}
$tail->nextNoah = $elt;
}
}
|
[
"private",
"function",
"addToNoahList",
"(",
"Element",
"$",
"elt",
")",
"{",
"$",
"noahKey",
"=",
"$",
"elt",
"->",
"getNoahKey",
"(",
")",
";",
"$",
"table",
"=",
"&",
"$",
"this",
"->",
"noahTableStack",
"[",
"count",
"(",
"$",
"this",
"->",
"noahTableStack",
")",
"-",
"1",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"table",
"[",
"$",
"noahKey",
"]",
")",
")",
"{",
"$",
"table",
"[",
"$",
"noahKey",
"]",
"=",
"$",
"elt",
";",
"}",
"else",
"{",
"$",
"tail",
"=",
"$",
"table",
"[",
"$",
"noahKey",
"]",
";",
"while",
"(",
"$",
"tail",
"->",
"nextNoah",
")",
"{",
"$",
"tail",
"=",
"$",
"tail",
"->",
"nextNoah",
";",
"}",
"$",
"tail",
"->",
"nextNoah",
"=",
"$",
"elt",
";",
"}",
"}"
] |
Add an element to a bucket of elements which are alike for the purposes
of the Noah's Ark clause.
@param Element $elt
|
[
"Add",
"an",
"element",
"to",
"a",
"bucket",
"of",
"elements",
"which",
"are",
"alike",
"for",
"the",
"purposes",
"of",
"the",
"Noah",
"s",
"Ark",
"clause",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/ActiveFormattingElements.php#L205-L217
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/ActiveFormattingElements.php
|
ActiveFormattingElements.removeFromNoahList
|
private function removeFromNoahList( Element $elt ) {
$table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
$key = $elt->getNoahKey();
$noahElt = $table[$key];
if ( $noahElt === $elt ) {
if ( $noahElt->nextNoah ) {
$table[$key] = $noahElt->nextNoah;
$noahElt->nextNoah = null;
} else {
unset( $table[$key] );
}
} else {
do {
$prevNoahElt = $noahElt;
$noahElt = $prevNoahElt->nextNoah;
if ( $noahElt === $elt ) {
// Found it, unlink
$prevNoahElt->nextNoah = $elt->nextNoah;
$elt->nextNoah = null;
break;
}
} while ( $noahElt );
}
}
|
php
|
private function removeFromNoahList( Element $elt ) {
$table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
$key = $elt->getNoahKey();
$noahElt = $table[$key];
if ( $noahElt === $elt ) {
if ( $noahElt->nextNoah ) {
$table[$key] = $noahElt->nextNoah;
$noahElt->nextNoah = null;
} else {
unset( $table[$key] );
}
} else {
do {
$prevNoahElt = $noahElt;
$noahElt = $prevNoahElt->nextNoah;
if ( $noahElt === $elt ) {
// Found it, unlink
$prevNoahElt->nextNoah = $elt->nextNoah;
$elt->nextNoah = null;
break;
}
} while ( $noahElt );
}
}
|
[
"private",
"function",
"removeFromNoahList",
"(",
"Element",
"$",
"elt",
")",
"{",
"$",
"table",
"=",
"&",
"$",
"this",
"->",
"noahTableStack",
"[",
"count",
"(",
"$",
"this",
"->",
"noahTableStack",
")",
"-",
"1",
"]",
";",
"$",
"key",
"=",
"$",
"elt",
"->",
"getNoahKey",
"(",
")",
";",
"$",
"noahElt",
"=",
"$",
"table",
"[",
"$",
"key",
"]",
";",
"if",
"(",
"$",
"noahElt",
"===",
"$",
"elt",
")",
"{",
"if",
"(",
"$",
"noahElt",
"->",
"nextNoah",
")",
"{",
"$",
"table",
"[",
"$",
"key",
"]",
"=",
"$",
"noahElt",
"->",
"nextNoah",
";",
"$",
"noahElt",
"->",
"nextNoah",
"=",
"null",
";",
"}",
"else",
"{",
"unset",
"(",
"$",
"table",
"[",
"$",
"key",
"]",
")",
";",
"}",
"}",
"else",
"{",
"do",
"{",
"$",
"prevNoahElt",
"=",
"$",
"noahElt",
";",
"$",
"noahElt",
"=",
"$",
"prevNoahElt",
"->",
"nextNoah",
";",
"if",
"(",
"$",
"noahElt",
"===",
"$",
"elt",
")",
"{",
"// Found it, unlink",
"$",
"prevNoahElt",
"->",
"nextNoah",
"=",
"$",
"elt",
"->",
"nextNoah",
";",
"$",
"elt",
"->",
"nextNoah",
"=",
"null",
";",
"break",
";",
"}",
"}",
"while",
"(",
"$",
"noahElt",
")",
";",
"}",
"}"
] |
Remove an element from its Noah's Ark bucket.
@param Element $elt
|
[
"Remove",
"an",
"element",
"from",
"its",
"Noah",
"s",
"Ark",
"bucket",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/ActiveFormattingElements.php#L224-L247
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/ActiveFormattingElements.php
|
ActiveFormattingElements.dump
|
public function dump() {
$prev = null;
$s = '';
for ( $node = $this->head; $node; $prev = $node, $node = $node->nextAFE ) {
if ( $node instanceof Marker ) {
$s .= "MARKER\n";
continue;
}
$s .= $node->getDebugTag();
if ( $node->nextNoah ) {
$s .= " (noah sibling: " . $node->nextNoah->getDebugTag() .
')';
}
if ( $node->nextAFE && $node->nextAFE->prevAFE !== $node ) {
$s .= " (reverse link is wrong!)";
}
$s .= "\n";
}
if ( $prev !== $this->tail ) {
$s .= "(tail pointer is wrong!)\n";
}
return $s;
}
|
php
|
public function dump() {
$prev = null;
$s = '';
for ( $node = $this->head; $node; $prev = $node, $node = $node->nextAFE ) {
if ( $node instanceof Marker ) {
$s .= "MARKER\n";
continue;
}
$s .= $node->getDebugTag();
if ( $node->nextNoah ) {
$s .= " (noah sibling: " . $node->nextNoah->getDebugTag() .
')';
}
if ( $node->nextAFE && $node->nextAFE->prevAFE !== $node ) {
$s .= " (reverse link is wrong!)";
}
$s .= "\n";
}
if ( $prev !== $this->tail ) {
$s .= "(tail pointer is wrong!)\n";
}
return $s;
}
|
[
"public",
"function",
"dump",
"(",
")",
"{",
"$",
"prev",
"=",
"null",
";",
"$",
"s",
"=",
"''",
";",
"for",
"(",
"$",
"node",
"=",
"$",
"this",
"->",
"head",
";",
"$",
"node",
";",
"$",
"prev",
"=",
"$",
"node",
",",
"$",
"node",
"=",
"$",
"node",
"->",
"nextAFE",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"Marker",
")",
"{",
"$",
"s",
".=",
"\"MARKER\\n\"",
";",
"continue",
";",
"}",
"$",
"s",
".=",
"$",
"node",
"->",
"getDebugTag",
"(",
")",
";",
"if",
"(",
"$",
"node",
"->",
"nextNoah",
")",
"{",
"$",
"s",
".=",
"\" (noah sibling: \"",
".",
"$",
"node",
"->",
"nextNoah",
"->",
"getDebugTag",
"(",
")",
".",
"')'",
";",
"}",
"if",
"(",
"$",
"node",
"->",
"nextAFE",
"&&",
"$",
"node",
"->",
"nextAFE",
"->",
"prevAFE",
"!==",
"$",
"node",
")",
"{",
"$",
"s",
".=",
"\" (reverse link is wrong!)\"",
";",
"}",
"$",
"s",
".=",
"\"\\n\"",
";",
"}",
"if",
"(",
"$",
"prev",
"!==",
"$",
"this",
"->",
"tail",
")",
"{",
"$",
"s",
".=",
"\"(tail pointer is wrong!)\\n\"",
";",
"}",
"return",
"$",
"s",
";",
"}"
] |
Get a string representation of the AFE list, for debugging
@return string
|
[
"Get",
"a",
"string",
"representation",
"of",
"the",
"AFE",
"list",
"for",
"debugging"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/ActiveFormattingElements.php#L316-L338
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/TreeBuilder.php
|
TreeBuilder.adjustedCurrentNode
|
public function adjustedCurrentNode() {
$current = $this->stack->current;
if ( $this->isFragment && ( !$current || $current->stackIndex === 0 ) ) {
return $this->fragmentContext;
} else {
return $current;
}
}
|
php
|
public function adjustedCurrentNode() {
$current = $this->stack->current;
if ( $this->isFragment && ( !$current || $current->stackIndex === 0 ) ) {
return $this->fragmentContext;
} else {
return $current;
}
}
|
[
"public",
"function",
"adjustedCurrentNode",
"(",
")",
"{",
"$",
"current",
"=",
"$",
"this",
"->",
"stack",
"->",
"current",
";",
"if",
"(",
"$",
"this",
"->",
"isFragment",
"&&",
"(",
"!",
"$",
"current",
"||",
"$",
"current",
"->",
"stackIndex",
"===",
"0",
")",
")",
"{",
"return",
"$",
"this",
"->",
"fragmentContext",
";",
"}",
"else",
"{",
"return",
"$",
"current",
";",
"}",
"}"
] |
Get the adjusted current node
@return Element|null
|
[
"Get",
"the",
"adjusted",
"current",
"node"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/TreeBuilder.php#L149-L156
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/TreeBuilder.php
|
TreeBuilder.pop
|
public function pop( $sourceStart, $sourceLength ) {
$element = $this->stack->pop();
$this->handler->endTag( $element, $sourceStart, $sourceLength );
return $element;
}
|
php
|
public function pop( $sourceStart, $sourceLength ) {
$element = $this->stack->pop();
$this->handler->endTag( $element, $sourceStart, $sourceLength );
return $element;
}
|
[
"public",
"function",
"pop",
"(",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
"{",
"$",
"element",
"=",
"$",
"this",
"->",
"stack",
"->",
"pop",
"(",
")",
";",
"$",
"this",
"->",
"handler",
"->",
"endTag",
"(",
"$",
"element",
",",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
";",
"return",
"$",
"element",
";",
"}"
] |
Pop the current node from the stack of open elements, and notify the
handler that we are done with that node.
@param int $sourceStart
@param int $sourceLength
@return Element
|
[
"Pop",
"the",
"current",
"node",
"from",
"the",
"stack",
"of",
"open",
"elements",
"and",
"notify",
"the",
"handler",
"that",
"we",
"are",
"done",
"with",
"that",
"node",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/TreeBuilder.php#L216-L220
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/TreeBuilder.php
|
TreeBuilder.checkUnclosed
|
public function checkUnclosed( $allowed, $pos ) {
if ( $this->ignoreErrors ) {
return;
}
$stack = $this->stack;
$unclosedErrors = [];
for ( $i = $stack->length() - 1; $i >= 0; $i-- ) {
$unclosedName = $stack->item( $i )->htmlName;
if ( !isset( $allowed[$unclosedName] ) ) {
$unclosedErrors[$unclosedName] = true;
}
}
if ( $unclosedErrors ) {
$names = implode( ', ', array_keys( $unclosedErrors ) );
$this->error( "closing unclosed $names", $pos );
}
}
|
php
|
public function checkUnclosed( $allowed, $pos ) {
if ( $this->ignoreErrors ) {
return;
}
$stack = $this->stack;
$unclosedErrors = [];
for ( $i = $stack->length() - 1; $i >= 0; $i-- ) {
$unclosedName = $stack->item( $i )->htmlName;
if ( !isset( $allowed[$unclosedName] ) ) {
$unclosedErrors[$unclosedName] = true;
}
}
if ( $unclosedErrors ) {
$names = implode( ', ', array_keys( $unclosedErrors ) );
$this->error( "closing unclosed $names", $pos );
}
}
|
[
"public",
"function",
"checkUnclosed",
"(",
"$",
"allowed",
",",
"$",
"pos",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"ignoreErrors",
")",
"{",
"return",
";",
"}",
"$",
"stack",
"=",
"$",
"this",
"->",
"stack",
";",
"$",
"unclosedErrors",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"$",
"stack",
"->",
"length",
"(",
")",
"-",
"1",
";",
"$",
"i",
">=",
"0",
";",
"$",
"i",
"--",
")",
"{",
"$",
"unclosedName",
"=",
"$",
"stack",
"->",
"item",
"(",
"$",
"i",
")",
"->",
"htmlName",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"allowed",
"[",
"$",
"unclosedName",
"]",
")",
")",
"{",
"$",
"unclosedErrors",
"[",
"$",
"unclosedName",
"]",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"$",
"unclosedErrors",
")",
"{",
"$",
"names",
"=",
"implode",
"(",
"', '",
",",
"array_keys",
"(",
"$",
"unclosedErrors",
")",
")",
";",
"$",
"this",
"->",
"error",
"(",
"\"closing unclosed $names\"",
",",
"$",
"pos",
")",
";",
"}",
"}"
] |
Check the stack to see if there is any element which is not on the list
of allowed elements. Raise an error if any are found.
@param array $allowed An array with the HTML element names in the key
@param int $pos
|
[
"Check",
"the",
"stack",
"to",
"see",
"if",
"there",
"is",
"any",
"element",
"which",
"is",
"not",
"on",
"the",
"list",
"of",
"allowed",
"elements",
".",
"Raise",
"an",
"error",
"if",
"any",
"are",
"found",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/TreeBuilder.php#L257-L274
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/TreeBuilder.php
|
TreeBuilder.reconstructAFE
|
public function reconstructAFE( $sourceStart ) {
$entry = $this->afe->getTail();
// If there are no entries in the list of active formatting elements,
// then there is nothing to reconstruct
if ( !$entry ) {
return;
}
// If the last is a marker, do nothing.
if ( $entry instanceof Marker ) {
return;
}
// Or if it is an open element, do nothing.
if ( $entry->stackIndex !== null ) {
return;
}
// Loop backward through the list until we find a marker or an
// open element
$foundIt = false;
while ( $entry->prevAFE ) {
$entry = $entry->prevAFE;
if ( $entry instanceof Marker || $entry->stackIndex !== null ) {
$foundIt = true;
break;
}
}
// Now loop forward, starting from the element after the current one (or
// the first element if we didn't find a marker or open element),
// recreating formatting elements and pushing them back onto the list
// of open elements.
if ( $foundIt ) {
$entry = $entry->nextAFE;
}
do {
$newElement = $this->insertForeign( HTMLData::NS_HTML, $entry->name,
$entry->attrs, false, $sourceStart, 0 );
$this->afe->replace( $entry, $newElement );
$entry = $newElement->nextAFE;
} while ( $entry );
}
|
php
|
public function reconstructAFE( $sourceStart ) {
$entry = $this->afe->getTail();
// If there are no entries in the list of active formatting elements,
// then there is nothing to reconstruct
if ( !$entry ) {
return;
}
// If the last is a marker, do nothing.
if ( $entry instanceof Marker ) {
return;
}
// Or if it is an open element, do nothing.
if ( $entry->stackIndex !== null ) {
return;
}
// Loop backward through the list until we find a marker or an
// open element
$foundIt = false;
while ( $entry->prevAFE ) {
$entry = $entry->prevAFE;
if ( $entry instanceof Marker || $entry->stackIndex !== null ) {
$foundIt = true;
break;
}
}
// Now loop forward, starting from the element after the current one (or
// the first element if we didn't find a marker or open element),
// recreating formatting elements and pushing them back onto the list
// of open elements.
if ( $foundIt ) {
$entry = $entry->nextAFE;
}
do {
$newElement = $this->insertForeign( HTMLData::NS_HTML, $entry->name,
$entry->attrs, false, $sourceStart, 0 );
$this->afe->replace( $entry, $newElement );
$entry = $newElement->nextAFE;
} while ( $entry );
}
|
[
"public",
"function",
"reconstructAFE",
"(",
"$",
"sourceStart",
")",
"{",
"$",
"entry",
"=",
"$",
"this",
"->",
"afe",
"->",
"getTail",
"(",
")",
";",
"// If there are no entries in the list of active formatting elements,",
"// then there is nothing to reconstruct",
"if",
"(",
"!",
"$",
"entry",
")",
"{",
"return",
";",
"}",
"// If the last is a marker, do nothing.",
"if",
"(",
"$",
"entry",
"instanceof",
"Marker",
")",
"{",
"return",
";",
"}",
"// Or if it is an open element, do nothing.",
"if",
"(",
"$",
"entry",
"->",
"stackIndex",
"!==",
"null",
")",
"{",
"return",
";",
"}",
"// Loop backward through the list until we find a marker or an",
"// open element",
"$",
"foundIt",
"=",
"false",
";",
"while",
"(",
"$",
"entry",
"->",
"prevAFE",
")",
"{",
"$",
"entry",
"=",
"$",
"entry",
"->",
"prevAFE",
";",
"if",
"(",
"$",
"entry",
"instanceof",
"Marker",
"||",
"$",
"entry",
"->",
"stackIndex",
"!==",
"null",
")",
"{",
"$",
"foundIt",
"=",
"true",
";",
"break",
";",
"}",
"}",
"// Now loop forward, starting from the element after the current one (or",
"// the first element if we didn't find a marker or open element),",
"// recreating formatting elements and pushing them back onto the list",
"// of open elements.",
"if",
"(",
"$",
"foundIt",
")",
"{",
"$",
"entry",
"=",
"$",
"entry",
"->",
"nextAFE",
";",
"}",
"do",
"{",
"$",
"newElement",
"=",
"$",
"this",
"->",
"insertForeign",
"(",
"HTMLData",
"::",
"NS_HTML",
",",
"$",
"entry",
"->",
"name",
",",
"$",
"entry",
"->",
"attrs",
",",
"false",
",",
"$",
"sourceStart",
",",
"0",
")",
";",
"$",
"this",
"->",
"afe",
"->",
"replace",
"(",
"$",
"entry",
",",
"$",
"newElement",
")",
";",
"$",
"entry",
"=",
"$",
"newElement",
"->",
"nextAFE",
";",
"}",
"while",
"(",
"$",
"entry",
")",
";",
"}"
] |
Reconstruct the active formatting elements.
@author C. Scott Ananian, Tim Starling
@param int $sourceStart
|
[
"Reconstruct",
"the",
"active",
"formatting",
"elements",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/TreeBuilder.php#L281-L321
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/TreeBuilder.php
|
TreeBuilder.generateImpliedEndTags
|
public function generateImpliedEndTags( $name, $pos ) {
$stack = $this->stack;
$current = $stack->current;
while ( $current && $current->htmlName !== $name &&
isset( self::$impliedEndTags[$current->htmlName] )
) {
$popped = $stack->pop();
$this->handler->endTag( $popped, $pos, 0 );
$current = $stack->current;
}
}
|
php
|
public function generateImpliedEndTags( $name, $pos ) {
$stack = $this->stack;
$current = $stack->current;
while ( $current && $current->htmlName !== $name &&
isset( self::$impliedEndTags[$current->htmlName] )
) {
$popped = $stack->pop();
$this->handler->endTag( $popped, $pos, 0 );
$current = $stack->current;
}
}
|
[
"public",
"function",
"generateImpliedEndTags",
"(",
"$",
"name",
",",
"$",
"pos",
")",
"{",
"$",
"stack",
"=",
"$",
"this",
"->",
"stack",
";",
"$",
"current",
"=",
"$",
"stack",
"->",
"current",
";",
"while",
"(",
"$",
"current",
"&&",
"$",
"current",
"->",
"htmlName",
"!==",
"$",
"name",
"&&",
"isset",
"(",
"self",
"::",
"$",
"impliedEndTags",
"[",
"$",
"current",
"->",
"htmlName",
"]",
")",
")",
"{",
"$",
"popped",
"=",
"$",
"stack",
"->",
"pop",
"(",
")",
";",
"$",
"this",
"->",
"handler",
"->",
"endTag",
"(",
"$",
"popped",
",",
"$",
"pos",
",",
"0",
")",
";",
"$",
"current",
"=",
"$",
"stack",
"->",
"current",
";",
"}",
"}"
] |
Generate implied end tags, optionally with an element to exclude.
@param string|null $name The name to exclude
@param int $pos The source position
|
[
"Generate",
"implied",
"end",
"tags",
"optionally",
"with",
"an",
"element",
"to",
"exclude",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/TreeBuilder.php#L604-L614
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/TreeBuilder.php
|
TreeBuilder.generateImpliedEndTagsAndPop
|
public function generateImpliedEndTagsAndPop( $name, $sourceStart, $sourceLength ) {
$this->generateImpliedEndTags( $name, $sourceStart );
if ( $this->stack->current->htmlName !== $name ) {
$this->error( "found </$name> but elements are open that cannot " .
"have implied end tags, closing them", $sourceStart );
}
$this->popAllUpToName( $name, $sourceStart, $sourceLength );
}
|
php
|
public function generateImpliedEndTagsAndPop( $name, $sourceStart, $sourceLength ) {
$this->generateImpliedEndTags( $name, $sourceStart );
if ( $this->stack->current->htmlName !== $name ) {
$this->error( "found </$name> but elements are open that cannot " .
"have implied end tags, closing them", $sourceStart );
}
$this->popAllUpToName( $name, $sourceStart, $sourceLength );
}
|
[
"public",
"function",
"generateImpliedEndTagsAndPop",
"(",
"$",
"name",
",",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
"{",
"$",
"this",
"->",
"generateImpliedEndTags",
"(",
"$",
"name",
",",
"$",
"sourceStart",
")",
";",
"if",
"(",
"$",
"this",
"->",
"stack",
"->",
"current",
"->",
"htmlName",
"!==",
"$",
"name",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"\"found </$name> but elements are open that cannot \"",
".",
"\"have implied end tags, closing them\"",
",",
"$",
"sourceStart",
")",
";",
"}",
"$",
"this",
"->",
"popAllUpToName",
"(",
"$",
"name",
",",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
";",
"}"
] |
Generate implied end tags, with an element to exclude, and if the
current element is not now the named excluded element, raise an error.
Then, pop all elements until an element with the name is popped from
the list.
@param string $name The name to exclude
@param int $sourceStart
@param int $sourceLength
|
[
"Generate",
"implied",
"end",
"tags",
"with",
"an",
"element",
"to",
"exclude",
"and",
"if",
"the",
"current",
"element",
"is",
"not",
"now",
"the",
"named",
"excluded",
"element",
"raise",
"an",
"error",
".",
"Then",
"pop",
"all",
"elements",
"until",
"an",
"element",
"with",
"the",
"name",
"is",
"popped",
"from",
"the",
"list",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/TreeBuilder.php#L642-L649
|
train
|
wikimedia/remex-html
|
RemexHtml/Tokenizer/TokenGenerator.php
|
TokenGenerator.generate
|
public static function generate( $text, $options ) {
$tg = new self( $text, $options );
$tg->tokenizer->beginStepping();
while ( $tg->tokenizer->step() ) {
foreach ( $tg->handler->tokens as $token ) {
yield $token;
}
$tg->handler->tokens = [];
}
foreach ( $tg->handler->tokens as $token ) {
yield $token;
}
}
|
php
|
public static function generate( $text, $options ) {
$tg = new self( $text, $options );
$tg->tokenizer->beginStepping();
while ( $tg->tokenizer->step() ) {
foreach ( $tg->handler->tokens as $token ) {
yield $token;
}
$tg->handler->tokens = [];
}
foreach ( $tg->handler->tokens as $token ) {
yield $token;
}
}
|
[
"public",
"static",
"function",
"generate",
"(",
"$",
"text",
",",
"$",
"options",
")",
"{",
"$",
"tg",
"=",
"new",
"self",
"(",
"$",
"text",
",",
"$",
"options",
")",
";",
"$",
"tg",
"->",
"tokenizer",
"->",
"beginStepping",
"(",
")",
";",
"while",
"(",
"$",
"tg",
"->",
"tokenizer",
"->",
"step",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"tg",
"->",
"handler",
"->",
"tokens",
"as",
"$",
"token",
")",
"{",
"yield",
"$",
"token",
";",
"}",
"$",
"tg",
"->",
"handler",
"->",
"tokens",
"=",
"[",
"]",
";",
"}",
"foreach",
"(",
"$",
"tg",
"->",
"handler",
"->",
"tokens",
"as",
"$",
"token",
")",
"{",
"yield",
"$",
"token",
";",
"}",
"}"
] |
Get a Generator which iterates over all tokens in the supplied HTML
@param string $text The HTML
@param array $options The Tokenizer options, see Tokenizer::__construct()
@return Generator
|
[
"Get",
"a",
"Generator",
"which",
"iterates",
"over",
"all",
"tokens",
"in",
"the",
"supplied",
"HTML"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Tokenizer/TokenGenerator.php#L32-L44
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/Element.php
|
Element.isHtmlIntegration
|
public function isHtmlIntegration() {
if ( $this->namespace === HTMLData::NS_MATHML ) {
if ( isset( $this->attrs['encoding'] ) ) {
$encoding = strtolower( $this->attrs['encoding'] );
return $encoding === 'text/html' || $encoding === 'application/xhtml+xml';
} else {
return false;
}
} elseif ( $this->namespace === HTMLData::NS_SVG ) {
return isset( self::$svgHtmlIntegration[$this->name] );
} else {
return false;
}
}
|
php
|
public function isHtmlIntegration() {
if ( $this->namespace === HTMLData::NS_MATHML ) {
if ( isset( $this->attrs['encoding'] ) ) {
$encoding = strtolower( $this->attrs['encoding'] );
return $encoding === 'text/html' || $encoding === 'application/xhtml+xml';
} else {
return false;
}
} elseif ( $this->namespace === HTMLData::NS_SVG ) {
return isset( self::$svgHtmlIntegration[$this->name] );
} else {
return false;
}
}
|
[
"public",
"function",
"isHtmlIntegration",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"namespace",
"===",
"HTMLData",
"::",
"NS_MATHML",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"attrs",
"[",
"'encoding'",
"]",
")",
")",
"{",
"$",
"encoding",
"=",
"strtolower",
"(",
"$",
"this",
"->",
"attrs",
"[",
"'encoding'",
"]",
")",
";",
"return",
"$",
"encoding",
"===",
"'text/html'",
"||",
"$",
"encoding",
"===",
"'application/xhtml+xml'",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"elseif",
"(",
"$",
"this",
"->",
"namespace",
"===",
"HTMLData",
"::",
"NS_SVG",
")",
"{",
"return",
"isset",
"(",
"self",
"::",
"$",
"svgHtmlIntegration",
"[",
"$",
"this",
"->",
"name",
"]",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] |
Is the element an HTML integration point?
@return bool
|
[
"Is",
"the",
"element",
"an",
"HTML",
"integration",
"point?"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/Element.php#L157-L170
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/Element.php
|
Element.getNoahKey
|
public function getNoahKey() {
if ( $this->noahKey === null ) {
$attrs = $this->attrs->getValues();
ksort( $attrs );
$this->noahKey = serialize( [ $this->htmlName, $attrs ] );
}
return $this->noahKey;
}
|
php
|
public function getNoahKey() {
if ( $this->noahKey === null ) {
$attrs = $this->attrs->getValues();
ksort( $attrs );
$this->noahKey = serialize( [ $this->htmlName, $attrs ] );
}
return $this->noahKey;
}
|
[
"public",
"function",
"getNoahKey",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"noahKey",
"===",
"null",
")",
"{",
"$",
"attrs",
"=",
"$",
"this",
"->",
"attrs",
"->",
"getValues",
"(",
")",
";",
"ksort",
"(",
"$",
"attrs",
")",
";",
"$",
"this",
"->",
"noahKey",
"=",
"serialize",
"(",
"[",
"$",
"this",
"->",
"htmlName",
",",
"$",
"attrs",
"]",
")",
";",
"}",
"return",
"$",
"this",
"->",
"noahKey",
";",
"}"
] |
Get a string key for the Noah's Ark algorithm
@return string
|
[
"Get",
"a",
"string",
"key",
"for",
"the",
"Noah",
"s",
"Ark",
"algorithm"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/Element.php#L177-L184
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/Stack.php
|
Stack.dump
|
public function dump() {
$s = '';
for ( $i = 0; $i < $this->length(); $i++ ) {
$item = $this->item( $i );
$s .= "$i. " . $item->getDebugTag();
if ( $i === $this->length() - 1 && $item !== $this->current ) {
$s .= " CURRENT POINTER INCORRECT";
}
$s .= "\n";
}
return $s;
}
|
php
|
public function dump() {
$s = '';
for ( $i = 0; $i < $this->length(); $i++ ) {
$item = $this->item( $i );
$s .= "$i. " . $item->getDebugTag();
if ( $i === $this->length() - 1 && $item !== $this->current ) {
$s .= " CURRENT POINTER INCORRECT";
}
$s .= "\n";
}
return $s;
}
|
[
"public",
"function",
"dump",
"(",
")",
"{",
"$",
"s",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"this",
"->",
"length",
"(",
")",
";",
"$",
"i",
"++",
")",
"{",
"$",
"item",
"=",
"$",
"this",
"->",
"item",
"(",
"$",
"i",
")",
";",
"$",
"s",
".=",
"\"$i. \"",
".",
"$",
"item",
"->",
"getDebugTag",
"(",
")",
";",
"if",
"(",
"$",
"i",
"===",
"$",
"this",
"->",
"length",
"(",
")",
"-",
"1",
"&&",
"$",
"item",
"!==",
"$",
"this",
"->",
"current",
")",
"{",
"$",
"s",
".=",
"\" CURRENT POINTER INCORRECT\"",
";",
"}",
"$",
"s",
".=",
"\"\\n\"",
";",
"}",
"return",
"$",
"s",
";",
"}"
] |
Get a string representation of the stack for debugging purposes.
@return string
|
[
"Get",
"a",
"string",
"representation",
"of",
"the",
"stack",
"for",
"debugging",
"purposes",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/Stack.php#L135-L146
|
train
|
wikimedia/remex-html
|
RemexHtml/TreeBuilder/CachingStack.php
|
CachingStack.getScopeTypesToStack
|
private function getScopeTypesToStack( $ns, $name ) {
if ( $ns === HTMLData::NS_HTML ) {
switch ( $name ) {
case 'html':
case 'table':
case 'template':
return self::$allScopes;
case 'applet':
case 'caption':
case 'td':
case 'th':
case 'marquee':
case 'object':
return self::$nonTableScopes;
case 'ol':
case 'ul':
return self::$listScopes;
case 'button':
return self::$buttonScopes;
case 'option':
case 'optgroup':
return [];
default:
return self::$selectOnly;
}
} elseif ( $ns === HTMLData::NS_MATHML ) {
if ( isset( self::$mathBreakers[$name] ) ) {
return self::$nonTableScopes;
} else {
return self::$selectOnly;
}
} elseif ( $ns === HTMLData::NS_SVG ) {
if ( isset( self::$svgBreakers[$name] ) ) {
return self::$nonTableScopes;
} else {
return self::$selectOnly;
}
} else {
return self::$selectOnly;
}
}
|
php
|
private function getScopeTypesToStack( $ns, $name ) {
if ( $ns === HTMLData::NS_HTML ) {
switch ( $name ) {
case 'html':
case 'table':
case 'template':
return self::$allScopes;
case 'applet':
case 'caption':
case 'td':
case 'th':
case 'marquee':
case 'object':
return self::$nonTableScopes;
case 'ol':
case 'ul':
return self::$listScopes;
case 'button':
return self::$buttonScopes;
case 'option':
case 'optgroup':
return [];
default:
return self::$selectOnly;
}
} elseif ( $ns === HTMLData::NS_MATHML ) {
if ( isset( self::$mathBreakers[$name] ) ) {
return self::$nonTableScopes;
} else {
return self::$selectOnly;
}
} elseif ( $ns === HTMLData::NS_SVG ) {
if ( isset( self::$svgBreakers[$name] ) ) {
return self::$nonTableScopes;
} else {
return self::$selectOnly;
}
} else {
return self::$selectOnly;
}
}
|
[
"private",
"function",
"getScopeTypesToStack",
"(",
"$",
"ns",
",",
"$",
"name",
")",
"{",
"if",
"(",
"$",
"ns",
"===",
"HTMLData",
"::",
"NS_HTML",
")",
"{",
"switch",
"(",
"$",
"name",
")",
"{",
"case",
"'html'",
":",
"case",
"'table'",
":",
"case",
"'template'",
":",
"return",
"self",
"::",
"$",
"allScopes",
";",
"case",
"'applet'",
":",
"case",
"'caption'",
":",
"case",
"'td'",
":",
"case",
"'th'",
":",
"case",
"'marquee'",
":",
"case",
"'object'",
":",
"return",
"self",
"::",
"$",
"nonTableScopes",
";",
"case",
"'ol'",
":",
"case",
"'ul'",
":",
"return",
"self",
"::",
"$",
"listScopes",
";",
"case",
"'button'",
":",
"return",
"self",
"::",
"$",
"buttonScopes",
";",
"case",
"'option'",
":",
"case",
"'optgroup'",
":",
"return",
"[",
"]",
";",
"default",
":",
"return",
"self",
"::",
"$",
"selectOnly",
";",
"}",
"}",
"elseif",
"(",
"$",
"ns",
"===",
"HTMLData",
"::",
"NS_MATHML",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"mathBreakers",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"nonTableScopes",
";",
"}",
"else",
"{",
"return",
"self",
"::",
"$",
"selectOnly",
";",
"}",
"}",
"elseif",
"(",
"$",
"ns",
"===",
"HTMLData",
"::",
"NS_SVG",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"svgBreakers",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"nonTableScopes",
";",
"}",
"else",
"{",
"return",
"self",
"::",
"$",
"selectOnly",
";",
"}",
"}",
"else",
"{",
"return",
"self",
"::",
"$",
"selectOnly",
";",
"}",
"}"
] |
For a given namespace and element name, get the list of scopes
for which a new scope should be created and the old one needs to
be pushed onto the scope stack.
|
[
"For",
"a",
"given",
"namespace",
"and",
"element",
"name",
"get",
"the",
"list",
"of",
"scopes",
"for",
"which",
"a",
"new",
"scope",
"should",
"be",
"created",
"and",
"the",
"old",
"one",
"needs",
"to",
"be",
"pushed",
"onto",
"the",
"scope",
"stack",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/TreeBuilder/CachingStack.php#L172-L217
|
train
|
wikimedia/remex-html
|
RemexHtml/Serializer/Serializer.php
|
Serializer.getLastChild
|
public function getLastChild( SerializerNode $node ) {
$children = $node->children;
$lastChildIndex = count( $children ) - 1;
$lastChild = $lastChildIndex >= 0 ? $children[$lastChildIndex] : null;
return $lastChild;
}
|
php
|
public function getLastChild( SerializerNode $node ) {
$children = $node->children;
$lastChildIndex = count( $children ) - 1;
$lastChild = $lastChildIndex >= 0 ? $children[$lastChildIndex] : null;
return $lastChild;
}
|
[
"public",
"function",
"getLastChild",
"(",
"SerializerNode",
"$",
"node",
")",
"{",
"$",
"children",
"=",
"$",
"node",
"->",
"children",
";",
"$",
"lastChildIndex",
"=",
"count",
"(",
"$",
"children",
")",
"-",
"1",
";",
"$",
"lastChild",
"=",
"$",
"lastChildIndex",
">=",
"0",
"?",
"$",
"children",
"[",
"$",
"lastChildIndex",
"]",
":",
"null",
";",
"return",
"$",
"lastChild",
";",
"}"
] |
Get the last child of a given SerializerNode
@param SerializerNode $node
@return SerializerNode|string|null
|
[
"Get",
"the",
"last",
"child",
"of",
"a",
"given",
"SerializerNode"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Serializer/Serializer.php#L103-L108
|
train
|
wikimedia/remex-html
|
RemexHtml/Serializer/Serializer.php
|
Serializer.insertElement
|
public function insertElement( $preposition, $refElement, Element $element, $void,
$sourceStart, $sourceLength
) {
list( $parent, $refNode ) = $this->interpretPlacement( $preposition, $refElement );
$children =& $parent->children;
$lastChildIndex = count( $children ) - 1;
$lastChild = $lastChildIndex >= 0 ? $children[$lastChildIndex] : null;
if ( $element->userData ) {
// This element has already been inserted, this is a reparenting operation
$self = $element->userData;
$oldParent = $this->nodes[$self->parentId];
$oldChildren =& $oldParent->children;
$oldChildIndex = array_search( $self, $oldChildren, true );
if ( $oldChildIndex === false ) {
throw new SerializerError( "cannot find node to reparent: " .
$element->getDebugTag() );
}
// Remove from the old parent, update parent pointer
$oldChildren[$oldChildIndex] = '';
$self->parentId = $parent->id;
} else {
// Inserting an element which has not been seen before
$id = $element->uid;
$self = new SerializerNode( $id, $parent->id, $element->namespace,
$element->name, $element->attrs, $void );
$this->nodes[$id] = $element->userData = $self;
}
if ( $preposition === TreeBuilder::BEFORE ) {
// Insert before element
if ( $lastChild !== $refNode ) {
$refIndex = array_search( $refNode, $children, true );
throw new SerializerError( "invalid insert position $refIndex/$lastChildIndex" );
}
$children[$lastChildIndex] = $self;
$children[$lastChildIndex + 1] = $refNode;
} else {
// Append to the list of children
$children[] = $self;
}
}
|
php
|
public function insertElement( $preposition, $refElement, Element $element, $void,
$sourceStart, $sourceLength
) {
list( $parent, $refNode ) = $this->interpretPlacement( $preposition, $refElement );
$children =& $parent->children;
$lastChildIndex = count( $children ) - 1;
$lastChild = $lastChildIndex >= 0 ? $children[$lastChildIndex] : null;
if ( $element->userData ) {
// This element has already been inserted, this is a reparenting operation
$self = $element->userData;
$oldParent = $this->nodes[$self->parentId];
$oldChildren =& $oldParent->children;
$oldChildIndex = array_search( $self, $oldChildren, true );
if ( $oldChildIndex === false ) {
throw new SerializerError( "cannot find node to reparent: " .
$element->getDebugTag() );
}
// Remove from the old parent, update parent pointer
$oldChildren[$oldChildIndex] = '';
$self->parentId = $parent->id;
} else {
// Inserting an element which has not been seen before
$id = $element->uid;
$self = new SerializerNode( $id, $parent->id, $element->namespace,
$element->name, $element->attrs, $void );
$this->nodes[$id] = $element->userData = $self;
}
if ( $preposition === TreeBuilder::BEFORE ) {
// Insert before element
if ( $lastChild !== $refNode ) {
$refIndex = array_search( $refNode, $children, true );
throw new SerializerError( "invalid insert position $refIndex/$lastChildIndex" );
}
$children[$lastChildIndex] = $self;
$children[$lastChildIndex + 1] = $refNode;
} else {
// Append to the list of children
$children[] = $self;
}
}
|
[
"public",
"function",
"insertElement",
"(",
"$",
"preposition",
",",
"$",
"refElement",
",",
"Element",
"$",
"element",
",",
"$",
"void",
",",
"$",
"sourceStart",
",",
"$",
"sourceLength",
")",
"{",
"list",
"(",
"$",
"parent",
",",
"$",
"refNode",
")",
"=",
"$",
"this",
"->",
"interpretPlacement",
"(",
"$",
"preposition",
",",
"$",
"refElement",
")",
";",
"$",
"children",
"=",
"&",
"$",
"parent",
"->",
"children",
";",
"$",
"lastChildIndex",
"=",
"count",
"(",
"$",
"children",
")",
"-",
"1",
";",
"$",
"lastChild",
"=",
"$",
"lastChildIndex",
">=",
"0",
"?",
"$",
"children",
"[",
"$",
"lastChildIndex",
"]",
":",
"null",
";",
"if",
"(",
"$",
"element",
"->",
"userData",
")",
"{",
"// This element has already been inserted, this is a reparenting operation",
"$",
"self",
"=",
"$",
"element",
"->",
"userData",
";",
"$",
"oldParent",
"=",
"$",
"this",
"->",
"nodes",
"[",
"$",
"self",
"->",
"parentId",
"]",
";",
"$",
"oldChildren",
"=",
"&",
"$",
"oldParent",
"->",
"children",
";",
"$",
"oldChildIndex",
"=",
"array_search",
"(",
"$",
"self",
",",
"$",
"oldChildren",
",",
"true",
")",
";",
"if",
"(",
"$",
"oldChildIndex",
"===",
"false",
")",
"{",
"throw",
"new",
"SerializerError",
"(",
"\"cannot find node to reparent: \"",
".",
"$",
"element",
"->",
"getDebugTag",
"(",
")",
")",
";",
"}",
"// Remove from the old parent, update parent pointer",
"$",
"oldChildren",
"[",
"$",
"oldChildIndex",
"]",
"=",
"''",
";",
"$",
"self",
"->",
"parentId",
"=",
"$",
"parent",
"->",
"id",
";",
"}",
"else",
"{",
"// Inserting an element which has not been seen before",
"$",
"id",
"=",
"$",
"element",
"->",
"uid",
";",
"$",
"self",
"=",
"new",
"SerializerNode",
"(",
"$",
"id",
",",
"$",
"parent",
"->",
"id",
",",
"$",
"element",
"->",
"namespace",
",",
"$",
"element",
"->",
"name",
",",
"$",
"element",
"->",
"attrs",
",",
"$",
"void",
")",
";",
"$",
"this",
"->",
"nodes",
"[",
"$",
"id",
"]",
"=",
"$",
"element",
"->",
"userData",
"=",
"$",
"self",
";",
"}",
"if",
"(",
"$",
"preposition",
"===",
"TreeBuilder",
"::",
"BEFORE",
")",
"{",
"// Insert before element",
"if",
"(",
"$",
"lastChild",
"!==",
"$",
"refNode",
")",
"{",
"$",
"refIndex",
"=",
"array_search",
"(",
"$",
"refNode",
",",
"$",
"children",
",",
"true",
")",
";",
"throw",
"new",
"SerializerError",
"(",
"\"invalid insert position $refIndex/$lastChildIndex\"",
")",
";",
"}",
"$",
"children",
"[",
"$",
"lastChildIndex",
"]",
"=",
"$",
"self",
";",
"$",
"children",
"[",
"$",
"lastChildIndex",
"+",
"1",
"]",
"=",
"$",
"refNode",
";",
"}",
"else",
"{",
"// Append to the list of children",
"$",
"children",
"[",
"]",
"=",
"$",
"self",
";",
"}",
"}"
] |
Insert an element
@param int $preposition
@param Element|SerializerNode|null $refElement
@param Element $element
@param bool $void
@param int $sourceStart
@param int $sourceLength
|
[
"Insert",
"an",
"element"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Serializer/Serializer.php#L190-L231
|
train
|
wikimedia/remex-html
|
RemexHtml/Serializer/Serializer.php
|
Serializer.serializeNode
|
private function serializeNode( SerializerNode $parent, SerializerNode $node, $destroy ) {
if ( $node->void ) {
$contents = null;
} else {
$contents = '';
foreach ( $node->children as $childIndex => $child ) {
if ( is_string( $child ) ) {
$contents .= $child;
} else {
$contents .= $this->serializeNode( $node, $child, $destroy );
}
}
}
if ( $destroy ) {
unset( $this->nodes[$node->id] );
}
return $this->formatter->element( $parent, $node, $contents );
}
|
php
|
private function serializeNode( SerializerNode $parent, SerializerNode $node, $destroy ) {
if ( $node->void ) {
$contents = null;
} else {
$contents = '';
foreach ( $node->children as $childIndex => $child ) {
if ( is_string( $child ) ) {
$contents .= $child;
} else {
$contents .= $this->serializeNode( $node, $child, $destroy );
}
}
}
if ( $destroy ) {
unset( $this->nodes[$node->id] );
}
return $this->formatter->element( $parent, $node, $contents );
}
|
[
"private",
"function",
"serializeNode",
"(",
"SerializerNode",
"$",
"parent",
",",
"SerializerNode",
"$",
"node",
",",
"$",
"destroy",
")",
"{",
"if",
"(",
"$",
"node",
"->",
"void",
")",
"{",
"$",
"contents",
"=",
"null",
";",
"}",
"else",
"{",
"$",
"contents",
"=",
"''",
";",
"foreach",
"(",
"$",
"node",
"->",
"children",
"as",
"$",
"childIndex",
"=>",
"$",
"child",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"child",
")",
")",
"{",
"$",
"contents",
".=",
"$",
"child",
";",
"}",
"else",
"{",
"$",
"contents",
".=",
"$",
"this",
"->",
"serializeNode",
"(",
"$",
"node",
",",
"$",
"child",
",",
"$",
"destroy",
")",
";",
"}",
"}",
"}",
"if",
"(",
"$",
"destroy",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"nodes",
"[",
"$",
"node",
"->",
"id",
"]",
")",
";",
"}",
"return",
"$",
"this",
"->",
"formatter",
"->",
"element",
"(",
"$",
"parent",
",",
"$",
"node",
",",
"$",
"contents",
")",
";",
"}"
] |
Serialize a specific node
@param SerializerNode $parent The parent of $node
@param SerializerNode $node The node to serialize
@param bool $destroy If true, the node and its descendants will be removed from $this->nodes
@return string
|
[
"Serialize",
"a",
"specific",
"node"
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Serializer/Serializer.php#L258-L275
|
train
|
wikimedia/remex-html
|
RemexHtml/Serializer/Serializer.php
|
Serializer.dump
|
public function dump() {
$s = $this->serializeNode( $this->root, $this->root, false );
return substr( $s, 2, -3 ) . "\n";
}
|
php
|
public function dump() {
$s = $this->serializeNode( $this->root, $this->root, false );
return substr( $s, 2, -3 ) . "\n";
}
|
[
"public",
"function",
"dump",
"(",
")",
"{",
"$",
"s",
"=",
"$",
"this",
"->",
"serializeNode",
"(",
"$",
"this",
"->",
"root",
",",
"$",
"this",
"->",
"root",
",",
"false",
")",
";",
"return",
"substr",
"(",
"$",
"s",
",",
"2",
",",
"-",
"3",
")",
".",
"\"\\n\"",
";",
"}"
] |
Get a text representation of the current state of the serializer, for
debugging.
@return string
|
[
"Get",
"a",
"text",
"representation",
"of",
"the",
"current",
"state",
"of",
"the",
"serializer",
"for",
"debugging",
"."
] |
6cab92774e567e2b78bad7bfa8f48523f47e4607
|
https://github.com/wikimedia/remex-html/blob/6cab92774e567e2b78bad7bfa8f48523f47e4607/RemexHtml/Serializer/Serializer.php#L352-L355
|
train
|
bwaidelich/Wwwision.GraphQL
|
Classes/View/GraphQlView.php
|
GraphQlView.formatResult
|
private function formatResult(ExecutionResult $executionResult)
{
$convertedResult = [
'data' => $executionResult->data,
];
if (!empty($executionResult->errors)) {
$convertedResult['errors'] = array_map(function(Error $error) {
$errorResult = [
'message' => $error->message,
'locations' => $error->getLocations()
];
$exception = $error->getPrevious();
if ($exception instanceof FlowException) {
$errorResult['message'] = HttpResponse::getStatusMessageByCode($exception->getStatusCode());
$errorResult['_exceptionCode'] = $exception->getCode();
$errorResult['_statusCode'] = $exception->getStatusCode();
$errorResult['_referenceCode'] = $exception->getReferenceCode();
}
if ($exception instanceof \Exception) {
$this->systemLogger->logException($exception);
}
return $errorResult;
}, $executionResult->errors);
}
if (!empty($executionResult->extensions)) {
$convertedResult['extensions'] = (array)$executionResult->extensions;
}
return $convertedResult;
}
|
php
|
private function formatResult(ExecutionResult $executionResult)
{
$convertedResult = [
'data' => $executionResult->data,
];
if (!empty($executionResult->errors)) {
$convertedResult['errors'] = array_map(function(Error $error) {
$errorResult = [
'message' => $error->message,
'locations' => $error->getLocations()
];
$exception = $error->getPrevious();
if ($exception instanceof FlowException) {
$errorResult['message'] = HttpResponse::getStatusMessageByCode($exception->getStatusCode());
$errorResult['_exceptionCode'] = $exception->getCode();
$errorResult['_statusCode'] = $exception->getStatusCode();
$errorResult['_referenceCode'] = $exception->getReferenceCode();
}
if ($exception instanceof \Exception) {
$this->systemLogger->logException($exception);
}
return $errorResult;
}, $executionResult->errors);
}
if (!empty($executionResult->extensions)) {
$convertedResult['extensions'] = (array)$executionResult->extensions;
}
return $convertedResult;
}
|
[
"private",
"function",
"formatResult",
"(",
"ExecutionResult",
"$",
"executionResult",
")",
"{",
"$",
"convertedResult",
"=",
"[",
"'data'",
"=>",
"$",
"executionResult",
"->",
"data",
",",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"executionResult",
"->",
"errors",
")",
")",
"{",
"$",
"convertedResult",
"[",
"'errors'",
"]",
"=",
"array_map",
"(",
"function",
"(",
"Error",
"$",
"error",
")",
"{",
"$",
"errorResult",
"=",
"[",
"'message'",
"=>",
"$",
"error",
"->",
"message",
",",
"'locations'",
"=>",
"$",
"error",
"->",
"getLocations",
"(",
")",
"]",
";",
"$",
"exception",
"=",
"$",
"error",
"->",
"getPrevious",
"(",
")",
";",
"if",
"(",
"$",
"exception",
"instanceof",
"FlowException",
")",
"{",
"$",
"errorResult",
"[",
"'message'",
"]",
"=",
"HttpResponse",
"::",
"getStatusMessageByCode",
"(",
"$",
"exception",
"->",
"getStatusCode",
"(",
")",
")",
";",
"$",
"errorResult",
"[",
"'_exceptionCode'",
"]",
"=",
"$",
"exception",
"->",
"getCode",
"(",
")",
";",
"$",
"errorResult",
"[",
"'_statusCode'",
"]",
"=",
"$",
"exception",
"->",
"getStatusCode",
"(",
")",
";",
"$",
"errorResult",
"[",
"'_referenceCode'",
"]",
"=",
"$",
"exception",
"->",
"getReferenceCode",
"(",
")",
";",
"}",
"if",
"(",
"$",
"exception",
"instanceof",
"\\",
"Exception",
")",
"{",
"$",
"this",
"->",
"systemLogger",
"->",
"logException",
"(",
"$",
"exception",
")",
";",
"}",
"return",
"$",
"errorResult",
";",
"}",
",",
"$",
"executionResult",
"->",
"errors",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"executionResult",
"->",
"extensions",
")",
")",
"{",
"$",
"convertedResult",
"[",
"'extensions'",
"]",
"=",
"(",
"array",
")",
"$",
"executionResult",
"->",
"extensions",
";",
"}",
"return",
"$",
"convertedResult",
";",
"}"
] |
Formats the result of the GraphQL execution, converting Flow exceptions by hiding the original exception message
and adding status- and referenceCode.
@param ExecutionResult $executionResult
@return array
|
[
"Formats",
"the",
"result",
"of",
"the",
"GraphQL",
"execution",
"converting",
"Flow",
"exceptions",
"by",
"hiding",
"the",
"original",
"exception",
"message",
"and",
"adding",
"status",
"-",
"and",
"referenceCode",
"."
] |
72581f35904999876ce5762969135adaf39375ad
|
https://github.com/bwaidelich/Wwwision.GraphQL/blob/72581f35904999876ce5762969135adaf39375ad/Classes/View/GraphQlView.php#L49-L77
|
train
|
verbb/field-manager
|
src/controllers/BaseController.php
|
BaseController.actionSaveField
|
public function actionSaveField()
{
$this->requirePostRequest();
$fieldsService = Craft::$app->getFields();
$request = Craft::$app->getRequest();
$type = $request->getRequiredBodyParam('type');
$field = $fieldsService->createField([
'type' => $type,
'id' => $request->getBodyParam('fieldId'),
'groupId' => $request->getRequiredBodyParam('group'),
'name' => $request->getBodyParam('name'),
'handle' => $request->getBodyParam('handle'),
'instructions' => $request->getBodyParam('instructions'),
'translationMethod' => $request->getBodyParam('translationMethod', Field::TRANSLATION_METHOD_NONE),
'translationKeyFormat' => $request->getBodyParam('translationKeyFormat'),
'settings' => $request->getBodyParam('types.' . $type),
]);
if (!$fieldsService->saveField($field)) {
return $this->asJson(['success' => false, 'error' => $field->getErrors()]);
}
return $this->asJson(['success' => true]);
}
|
php
|
public function actionSaveField()
{
$this->requirePostRequest();
$fieldsService = Craft::$app->getFields();
$request = Craft::$app->getRequest();
$type = $request->getRequiredBodyParam('type');
$field = $fieldsService->createField([
'type' => $type,
'id' => $request->getBodyParam('fieldId'),
'groupId' => $request->getRequiredBodyParam('group'),
'name' => $request->getBodyParam('name'),
'handle' => $request->getBodyParam('handle'),
'instructions' => $request->getBodyParam('instructions'),
'translationMethod' => $request->getBodyParam('translationMethod', Field::TRANSLATION_METHOD_NONE),
'translationKeyFormat' => $request->getBodyParam('translationKeyFormat'),
'settings' => $request->getBodyParam('types.' . $type),
]);
if (!$fieldsService->saveField($field)) {
return $this->asJson(['success' => false, 'error' => $field->getErrors()]);
}
return $this->asJson(['success' => true]);
}
|
[
"public",
"function",
"actionSaveField",
"(",
")",
"{",
"$",
"this",
"->",
"requirePostRequest",
"(",
")",
";",
"$",
"fieldsService",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getFields",
"(",
")",
";",
"$",
"request",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getRequest",
"(",
")",
";",
"$",
"type",
"=",
"$",
"request",
"->",
"getRequiredBodyParam",
"(",
"'type'",
")",
";",
"$",
"field",
"=",
"$",
"fieldsService",
"->",
"createField",
"(",
"[",
"'type'",
"=>",
"$",
"type",
",",
"'id'",
"=>",
"$",
"request",
"->",
"getBodyParam",
"(",
"'fieldId'",
")",
",",
"'groupId'",
"=>",
"$",
"request",
"->",
"getRequiredBodyParam",
"(",
"'group'",
")",
",",
"'name'",
"=>",
"$",
"request",
"->",
"getBodyParam",
"(",
"'name'",
")",
",",
"'handle'",
"=>",
"$",
"request",
"->",
"getBodyParam",
"(",
"'handle'",
")",
",",
"'instructions'",
"=>",
"$",
"request",
"->",
"getBodyParam",
"(",
"'instructions'",
")",
",",
"'translationMethod'",
"=>",
"$",
"request",
"->",
"getBodyParam",
"(",
"'translationMethod'",
",",
"Field",
"::",
"TRANSLATION_METHOD_NONE",
")",
",",
"'translationKeyFormat'",
"=>",
"$",
"request",
"->",
"getBodyParam",
"(",
"'translationKeyFormat'",
")",
",",
"'settings'",
"=>",
"$",
"request",
"->",
"getBodyParam",
"(",
"'types.'",
".",
"$",
"type",
")",
",",
"]",
")",
";",
"if",
"(",
"!",
"$",
"fieldsService",
"->",
"saveField",
"(",
"$",
"field",
")",
")",
"{",
"return",
"$",
"this",
"->",
"asJson",
"(",
"[",
"'success'",
"=>",
"false",
",",
"'error'",
"=>",
"$",
"field",
"->",
"getErrors",
"(",
")",
"]",
")",
";",
"}",
"return",
"$",
"this",
"->",
"asJson",
"(",
"[",
"'success'",
"=>",
"true",
"]",
")",
";",
"}"
] |
From Craft's native saveField, which doesn't really support Ajax...
|
[
"From",
"Craft",
"s",
"native",
"saveField",
"which",
"doesn",
"t",
"really",
"support",
"Ajax",
"..."
] |
7e523ae41715ea888910a604a4b37f5503c04b39
|
https://github.com/verbb/field-manager/blob/7e523ae41715ea888910a604a4b37f5503c04b39/src/controllers/BaseController.php#L231-L256
|
train
|
Superbalist/laravel-pubsub
|
src/PubSubServiceProvider.php
|
PubSubServiceProvider.registerAdapterDependencies
|
protected function registerAdapterDependencies()
{
$this->app->bind('pubsub.redis.redis_client', function ($app, $parameters) {
return new RedisClient($parameters['config']);
});
$this->app->bind('pubsub.gcloud.pub_sub_client', function ($app, $parameters) {
return new GoogleCloudPubSubClient($parameters['config']);
});
$this->app->bind('pubsub.kafka.topic_conf', function () {
return new \RdKafka\TopicConf();
});
$this->app->bind('pubsub.kafka.producer', function () {
return new \RdKafka\Producer();
});
$this->app->bind('pubsub.kafka.conf', function () {
return new \RdKafka\Conf();
});
$this->app->bind('pubsub.kafka.consumer', function ($app, $parameters) {
return new \RdKafka\KafkaConsumer($parameters['conf']);
});
$this->app->bind('pubsub.http.client', function () {
return new Client();
});
}
|
php
|
protected function registerAdapterDependencies()
{
$this->app->bind('pubsub.redis.redis_client', function ($app, $parameters) {
return new RedisClient($parameters['config']);
});
$this->app->bind('pubsub.gcloud.pub_sub_client', function ($app, $parameters) {
return new GoogleCloudPubSubClient($parameters['config']);
});
$this->app->bind('pubsub.kafka.topic_conf', function () {
return new \RdKafka\TopicConf();
});
$this->app->bind('pubsub.kafka.producer', function () {
return new \RdKafka\Producer();
});
$this->app->bind('pubsub.kafka.conf', function () {
return new \RdKafka\Conf();
});
$this->app->bind('pubsub.kafka.consumer', function ($app, $parameters) {
return new \RdKafka\KafkaConsumer($parameters['conf']);
});
$this->app->bind('pubsub.http.client', function () {
return new Client();
});
}
|
[
"protected",
"function",
"registerAdapterDependencies",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'pubsub.redis.redis_client'",
",",
"function",
"(",
"$",
"app",
",",
"$",
"parameters",
")",
"{",
"return",
"new",
"RedisClient",
"(",
"$",
"parameters",
"[",
"'config'",
"]",
")",
";",
"}",
")",
";",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'pubsub.gcloud.pub_sub_client'",
",",
"function",
"(",
"$",
"app",
",",
"$",
"parameters",
")",
"{",
"return",
"new",
"GoogleCloudPubSubClient",
"(",
"$",
"parameters",
"[",
"'config'",
"]",
")",
";",
"}",
")",
";",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'pubsub.kafka.topic_conf'",
",",
"function",
"(",
")",
"{",
"return",
"new",
"\\",
"RdKafka",
"\\",
"TopicConf",
"(",
")",
";",
"}",
")",
";",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'pubsub.kafka.producer'",
",",
"function",
"(",
")",
"{",
"return",
"new",
"\\",
"RdKafka",
"\\",
"Producer",
"(",
")",
";",
"}",
")",
";",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'pubsub.kafka.conf'",
",",
"function",
"(",
")",
"{",
"return",
"new",
"\\",
"RdKafka",
"\\",
"Conf",
"(",
")",
";",
"}",
")",
";",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'pubsub.kafka.consumer'",
",",
"function",
"(",
"$",
"app",
",",
"$",
"parameters",
")",
"{",
"return",
"new",
"\\",
"RdKafka",
"\\",
"KafkaConsumer",
"(",
"$",
"parameters",
"[",
"'conf'",
"]",
")",
";",
"}",
")",
";",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'pubsub.http.client'",
",",
"function",
"(",
")",
"{",
"return",
"new",
"Client",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Register adapter dependencies in the container.
|
[
"Register",
"adapter",
"dependencies",
"in",
"the",
"container",
"."
] |
194e079f44279cf89a029c6e0a7fa949bb934970
|
https://github.com/Superbalist/laravel-pubsub/blob/194e079f44279cf89a029c6e0a7fa949bb934970/src/PubSubServiceProvider.php#L53-L82
|
train
|
Superbalist/laravel-pubsub
|
src/PubSubManager.php
|
PubSubManager.makeConnection
|
protected function makeConnection($name)
{
$config = $this->getConnectionConfig($name);
if (isset($this->extensions[$name])) {
return call_user_func($this->extensions[$name], $config, $name);
}
if (!isset($config['driver'])) {
throw new InvalidArgumentException(
sprintf('The pub-sub connection [%s] is missing a "driver" config var.', $name)
);
}
return $this->factory->make($config['driver'], array_except($config, ['driver']));
}
|
php
|
protected function makeConnection($name)
{
$config = $this->getConnectionConfig($name);
if (isset($this->extensions[$name])) {
return call_user_func($this->extensions[$name], $config, $name);
}
if (!isset($config['driver'])) {
throw new InvalidArgumentException(
sprintf('The pub-sub connection [%s] is missing a "driver" config var.', $name)
);
}
return $this->factory->make($config['driver'], array_except($config, ['driver']));
}
|
[
"protected",
"function",
"makeConnection",
"(",
"$",
"name",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConnectionConfig",
"(",
"$",
"name",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"extensions",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"call_user_func",
"(",
"$",
"this",
"->",
"extensions",
"[",
"$",
"name",
"]",
",",
"$",
"config",
",",
"$",
"name",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"config",
"[",
"'driver'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The pub-sub connection [%s] is missing a \"driver\" config var.'",
",",
"$",
"name",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"factory",
"->",
"make",
"(",
"$",
"config",
"[",
"'driver'",
"]",
",",
"array_except",
"(",
"$",
"config",
",",
"[",
"'driver'",
"]",
")",
")",
";",
"}"
] |
Make an instance of a pub-sub adapter interface.
@param string $name
@return PubSubAdapterInterface
|
[
"Make",
"an",
"instance",
"of",
"a",
"pub",
"-",
"sub",
"adapter",
"interface",
"."
] |
194e079f44279cf89a029c6e0a7fa949bb934970
|
https://github.com/Superbalist/laravel-pubsub/blob/194e079f44279cf89a029c6e0a7fa949bb934970/src/PubSubManager.php#L68-L83
|
train
|
Superbalist/laravel-pubsub
|
src/PubSubManager.php
|
PubSubManager.getConnectionConfig
|
protected function getConnectionConfig($name)
{
$connections = $this->getConfig()['connections'];
if (!isset($connections[$name])) {
throw new InvalidArgumentException(sprintf('The pub-sub connection [%s] is not configured.', $name));
}
$config = $connections[$name];
if (isset($config['subscribe_connection'])) {
$config['subscribe_connection_config'] = $this->getConnectionConfig($config['subscribe_connection']);
}
return $config;
}
|
php
|
protected function getConnectionConfig($name)
{
$connections = $this->getConfig()['connections'];
if (!isset($connections[$name])) {
throw new InvalidArgumentException(sprintf('The pub-sub connection [%s] is not configured.', $name));
}
$config = $connections[$name];
if (isset($config['subscribe_connection'])) {
$config['subscribe_connection_config'] = $this->getConnectionConfig($config['subscribe_connection']);
}
return $config;
}
|
[
"protected",
"function",
"getConnectionConfig",
"(",
"$",
"name",
")",
"{",
"$",
"connections",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
"[",
"'connections'",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"connections",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The pub-sub connection [%s] is not configured.'",
",",
"$",
"name",
")",
")",
";",
"}",
"$",
"config",
"=",
"$",
"connections",
"[",
"$",
"name",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"config",
"[",
"'subscribe_connection'",
"]",
")",
")",
"{",
"$",
"config",
"[",
"'subscribe_connection_config'",
"]",
"=",
"$",
"this",
"->",
"getConnectionConfig",
"(",
"$",
"config",
"[",
"'subscribe_connection'",
"]",
")",
";",
"}",
"return",
"$",
"config",
";",
"}"
] |
Return the pubsub config for the given connection.
@param string $name
@return array
|
[
"Return",
"the",
"pubsub",
"config",
"for",
"the",
"given",
"connection",
"."
] |
194e079f44279cf89a029c6e0a7fa949bb934970
|
https://github.com/Superbalist/laravel-pubsub/blob/194e079f44279cf89a029c6e0a7fa949bb934970/src/PubSubManager.php#L92-L106
|
train
|
Superbalist/laravel-pubsub
|
src/PubSubConnectionFactory.php
|
PubSubConnectionFactory.make
|
public function make($driver, array $config = [])
{
switch ($driver) {
case '/dev/null':
return new DevNullPubSubAdapter();
case 'local':
return new LocalPubSubAdapter();
case 'redis':
return $this->makeRedisAdapter($config);
case 'kafka':
return $this->makeKafkaAdapter($config);
case 'gcloud':
return $this->makeGoogleCloudAdapter($config);
case 'http':
return $this->makeHTTPAdapter($config);
}
throw new InvalidArgumentException(sprintf('The driver [%s] is not supported.', $driver));
}
|
php
|
public function make($driver, array $config = [])
{
switch ($driver) {
case '/dev/null':
return new DevNullPubSubAdapter();
case 'local':
return new LocalPubSubAdapter();
case 'redis':
return $this->makeRedisAdapter($config);
case 'kafka':
return $this->makeKafkaAdapter($config);
case 'gcloud':
return $this->makeGoogleCloudAdapter($config);
case 'http':
return $this->makeHTTPAdapter($config);
}
throw new InvalidArgumentException(sprintf('The driver [%s] is not supported.', $driver));
}
|
[
"public",
"function",
"make",
"(",
"$",
"driver",
",",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"switch",
"(",
"$",
"driver",
")",
"{",
"case",
"'/dev/null'",
":",
"return",
"new",
"DevNullPubSubAdapter",
"(",
")",
";",
"case",
"'local'",
":",
"return",
"new",
"LocalPubSubAdapter",
"(",
")",
";",
"case",
"'redis'",
":",
"return",
"$",
"this",
"->",
"makeRedisAdapter",
"(",
"$",
"config",
")",
";",
"case",
"'kafka'",
":",
"return",
"$",
"this",
"->",
"makeKafkaAdapter",
"(",
"$",
"config",
")",
";",
"case",
"'gcloud'",
":",
"return",
"$",
"this",
"->",
"makeGoogleCloudAdapter",
"(",
"$",
"config",
")",
";",
"case",
"'http'",
":",
"return",
"$",
"this",
"->",
"makeHTTPAdapter",
"(",
"$",
"config",
")",
";",
"}",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The driver [%s] is not supported.'",
",",
"$",
"driver",
")",
")",
";",
"}"
] |
Factory a PubSubAdapterInterface.
@param string $driver
@param array $config
@return PubSubAdapterInterface
|
[
"Factory",
"a",
"PubSubAdapterInterface",
"."
] |
194e079f44279cf89a029c6e0a7fa949bb934970
|
https://github.com/Superbalist/laravel-pubsub/blob/194e079f44279cf89a029c6e0a7fa949bb934970/src/PubSubConnectionFactory.php#L38-L56
|
train
|
Superbalist/laravel-pubsub
|
src/PubSubConnectionFactory.php
|
PubSubConnectionFactory.makeKafkaAdapter
|
protected function makeKafkaAdapter(array $config)
{
// create producer
$producer = $this->container->makeWith('pubsub.kafka.producer');
$producer->addBrokers($config['brokers']);
// create consumer
$topicConf = $this->container->makeWith('pubsub.kafka.topic_conf');
$topicConf->set('auto.offset.reset', 'smallest');
$conf = $this->container->makeWith('pubsub.kafka.conf');
$conf->set('group.id', array_get($config, 'consumer_group_id', 'php-pubsub'));
$conf->set('metadata.broker.list', $config['brokers']);
$conf->set('enable.auto.commit', 'false');
$conf->set('offset.store.method', 'broker');
$conf->setDefaultTopicConf($topicConf);
$consumer = $this->container->makeWith('pubsub.kafka.consumer', ['conf' => $conf]);
return new KafkaPubSubAdapter($producer, $consumer);
}
|
php
|
protected function makeKafkaAdapter(array $config)
{
// create producer
$producer = $this->container->makeWith('pubsub.kafka.producer');
$producer->addBrokers($config['brokers']);
// create consumer
$topicConf = $this->container->makeWith('pubsub.kafka.topic_conf');
$topicConf->set('auto.offset.reset', 'smallest');
$conf = $this->container->makeWith('pubsub.kafka.conf');
$conf->set('group.id', array_get($config, 'consumer_group_id', 'php-pubsub'));
$conf->set('metadata.broker.list', $config['brokers']);
$conf->set('enable.auto.commit', 'false');
$conf->set('offset.store.method', 'broker');
$conf->setDefaultTopicConf($topicConf);
$consumer = $this->container->makeWith('pubsub.kafka.consumer', ['conf' => $conf]);
return new KafkaPubSubAdapter($producer, $consumer);
}
|
[
"protected",
"function",
"makeKafkaAdapter",
"(",
"array",
"$",
"config",
")",
"{",
"// create producer",
"$",
"producer",
"=",
"$",
"this",
"->",
"container",
"->",
"makeWith",
"(",
"'pubsub.kafka.producer'",
")",
";",
"$",
"producer",
"->",
"addBrokers",
"(",
"$",
"config",
"[",
"'brokers'",
"]",
")",
";",
"// create consumer",
"$",
"topicConf",
"=",
"$",
"this",
"->",
"container",
"->",
"makeWith",
"(",
"'pubsub.kafka.topic_conf'",
")",
";",
"$",
"topicConf",
"->",
"set",
"(",
"'auto.offset.reset'",
",",
"'smallest'",
")",
";",
"$",
"conf",
"=",
"$",
"this",
"->",
"container",
"->",
"makeWith",
"(",
"'pubsub.kafka.conf'",
")",
";",
"$",
"conf",
"->",
"set",
"(",
"'group.id'",
",",
"array_get",
"(",
"$",
"config",
",",
"'consumer_group_id'",
",",
"'php-pubsub'",
")",
")",
";",
"$",
"conf",
"->",
"set",
"(",
"'metadata.broker.list'",
",",
"$",
"config",
"[",
"'brokers'",
"]",
")",
";",
"$",
"conf",
"->",
"set",
"(",
"'enable.auto.commit'",
",",
"'false'",
")",
";",
"$",
"conf",
"->",
"set",
"(",
"'offset.store.method'",
",",
"'broker'",
")",
";",
"$",
"conf",
"->",
"setDefaultTopicConf",
"(",
"$",
"topicConf",
")",
";",
"$",
"consumer",
"=",
"$",
"this",
"->",
"container",
"->",
"makeWith",
"(",
"'pubsub.kafka.consumer'",
",",
"[",
"'conf'",
"=>",
"$",
"conf",
"]",
")",
";",
"return",
"new",
"KafkaPubSubAdapter",
"(",
"$",
"producer",
",",
"$",
"consumer",
")",
";",
"}"
] |
Factory a KafkaPubSubAdapter.
@param array $config
@return KafkaPubSubAdapter
|
[
"Factory",
"a",
"KafkaPubSubAdapter",
"."
] |
194e079f44279cf89a029c6e0a7fa949bb934970
|
https://github.com/Superbalist/laravel-pubsub/blob/194e079f44279cf89a029c6e0a7fa949bb934970/src/PubSubConnectionFactory.php#L83-L103
|
train
|
Superbalist/laravel-pubsub
|
src/PubSubConnectionFactory.php
|
PubSubConnectionFactory.makeHTTPAdapter
|
protected function makeHTTPAdapter(array $config)
{
$client = $this->container->make('pubsub.http.client');
$adapter = $this->make(
$config['subscribe_connection_config']['driver'],
$config['subscribe_connection_config']
);
return new HTTPPubSubAdapter($client, $config['uri'], $adapter);
}
|
php
|
protected function makeHTTPAdapter(array $config)
{
$client = $this->container->make('pubsub.http.client');
$adapter = $this->make(
$config['subscribe_connection_config']['driver'],
$config['subscribe_connection_config']
);
return new HTTPPubSubAdapter($client, $config['uri'], $adapter);
}
|
[
"protected",
"function",
"makeHTTPAdapter",
"(",
"array",
"$",
"config",
")",
"{",
"$",
"client",
"=",
"$",
"this",
"->",
"container",
"->",
"make",
"(",
"'pubsub.http.client'",
")",
";",
"$",
"adapter",
"=",
"$",
"this",
"->",
"make",
"(",
"$",
"config",
"[",
"'subscribe_connection_config'",
"]",
"[",
"'driver'",
"]",
",",
"$",
"config",
"[",
"'subscribe_connection_config'",
"]",
")",
";",
"return",
"new",
"HTTPPubSubAdapter",
"(",
"$",
"client",
",",
"$",
"config",
"[",
"'uri'",
"]",
",",
"$",
"adapter",
")",
";",
"}"
] |
Factory a HTTPPubSubAdapter.
@param array $config
@return HTTPPubSubAdapter
|
[
"Factory",
"a",
"HTTPPubSubAdapter",
"."
] |
194e079f44279cf89a029c6e0a7fa949bb934970
|
https://github.com/Superbalist/laravel-pubsub/blob/194e079f44279cf89a029c6e0a7fa949bb934970/src/PubSubConnectionFactory.php#L149-L157
|
train
|
bugsnag/bugsnag-symfony
|
DependencyInjection/ClientFactory.php
|
ClientFactory.setupUserDetection
|
protected function setupUserDetection(Client $client, TokenStorageInterface $tokens, AuthorizationCheckerInterface $checker)
{
$client->registerCallback(new CustomUser(function () use ($tokens, $checker) {
$token = $tokens->getToken();
if (!$token || !$checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return;
}
$user = $token->getUser();
if ($user instanceof UserInterface) {
return ['id' => $user->getUsername()];
}
return ['id' => (string) $user];
}));
}
|
php
|
protected function setupUserDetection(Client $client, TokenStorageInterface $tokens, AuthorizationCheckerInterface $checker)
{
$client->registerCallback(new CustomUser(function () use ($tokens, $checker) {
$token = $tokens->getToken();
if (!$token || !$checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return;
}
$user = $token->getUser();
if ($user instanceof UserInterface) {
return ['id' => $user->getUsername()];
}
return ['id' => (string) $user];
}));
}
|
[
"protected",
"function",
"setupUserDetection",
"(",
"Client",
"$",
"client",
",",
"TokenStorageInterface",
"$",
"tokens",
",",
"AuthorizationCheckerInterface",
"$",
"checker",
")",
"{",
"$",
"client",
"->",
"registerCallback",
"(",
"new",
"CustomUser",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"tokens",
",",
"$",
"checker",
")",
"{",
"$",
"token",
"=",
"$",
"tokens",
"->",
"getToken",
"(",
")",
";",
"if",
"(",
"!",
"$",
"token",
"||",
"!",
"$",
"checker",
"->",
"isGranted",
"(",
"'IS_AUTHENTICATED_REMEMBERED'",
")",
")",
"{",
"return",
";",
"}",
"$",
"user",
"=",
"$",
"token",
"->",
"getUser",
"(",
")",
";",
"if",
"(",
"$",
"user",
"instanceof",
"UserInterface",
")",
"{",
"return",
"[",
"'id'",
"=>",
"$",
"user",
"->",
"getUsername",
"(",
")",
"]",
";",
"}",
"return",
"[",
"'id'",
"=>",
"(",
"string",
")",
"$",
"user",
"]",
";",
"}",
")",
")",
";",
"}"
] |
Setup user detection.
@param \Bugsnag\Client $client
@param \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface $tokens
@param \Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface $checker
@return void
|
[
"Setup",
"user",
"detection",
"."
] |
c8c295905c7a2372a4489bf0d964b42d76c82346
|
https://github.com/bugsnag/bugsnag-symfony/blob/c8c295905c7a2372a4489bf0d964b42d76c82346/DependencyInjection/ClientFactory.php#L273-L290
|
train
|
bugsnag/bugsnag-symfony
|
EventListener/BugsnagListener.php
|
BugsnagListener.onKernelException
|
public function onKernelException(GetResponseForExceptionEvent $event)
{
if (!$this->auto) {
return;
}
$exception = $event->getException();
$report = Report::fromPHPThrowable(
$this->client->getConfig(),
$exception
);
$report->setUnhandled(true);
$report->setSeverityReason([
'type' => 'unhandledExceptionMiddleware',
'attributes' => [
'framework' => 'Symfony',
],
]);
$this->client->notify($report);
}
|
php
|
public function onKernelException(GetResponseForExceptionEvent $event)
{
if (!$this->auto) {
return;
}
$exception = $event->getException();
$report = Report::fromPHPThrowable(
$this->client->getConfig(),
$exception
);
$report->setUnhandled(true);
$report->setSeverityReason([
'type' => 'unhandledExceptionMiddleware',
'attributes' => [
'framework' => 'Symfony',
],
]);
$this->client->notify($report);
}
|
[
"public",
"function",
"onKernelException",
"(",
"GetResponseForExceptionEvent",
"$",
"event",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"auto",
")",
"{",
"return",
";",
"}",
"$",
"exception",
"=",
"$",
"event",
"->",
"getException",
"(",
")",
";",
"$",
"report",
"=",
"Report",
"::",
"fromPHPThrowable",
"(",
"$",
"this",
"->",
"client",
"->",
"getConfig",
"(",
")",
",",
"$",
"exception",
")",
";",
"$",
"report",
"->",
"setUnhandled",
"(",
"true",
")",
";",
"$",
"report",
"->",
"setSeverityReason",
"(",
"[",
"'type'",
"=>",
"'unhandledExceptionMiddleware'",
",",
"'attributes'",
"=>",
"[",
"'framework'",
"=>",
"'Symfony'",
",",
"]",
",",
"]",
")",
";",
"$",
"this",
"->",
"client",
"->",
"notify",
"(",
"$",
"report",
")",
";",
"}"
] |
Handle an http kernel exception.
@param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
@return void
|
[
"Handle",
"an",
"http",
"kernel",
"exception",
"."
] |
c8c295905c7a2372a4489bf0d964b42d76c82346
|
https://github.com/bugsnag/bugsnag-symfony/blob/c8c295905c7a2372a4489bf0d964b42d76c82346/EventListener/BugsnagListener.php#L77-L98
|
train
|
bugsnag/bugsnag-symfony
|
EventListener/BugsnagListener.php
|
BugsnagListener.onConsoleException
|
public function onConsoleException(ConsoleExceptionEvent $event)
{
if (!$this->auto) {
return;
}
$exception = $event->getException();
$meta = [
'command' => [
'name' => $event->getCommand()->getName(),
'status' => $event->getExitCode(),
],
];
$report = Report::fromPHPThrowable(
$this->client->getConfig(),
$exception
);
$report->setUnhandled(true);
$report->setSeverityReason([
'type' => 'unhandledExceptionMiddleware',
'attributes' => [
'framework' => 'Symfony',
],
]);
$report->setMetaData($meta);
$this->client->notify($report);
}
|
php
|
public function onConsoleException(ConsoleExceptionEvent $event)
{
if (!$this->auto) {
return;
}
$exception = $event->getException();
$meta = [
'command' => [
'name' => $event->getCommand()->getName(),
'status' => $event->getExitCode(),
],
];
$report = Report::fromPHPThrowable(
$this->client->getConfig(),
$exception
);
$report->setUnhandled(true);
$report->setSeverityReason([
'type' => 'unhandledExceptionMiddleware',
'attributes' => [
'framework' => 'Symfony',
],
]);
$report->setMetaData($meta);
$this->client->notify($report);
}
|
[
"public",
"function",
"onConsoleException",
"(",
"ConsoleExceptionEvent",
"$",
"event",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"auto",
")",
"{",
"return",
";",
"}",
"$",
"exception",
"=",
"$",
"event",
"->",
"getException",
"(",
")",
";",
"$",
"meta",
"=",
"[",
"'command'",
"=>",
"[",
"'name'",
"=>",
"$",
"event",
"->",
"getCommand",
"(",
")",
"->",
"getName",
"(",
")",
",",
"'status'",
"=>",
"$",
"event",
"->",
"getExitCode",
"(",
")",
",",
"]",
",",
"]",
";",
"$",
"report",
"=",
"Report",
"::",
"fromPHPThrowable",
"(",
"$",
"this",
"->",
"client",
"->",
"getConfig",
"(",
")",
",",
"$",
"exception",
")",
";",
"$",
"report",
"->",
"setUnhandled",
"(",
"true",
")",
";",
"$",
"report",
"->",
"setSeverityReason",
"(",
"[",
"'type'",
"=>",
"'unhandledExceptionMiddleware'",
",",
"'attributes'",
"=>",
"[",
"'framework'",
"=>",
"'Symfony'",
",",
"]",
",",
"]",
")",
";",
"$",
"report",
"->",
"setMetaData",
"(",
"$",
"meta",
")",
";",
"$",
"this",
"->",
"client",
"->",
"notify",
"(",
"$",
"report",
")",
";",
"}"
] |
Handle a console exception.
@param \Symfony\Component\Console\Event\ConsoleExceptionEvent $event
@return void
|
[
"Handle",
"a",
"console",
"exception",
"."
] |
c8c295905c7a2372a4489bf0d964b42d76c82346
|
https://github.com/bugsnag/bugsnag-symfony/blob/c8c295905c7a2372a4489bf0d964b42d76c82346/EventListener/BugsnagListener.php#L107-L136
|
train
|
bugsnag/bugsnag-symfony
|
DependencyInjection/Configuration.php
|
Configuration.getConfigTreeBuilder
|
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('bugsnag');
$rootNode
->children()
->scalarNode('api_key')
->defaultValue(getenv('BUGSNAG_API_KEY') ?: null)
->end()
->scalarNode('endpoint')
->defaultValue(getenv('BUGSNAG_ENDPOINT') ?: null)
->end()
->booleanNode('callbacks')
->defaultValue(true)
->end()
->booleanNode('user')
->defaultValue(true)
->end()
->scalarNode('app_type')
->defaultNull()
->end()
->scalarNode('app_version')
->defaultNull()
->end()
->booleanNode('batch_sending')
->defaultValue(true)
->end()
->scalarNode('hostname')
->defaultNull()
->end()
->booleanNode('send_code')
->defaultValue(true)
->end()
->scalarNode('release_stage')
->defaultNull()
->end()
->scalarNode('strip_path')
->defaultNull()
->end()
->scalarNode('project_root')
->defaultNull()
->end()
->booleanNode('auto_notify')
->defaultValue(true)
->end()
->scalarNode('resolver')
->defaultValue(SymfonyResolver::class)
->end()
->scalarNode('factory')
->defaultValue(ClientFactory::class)
->end()
->scalarNode('client')
->defaultValue(Client::class)
->end()
->scalarNode('listener')
->defaultValue(BugsnagListener::class)
->end()
->arrayNode('notify_release_stages')
->prototype('scalar')->end()
->treatNullLike([])
->defaultValue([])
->end()
->arrayNode('filters')
->prototype('scalar')->end()
->treatNullLike([])
->defaultValue([])
->end()
->end();
return $treeBuilder;
}
|
php
|
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('bugsnag');
$rootNode
->children()
->scalarNode('api_key')
->defaultValue(getenv('BUGSNAG_API_KEY') ?: null)
->end()
->scalarNode('endpoint')
->defaultValue(getenv('BUGSNAG_ENDPOINT') ?: null)
->end()
->booleanNode('callbacks')
->defaultValue(true)
->end()
->booleanNode('user')
->defaultValue(true)
->end()
->scalarNode('app_type')
->defaultNull()
->end()
->scalarNode('app_version')
->defaultNull()
->end()
->booleanNode('batch_sending')
->defaultValue(true)
->end()
->scalarNode('hostname')
->defaultNull()
->end()
->booleanNode('send_code')
->defaultValue(true)
->end()
->scalarNode('release_stage')
->defaultNull()
->end()
->scalarNode('strip_path')
->defaultNull()
->end()
->scalarNode('project_root')
->defaultNull()
->end()
->booleanNode('auto_notify')
->defaultValue(true)
->end()
->scalarNode('resolver')
->defaultValue(SymfonyResolver::class)
->end()
->scalarNode('factory')
->defaultValue(ClientFactory::class)
->end()
->scalarNode('client')
->defaultValue(Client::class)
->end()
->scalarNode('listener')
->defaultValue(BugsnagListener::class)
->end()
->arrayNode('notify_release_stages')
->prototype('scalar')->end()
->treatNullLike([])
->defaultValue([])
->end()
->arrayNode('filters')
->prototype('scalar')->end()
->treatNullLike([])
->defaultValue([])
->end()
->end();
return $treeBuilder;
}
|
[
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
")",
";",
"$",
"rootNode",
"=",
"$",
"treeBuilder",
"->",
"root",
"(",
"'bugsnag'",
")",
";",
"$",
"rootNode",
"->",
"children",
"(",
")",
"->",
"scalarNode",
"(",
"'api_key'",
")",
"->",
"defaultValue",
"(",
"getenv",
"(",
"'BUGSNAG_API_KEY'",
")",
"?",
":",
"null",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'endpoint'",
")",
"->",
"defaultValue",
"(",
"getenv",
"(",
"'BUGSNAG_ENDPOINT'",
")",
"?",
":",
"null",
")",
"->",
"end",
"(",
")",
"->",
"booleanNode",
"(",
"'callbacks'",
")",
"->",
"defaultValue",
"(",
"true",
")",
"->",
"end",
"(",
")",
"->",
"booleanNode",
"(",
"'user'",
")",
"->",
"defaultValue",
"(",
"true",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'app_type'",
")",
"->",
"defaultNull",
"(",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'app_version'",
")",
"->",
"defaultNull",
"(",
")",
"->",
"end",
"(",
")",
"->",
"booleanNode",
"(",
"'batch_sending'",
")",
"->",
"defaultValue",
"(",
"true",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'hostname'",
")",
"->",
"defaultNull",
"(",
")",
"->",
"end",
"(",
")",
"->",
"booleanNode",
"(",
"'send_code'",
")",
"->",
"defaultValue",
"(",
"true",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'release_stage'",
")",
"->",
"defaultNull",
"(",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'strip_path'",
")",
"->",
"defaultNull",
"(",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'project_root'",
")",
"->",
"defaultNull",
"(",
")",
"->",
"end",
"(",
")",
"->",
"booleanNode",
"(",
"'auto_notify'",
")",
"->",
"defaultValue",
"(",
"true",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'resolver'",
")",
"->",
"defaultValue",
"(",
"SymfonyResolver",
"::",
"class",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'factory'",
")",
"->",
"defaultValue",
"(",
"ClientFactory",
"::",
"class",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'client'",
")",
"->",
"defaultValue",
"(",
"Client",
"::",
"class",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'listener'",
")",
"->",
"defaultValue",
"(",
"BugsnagListener",
"::",
"class",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'notify_release_stages'",
")",
"->",
"prototype",
"(",
"'scalar'",
")",
"->",
"end",
"(",
")",
"->",
"treatNullLike",
"(",
"[",
"]",
")",
"->",
"defaultValue",
"(",
"[",
"]",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'filters'",
")",
"->",
"prototype",
"(",
"'scalar'",
")",
"->",
"end",
"(",
")",
"->",
"treatNullLike",
"(",
"[",
"]",
")",
"->",
"defaultValue",
"(",
"[",
"]",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
";",
"return",
"$",
"treeBuilder",
";",
"}"
] |
Get the configuration tree builder.
@return \Symfony\Component\Config\Definition\Builder\TreeBuilder
|
[
"Get",
"the",
"configuration",
"tree",
"builder",
"."
] |
c8c295905c7a2372a4489bf0d964b42d76c82346
|
https://github.com/bugsnag/bugsnag-symfony/blob/c8c295905c7a2372a4489bf0d964b42d76c82346/DependencyInjection/Configuration.php#L18-L89
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.