text
stringlengths 2
104M
| meta
dict |
---|---|
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a variable is divisible by a number.
*
* {% if loop.index is divisible by(3) %}
*
* @author Fabien Potencier <[email protected]>
*/
class DivisiblebyTest extends TestExpression
{
public function compile(Compiler $compiler): void
{
$compiler
->raw('(0 == ')
->subcompile($this->getNode('node'))
->raw(' % ')
->subcompile($this->getNode('arguments')->getNode(0))
->raw(')')
;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a variable is the same as another one (=== in PHP).
*
* @author Fabien Potencier <[email protected]>
*/
class SameasTest extends TestExpression
{
public function compile(Compiler $compiler): void
{
$compiler
->raw('(')
->subcompile($this->getNode('node'))
->raw(' === ')
->subcompile($this->getNode('arguments')->getNode(0))
->raw(')')
;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a number is odd.
*
* {{ var is odd }}
*
* @author Fabien Potencier <[email protected]>
*/
class OddTest extends TestExpression
{
public function compile(Compiler $compiler): void
{
$compiler
->raw('(')
->subcompile($this->getNode('node'))
->raw(' % 2 != 0')
->raw(')')
;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a variable is the exact same value as a constant.
*
* {% if post.status is constant('Post::PUBLISHED') %}
* the status attribute is exactly the same as Post::PUBLISHED
* {% endif %}
*
* @author Fabien Potencier <[email protected]>
*/
class ConstantTest extends TestExpression
{
public function compile(Compiler $compiler): void
{
$compiler
->raw('(')
->subcompile($this->getNode('node'))
->raw(' === constant(')
;
if ($this->getNode('arguments')->hasNode(1)) {
$compiler
->raw('get_class(')
->subcompile($this->getNode('arguments')->getNode(1))
->raw(')."::".')
;
}
$compiler
->subcompile($this->getNode('arguments')->getNode(0))
->raw('))')
;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks that a variable is null.
*
* {{ var is none }}
*
* @author Fabien Potencier <[email protected]>
*/
class NullTest extends TestExpression
{
public function compile(Compiler $compiler): void
{
$compiler
->raw('(null === ')
->subcompile($this->getNode('node'))
->raw(')')
;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Filter;
use Twig\Compiler;
use Twig\Node\Expression\ConditionalExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Expression\Test\DefinedTest;
use Twig\Node\Node;
/**
* Returns the value or the default value when it is undefined or empty.
*
* {{ var.foo|default('foo item on var is not defined') }}
*
* @author Fabien Potencier <[email protected]>
*/
class DefaultFilter extends FilterExpression
{
public function __construct(Node $node, ConstantExpression $filterName, Node $arguments, int $lineno, string $tag = null)
{
$default = new FilterExpression($node, new ConstantExpression('default', $node->getTemplateLine()), $arguments, $node->getTemplateLine());
if ('default' === $filterName->getAttribute('value') && ($node instanceof NameExpression || $node instanceof GetAttrExpression)) {
$test = new DefinedTest(clone $node, 'defined', new Node(), $node->getTemplateLine());
$false = \count($arguments) ? $arguments->getNode(0) : new ConstantExpression('', $node->getTemplateLine());
$node = new ConditionalExpression($test, $default, $false, $node->getTemplateLine());
} else {
$node = $default;
}
parent::__construct($node, $filterName, $arguments, $lineno, $tag);
}
public function compile(Compiler $compiler): void
{
$compiler->subcompile($this->getNode('node'));
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Unary;
use Twig\Compiler;
class NotUnary extends AbstractUnary
{
public function operator(Compiler $compiler): Compiler
{
return $compiler->raw('!');
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Unary;
use Twig\Compiler;
class PosUnary extends AbstractUnary
{
public function operator(Compiler $compiler): Compiler
{
return $compiler->raw('+');
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Unary;
use Twig\Compiler;
class NegUnary extends AbstractUnary
{
public function operator(Compiler $compiler): Compiler
{
return $compiler->raw('-');
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Unary;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Node;
abstract class AbstractUnary extends AbstractExpression
{
public function __construct(Node $node, int $lineno)
{
parent::__construct(['node' => $node], [], $lineno);
}
public function compile(Compiler $compiler): void
{
$compiler->raw(' ');
$this->operator($compiler);
$compiler->subcompile($this->getNode('node'));
}
abstract public function operator(Compiler $compiler): Compiler;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension {
use Twig\ExpressionParser;
use Twig\Node\Expression\Binary\AddBinary;
use Twig\Node\Expression\Binary\AndBinary;
use Twig\Node\Expression\Binary\BitwiseAndBinary;
use Twig\Node\Expression\Binary\BitwiseOrBinary;
use Twig\Node\Expression\Binary\BitwiseXorBinary;
use Twig\Node\Expression\Binary\ConcatBinary;
use Twig\Node\Expression\Binary\DivBinary;
use Twig\Node\Expression\Binary\EndsWithBinary;
use Twig\Node\Expression\Binary\EqualBinary;
use Twig\Node\Expression\Binary\FloorDivBinary;
use Twig\Node\Expression\Binary\GreaterBinary;
use Twig\Node\Expression\Binary\GreaterEqualBinary;
use Twig\Node\Expression\Binary\InBinary;
use Twig\Node\Expression\Binary\LessBinary;
use Twig\Node\Expression\Binary\LessEqualBinary;
use Twig\Node\Expression\Binary\MatchesBinary;
use Twig\Node\Expression\Binary\ModBinary;
use Twig\Node\Expression\Binary\MulBinary;
use Twig\Node\Expression\Binary\NotEqualBinary;
use Twig\Node\Expression\Binary\NotInBinary;
use Twig\Node\Expression\Binary\OrBinary;
use Twig\Node\Expression\Binary\PowerBinary;
use Twig\Node\Expression\Binary\RangeBinary;
use Twig\Node\Expression\Binary\SpaceshipBinary;
use Twig\Node\Expression\Binary\StartsWithBinary;
use Twig\Node\Expression\Binary\SubBinary;
use Twig\Node\Expression\Filter\DefaultFilter;
use Twig\Node\Expression\NullCoalesceExpression;
use Twig\Node\Expression\Test\ConstantTest;
use Twig\Node\Expression\Test\DefinedTest;
use Twig\Node\Expression\Test\DivisiblebyTest;
use Twig\Node\Expression\Test\EvenTest;
use Twig\Node\Expression\Test\NullTest;
use Twig\Node\Expression\Test\OddTest;
use Twig\Node\Expression\Test\SameasTest;
use Twig\Node\Expression\Unary\NegUnary;
use Twig\Node\Expression\Unary\NotUnary;
use Twig\Node\Expression\Unary\PosUnary;
use Twig\NodeVisitor\MacroAutoImportNodeVisitor;
use Twig\TokenParser\ApplyTokenParser;
use Twig\TokenParser\BlockTokenParser;
use Twig\TokenParser\DeprecatedTokenParser;
use Twig\TokenParser\DoTokenParser;
use Twig\TokenParser\EmbedTokenParser;
use Twig\TokenParser\ExtendsTokenParser;
use Twig\TokenParser\FlushTokenParser;
use Twig\TokenParser\ForTokenParser;
use Twig\TokenParser\FromTokenParser;
use Twig\TokenParser\IfTokenParser;
use Twig\TokenParser\ImportTokenParser;
use Twig\TokenParser\IncludeTokenParser;
use Twig\TokenParser\MacroTokenParser;
use Twig\TokenParser\SetTokenParser;
use Twig\TokenParser\UseTokenParser;
use Twig\TokenParser\WithTokenParser;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
final class CoreExtension extends AbstractExtension
{
private $dateFormats = ['F j, Y H:i', '%d days'];
private $numberFormat = [0, '.', ','];
private $timezone = null;
/**
* Sets the default format to be used by the date filter.
*
* @param string $format The default date format string
* @param string $dateIntervalFormat The default date interval format string
*/
public function setDateFormat($format = null, $dateIntervalFormat = null)
{
if (null !== $format) {
$this->dateFormats[0] = $format;
}
if (null !== $dateIntervalFormat) {
$this->dateFormats[1] = $dateIntervalFormat;
}
}
/**
* Gets the default format to be used by the date filter.
*
* @return array The default date format string and the default date interval format string
*/
public function getDateFormat()
{
return $this->dateFormats;
}
/**
* Sets the default timezone to be used by the date filter.
*
* @param \DateTimeZone|string $timezone The default timezone string or a \DateTimeZone object
*/
public function setTimezone($timezone)
{
$this->timezone = $timezone instanceof \DateTimeZone ? $timezone : new \DateTimeZone($timezone);
}
/**
* Gets the default timezone to be used by the date filter.
*
* @return \DateTimeZone The default timezone currently in use
*/
public function getTimezone()
{
if (null === $this->timezone) {
$this->timezone = new \DateTimeZone(date_default_timezone_get());
}
return $this->timezone;
}
/**
* Sets the default format to be used by the number_format filter.
*
* @param int $decimal the number of decimal places to use
* @param string $decimalPoint the character(s) to use for the decimal point
* @param string $thousandSep the character(s) to use for the thousands separator
*/
public function setNumberFormat($decimal, $decimalPoint, $thousandSep)
{
$this->numberFormat = [$decimal, $decimalPoint, $thousandSep];
}
/**
* Get the default format used by the number_format filter.
*
* @return array The arguments for number_format()
*/
public function getNumberFormat()
{
return $this->numberFormat;
}
public function getTokenParsers(): array
{
return [
new ApplyTokenParser(),
new ForTokenParser(),
new IfTokenParser(),
new ExtendsTokenParser(),
new IncludeTokenParser(),
new BlockTokenParser(),
new UseTokenParser(),
new MacroTokenParser(),
new ImportTokenParser(),
new FromTokenParser(),
new SetTokenParser(),
new FlushTokenParser(),
new DoTokenParser(),
new EmbedTokenParser(),
new WithTokenParser(),
new DeprecatedTokenParser(),
];
}
public function getFilters(): array
{
return [
// formatting filters
new TwigFilter('date', 'twig_date_format_filter', ['needs_environment' => true]),
new TwigFilter('date_modify', 'twig_date_modify_filter', ['needs_environment' => true]),
new TwigFilter('format', 'twig_sprintf'),
new TwigFilter('replace', 'twig_replace_filter'),
new TwigFilter('number_format', 'twig_number_format_filter', ['needs_environment' => true]),
new TwigFilter('abs', 'abs'),
new TwigFilter('round', 'twig_round'),
// encoding
new TwigFilter('url_encode', 'twig_urlencode_filter'),
new TwigFilter('json_encode', 'json_encode'),
new TwigFilter('convert_encoding', 'twig_convert_encoding'),
// string filters
new TwigFilter('title', 'twig_title_string_filter', ['needs_environment' => true]),
new TwigFilter('capitalize', 'twig_capitalize_string_filter', ['needs_environment' => true]),
new TwigFilter('upper', 'twig_upper_filter', ['needs_environment' => true]),
new TwigFilter('lower', 'twig_lower_filter', ['needs_environment' => true]),
new TwigFilter('striptags', 'twig_striptags'),
new TwigFilter('trim', 'twig_trim_filter'),
new TwigFilter('nl2br', 'twig_nl2br', ['pre_escape' => 'html', 'is_safe' => ['html']]),
new TwigFilter('spaceless', 'twig_spaceless', ['is_safe' => ['html']]),
// array helpers
new TwigFilter('join', 'twig_join_filter'),
new TwigFilter('split', 'twig_split_filter', ['needs_environment' => true]),
new TwigFilter('sort', 'twig_sort_filter', ['needs_environment' => true]),
new TwigFilter('merge', 'twig_array_merge'),
new TwigFilter('batch', 'twig_array_batch'),
new TwigFilter('column', 'twig_array_column'),
new TwigFilter('filter', 'twig_array_filter', ['needs_environment' => true]),
new TwigFilter('map', 'twig_array_map', ['needs_environment' => true]),
new TwigFilter('reduce', 'twig_array_reduce', ['needs_environment' => true]),
// string/array filters
new TwigFilter('reverse', 'twig_reverse_filter', ['needs_environment' => true]),
new TwigFilter('length', 'twig_length_filter', ['needs_environment' => true]),
new TwigFilter('slice', 'twig_slice', ['needs_environment' => true]),
new TwigFilter('first', 'twig_first', ['needs_environment' => true]),
new TwigFilter('last', 'twig_last', ['needs_environment' => true]),
// iteration and runtime
new TwigFilter('default', '_twig_default_filter', ['node_class' => DefaultFilter::class]),
new TwigFilter('keys', 'twig_get_array_keys_filter'),
];
}
public function getFunctions(): array
{
return [
new TwigFunction('max', 'max'),
new TwigFunction('min', 'min'),
new TwigFunction('range', 'range'),
new TwigFunction('constant', 'twig_constant'),
new TwigFunction('cycle', 'twig_cycle'),
new TwigFunction('random', 'twig_random', ['needs_environment' => true]),
new TwigFunction('date', 'twig_date_converter', ['needs_environment' => true]),
new TwigFunction('include', 'twig_include', ['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]),
new TwigFunction('source', 'twig_source', ['needs_environment' => true, 'is_safe' => ['all']]),
];
}
public function getTests(): array
{
return [
new TwigTest('even', null, ['node_class' => EvenTest::class]),
new TwigTest('odd', null, ['node_class' => OddTest::class]),
new TwigTest('defined', null, ['node_class' => DefinedTest::class]),
new TwigTest('same as', null, ['node_class' => SameasTest::class, 'one_mandatory_argument' => true]),
new TwigTest('none', null, ['node_class' => NullTest::class]),
new TwigTest('null', null, ['node_class' => NullTest::class]),
new TwigTest('divisible by', null, ['node_class' => DivisiblebyTest::class, 'one_mandatory_argument' => true]),
new TwigTest('constant', null, ['node_class' => ConstantTest::class]),
new TwigTest('empty', 'twig_test_empty'),
new TwigTest('iterable', 'twig_test_iterable'),
];
}
public function getNodeVisitors(): array
{
return [new MacroAutoImportNodeVisitor()];
}
public function getOperators(): array
{
return [
[
'not' => ['precedence' => 50, 'class' => NotUnary::class],
'-' => ['precedence' => 500, 'class' => NegUnary::class],
'+' => ['precedence' => 500, 'class' => PosUnary::class],
],
[
'or' => ['precedence' => 10, 'class' => OrBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'and' => ['precedence' => 15, 'class' => AndBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'b-or' => ['precedence' => 16, 'class' => BitwiseOrBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'b-xor' => ['precedence' => 17, 'class' => BitwiseXorBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'b-and' => ['precedence' => 18, 'class' => BitwiseAndBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'==' => ['precedence' => 20, 'class' => EqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'!=' => ['precedence' => 20, 'class' => NotEqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'<=>' => ['precedence' => 20, 'class' => SpaceshipBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'<' => ['precedence' => 20, 'class' => LessBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'>' => ['precedence' => 20, 'class' => GreaterBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'>=' => ['precedence' => 20, 'class' => GreaterEqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'<=' => ['precedence' => 20, 'class' => LessEqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'not in' => ['precedence' => 20, 'class' => NotInBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'in' => ['precedence' => 20, 'class' => InBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'matches' => ['precedence' => 20, 'class' => MatchesBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'starts with' => ['precedence' => 20, 'class' => StartsWithBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'ends with' => ['precedence' => 20, 'class' => EndsWithBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'..' => ['precedence' => 25, 'class' => RangeBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'+' => ['precedence' => 30, 'class' => AddBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'-' => ['precedence' => 30, 'class' => SubBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'~' => ['precedence' => 40, 'class' => ConcatBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'*' => ['precedence' => 60, 'class' => MulBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'/' => ['precedence' => 60, 'class' => DivBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'//' => ['precedence' => 60, 'class' => FloorDivBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'%' => ['precedence' => 60, 'class' => ModBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'is' => ['precedence' => 100, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'is not' => ['precedence' => 100, 'associativity' => ExpressionParser::OPERATOR_LEFT],
'**' => ['precedence' => 200, 'class' => PowerBinary::class, 'associativity' => ExpressionParser::OPERATOR_RIGHT],
'??' => ['precedence' => 300, 'class' => NullCoalesceExpression::class, 'associativity' => ExpressionParser::OPERATOR_RIGHT],
],
];
}
}
}
namespace {
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Extension\CoreExtension;
use Twig\Extension\SandboxExtension;
use Twig\Markup;
use Twig\Source;
use Twig\Template;
use Twig\TemplateWrapper;
/**
* Cycles over a value.
*
* @param \ArrayAccess|array $values
* @param int $position The cycle position
*
* @return string The next value in the cycle
*/
function twig_cycle($values, $position)
{
if (!\is_array($values) && !$values instanceof \ArrayAccess) {
return $values;
}
return $values[$position % \count($values)];
}
/**
* Returns a random value depending on the supplied parameter type:
* - a random item from a \Traversable or array
* - a random character from a string
* - a random integer between 0 and the integer parameter.
*
* @param \Traversable|array|int|float|string $values The values to pick a random item from
* @param int|null $max Maximum value used when $values is an int
*
* @throws RuntimeError when $values is an empty array (does not apply to an empty string which is returned as is)
*
* @return mixed A random value from the given sequence
*/
function twig_random(Environment $env, $values = null, $max = null)
{
if (null === $values) {
return null === $max ? mt_rand() : mt_rand(0, (int) $max);
}
if (\is_int($values) || \is_float($values)) {
if (null === $max) {
if ($values < 0) {
$max = 0;
$min = $values;
} else {
$max = $values;
$min = 0;
}
} else {
$min = $values;
$max = $max;
}
return mt_rand((int) $min, (int) $max);
}
if (\is_string($values)) {
if ('' === $values) {
return '';
}
$charset = $env->getCharset();
if ('UTF-8' !== $charset) {
$values = twig_convert_encoding($values, 'UTF-8', $charset);
}
// unicode version of str_split()
// split at all positions, but not after the start and not before the end
$values = preg_split('/(?<!^)(?!$)/u', $values);
if ('UTF-8' !== $charset) {
foreach ($values as $i => $value) {
$values[$i] = twig_convert_encoding($value, $charset, 'UTF-8');
}
}
}
if (!twig_test_iterable($values)) {
return $values;
}
$values = twig_to_array($values);
if (0 === \count($values)) {
throw new RuntimeError('The random function cannot pick from an empty array.');
}
return $values[array_rand($values, 1)];
}
/**
* Converts a date to the given format.
*
* {{ post.published_at|date("m/d/Y") }}
*
* @param \DateTimeInterface|\DateInterval|string $date A date
* @param string|null $format The target format, null to use the default
* @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged
*
* @return string The formatted date
*/
function twig_date_format_filter(Environment $env, $date, $format = null, $timezone = null)
{
if (null === $format) {
$formats = $env->getExtension(CoreExtension::class)->getDateFormat();
$format = $date instanceof \DateInterval ? $formats[1] : $formats[0];
}
if ($date instanceof \DateInterval) {
return $date->format($format);
}
return twig_date_converter($env, $date, $timezone)->format($format);
}
/**
* Returns a new date object modified.
*
* {{ post.published_at|date_modify("-1day")|date("m/d/Y") }}
*
* @param \DateTimeInterface|string $date A date
* @param string $modifier A modifier string
*
* @return \DateTimeInterface
*/
function twig_date_modify_filter(Environment $env, $date, $modifier)
{
$date = twig_date_converter($env, $date, false);
return $date->modify($modifier);
}
/**
* Returns a formatted string.
*
* @param string|null $format
* @param ...$values
*
* @return string
*/
function twig_sprintf($format, ...$values)
{
return sprintf($format ?? '', ...$values);
}
/**
* Converts an input to a \DateTime instance.
*
* {% if date(user.created_at) < date('+2days') %}
* {# do something #}
* {% endif %}
*
* @param \DateTimeInterface|string|null $date A date or null to use the current time
* @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged
*
* @return \DateTimeInterface
*/
function twig_date_converter(Environment $env, $date = null, $timezone = null)
{
// determine the timezone
if (false !== $timezone) {
if (null === $timezone) {
$timezone = $env->getExtension(CoreExtension::class)->getTimezone();
} elseif (!$timezone instanceof \DateTimeZone) {
$timezone = new \DateTimeZone($timezone);
}
}
// immutable dates
if ($date instanceof \DateTimeImmutable) {
return false !== $timezone ? $date->setTimezone($timezone) : $date;
}
if ($date instanceof \DateTimeInterface) {
$date = clone $date;
if (false !== $timezone) {
$date->setTimezone($timezone);
}
return $date;
}
if (null === $date || 'now' === $date) {
if (null === $date) {
$date = 'now';
}
return new \DateTime($date, false !== $timezone ? $timezone : $env->getExtension(CoreExtension::class)->getTimezone());
}
$asString = (string) $date;
if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) {
$date = new \DateTime('@'.$date);
} else {
$date = new \DateTime($date, $env->getExtension(CoreExtension::class)->getTimezone());
}
if (false !== $timezone) {
$date->setTimezone($timezone);
}
return $date;
}
/**
* Replaces strings within a string.
*
* @param string|null $str String to replace in
* @param array|\Traversable $from Replace values
*
* @return string
*/
function twig_replace_filter($str, $from)
{
if (!twig_test_iterable($from)) {
throw new RuntimeError(sprintf('The "replace" filter expects an array or "Traversable" as replace values, got "%s".', \is_object($from) ? \get_class($from) : \gettype($from)));
}
return strtr($str ?? '', twig_to_array($from));
}
/**
* Rounds a number.
*
* @param int|float|string|null $value The value to round
* @param int|float $precision The rounding precision
* @param string $method The method to use for rounding
*
* @return int|float The rounded number
*/
function twig_round($value, $precision = 0, $method = 'common')
{
$value = (float) $value;
if ('common' === $method) {
return round($value, $precision);
}
if ('ceil' !== $method && 'floor' !== $method) {
throw new RuntimeError('The round filter only supports the "common", "ceil", and "floor" methods.');
}
return $method($value * 10 ** $precision) / 10 ** $precision;
}
/**
* Number format filter.
*
* All of the formatting options can be left null, in that case the defaults will
* be used. Supplying any of the parameters will override the defaults set in the
* environment object.
*
* @param mixed $number A float/int/string of the number to format
* @param int $decimal the number of decimal points to display
* @param string $decimalPoint the character(s) to use for the decimal point
* @param string $thousandSep the character(s) to use for the thousands separator
*
* @return string The formatted number
*/
function twig_number_format_filter(Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null)
{
$defaults = $env->getExtension(CoreExtension::class)->getNumberFormat();
if (null === $decimal) {
$decimal = $defaults[0];
}
if (null === $decimalPoint) {
$decimalPoint = $defaults[1];
}
if (null === $thousandSep) {
$thousandSep = $defaults[2];
}
return number_format((float) $number, $decimal, $decimalPoint, $thousandSep);
}
/**
* URL encodes (RFC 3986) a string as a path segment or an array as a query string.
*
* @param string|array|null $url A URL or an array of query parameters
*
* @return string The URL encoded value
*/
function twig_urlencode_filter($url)
{
if (\is_array($url)) {
return http_build_query($url, '', '&', \PHP_QUERY_RFC3986);
}
return rawurlencode($url ?? '');
}
/**
* Merges an array with another one.
*
* {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
*
* {% set items = items|merge({ 'peugeot': 'car' }) %}
*
* {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #}
*
* @param array|\Traversable $arr1 An array
* @param array|\Traversable $arr2 An array
*
* @return array The merged array
*/
function twig_array_merge($arr1, $arr2)
{
if (!twig_test_iterable($arr1)) {
throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($arr1)));
}
if (!twig_test_iterable($arr2)) {
throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as second argument.', \gettype($arr2)));
}
return array_merge(twig_to_array($arr1), twig_to_array($arr2));
}
/**
* Slices a variable.
*
* @param mixed $item A variable
* @param int $start Start of the slice
* @param int $length Size of the slice
* @param bool $preserveKeys Whether to preserve key or not (when the input is an array)
*
* @return mixed The sliced variable
*/
function twig_slice(Environment $env, $item, $start, $length = null, $preserveKeys = false)
{
if ($item instanceof \Traversable) {
while ($item instanceof \IteratorAggregate) {
$item = $item->getIterator();
}
if ($start >= 0 && $length >= 0 && $item instanceof \Iterator) {
try {
return iterator_to_array(new \LimitIterator($item, $start, null === $length ? -1 : $length), $preserveKeys);
} catch (\OutOfBoundsException $e) {
return [];
}
}
$item = iterator_to_array($item, $preserveKeys);
}
if (\is_array($item)) {
return \array_slice($item, $start, $length, $preserveKeys);
}
return (string) mb_substr((string) $item, $start, $length, $env->getCharset());
}
/**
* Returns the first element of the item.
*
* @param mixed $item A variable
*
* @return mixed The first element of the item
*/
function twig_first(Environment $env, $item)
{
$elements = twig_slice($env, $item, 0, 1, false);
return \is_string($elements) ? $elements : current($elements);
}
/**
* Returns the last element of the item.
*
* @param mixed $item A variable
*
* @return mixed The last element of the item
*/
function twig_last(Environment $env, $item)
{
$elements = twig_slice($env, $item, -1, 1, false);
return \is_string($elements) ? $elements : current($elements);
}
/**
* Joins the values to a string.
*
* The separators between elements are empty strings per default, you can define them with the optional parameters.
*
* {{ [1, 2, 3]|join(', ', ' and ') }}
* {# returns 1, 2 and 3 #}
*
* {{ [1, 2, 3]|join('|') }}
* {# returns 1|2|3 #}
*
* {{ [1, 2, 3]|join }}
* {# returns 123 #}
*
* @param array $value An array
* @param string $glue The separator
* @param string|null $and The separator for the last pair
*
* @return string The concatenated string
*/
function twig_join_filter($value, $glue = '', $and = null)
{
if (!twig_test_iterable($value)) {
$value = (array) $value;
}
$value = twig_to_array($value, false);
if (0 === \count($value)) {
return '';
}
if (null === $and || $and === $glue) {
return implode($glue, $value);
}
if (1 === \count($value)) {
return $value[0];
}
return implode($glue, \array_slice($value, 0, -1)).$and.$value[\count($value) - 1];
}
/**
* Splits the string into an array.
*
* {{ "one,two,three"|split(',') }}
* {# returns [one, two, three] #}
*
* {{ "one,two,three,four,five"|split(',', 3) }}
* {# returns [one, two, "three,four,five"] #}
*
* {{ "123"|split('') }}
* {# returns [1, 2, 3] #}
*
* {{ "aabbcc"|split('', 2) }}
* {# returns [aa, bb, cc] #}
*
* @param string|null $value A string
* @param string $delimiter The delimiter
* @param int $limit The limit
*
* @return array The split string as an array
*/
function twig_split_filter(Environment $env, $value, $delimiter, $limit = null)
{
$value = $value ?? '';
if (\strlen($delimiter) > 0) {
return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit);
}
if ($limit <= 1) {
return preg_split('/(?<!^)(?!$)/u', $value);
}
$length = mb_strlen($value, $env->getCharset());
if ($length < $limit) {
return [$value];
}
$r = [];
for ($i = 0; $i < $length; $i += $limit) {
$r[] = mb_substr($value, $i, $limit, $env->getCharset());
}
return $r;
}
// The '_default' filter is used internally to avoid using the ternary operator
// which costs a lot for big contexts (before PHP 5.4). So, on average,
// a function call is cheaper.
/**
* @internal
*/
function _twig_default_filter($value, $default = '')
{
if (twig_test_empty($value)) {
return $default;
}
return $value;
}
/**
* Returns the keys for the given array.
*
* It is useful when you want to iterate over the keys of an array:
*
* {% for key in array|keys %}
* {# ... #}
* {% endfor %}
*
* @param array $array An array
*
* @return array The keys
*/
function twig_get_array_keys_filter($array)
{
if ($array instanceof \Traversable) {
while ($array instanceof \IteratorAggregate) {
$array = $array->getIterator();
}
$keys = [];
if ($array instanceof \Iterator) {
$array->rewind();
while ($array->valid()) {
$keys[] = $array->key();
$array->next();
}
return $keys;
}
foreach ($array as $key => $item) {
$keys[] = $key;
}
return $keys;
}
if (!\is_array($array)) {
return [];
}
return array_keys($array);
}
/**
* Reverses a variable.
*
* @param array|\Traversable|string|null $item An array, a \Traversable instance, or a string
* @param bool $preserveKeys Whether to preserve key or not
*
* @return mixed The reversed input
*/
function twig_reverse_filter(Environment $env, $item, $preserveKeys = false)
{
if ($item instanceof \Traversable) {
return array_reverse(iterator_to_array($item), $preserveKeys);
}
if (\is_array($item)) {
return array_reverse($item, $preserveKeys);
}
$string = (string) $item;
$charset = $env->getCharset();
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, 'UTF-8', $charset);
}
preg_match_all('/./us', $string, $matches);
$string = implode('', array_reverse($matches[0]));
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, $charset, 'UTF-8');
}
return $string;
}
/**
* Sorts an array.
*
* @param array|\Traversable $array
*
* @return array
*/
function twig_sort_filter(Environment $env, $array, $arrow = null)
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
} elseif (!\is_array($array)) {
throw new RuntimeError(sprintf('The sort filter only works with arrays or "Traversable", got "%s".', \gettype($array)));
}
if (null !== $arrow) {
twig_check_arrow_in_sandbox($env, $arrow, 'sort', 'filter');
uasort($array, $arrow);
} else {
asort($array);
}
return $array;
}
/**
* @internal
*/
function twig_in_filter($value, $compare)
{
if ($value instanceof Markup) {
$value = (string) $value;
}
if ($compare instanceof Markup) {
$compare = (string) $compare;
}
if (\is_string($compare)) {
if (\is_string($value) || \is_int($value) || \is_float($value)) {
return '' === $value || false !== strpos($compare, (string) $value);
}
return false;
}
if (!is_iterable($compare)) {
return false;
}
if (\is_object($value) || \is_resource($value)) {
if (!\is_array($compare)) {
foreach ($compare as $item) {
if ($item === $value) {
return true;
}
}
return false;
}
return \in_array($value, $compare, true);
}
foreach ($compare as $item) {
if (0 === twig_compare($value, $item)) {
return true;
}
}
return false;
}
/**
* Compares two values using a more strict version of the PHP non-strict comparison operator.
*
* @see https://wiki.php.net/rfc/string_to_number_comparison
* @see https://wiki.php.net/rfc/trailing_whitespace_numerics
*
* @internal
*/
function twig_compare($a, $b)
{
// int <=> string
if (\is_int($a) && \is_string($b)) {
$bTrim = trim($b, " \t\n\r\v\f");
if (!is_numeric($bTrim)) {
return (string) $a <=> $b;
}
if ((int) $bTrim == $bTrim) {
return $a <=> (int) $bTrim;
} else {
return (float) $a <=> (float) $bTrim;
}
}
if (\is_string($a) && \is_int($b)) {
$aTrim = trim($a, " \t\n\r\v\f");
if (!is_numeric($aTrim)) {
return $a <=> (string) $b;
}
if ((int) $aTrim == $aTrim) {
return (int) $aTrim <=> $b;
} else {
return (float) $aTrim <=> (float) $b;
}
}
// float <=> string
if (\is_float($a) && \is_string($b)) {
if (is_nan($a)) {
return 1;
}
$bTrim = trim($b, " \t\n\r\v\f");
if (!is_numeric($bTrim)) {
return (string) $a <=> $b;
}
return $a <=> (float) $bTrim;
}
if (\is_string($a) && \is_float($b)) {
if (is_nan($b)) {
return 1;
}
$aTrim = trim($a, " \t\n\r\v\f");
if (!is_numeric($aTrim)) {
return $a <=> (string) $b;
}
return (float) $aTrim <=> $b;
}
// fallback to <=>
return $a <=> $b;
}
/**
* Returns a trimmed string.
*
* @param string|null $string
* @param string|null $characterMask
* @param string $side
*
* @return string
*
* @throws RuntimeError When an invalid trimming side is used (not a string or not 'left', 'right', or 'both')
*/
function twig_trim_filter($string, $characterMask = null, $side = 'both')
{
if (null === $characterMask) {
$characterMask = " \t\n\r\0\x0B";
}
switch ($side) {
case 'both':
return trim($string ?? '', $characterMask);
case 'left':
return ltrim($string ?? '', $characterMask);
case 'right':
return rtrim($string ?? '', $characterMask);
default:
throw new RuntimeError('Trimming side must be "left", "right" or "both".');
}
}
/**
* Inserts HTML line breaks before all newlines in a string.
*
* @param string|null $string
*
* @return string
*/
function twig_nl2br($string)
{
return nl2br($string ?? '');
}
/**
* Removes whitespaces between HTML tags.
*
* @param string|null $string
*
* @return string
*/
function twig_spaceless($content)
{
return trim(preg_replace('/>\s+</', '><', $content ?? ''));
}
/**
* @param string|null $string
* @param string $to
* @param string $from
*
* @return string
*/
function twig_convert_encoding($string, $to, $from)
{
if (!\function_exists('iconv')) {
throw new RuntimeError('Unable to convert encoding: required function iconv() does not exist. You should install ext-iconv or symfony/polyfill-iconv.');
}
return iconv($from, $to, $string ?? '');
}
/**
* Returns the length of a variable.
*
* @param mixed $thing A variable
*
* @return int The length of the value
*/
function twig_length_filter(Environment $env, $thing)
{
if (null === $thing) {
return 0;
}
if (is_scalar($thing)) {
return mb_strlen($thing, $env->getCharset());
}
if ($thing instanceof \Countable || \is_array($thing) || $thing instanceof \SimpleXMLElement) {
return \count($thing);
}
if ($thing instanceof \Traversable) {
return iterator_count($thing);
}
if (method_exists($thing, '__toString') && !$thing instanceof \Countable) {
return mb_strlen((string) $thing, $env->getCharset());
}
return 1;
}
/**
* Converts a string to uppercase.
*
* @param string|null $string A string
*
* @return string The uppercased string
*/
function twig_upper_filter(Environment $env, $string)
{
return mb_strtoupper($string ?? '', $env->getCharset());
}
/**
* Converts a string to lowercase.
*
* @param string|null $string A string
*
* @return string The lowercased string
*/
function twig_lower_filter(Environment $env, $string)
{
return mb_strtolower($string ?? '', $env->getCharset());
}
/**
* Strips HTML and PHP tags from a string.
*
* @param string|null $string
* @param string[]|string|null $string
*
* @return string
*/
function twig_striptags($string, $allowable_tags = null)
{
return strip_tags($string ?? '', $allowable_tags);
}
/**
* Returns a titlecased string.
*
* @param string|null $string A string
*
* @return string The titlecased string
*/
function twig_title_string_filter(Environment $env, $string)
{
if (null !== $charset = $env->getCharset()) {
return mb_convert_case($string ?? '', \MB_CASE_TITLE, $charset);
}
return ucwords(strtolower($string ?? ''));
}
/**
* Returns a capitalized string.
*
* @param string|null $string A string
*
* @return string The capitalized string
*/
function twig_capitalize_string_filter(Environment $env, $string)
{
$charset = $env->getCharset();
return mb_strtoupper(mb_substr($string ?? '', 0, 1, $charset), $charset).mb_strtolower(mb_substr($string ?? '', 1, null, $charset), $charset);
}
/**
* @internal
*/
function twig_call_macro(Template $template, string $method, array $args, int $lineno, array $context, Source $source)
{
if (!method_exists($template, $method)) {
$parent = $template;
while ($parent = $parent->getParent($context)) {
if (method_exists($parent, $method)) {
return $parent->$method(...$args);
}
}
throw new RuntimeError(sprintf('Macro "%s" is not defined in template "%s".', substr($method, \strlen('macro_')), $template->getTemplateName()), $lineno, $source);
}
return $template->$method(...$args);
}
/**
* @internal
*/
function twig_ensure_traversable($seq)
{
if ($seq instanceof \Traversable || \is_array($seq)) {
return $seq;
}
return [];
}
/**
* @internal
*/
function twig_to_array($seq, $preserveKeys = true)
{
if ($seq instanceof \Traversable) {
return iterator_to_array($seq, $preserveKeys);
}
if (!\is_array($seq)) {
return $seq;
}
return $preserveKeys ? $seq : array_values($seq);
}
/**
* Checks if a variable is empty.
*
* {# evaluates to true if the foo variable is null, false, or the empty string #}
* {% if foo is empty %}
* {# ... #}
* {% endif %}
*
* @param mixed $value A variable
*
* @return bool true if the value is empty, false otherwise
*/
function twig_test_empty($value)
{
if ($value instanceof \Countable) {
return 0 === \count($value);
}
if ($value instanceof \Traversable) {
return !iterator_count($value);
}
if (\is_object($value) && method_exists($value, '__toString')) {
return '' === (string) $value;
}
return '' === $value || false === $value || null === $value || [] === $value;
}
/**
* Checks if a variable is traversable.
*
* {# evaluates to true if the foo variable is an array or a traversable object #}
* {% if foo is iterable %}
* {# ... #}
* {% endif %}
*
* @param mixed $value A variable
*
* @return bool true if the value is traversable
*/
function twig_test_iterable($value)
{
return $value instanceof \Traversable || \is_array($value);
}
/**
* Renders a template.
*
* @param array $context
* @param string|array $template The template to render or an array of templates to try consecutively
* @param array $variables The variables to pass to the template
* @param bool $withContext
* @param bool $ignoreMissing Whether to ignore missing templates or not
* @param bool $sandboxed Whether to sandbox the template or not
*
* @return string The rendered template
*/
function twig_include(Environment $env, $context, $template, $variables = [], $withContext = true, $ignoreMissing = false, $sandboxed = false)
{
$alreadySandboxed = false;
$sandbox = null;
if ($withContext) {
$variables = array_merge($context, $variables);
}
if ($isSandboxed = $sandboxed && $env->hasExtension(SandboxExtension::class)) {
$sandbox = $env->getExtension(SandboxExtension::class);
if (!$alreadySandboxed = $sandbox->isSandboxed()) {
$sandbox->enableSandbox();
}
foreach ((\is_array($template) ? $template : [$template]) as $name) {
// if a Template instance is passed, it might have been instantiated outside of a sandbox, check security
if ($name instanceof TemplateWrapper || $name instanceof Template) {
$name->unwrap()->checkSecurity();
}
}
}
try {
$loaded = null;
try {
$loaded = $env->resolveTemplate($template);
} catch (LoaderError $e) {
if (!$ignoreMissing) {
throw $e;
}
}
return $loaded ? $loaded->render($variables) : '';
} finally {
if ($isSandboxed && !$alreadySandboxed) {
$sandbox->disableSandbox();
}
}
}
/**
* Returns a template content without rendering it.
*
* @param string $name The template name
* @param bool $ignoreMissing Whether to ignore missing templates or not
*
* @return string The template source
*/
function twig_source(Environment $env, $name, $ignoreMissing = false)
{
$loader = $env->getLoader();
try {
return $loader->getSourceContext($name)->getCode();
} catch (LoaderError $e) {
if (!$ignoreMissing) {
throw $e;
}
}
}
/**
* Provides the ability to get constants from instances as well as class/global constants.
*
* @param string $constant The name of the constant
* @param object|null $object The object to get the constant from
*
* @return string
*/
function twig_constant($constant, $object = null)
{
if (null !== $object) {
if ('class' === $constant) {
return \get_class($object);
}
$constant = \get_class($object).'::'.$constant;
}
return \constant($constant);
}
/**
* Checks if a constant exists.
*
* @param string $constant The name of the constant
* @param object|null $object The object to get the constant from
*
* @return bool
*/
function twig_constant_is_defined($constant, $object = null)
{
if (null !== $object) {
if ('class' === $constant) {
return true;
}
$constant = \get_class($object).'::'.$constant;
}
return \defined($constant);
}
/**
* Batches item.
*
* @param array $items An array of items
* @param int $size The size of the batch
* @param mixed $fill A value used to fill missing items
*
* @return array
*/
function twig_array_batch($items, $size, $fill = null, $preserveKeys = true)
{
if (!twig_test_iterable($items)) {
throw new RuntimeError(sprintf('The "batch" filter expects an array or "Traversable", got "%s".', \is_object($items) ? \get_class($items) : \gettype($items)));
}
$size = ceil($size);
$result = array_chunk(twig_to_array($items, $preserveKeys), $size, $preserveKeys);
if (null !== $fill && $result) {
$last = \count($result) - 1;
if ($fillCount = $size - \count($result[$last])) {
for ($i = 0; $i < $fillCount; ++$i) {
$result[$last][] = $fill;
}
}
}
return $result;
}
/**
* Returns the attribute value for a given array/object.
*
* @param mixed $object The object or array from where to get the item
* @param mixed $item The item to get from the array or object
* @param array $arguments An array of arguments to pass if the item is an object method
* @param string $type The type of attribute (@see \Twig\Template constants)
* @param bool $isDefinedTest Whether this is only a defined check
* @param bool $ignoreStrictCheck Whether to ignore the strict attribute check or not
* @param int $lineno The template line where the attribute was called
*
* @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true
*
* @throws RuntimeError if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false
*
* @internal
*/
function twig_get_attribute(Environment $env, Source $source, $object, $item, array $arguments = [], $type = /* Template::ANY_CALL */ 'any', $isDefinedTest = false, $ignoreStrictCheck = false, $sandboxed = false, int $lineno = -1)
{
// array
if (/* Template::METHOD_CALL */ 'method' !== $type) {
$arrayItem = \is_bool($item) || \is_float($item) ? (int) $item : $item;
if (((\is_array($object) || $object instanceof \ArrayObject) && (isset($object[$arrayItem]) || \array_key_exists($arrayItem, (array) $object)))
|| ($object instanceof ArrayAccess && isset($object[$arrayItem]))
) {
if ($isDefinedTest) {
return true;
}
return $object[$arrayItem];
}
if (/* Template::ARRAY_CALL */ 'array' === $type || !\is_object($object)) {
if ($isDefinedTest) {
return false;
}
if ($ignoreStrictCheck || !$env->isStrictVariables()) {
return;
}
if ($object instanceof ArrayAccess) {
$message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.', $arrayItem, \get_class($object));
} elseif (\is_object($object)) {
$message = sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.', $item, \get_class($object));
} elseif (\is_array($object)) {
if (empty($object)) {
$message = sprintf('Key "%s" does not exist as the array is empty.', $arrayItem);
} else {
$message = sprintf('Key "%s" for array with keys "%s" does not exist.', $arrayItem, implode(', ', array_keys($object)));
}
} elseif (/* Template::ARRAY_CALL */ 'array' === $type) {
if (null === $object) {
$message = sprintf('Impossible to access a key ("%s") on a null variable.', $item);
} else {
$message = sprintf('Impossible to access a key ("%s") on a %s variable ("%s").', $item, \gettype($object), $object);
}
} elseif (null === $object) {
$message = sprintf('Impossible to access an attribute ("%s") on a null variable.', $item);
} else {
$message = sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s").', $item, \gettype($object), $object);
}
throw new RuntimeError($message, $lineno, $source);
}
}
if (!\is_object($object)) {
if ($isDefinedTest) {
return false;
}
if ($ignoreStrictCheck || !$env->isStrictVariables()) {
return;
}
if (null === $object) {
$message = sprintf('Impossible to invoke a method ("%s") on a null variable.', $item);
} elseif (\is_array($object)) {
$message = sprintf('Impossible to invoke a method ("%s") on an array.', $item);
} else {
$message = sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s").', $item, \gettype($object), $object);
}
throw new RuntimeError($message, $lineno, $source);
}
if ($object instanceof Template) {
throw new RuntimeError('Accessing \Twig\Template attributes is forbidden.', $lineno, $source);
}
// object property
if (/* Template::METHOD_CALL */ 'method' !== $type) {
if (isset($object->$item) || \array_key_exists((string) $item, (array) $object)) {
if ($isDefinedTest) {
return true;
}
if ($sandboxed) {
$env->getExtension(SandboxExtension::class)->checkPropertyAllowed($object, $item, $lineno, $source);
}
return $object->$item;
}
}
static $cache = [];
$class = \get_class($object);
// object method
// precedence: getXxx() > isXxx() > hasXxx()
if (!isset($cache[$class])) {
$methods = get_class_methods($object);
sort($methods);
$lcMethods = array_map(function ($value) { return strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); }, $methods);
$classCache = [];
foreach ($methods as $i => $method) {
$classCache[$method] = $method;
$classCache[$lcName = $lcMethods[$i]] = $method;
if ('g' === $lcName[0] && 0 === strpos($lcName, 'get')) {
$name = substr($method, 3);
$lcName = substr($lcName, 3);
} elseif ('i' === $lcName[0] && 0 === strpos($lcName, 'is')) {
$name = substr($method, 2);
$lcName = substr($lcName, 2);
} elseif ('h' === $lcName[0] && 0 === strpos($lcName, 'has')) {
$name = substr($method, 3);
$lcName = substr($lcName, 3);
if (\in_array('is'.$lcName, $lcMethods)) {
continue;
}
} else {
continue;
}
// skip get() and is() methods (in which case, $name is empty)
if ($name) {
if (!isset($classCache[$name])) {
$classCache[$name] = $method;
}
if (!isset($classCache[$lcName])) {
$classCache[$lcName] = $method;
}
}
}
$cache[$class] = $classCache;
}
$call = false;
if (isset($cache[$class][$item])) {
$method = $cache[$class][$item];
} elseif (isset($cache[$class][$lcItem = strtr($item, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')])) {
$method = $cache[$class][$lcItem];
} elseif (isset($cache[$class]['__call'])) {
$method = $item;
$call = true;
} else {
if ($isDefinedTest) {
return false;
}
if ($ignoreStrictCheck || !$env->isStrictVariables()) {
return;
}
throw new RuntimeError(sprintf('Neither the property "%1$s" nor one of the methods "%1$s()", "get%1$s()"/"is%1$s()"/"has%1$s()" or "__call()" exist and have public access in class "%2$s".', $item, $class), $lineno, $source);
}
if ($isDefinedTest) {
return true;
}
if ($sandboxed) {
$env->getExtension(SandboxExtension::class)->checkMethodAllowed($object, $method, $lineno, $source);
}
// Some objects throw exceptions when they have __call, and the method we try
// to call is not supported. If ignoreStrictCheck is true, we should return null.
try {
$ret = $object->$method(...$arguments);
} catch (\BadMethodCallException $e) {
if ($call && ($ignoreStrictCheck || !$env->isStrictVariables())) {
return;
}
throw $e;
}
return $ret;
}
/**
* Returns the values from a single column in the input array.
*
* <pre>
* {% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %}
*
* {% set fruits = items|column('fruit') %}
*
* {# fruits now contains ['apple', 'orange'] #}
* </pre>
*
* @param array|Traversable $array An array
* @param mixed $name The column name
* @param mixed $index The column to use as the index/keys for the returned array
*
* @return array The array of values
*/
function twig_array_column($array, $name, $index = null): array
{
if ($array instanceof Traversable) {
$array = iterator_to_array($array);
} elseif (!\is_array($array)) {
throw new RuntimeError(sprintf('The column filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($array)));
}
return array_column($array, $name, $index);
}
function twig_array_filter(Environment $env, $array, $arrow)
{
if (!twig_test_iterable($array)) {
throw new RuntimeError(sprintf('The "filter" filter expects an array or "Traversable", got "%s".', \is_object($array) ? \get_class($array) : \gettype($array)));
}
twig_check_arrow_in_sandbox($env, $arrow, 'filter', 'filter');
if (\is_array($array)) {
return array_filter($array, $arrow, \ARRAY_FILTER_USE_BOTH);
}
// the IteratorIterator wrapping is needed as some internal PHP classes are \Traversable but do not implement \Iterator
return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow);
}
function twig_array_map(Environment $env, $array, $arrow)
{
twig_check_arrow_in_sandbox($env, $arrow, 'map', 'filter');
$r = [];
foreach ($array as $k => $v) {
$r[$k] = $arrow($v, $k);
}
return $r;
}
function twig_array_reduce(Environment $env, $array, $arrow, $initial = null)
{
twig_check_arrow_in_sandbox($env, $arrow, 'reduce', 'filter');
if (!\is_array($array)) {
if (!$array instanceof \Traversable) {
throw new RuntimeError(sprintf('The "reduce" filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($array)));
}
$array = iterator_to_array($array);
}
return array_reduce($array, $arrow, $initial);
}
function twig_check_arrow_in_sandbox(Environment $env, $arrow, $thing, $type)
{
if (!$arrow instanceof Closure && $env->hasExtension('\Twig\Extension\SandboxExtension') && $env->getExtension('\Twig\Extension\SandboxExtension')->isSandboxed()) {
throw new RuntimeError(sprintf('The callable passed to the "%s" %s must be a Closure in sandbox mode.', $thing, $type));
}
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\NodeVisitor\SandboxNodeVisitor;
use Twig\Sandbox\SecurityNotAllowedMethodError;
use Twig\Sandbox\SecurityNotAllowedPropertyError;
use Twig\Sandbox\SecurityPolicyInterface;
use Twig\Source;
use Twig\TokenParser\SandboxTokenParser;
final class SandboxExtension extends AbstractExtension
{
private $sandboxedGlobally;
private $sandboxed;
private $policy;
public function __construct(SecurityPolicyInterface $policy, $sandboxed = false)
{
$this->policy = $policy;
$this->sandboxedGlobally = $sandboxed;
}
public function getTokenParsers(): array
{
return [new SandboxTokenParser()];
}
public function getNodeVisitors(): array
{
return [new SandboxNodeVisitor()];
}
public function enableSandbox(): void
{
$this->sandboxed = true;
}
public function disableSandbox(): void
{
$this->sandboxed = false;
}
public function isSandboxed(): bool
{
return $this->sandboxedGlobally || $this->sandboxed;
}
public function isSandboxedGlobally(): bool
{
return $this->sandboxedGlobally;
}
public function setSecurityPolicy(SecurityPolicyInterface $policy)
{
$this->policy = $policy;
}
public function getSecurityPolicy(): SecurityPolicyInterface
{
return $this->policy;
}
public function checkSecurity($tags, $filters, $functions): void
{
if ($this->isSandboxed()) {
$this->policy->checkSecurity($tags, $filters, $functions);
}
}
public function checkMethodAllowed($obj, $method, int $lineno = -1, Source $source = null): void
{
if ($this->isSandboxed()) {
try {
$this->policy->checkMethodAllowed($obj, $method);
} catch (SecurityNotAllowedMethodError $e) {
$e->setSourceContext($source);
$e->setTemplateLine($lineno);
throw $e;
}
}
}
public function checkPropertyAllowed($obj, $property, int $lineno = -1, Source $source = null): void
{
if ($this->isSandboxed()) {
try {
$this->policy->checkPropertyAllowed($obj, $property);
} catch (SecurityNotAllowedPropertyError $e) {
$e->setSourceContext($source);
$e->setTemplateLine($lineno);
throw $e;
}
}
}
public function ensureToStringAllowed($obj, int $lineno = -1, Source $source = null)
{
if ($this->isSandboxed() && \is_object($obj) && method_exists($obj, '__toString')) {
try {
$this->policy->checkMethodAllowed($obj, '__toString');
} catch (SecurityNotAllowedMethodError $e) {
$e->setSourceContext($source);
$e->setTemplateLine($lineno);
throw $e;
}
}
return $obj;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension {
use Twig\TwigFunction;
final class StringLoaderExtension extends AbstractExtension
{
public function getFunctions(): array
{
return [
new TwigFunction('template_from_string', 'twig_template_from_string', ['needs_environment' => true]),
];
}
}
}
namespace {
use Twig\Environment;
use Twig\TemplateWrapper;
/**
* Loads a template from a string.
*
* {{ include(template_from_string("Hello {{ name }}")) }}
*
* @param string $template A template as a string or object implementing __toString()
* @param string $name An optional name of the template to be used in error messages
*/
function twig_template_from_string(Environment $env, $template, string $name = null): TemplateWrapper
{
return $env->createTemplate((string) $template, $name);
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
abstract class AbstractExtension implements ExtensionInterface
{
public function getTokenParsers()
{
return [];
}
public function getNodeVisitors()
{
return [];
}
public function getFilters()
{
return [];
}
public function getTests()
{
return [];
}
public function getFunctions()
{
return [];
}
public function getOperators()
{
return [];
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\NodeVisitor\NodeVisitorInterface;
use Twig\TokenParser\TokenParserInterface;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
/**
* Interface implemented by extension classes.
*
* @author Fabien Potencier <[email protected]>
*/
interface ExtensionInterface
{
/**
* Returns the token parser instances to add to the existing list.
*
* @return TokenParserInterface[]
*/
public function getTokenParsers();
/**
* Returns the node visitor instances to add to the existing list.
*
* @return NodeVisitorInterface[]
*/
public function getNodeVisitors();
/**
* Returns a list of filters to add to the existing list.
*
* @return TwigFilter[]
*/
public function getFilters();
/**
* Returns a list of tests to add to the existing list.
*
* @return TwigTest[]
*/
public function getTests();
/**
* Returns a list of functions to add to the existing list.
*
* @return TwigFunction[]
*/
public function getFunctions();
/**
* Returns a list of operators to add to the existing list.
*
* @return array<array> First array of unary operators, second array of binary operators
*/
public function getOperators();
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension {
use Twig\TwigFunction;
final class DebugExtension extends AbstractExtension
{
public function getFunctions(): array
{
// dump is safe if var_dump is overridden by xdebug
$isDumpOutputHtmlSafe = \extension_loaded('xdebug')
// false means that it was not set (and the default is on) or it explicitly enabled
&& (false === ini_get('xdebug.overload_var_dump') || ini_get('xdebug.overload_var_dump'))
// false means that it was not set (and the default is on) or it explicitly enabled
// xdebug.overload_var_dump produces HTML only when html_errors is also enabled
&& (false === ini_get('html_errors') || ini_get('html_errors'))
|| 'cli' === \PHP_SAPI
;
return [
new TwigFunction('dump', 'twig_var_dump', ['is_safe' => $isDumpOutputHtmlSafe ? ['html'] : [], 'needs_context' => true, 'needs_environment' => true, 'is_variadic' => true]),
];
}
}
}
namespace {
use Twig\Environment;
use Twig\Template;
use Twig\TemplateWrapper;
function twig_var_dump(Environment $env, $context, ...$vars)
{
if (!$env->isDebug()) {
return;
}
ob_start();
if (!$vars) {
$vars = [];
foreach ($context as $key => $value) {
if (!$value instanceof Template && !$value instanceof TemplateWrapper) {
$vars[$key] = $value;
}
}
var_dump($vars);
} else {
var_dump(...$vars);
}
return ob_get_clean();
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\Profiler\NodeVisitor\ProfilerNodeVisitor;
use Twig\Profiler\Profile;
class ProfilerExtension extends AbstractExtension
{
private $actives = [];
public function __construct(Profile $profile)
{
$this->actives[] = $profile;
}
/**
* @return void
*/
public function enter(Profile $profile)
{
$this->actives[0]->addProfile($profile);
array_unshift($this->actives, $profile);
}
/**
* @return void
*/
public function leave(Profile $profile)
{
$profile->leave();
array_shift($this->actives);
if (1 === \count($this->actives)) {
$this->actives[0]->leave();
}
}
public function getNodeVisitors(): array
{
return [new ProfilerNodeVisitor(static::class)];
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\NodeVisitor\OptimizerNodeVisitor;
final class OptimizerExtension extends AbstractExtension
{
private $optimizers;
public function __construct(int $optimizers = -1)
{
$this->optimizers = $optimizers;
}
public function getNodeVisitors(): array
{
return [new OptimizerNodeVisitor($this->optimizers)];
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension {
use Twig\FileExtensionEscapingStrategy;
use Twig\NodeVisitor\EscaperNodeVisitor;
use Twig\TokenParser\AutoEscapeTokenParser;
use Twig\TwigFilter;
final class EscaperExtension extends AbstractExtension
{
private $defaultStrategy;
private $escapers = [];
/** @internal */
public $safeClasses = [];
/** @internal */
public $safeLookup = [];
/**
* @param string|false|callable $defaultStrategy An escaping strategy
*
* @see setDefaultStrategy()
*/
public function __construct($defaultStrategy = 'html')
{
$this->setDefaultStrategy($defaultStrategy);
}
public function getTokenParsers(): array
{
return [new AutoEscapeTokenParser()];
}
public function getNodeVisitors(): array
{
return [new EscaperNodeVisitor()];
}
public function getFilters(): array
{
return [
new TwigFilter('escape', 'twig_escape_filter', ['needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe']),
new TwigFilter('e', 'twig_escape_filter', ['needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe']),
new TwigFilter('raw', 'twig_raw_filter', ['is_safe' => ['all']]),
];
}
/**
* Sets the default strategy to use when not defined by the user.
*
* The strategy can be a valid PHP callback that takes the template
* name as an argument and returns the strategy to use.
*
* @param string|false|callable $defaultStrategy An escaping strategy
*/
public function setDefaultStrategy($defaultStrategy): void
{
if ('name' === $defaultStrategy) {
$defaultStrategy = [FileExtensionEscapingStrategy::class, 'guess'];
}
$this->defaultStrategy = $defaultStrategy;
}
/**
* Gets the default strategy to use when not defined by the user.
*
* @param string $name The template name
*
* @return string|false The default strategy to use for the template
*/
public function getDefaultStrategy(string $name)
{
// disable string callables to avoid calling a function named html or js,
// or any other upcoming escaping strategy
if (!\is_string($this->defaultStrategy) && false !== $this->defaultStrategy) {
return \call_user_func($this->defaultStrategy, $name);
}
return $this->defaultStrategy;
}
/**
* Defines a new escaper to be used via the escape filter.
*
* @param string $strategy The strategy name that should be used as a strategy in the escape call
* @param callable $callable A valid PHP callable
*/
public function setEscaper($strategy, callable $callable)
{
$this->escapers[$strategy] = $callable;
}
/**
* Gets all defined escapers.
*
* @return callable[] An array of escapers
*/
public function getEscapers()
{
return $this->escapers;
}
public function setSafeClasses(array $safeClasses = [])
{
$this->safeClasses = [];
$this->safeLookup = [];
foreach ($safeClasses as $class => $strategies) {
$this->addSafeClass($class, $strategies);
}
}
public function addSafeClass(string $class, array $strategies)
{
$class = ltrim($class, '\\');
if (!isset($this->safeClasses[$class])) {
$this->safeClasses[$class] = [];
}
$this->safeClasses[$class] = array_merge($this->safeClasses[$class], $strategies);
foreach ($strategies as $strategy) {
$this->safeLookup[$strategy][$class] = true;
}
}
}
}
namespace {
use Twig\Environment;
use Twig\Error\RuntimeError;
use Twig\Extension\EscaperExtension;
use Twig\Markup;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Node;
/**
* Marks a variable as being safe.
*
* @param string $string A PHP variable
*/
function twig_raw_filter($string)
{
return $string;
}
/**
* Escapes a string.
*
* @param mixed $string The value to be escaped
* @param string $strategy The escaping strategy
* @param string $charset The charset
* @param bool $autoescape Whether the function is called by the auto-escaping feature (true) or by the developer (false)
*
* @return string
*/
function twig_escape_filter(Environment $env, $string, $strategy = 'html', $charset = null, $autoescape = false)
{
if ($autoescape && $string instanceof Markup) {
return $string;
}
if (!\is_string($string)) {
if (\is_object($string) && method_exists($string, '__toString')) {
if ($autoescape) {
$c = \get_class($string);
$ext = $env->getExtension(EscaperExtension::class);
if (!isset($ext->safeClasses[$c])) {
$ext->safeClasses[$c] = [];
foreach (class_parents($string) + class_implements($string) as $class) {
if (isset($ext->safeClasses[$class])) {
$ext->safeClasses[$c] = array_unique(array_merge($ext->safeClasses[$c], $ext->safeClasses[$class]));
foreach ($ext->safeClasses[$class] as $s) {
$ext->safeLookup[$s][$c] = true;
}
}
}
}
if (isset($ext->safeLookup[$strategy][$c]) || isset($ext->safeLookup['all'][$c])) {
return (string) $string;
}
}
$string = (string) $string;
} elseif (\in_array($strategy, ['html', 'js', 'css', 'html_attr', 'url'])) {
return $string;
}
}
if ('' === $string) {
return '';
}
if (null === $charset) {
$charset = $env->getCharset();
}
switch ($strategy) {
case 'html':
// see https://www.php.net/htmlspecialchars
// Using a static variable to avoid initializing the array
// each time the function is called. Moving the declaration on the
// top of the function slow downs other escaping strategies.
static $htmlspecialcharsCharsets = [
'ISO-8859-1' => true, 'ISO8859-1' => true,
'ISO-8859-15' => true, 'ISO8859-15' => true,
'utf-8' => true, 'UTF-8' => true,
'CP866' => true, 'IBM866' => true, '866' => true,
'CP1251' => true, 'WINDOWS-1251' => true, 'WIN-1251' => true,
'1251' => true,
'CP1252' => true, 'WINDOWS-1252' => true, '1252' => true,
'KOI8-R' => true, 'KOI8-RU' => true, 'KOI8R' => true,
'BIG5' => true, '950' => true,
'GB2312' => true, '936' => true,
'BIG5-HKSCS' => true,
'SHIFT_JIS' => true, 'SJIS' => true, '932' => true,
'EUC-JP' => true, 'EUCJP' => true,
'ISO8859-5' => true, 'ISO-8859-5' => true, 'MACROMAN' => true,
];
if (isset($htmlspecialcharsCharsets[$charset])) {
return htmlspecialchars($string, \ENT_QUOTES | \ENT_SUBSTITUTE, $charset);
}
if (isset($htmlspecialcharsCharsets[strtoupper($charset)])) {
// cache the lowercase variant for future iterations
$htmlspecialcharsCharsets[$charset] = true;
return htmlspecialchars($string, \ENT_QUOTES | \ENT_SUBSTITUTE, $charset);
}
$string = twig_convert_encoding($string, 'UTF-8', $charset);
$string = htmlspecialchars($string, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8');
return iconv('UTF-8', $charset, $string);
case 'js':
// escape all non-alphanumeric characters
// into their \x or \uHHHH representations
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, 'UTF-8', $charset);
}
if (!preg_match('//u', $string)) {
throw new RuntimeError('The string to escape is not a valid UTF-8 string.');
}
$string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', function ($matches) {
$char = $matches[0];
/*
* A few characters have short escape sequences in JSON and JavaScript.
* Escape sequences supported only by JavaScript, not JSON, are omitted.
* \" is also supported but omitted, because the resulting string is not HTML safe.
*/
static $shortMap = [
'\\' => '\\\\',
'/' => '\\/',
"\x08" => '\b',
"\x0C" => '\f',
"\x0A" => '\n',
"\x0D" => '\r',
"\x09" => '\t',
];
if (isset($shortMap[$char])) {
return $shortMap[$char];
}
$codepoint = mb_ord($char, 'UTF-8');
if (0x10000 > $codepoint) {
return sprintf('\u%04X', $codepoint);
}
// Split characters outside the BMP into surrogate pairs
// https://tools.ietf.org/html/rfc2781.html#section-2.1
$u = $codepoint - 0x10000;
$high = 0xD800 | ($u >> 10);
$low = 0xDC00 | ($u & 0x3FF);
return sprintf('\u%04X\u%04X', $high, $low);
}, $string);
if ('UTF-8' !== $charset) {
$string = iconv('UTF-8', $charset, $string);
}
return $string;
case 'css':
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, 'UTF-8', $charset);
}
if (!preg_match('//u', $string)) {
throw new RuntimeError('The string to escape is not a valid UTF-8 string.');
}
$string = preg_replace_callback('#[^a-zA-Z0-9]#Su', function ($matches) {
$char = $matches[0];
return sprintf('\\%X ', 1 === \strlen($char) ? \ord($char) : mb_ord($char, 'UTF-8'));
}, $string);
if ('UTF-8' !== $charset) {
$string = iconv('UTF-8', $charset, $string);
}
return $string;
case 'html_attr':
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, 'UTF-8', $charset);
}
if (!preg_match('//u', $string)) {
throw new RuntimeError('The string to escape is not a valid UTF-8 string.');
}
$string = preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su', function ($matches) {
/**
* This function is adapted from code coming from Zend Framework.
*
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (https://www.zend.com)
* @license https://framework.zend.com/license/new-bsd New BSD License
*/
$chr = $matches[0];
$ord = \ord($chr);
/*
* The following replaces characters undefined in HTML with the
* hex entity for the Unicode replacement character.
*/
if (($ord <= 0x1f && "\t" != $chr && "\n" != $chr && "\r" != $chr) || ($ord >= 0x7f && $ord <= 0x9f)) {
return '�';
}
/*
* Check if the current character to escape has a name entity we should
* replace it with while grabbing the hex value of the character.
*/
if (1 === \strlen($chr)) {
/*
* While HTML supports far more named entities, the lowest common denominator
* has become HTML5's XML Serialisation which is restricted to the those named
* entities that XML supports. Using HTML entities would result in this error:
* XML Parsing Error: undefined entity
*/
static $entityMap = [
34 => '"', /* quotation mark */
38 => '&', /* ampersand */
60 => '<', /* less-than sign */
62 => '>', /* greater-than sign */
];
if (isset($entityMap[$ord])) {
return $entityMap[$ord];
}
return sprintf('&#x%02X;', $ord);
}
/*
* Per OWASP recommendations, we'll use hex entities for any other
* characters where a named entity does not exist.
*/
return sprintf('&#x%04X;', mb_ord($chr, 'UTF-8'));
}, $string);
if ('UTF-8' !== $charset) {
$string = iconv('UTF-8', $charset, $string);
}
return $string;
case 'url':
return rawurlencode($string);
default:
$escapers = $env->getExtension(EscaperExtension::class)->getEscapers();
if (array_key_exists($strategy, $escapers)) {
return $escapers[$strategy]($env, $string, $charset);
}
$validStrategies = implode(', ', array_merge(['html', 'js', 'url', 'css', 'html_attr'], array_keys($escapers)));
throw new RuntimeError(sprintf('Invalid escaping strategy "%s" (valid ones: %s).', $strategy, $validStrategies));
}
}
/**
* @internal
*/
function twig_escape_filter_is_safe(Node $filterArgs)
{
foreach ($filterArgs as $arg) {
if ($arg instanceof ConstantExpression) {
return [$arg->getAttribute('value')];
}
return [];
}
return ['html'];
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
/**
* Enables usage of the deprecated Twig\Extension\AbstractExtension::getGlobals() method.
*
* Explicitly implement this interface if you really need to implement the
* deprecated getGlobals() method in your extensions.
*
* @author Fabien Potencier <[email protected]>
*/
interface GlobalsInterface
{
public function getGlobals(): array;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
/**
* @author Grégoire Pineau <[email protected]>
*/
interface RuntimeExtensionInterface
{
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\NodeVisitor\NodeVisitorInterface;
use Twig\TokenParser\TokenParserInterface;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
/**
* Used by \Twig\Environment as a staging area.
*
* @author Fabien Potencier <[email protected]>
*
* @internal
*/
final class StagingExtension extends AbstractExtension
{
private $functions = [];
private $filters = [];
private $visitors = [];
private $tokenParsers = [];
private $tests = [];
public function addFunction(TwigFunction $function): void
{
if (isset($this->functions[$function->getName()])) {
throw new \LogicException(sprintf('Function "%s" is already registered.', $function->getName()));
}
$this->functions[$function->getName()] = $function;
}
public function getFunctions(): array
{
return $this->functions;
}
public function addFilter(TwigFilter $filter): void
{
if (isset($this->filters[$filter->getName()])) {
throw new \LogicException(sprintf('Filter "%s" is already registered.', $filter->getName()));
}
$this->filters[$filter->getName()] = $filter;
}
public function getFilters(): array
{
return $this->filters;
}
public function addNodeVisitor(NodeVisitorInterface $visitor): void
{
$this->visitors[] = $visitor;
}
public function getNodeVisitors(): array
{
return $this->visitors;
}
public function addTokenParser(TokenParserInterface $parser): void
{
if (isset($this->tokenParsers[$parser->getTag()])) {
throw new \LogicException(sprintf('Tag "%s" is already registered.', $parser->getTag()));
}
$this->tokenParsers[$parser->getTag()] = $parser;
}
public function getTokenParsers(): array
{
return $this->tokenParsers;
}
public function addTest(TwigTest $test): void
{
if (isset($this->tests[$test->getName()])) {
throw new \LogicException(sprintf('Test "%s" is already registered.', $test->getName()));
}
$this->tests[$test->getName()] = $test;
}
public function getTests(): array
{
return $this->tests;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\FlushNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Flushes the output to the client.
*
* @see flush()
*
* @internal
*/
final class FlushTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$this->parser->getStream()->expect(/* Token::BLOCK_END_TYPE */ 3);
return new FlushNode($token->getLine(), $this->getTag());
}
public function getTag(): string
{
return 'flush';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\ImportNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Imports macros.
*
* {% import 'forms.html' as forms %}
*
* @internal
*/
final class ImportTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$macro = $this->parser->getExpressionParser()->parseExpression();
$this->parser->getStream()->expect(/* Token::NAME_TYPE */ 5, 'as');
$var = new AssignNameExpression($this->parser->getStream()->expect(/* Token::NAME_TYPE */ 5)->getValue(), $token->getLine());
$this->parser->getStream()->expect(/* Token::BLOCK_END_TYPE */ 3);
$this->parser->addImportedSymbol('template', $var->getAttribute('name'));
return new ImportNode($macro, $var, $token->getLine(), $this->getTag(), $this->parser->isMainScope());
}
public function getTag(): string
{
return 'import';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Node;
use Twig\Token;
/**
* Imports blocks defined in another template into the current template.
*
* {% extends "base.html" %}
*
* {% use "blocks.html" %}
*
* {% block title %}{% endblock %}
* {% block content %}{% endblock %}
*
* @see https://twig.symfony.com/doc/templates.html#horizontal-reuse for details.
*
* @internal
*/
final class UseTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$template = $this->parser->getExpressionParser()->parseExpression();
$stream = $this->parser->getStream();
if (!$template instanceof ConstantExpression) {
throw new SyntaxError('The template references in a "use" statement must be a string.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$targets = [];
if ($stream->nextIf('with')) {
do {
$name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
$alias = $name;
if ($stream->nextIf('as')) {
$alias = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
}
$targets[$name] = new ConstantExpression($alias, -1);
if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
break;
}
} while (true);
}
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$this->parser->addTrait(new Node(['template' => $template, 'targets' => new Node($targets)]));
return new Node();
}
public function getTag(): string
{
return 'use';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Parser;
/**
* Base class for all token parsers.
*
* @author Fabien Potencier <[email protected]>
*/
abstract class AbstractTokenParser implements TokenParserInterface
{
/**
* @var Parser
*/
protected $parser;
public function setParser(Parser $parser): void
{
$this->parser = $parser;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\DoNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Evaluates an expression, discarding the returned value.
*
* @internal
*/
final class DoTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$expr = $this->parser->getExpressionParser()->parseExpression();
$this->parser->getStream()->expect(/* Token::BLOCK_END_TYPE */ 3);
return new DoNode($expr, $token->getLine(), $this->getTag());
}
public function getTag(): string
{
return 'do';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\Node;
use Twig\Parser;
use Twig\Token;
/**
* Interface implemented by token parsers.
*
* @author Fabien Potencier <[email protected]>
*/
interface TokenParserInterface
{
/**
* Sets the parser associated with this token parser.
*/
public function setParser(Parser $parser): void;
/**
* Parses a token and returns a node.
*
* @return Node
*
* @throws SyntaxError
*/
public function parse(Token $token);
/**
* Gets the tag name associated with this token parser.
*
* @return string
*/
public function getTag();
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\BodyNode;
use Twig\Node\MacroNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Defines a macro.
*
* {% macro input(name, value, type, size) %}
* <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
* {% endmacro %}
*
* @internal
*/
final class MacroTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
$arguments = $this->parser->getExpressionParser()->parseArguments(true, true);
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$this->parser->pushLocalScope();
$body = $this->parser->subparse([$this, 'decideBlockEnd'], true);
if ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) {
$value = $token->getValue();
if ($value != $name) {
throw new SyntaxError(sprintf('Expected endmacro for macro "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
}
$this->parser->popLocalScope();
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$this->parser->setMacro($name, new MacroNode($name, new BodyNode([$body]), $arguments, $lineno, $this->getTag()));
return new Node();
}
public function decideBlockEnd(Token $token): bool
{
return $token->test('endmacro');
}
public function getTag(): string
{
return 'macro';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\IncludeNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Includes a template.
*
* {% include 'header.html' %}
* Body
* {% include 'footer.html' %}
*
* @internal
*/
class IncludeTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$expr = $this->parser->getExpressionParser()->parseExpression();
list($variables, $only, $ignoreMissing) = $this->parseArguments();
return new IncludeNode($expr, $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag());
}
protected function parseArguments()
{
$stream = $this->parser->getStream();
$ignoreMissing = false;
if ($stream->nextIf(/* Token::NAME_TYPE */ 5, 'ignore')) {
$stream->expect(/* Token::NAME_TYPE */ 5, 'missing');
$ignoreMissing = true;
}
$variables = null;
if ($stream->nextIf(/* Token::NAME_TYPE */ 5, 'with')) {
$variables = $this->parser->getExpressionParser()->parseExpression();
}
$only = false;
if ($stream->nextIf(/* Token::NAME_TYPE */ 5, 'only')) {
$only = true;
}
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
return [$variables, $only, $ignoreMissing];
}
public function getTag(): string
{
return 'include';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\DeprecatedNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Deprecates a section of a template.
*
* {% deprecated 'The "base.twig" template is deprecated, use "layout.twig" instead.' %}
* {% extends 'layout.html.twig' %}
*
* @author Yonel Ceruto <[email protected]>
*
* @internal
*/
final class DeprecatedTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$expr = $this->parser->getExpressionParser()->parseExpression();
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
return new DeprecatedNode($expr, $token->getLine(), $this->getTag());
}
public function getTag(): string
{
return 'deprecated';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\ImportNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Imports macros.
*
* {% from 'forms.html' import forms %}
*
* @internal
*/
final class FromTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$macro = $this->parser->getExpressionParser()->parseExpression();
$stream = $this->parser->getStream();
$stream->expect(/* Token::NAME_TYPE */ 5, 'import');
$targets = [];
do {
$name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
$alias = $name;
if ($stream->nextIf('as')) {
$alias = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
}
$targets[$name] = $alias;
if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
break;
}
} while (true);
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$var = new AssignNameExpression($this->parser->getVarName(), $token->getLine());
$node = new ImportNode($macro, $var, $token->getLine(), $this->getTag(), $this->parser->isMainScope());
foreach ($targets as $name => $alias) {
$this->parser->addImportedSymbol('function', $alias, 'macro_'.$name, $var);
}
return $node;
}
public function getTag(): string
{
return 'from';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\EmbedNode;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Node;
use Twig\Token;
/**
* Embeds a template.
*
* @internal
*/
final class EmbedTokenParser extends IncludeTokenParser
{
public function parse(Token $token): Node
{
$stream = $this->parser->getStream();
$parent = $this->parser->getExpressionParser()->parseExpression();
list($variables, $only, $ignoreMissing) = $this->parseArguments();
$parentToken = $fakeParentToken = new Token(/* Token::STRING_TYPE */ 7, '__parent__', $token->getLine());
if ($parent instanceof ConstantExpression) {
$parentToken = new Token(/* Token::STRING_TYPE */ 7, $parent->getAttribute('value'), $token->getLine());
} elseif ($parent instanceof NameExpression) {
$parentToken = new Token(/* Token::NAME_TYPE */ 5, $parent->getAttribute('name'), $token->getLine());
}
// inject a fake parent to make the parent() function work
$stream->injectTokens([
new Token(/* Token::BLOCK_START_TYPE */ 1, '', $token->getLine()),
new Token(/* Token::NAME_TYPE */ 5, 'extends', $token->getLine()),
$parentToken,
new Token(/* Token::BLOCK_END_TYPE */ 3, '', $token->getLine()),
]);
$module = $this->parser->parse($stream, [$this, 'decideBlockEnd'], true);
// override the parent with the correct one
if ($fakeParentToken === $parentToken) {
$module->setNode('parent', $parent);
}
$this->parser->embedTemplate($module);
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
return new EmbedNode($module->getTemplateName(), $module->getAttribute('index'), $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag());
}
public function decideBlockEnd(Token $token): bool
{
return $token->test('endembed');
}
public function getTag(): string
{
return 'embed';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\IncludeNode;
use Twig\Node\Node;
use Twig\Node\SandboxNode;
use Twig\Node\TextNode;
use Twig\Token;
/**
* Marks a section of a template as untrusted code that must be evaluated in the sandbox mode.
*
* {% sandbox %}
* {% include 'user.html' %}
* {% endsandbox %}
*
* @see https://twig.symfony.com/doc/api.html#sandbox-extension for details
*
* @internal
*/
final class SandboxTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$stream = $this->parser->getStream();
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$body = $this->parser->subparse([$this, 'decideBlockEnd'], true);
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
// in a sandbox tag, only include tags are allowed
if (!$body instanceof IncludeNode) {
foreach ($body as $node) {
if ($node instanceof TextNode && ctype_space($node->getAttribute('data'))) {
continue;
}
if (!$node instanceof IncludeNode) {
throw new SyntaxError('Only "include" tags are allowed within a "sandbox" section.', $node->getTemplateLine(), $stream->getSourceContext());
}
}
}
return new SandboxNode($body, $token->getLine(), $this->getTag());
}
public function decideBlockEnd(Token $token): bool
{
return $token->test('endsandbox');
}
public function getTag(): string
{
return 'sandbox';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\Node;
use Twig\Node\WithNode;
use Twig\Token;
/**
* Creates a nested scope.
*
* @author Fabien Potencier <[email protected]>
*
* @internal
*/
final class WithTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$stream = $this->parser->getStream();
$variables = null;
$only = false;
if (!$stream->test(/* Token::BLOCK_END_TYPE */ 3)) {
$variables = $this->parser->getExpressionParser()->parseExpression();
$only = (bool) $stream->nextIf(/* Token::NAME_TYPE */ 5, 'only');
}
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$body = $this->parser->subparse([$this, 'decideWithEnd'], true);
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
return new WithNode($body, $variables, $only, $token->getLine(), $this->getTag());
}
public function decideWithEnd(Token $token): bool
{
return $token->test('endwith');
}
public function getTag(): string
{
return 'with';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\Expression\TempNameExpression;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\Node\SetNode;
use Twig\Token;
/**
* Applies filters on a section of a template.
*
* {% apply upper %}
* This text becomes uppercase
* {% endapply %}
*
* @internal
*/
final class ApplyTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$lineno = $token->getLine();
$name = $this->parser->getVarName();
$ref = new TempNameExpression($name, $lineno);
$ref->setAttribute('always_defined', true);
$filter = $this->parser->getExpressionParser()->parseFilterExpressionRaw($ref, $this->getTag());
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this, 'decideApplyEnd'], true);
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
return new Node([
new SetNode(true, $ref, $body, $lineno, $this->getTag()),
new PrintNode($filter, $lineno, $this->getTag()),
]);
}
public function decideApplyEnd(Token $token): bool
{
return $token->test('endapply');
}
public function getTag(): string
{
return 'apply';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\IfNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Tests a condition.
*
* {% if users %}
* <ul>
* {% for user in users %}
* <li>{{ user.username|e }}</li>
* {% endfor %}
* </ul>
* {% endif %}
*
* @internal
*/
final class IfTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$lineno = $token->getLine();
$expr = $this->parser->getExpressionParser()->parseExpression();
$stream = $this->parser->getStream();
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$body = $this->parser->subparse([$this, 'decideIfFork']);
$tests = [$expr, $body];
$else = null;
$end = false;
while (!$end) {
switch ($stream->next()->getValue()) {
case 'else':
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$else = $this->parser->subparse([$this, 'decideIfEnd']);
break;
case 'elseif':
$expr = $this->parser->getExpressionParser()->parseExpression();
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$body = $this->parser->subparse([$this, 'decideIfFork']);
$tests[] = $expr;
$tests[] = $body;
break;
case 'endif':
$end = true;
break;
default:
throw new SyntaxError(sprintf('Unexpected end of template. Twig was looking for the following tags "else", "elseif", or "endif" to close the "if" block started at line %d).', $lineno), $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
}
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
return new IfNode(new Node($tests), $else, $lineno, $this->getTag());
}
public function decideIfFork(Token $token): bool
{
return $token->test(['elseif', 'else', 'endif']);
}
public function decideIfEnd(Token $token): bool
{
return $token->test(['endif']);
}
public function getTag(): string
{
return 'if';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\AutoEscapeNode;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Node;
use Twig\Token;
/**
* Marks a section of a template to be escaped or not.
*
* @internal
*/
final class AutoEscapeTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
if ($stream->test(/* Token::BLOCK_END_TYPE */ 3)) {
$value = 'html';
} else {
$expr = $this->parser->getExpressionParser()->parseExpression();
if (!$expr instanceof ConstantExpression) {
throw new SyntaxError('An escaping strategy must be a string or false.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$value = $expr->getAttribute('value');
}
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$body = $this->parser->subparse([$this, 'decideBlockEnd'], true);
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
return new AutoEscapeNode($value, $body, $lineno, $this->getTag());
}
public function decideBlockEnd(Token $token): bool
{
return $token->test('endautoescape');
}
public function getTag(): string
{
return 'autoescape';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\ForNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Loops over each item of a sequence.
*
* <ul>
* {% for user in users %}
* <li>{{ user.username|e }}</li>
* {% endfor %}
* </ul>
*
* @internal
*/
final class ForTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$targets = $this->parser->getExpressionParser()->parseAssignmentExpression();
$stream->expect(/* Token::OPERATOR_TYPE */ 8, 'in');
$seq = $this->parser->getExpressionParser()->parseExpression();
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$body = $this->parser->subparse([$this, 'decideForFork']);
if ('else' == $stream->next()->getValue()) {
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$else = $this->parser->subparse([$this, 'decideForEnd'], true);
} else {
$else = null;
}
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
if (\count($targets) > 1) {
$keyTarget = $targets->getNode(0);
$keyTarget = new AssignNameExpression($keyTarget->getAttribute('name'), $keyTarget->getTemplateLine());
$valueTarget = $targets->getNode(1);
} else {
$keyTarget = new AssignNameExpression('_key', $lineno);
$valueTarget = $targets->getNode(0);
}
$valueTarget = new AssignNameExpression($valueTarget->getAttribute('name'), $valueTarget->getTemplateLine());
return new ForNode($keyTarget, $valueTarget, $seq, null, $body, $else, $lineno, $this->getTag());
}
public function decideForFork(Token $token): bool
{
return $token->test(['else', 'endfor']);
}
public function decideForEnd(Token $token): bool
{
return $token->test('endfor');
}
public function getTag(): string
{
return 'for';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\Node;
use Twig\Node\SetNode;
use Twig\Token;
/**
* Defines a variable.
*
* {% set foo = 'foo' %}
* {% set foo = [1, 2] %}
* {% set foo = {'foo': 'bar'} %}
* {% set foo = 'foo' ~ 'bar' %}
* {% set foo, bar = 'foo', 'bar' %}
* {% set foo %}Some content{% endset %}
*
* @internal
*/
final class SetTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$names = $this->parser->getExpressionParser()->parseAssignmentExpression();
$capture = false;
if ($stream->nextIf(/* Token::OPERATOR_TYPE */ 8, '=')) {
$values = $this->parser->getExpressionParser()->parseMultitargetExpression();
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
if (\count($names) !== \count($values)) {
throw new SyntaxError('When using set, you must have the same number of variables and assignments.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
} else {
$capture = true;
if (\count($names) > 1) {
throw new SyntaxError('When using set with a block, you cannot have a multi-target.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$values = $this->parser->subparse([$this, 'decideBlockEnd'], true);
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
}
return new SetNode($capture, $names, $values, $lineno, $this->getTag());
}
public function decideBlockEnd(Token $token): bool
{
return $token->test('endset');
}
public function getTag(): string
{
return 'set';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\BlockNode;
use Twig\Node\BlockReferenceNode;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\Token;
/**
* Marks a section of a template as being reusable.
*
* {% block head %}
* <link rel="stylesheet" href="style.css" />
* <title>{% block title %}{% endblock %} - My Webpage</title>
* {% endblock %}
*
* @internal
*/
final class BlockTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
if ($this->parser->hasBlock($name)) {
throw new SyntaxError(sprintf("The block '%s' has already been defined line %d.", $name, $this->parser->getBlock($name)->getTemplateLine()), $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$this->parser->setBlock($name, $block = new BlockNode($name, new Node([]), $lineno));
$this->parser->pushLocalScope();
$this->parser->pushBlockStack($name);
if ($stream->nextIf(/* Token::BLOCK_END_TYPE */ 3)) {
$body = $this->parser->subparse([$this, 'decideBlockEnd'], true);
if ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) {
$value = $token->getValue();
if ($value != $name) {
throw new SyntaxError(sprintf('Expected endblock for block "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
}
} else {
$body = new Node([
new PrintNode($this->parser->getExpressionParser()->parseExpression(), $lineno),
]);
}
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
$block->setNode('body', $body);
$this->parser->popBlockStack();
$this->parser->popLocalScope();
return new BlockReferenceNode($name, $lineno, $this->getTag());
}
public function decideBlockEnd(Token $token): bool
{
return $token->test('endblock');
}
public function getTag(): string
{
return 'block';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\Node;
use Twig\Token;
/**
* Extends a template by another one.
*
* {% extends "base.html" %}
*
* @internal
*/
final class ExtendsTokenParser extends AbstractTokenParser
{
public function parse(Token $token): Node
{
$stream = $this->parser->getStream();
if ($this->parser->peekBlockStack()) {
throw new SyntaxError('Cannot use "extend" in a block.', $token->getLine(), $stream->getSourceContext());
} elseif (!$this->parser->isMainScope()) {
throw new SyntaxError('Cannot use "extend" in a macro.', $token->getLine(), $stream->getSourceContext());
}
if (null !== $this->parser->getParent()) {
throw new SyntaxError('Multiple extends tags are forbidden.', $token->getLine(), $stream->getSourceContext());
}
$this->parser->setParent($this->parser->getExpressionParser()->parseExpression());
$stream->expect(/* Token::BLOCK_END_TYPE */ 3);
return new Node();
}
public function getTag(): string
{
return 'extends';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Cache;
/**
* Implements a no-cache strategy.
*
* @author Fabien Potencier <[email protected]>
*/
final class NullCache implements CacheInterface
{
public function generateKey(string $name, string $className): string
{
return '';
}
public function write(string $key, string $content): void
{
}
public function load(string $key): void
{
}
public function getTimestamp(string $key): int
{
return 0;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Cache;
/**
* Interface implemented by cache classes.
*
* It is highly recommended to always store templates on the filesystem to
* benefit from the PHP opcode cache. This interface is mostly useful if you
* need to implement a custom strategy for storing templates on the filesystem.
*
* @author Andrew Tch <[email protected]>
*/
interface CacheInterface
{
/**
* Generates a cache key for the given template class name.
*/
public function generateKey(string $name, string $className): string;
/**
* Writes the compiled template to cache.
*
* @param string $content The template representation as a PHP class
*/
public function write(string $key, string $content): void;
/**
* Loads a template from the cache.
*/
public function load(string $key): void;
/**
* Returns the modification timestamp of a key.
*/
public function getTimestamp(string $key): int;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Cache;
/**
* Implements a cache on the filesystem.
*
* @author Andrew Tch <[email protected]>
*/
class FilesystemCache implements CacheInterface
{
public const FORCE_BYTECODE_INVALIDATION = 1;
private $directory;
private $options;
public function __construct(string $directory, int $options = 0)
{
$this->directory = rtrim($directory, '\/').'/';
$this->options = $options;
}
public function generateKey(string $name, string $className): string
{
$hash = hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $className);
return $this->directory.$hash[0].$hash[1].'/'.$hash.'.php';
}
public function load(string $key): void
{
if (is_file($key)) {
@include_once $key;
}
}
public function write(string $key, string $content): void
{
$dir = \dirname($key);
if (!is_dir($dir)) {
if (false === @mkdir($dir, 0777, true)) {
clearstatcache(true, $dir);
if (!is_dir($dir)) {
throw new \RuntimeException(sprintf('Unable to create the cache directory (%s).', $dir));
}
}
} elseif (!is_writable($dir)) {
throw new \RuntimeException(sprintf('Unable to write in the cache directory (%s).', $dir));
}
$tmpFile = tempnam($dir, basename($key));
if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $key)) {
@chmod($key, 0666 & ~umask());
if (self::FORCE_BYTECODE_INVALIDATION == ($this->options & self::FORCE_BYTECODE_INVALIDATION)) {
// Compile cached file into bytecode cache
if (\function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN)) {
@opcache_invalidate($key, true);
} elseif (\function_exists('apc_compile_file')) {
apc_compile_file($key);
}
}
return;
}
throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $key));
}
public function getTimestamp(string $key): int
{
if (!is_file($key)) {
return 0;
}
return (int) @filemtime($key);
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Error;
use Twig\Source;
use Twig\Template;
/**
* Twig base exception.
*
* This exception class and its children must only be used when
* an error occurs during the loading of a template, when a syntax error
* is detected in a template, or when rendering a template. Other
* errors must use regular PHP exception classes (like when the template
* cache directory is not writable for instance).
*
* To help debugging template issues, this class tracks the original template
* name and line where the error occurred.
*
* Whenever possible, you must set these information (original template name
* and line number) yourself by passing them to the constructor. If some or all
* these information are not available from where you throw the exception, then
* this class will guess them automatically (when the line number is set to -1
* and/or the name is set to null). As this is a costly operation, this
* can be disabled by passing false for both the name and the line number
* when creating a new instance of this class.
*
* @author Fabien Potencier <[email protected]>
*/
class Error extends \Exception
{
private $lineno;
private $name;
private $rawMessage;
private $sourcePath;
private $sourceCode;
/**
* Constructor.
*
* By default, automatic guessing is enabled.
*
* @param string $message The error message
* @param int $lineno The template line where the error occurred
* @param Source|null $source The source context where the error occurred
*/
public function __construct(string $message, int $lineno = -1, Source $source = null, \Exception $previous = null)
{
parent::__construct('', 0, $previous);
if (null === $source) {
$name = null;
} else {
$name = $source->getName();
$this->sourceCode = $source->getCode();
$this->sourcePath = $source->getPath();
}
$this->lineno = $lineno;
$this->name = $name;
$this->rawMessage = $message;
$this->updateRepr();
}
public function getRawMessage(): string
{
return $this->rawMessage;
}
public function getTemplateLine(): int
{
return $this->lineno;
}
public function setTemplateLine(int $lineno): void
{
$this->lineno = $lineno;
$this->updateRepr();
}
public function getSourceContext(): ?Source
{
return $this->name ? new Source($this->sourceCode, $this->name, $this->sourcePath) : null;
}
public function setSourceContext(Source $source = null): void
{
if (null === $source) {
$this->sourceCode = $this->name = $this->sourcePath = null;
} else {
$this->sourceCode = $source->getCode();
$this->name = $source->getName();
$this->sourcePath = $source->getPath();
}
$this->updateRepr();
}
public function guess(): void
{
$this->guessTemplateInfo();
$this->updateRepr();
}
public function appendMessage($rawMessage): void
{
$this->rawMessage .= $rawMessage;
$this->updateRepr();
}
private function updateRepr(): void
{
$this->message = $this->rawMessage;
if ($this->sourcePath && $this->lineno > 0) {
$this->file = $this->sourcePath;
$this->line = $this->lineno;
return;
}
$dot = false;
if ('.' === substr($this->message, -1)) {
$this->message = substr($this->message, 0, -1);
$dot = true;
}
$questionMark = false;
if ('?' === substr($this->message, -1)) {
$this->message = substr($this->message, 0, -1);
$questionMark = true;
}
if ($this->name) {
if (\is_string($this->name) || (\is_object($this->name) && method_exists($this->name, '__toString'))) {
$name = sprintf('"%s"', $this->name);
} else {
$name = json_encode($this->name);
}
$this->message .= sprintf(' in %s', $name);
}
if ($this->lineno && $this->lineno >= 0) {
$this->message .= sprintf(' at line %d', $this->lineno);
}
if ($dot) {
$this->message .= '.';
}
if ($questionMark) {
$this->message .= '?';
}
}
private function guessTemplateInfo(): void
{
$template = null;
$templateClass = null;
$backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS | \DEBUG_BACKTRACE_PROVIDE_OBJECT);
foreach ($backtrace as $trace) {
if (isset($trace['object']) && $trace['object'] instanceof Template) {
$currentClass = \get_class($trace['object']);
$isEmbedContainer = null === $templateClass ? false : 0 === strpos($templateClass, $currentClass);
if (null === $this->name || ($this->name == $trace['object']->getTemplateName() && !$isEmbedContainer)) {
$template = $trace['object'];
$templateClass = \get_class($trace['object']);
}
}
}
// update template name
if (null !== $template && null === $this->name) {
$this->name = $template->getTemplateName();
}
// update template path if any
if (null !== $template && null === $this->sourcePath) {
$src = $template->getSourceContext();
$this->sourceCode = $src->getCode();
$this->sourcePath = $src->getPath();
}
if (null === $template || $this->lineno > -1) {
return;
}
$r = new \ReflectionObject($template);
$file = $r->getFileName();
$exceptions = [$e = $this];
while ($e = $e->getPrevious()) {
$exceptions[] = $e;
}
while ($e = array_pop($exceptions)) {
$traces = $e->getTrace();
array_unshift($traces, ['file' => $e->getFile(), 'line' => $e->getLine()]);
while ($trace = array_shift($traces)) {
if (!isset($trace['file']) || !isset($trace['line']) || $file != $trace['file']) {
continue;
}
foreach ($template->getDebugInfo() as $codeLine => $templateLine) {
if ($codeLine <= $trace['line']) {
// update template line
$this->lineno = $templateLine;
return;
}
}
}
}
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Error;
/**
* Exception thrown when an error occurs at runtime.
*
* @author Fabien Potencier <[email protected]>
*/
class RuntimeError extends Error
{
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Error;
/**
* \Exception thrown when a syntax error occurs during lexing or parsing of a template.
*
* @author Fabien Potencier <[email protected]>
*/
class SyntaxError extends Error
{
/**
* Tweaks the error message to include suggestions.
*
* @param string $name The original name of the item that does not exist
* @param array $items An array of possible items
*/
public function addSuggestions(string $name, array $items): void
{
$alternatives = [];
foreach ($items as $item) {
$lev = levenshtein($name, $item);
if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
$alternatives[$item] = $lev;
}
}
if (!$alternatives) {
return;
}
asort($alternatives);
$this->appendMessage(sprintf(' Did you mean "%s"?', implode('", "', array_keys($alternatives))));
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Error;
/**
* Exception thrown when an error occurs during template loading.
*
* @author Fabien Potencier <[email protected]>
*/
class LoaderError extends Error
{
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Extension\EscaperExtension;
use Twig\Node\AutoEscapeNode;
use Twig\Node\BlockNode;
use Twig\Node\BlockReferenceNode;
use Twig\Node\DoNode;
use Twig\Node\Expression\ConditionalExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\InlinePrint;
use Twig\Node\ImportNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\NodeTraverser;
/**
* @author Fabien Potencier <[email protected]>
*
* @internal
*/
final class EscaperNodeVisitor implements NodeVisitorInterface
{
private $statusStack = [];
private $blocks = [];
private $safeAnalysis;
private $traverser;
private $defaultStrategy = false;
private $safeVars = [];
public function __construct()
{
$this->safeAnalysis = new SafeAnalysisNodeVisitor();
}
public function enterNode(Node $node, Environment $env): Node
{
if ($node instanceof ModuleNode) {
if ($env->hasExtension(EscaperExtension::class) && $defaultStrategy = $env->getExtension(EscaperExtension::class)->getDefaultStrategy($node->getTemplateName())) {
$this->defaultStrategy = $defaultStrategy;
}
$this->safeVars = [];
$this->blocks = [];
} elseif ($node instanceof AutoEscapeNode) {
$this->statusStack[] = $node->getAttribute('value');
} elseif ($node instanceof BlockNode) {
$this->statusStack[] = isset($this->blocks[$node->getAttribute('name')]) ? $this->blocks[$node->getAttribute('name')] : $this->needEscaping($env);
} elseif ($node instanceof ImportNode) {
$this->safeVars[] = $node->getNode('var')->getAttribute('name');
}
return $node;
}
public function leaveNode(Node $node, Environment $env): ?Node
{
if ($node instanceof ModuleNode) {
$this->defaultStrategy = false;
$this->safeVars = [];
$this->blocks = [];
} elseif ($node instanceof FilterExpression) {
return $this->preEscapeFilterNode($node, $env);
} elseif ($node instanceof PrintNode && false !== $type = $this->needEscaping($env)) {
$expression = $node->getNode('expr');
if ($expression instanceof ConditionalExpression && $this->shouldUnwrapConditional($expression, $env, $type)) {
return new DoNode($this->unwrapConditional($expression, $env, $type), $expression->getTemplateLine());
}
return $this->escapePrintNode($node, $env, $type);
}
if ($node instanceof AutoEscapeNode || $node instanceof BlockNode) {
array_pop($this->statusStack);
} elseif ($node instanceof BlockReferenceNode) {
$this->blocks[$node->getAttribute('name')] = $this->needEscaping($env);
}
return $node;
}
private function shouldUnwrapConditional(ConditionalExpression $expression, Environment $env, string $type): bool
{
$expr2Safe = $this->isSafeFor($type, $expression->getNode('expr2'), $env);
$expr3Safe = $this->isSafeFor($type, $expression->getNode('expr3'), $env);
return $expr2Safe !== $expr3Safe;
}
private function unwrapConditional(ConditionalExpression $expression, Environment $env, string $type): ConditionalExpression
{
// convert "echo a ? b : c" to "a ? echo b : echo c" recursively
$expr2 = $expression->getNode('expr2');
if ($expr2 instanceof ConditionalExpression && $this->shouldUnwrapConditional($expr2, $env, $type)) {
$expr2 = $this->unwrapConditional($expr2, $env, $type);
} else {
$expr2 = $this->escapeInlinePrintNode(new InlinePrint($expr2, $expr2->getTemplateLine()), $env, $type);
}
$expr3 = $expression->getNode('expr3');
if ($expr3 instanceof ConditionalExpression && $this->shouldUnwrapConditional($expr3, $env, $type)) {
$expr3 = $this->unwrapConditional($expr3, $env, $type);
} else {
$expr3 = $this->escapeInlinePrintNode(new InlinePrint($expr3, $expr3->getTemplateLine()), $env, $type);
}
return new ConditionalExpression($expression->getNode('expr1'), $expr2, $expr3, $expression->getTemplateLine());
}
private function escapeInlinePrintNode(InlinePrint $node, Environment $env, string $type): Node
{
$expression = $node->getNode('node');
if ($this->isSafeFor($type, $expression, $env)) {
return $node;
}
return new InlinePrint($this->getEscaperFilter($type, $expression), $node->getTemplateLine());
}
private function escapePrintNode(PrintNode $node, Environment $env, string $type): Node
{
if (false === $type) {
return $node;
}
$expression = $node->getNode('expr');
if ($this->isSafeFor($type, $expression, $env)) {
return $node;
}
$class = \get_class($node);
return new $class($this->getEscaperFilter($type, $expression), $node->getTemplateLine());
}
private function preEscapeFilterNode(FilterExpression $filter, Environment $env): FilterExpression
{
$name = $filter->getNode('filter')->getAttribute('value');
$type = $env->getFilter($name)->getPreEscape();
if (null === $type) {
return $filter;
}
$node = $filter->getNode('node');
if ($this->isSafeFor($type, $node, $env)) {
return $filter;
}
$filter->setNode('node', $this->getEscaperFilter($type, $node));
return $filter;
}
private function isSafeFor(string $type, Node $expression, Environment $env): bool
{
$safe = $this->safeAnalysis->getSafe($expression);
if (null === $safe) {
if (null === $this->traverser) {
$this->traverser = new NodeTraverser($env, [$this->safeAnalysis]);
}
$this->safeAnalysis->setSafeVars($this->safeVars);
$this->traverser->traverse($expression);
$safe = $this->safeAnalysis->getSafe($expression);
}
return \in_array($type, $safe) || \in_array('all', $safe);
}
private function needEscaping(Environment $env)
{
if (\count($this->statusStack)) {
return $this->statusStack[\count($this->statusStack) - 1];
}
return $this->defaultStrategy ? $this->defaultStrategy : false;
}
private function getEscaperFilter(string $type, Node $node): FilterExpression
{
$line = $node->getTemplateLine();
$name = new ConstantExpression('escape', $line);
$args = new Node([new ConstantExpression($type, $line), new ConstantExpression(null, $line), new ConstantExpression(true, $line)]);
return new FilterExpression($node, $name, $args, $line);
}
public function getPriority(): int
{
return 0;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\MethodCallExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\ImportNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
/**
* @author Fabien Potencier <[email protected]>
*
* @internal
*/
final class MacroAutoImportNodeVisitor implements NodeVisitorInterface
{
private $inAModule = false;
private $hasMacroCalls = false;
public function enterNode(Node $node, Environment $env): Node
{
if ($node instanceof ModuleNode) {
$this->inAModule = true;
$this->hasMacroCalls = false;
}
return $node;
}
public function leaveNode(Node $node, Environment $env): Node
{
if ($node instanceof ModuleNode) {
$this->inAModule = false;
if ($this->hasMacroCalls) {
$node->getNode('constructor_end')->setNode('_auto_macro_import', new ImportNode(new NameExpression('_self', 0), new AssignNameExpression('_self', 0), 0, 'import', true));
}
} elseif ($this->inAModule) {
if (
$node instanceof GetAttrExpression &&
$node->getNode('node') instanceof NameExpression &&
'_self' === $node->getNode('node')->getAttribute('name') &&
$node->getNode('attribute') instanceof ConstantExpression
) {
$this->hasMacroCalls = true;
$name = $node->getNode('attribute')->getAttribute('value');
$node = new MethodCallExpression($node->getNode('node'), 'macro_'.$name, $node->getNode('arguments'), $node->getTemplateLine());
$node->setAttribute('safe', true);
}
}
return $node;
}
public function getPriority(): int
{
// we must be ran before auto-escaping
return -10;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\Node;
/**
* Used to make node visitors compatible with Twig 1.x and 2.x.
*
* To be removed in Twig 3.1.
*
* @author Fabien Potencier <[email protected]>
*/
abstract class AbstractNodeVisitor implements NodeVisitorInterface
{
final public function enterNode(Node $node, Environment $env): Node
{
return $this->doEnterNode($node, $env);
}
final public function leaveNode(Node $node, Environment $env): ?Node
{
return $this->doLeaveNode($node, $env);
}
/**
* Called before child nodes are visited.
*
* @return Node The modified node
*/
abstract protected function doEnterNode(Node $node, Environment $env);
/**
* Called after child nodes are visited.
*
* @return Node|null The modified node or null if the node must be removed
*/
abstract protected function doLeaveNode(Node $node, Environment $env);
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\Node;
/**
* Interface for node visitor classes.
*
* @author Fabien Potencier <[email protected]>
*/
interface NodeVisitorInterface
{
/**
* Called before child nodes are visited.
*
* @return Node The modified node
*/
public function enterNode(Node $node, Environment $env): Node;
/**
* Called after child nodes are visited.
*
* @return Node|null The modified node or null if the node must be removed
*/
public function leaveNode(Node $node, Environment $env): ?Node;
/**
* Returns the priority for this visitor.
*
* Priority should be between -10 and 10 (0 is the default).
*
* @return int The priority level
*/
public function getPriority();
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\BlockReferenceNode;
use Twig\Node\Expression\BlockReferenceExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\FunctionExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Expression\ParentExpression;
use Twig\Node\ForNode;
use Twig\Node\IncludeNode;
use Twig\Node\Node;
use Twig\Node\PrintNode;
/**
* Tries to optimize the AST.
*
* This visitor is always the last registered one.
*
* You can configure which optimizations you want to activate via the
* optimizer mode.
*
* @author Fabien Potencier <[email protected]>
*
* @internal
*/
final class OptimizerNodeVisitor implements NodeVisitorInterface
{
public const OPTIMIZE_ALL = -1;
public const OPTIMIZE_NONE = 0;
public const OPTIMIZE_FOR = 2;
public const OPTIMIZE_RAW_FILTER = 4;
private $loops = [];
private $loopsTargets = [];
private $optimizers;
/**
* @param int $optimizers The optimizer mode
*/
public function __construct(int $optimizers = -1)
{
if ($optimizers > (self::OPTIMIZE_FOR | self::OPTIMIZE_RAW_FILTER)) {
throw new \InvalidArgumentException(sprintf('Optimizer mode "%s" is not valid.', $optimizers));
}
$this->optimizers = $optimizers;
}
public function enterNode(Node $node, Environment $env): Node
{
if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR & $this->optimizers)) {
$this->enterOptimizeFor($node, $env);
}
return $node;
}
public function leaveNode(Node $node, Environment $env): ?Node
{
if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR & $this->optimizers)) {
$this->leaveOptimizeFor($node, $env);
}
if (self::OPTIMIZE_RAW_FILTER === (self::OPTIMIZE_RAW_FILTER & $this->optimizers)) {
$node = $this->optimizeRawFilter($node, $env);
}
$node = $this->optimizePrintNode($node, $env);
return $node;
}
/**
* Optimizes print nodes.
*
* It replaces:
*
* * "echo $this->render(Parent)Block()" with "$this->display(Parent)Block()"
*/
private function optimizePrintNode(Node $node, Environment $env): Node
{
if (!$node instanceof PrintNode) {
return $node;
}
$exprNode = $node->getNode('expr');
if (
$exprNode instanceof BlockReferenceExpression ||
$exprNode instanceof ParentExpression
) {
$exprNode->setAttribute('output', true);
return $exprNode;
}
return $node;
}
/**
* Removes "raw" filters.
*/
private function optimizeRawFilter(Node $node, Environment $env): Node
{
if ($node instanceof FilterExpression && 'raw' == $node->getNode('filter')->getAttribute('value')) {
return $node->getNode('node');
}
return $node;
}
/**
* Optimizes "for" tag by removing the "loop" variable creation whenever possible.
*/
private function enterOptimizeFor(Node $node, Environment $env): void
{
if ($node instanceof ForNode) {
// disable the loop variable by default
$node->setAttribute('with_loop', false);
array_unshift($this->loops, $node);
array_unshift($this->loopsTargets, $node->getNode('value_target')->getAttribute('name'));
array_unshift($this->loopsTargets, $node->getNode('key_target')->getAttribute('name'));
} elseif (!$this->loops) {
// we are outside a loop
return;
}
// when do we need to add the loop variable back?
// the loop variable is referenced for the current loop
elseif ($node instanceof NameExpression && 'loop' === $node->getAttribute('name')) {
$node->setAttribute('always_defined', true);
$this->addLoopToCurrent();
}
// optimize access to loop targets
elseif ($node instanceof NameExpression && \in_array($node->getAttribute('name'), $this->loopsTargets)) {
$node->setAttribute('always_defined', true);
}
// block reference
elseif ($node instanceof BlockReferenceNode || $node instanceof BlockReferenceExpression) {
$this->addLoopToCurrent();
}
// include without the only attribute
elseif ($node instanceof IncludeNode && !$node->getAttribute('only')) {
$this->addLoopToAll();
}
// include function without the with_context=false parameter
elseif ($node instanceof FunctionExpression
&& 'include' === $node->getAttribute('name')
&& (!$node->getNode('arguments')->hasNode('with_context')
|| false !== $node->getNode('arguments')->getNode('with_context')->getAttribute('value')
)
) {
$this->addLoopToAll();
}
// the loop variable is referenced via an attribute
elseif ($node instanceof GetAttrExpression
&& (!$node->getNode('attribute') instanceof ConstantExpression
|| 'parent' === $node->getNode('attribute')->getAttribute('value')
)
&& (true === $this->loops[0]->getAttribute('with_loop')
|| ($node->getNode('node') instanceof NameExpression
&& 'loop' === $node->getNode('node')->getAttribute('name')
)
)
) {
$this->addLoopToAll();
}
}
/**
* Optimizes "for" tag by removing the "loop" variable creation whenever possible.
*/
private function leaveOptimizeFor(Node $node, Environment $env): void
{
if ($node instanceof ForNode) {
array_shift($this->loops);
array_shift($this->loopsTargets);
array_shift($this->loopsTargets);
}
}
private function addLoopToCurrent(): void
{
$this->loops[0]->setAttribute('with_loop', true);
}
private function addLoopToAll(): void
{
foreach ($this->loops as $loop) {
$loop->setAttribute('with_loop', true);
}
}
public function getPriority(): int
{
return 255;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\Expression\BlockReferenceExpression;
use Twig\Node\Expression\ConditionalExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\FunctionExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\MethodCallExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Expression\ParentExpression;
use Twig\Node\Node;
/**
* @internal
*/
final class SafeAnalysisNodeVisitor implements NodeVisitorInterface
{
private $data = [];
private $safeVars = [];
public function setSafeVars(array $safeVars): void
{
$this->safeVars = $safeVars;
}
public function getSafe(Node $node)
{
$hash = spl_object_hash($node);
if (!isset($this->data[$hash])) {
return;
}
foreach ($this->data[$hash] as $bucket) {
if ($bucket['key'] !== $node) {
continue;
}
if (\in_array('html_attr', $bucket['value'])) {
$bucket['value'][] = 'html';
}
return $bucket['value'];
}
}
private function setSafe(Node $node, array $safe): void
{
$hash = spl_object_hash($node);
if (isset($this->data[$hash])) {
foreach ($this->data[$hash] as &$bucket) {
if ($bucket['key'] === $node) {
$bucket['value'] = $safe;
return;
}
}
}
$this->data[$hash][] = [
'key' => $node,
'value' => $safe,
];
}
public function enterNode(Node $node, Environment $env): Node
{
return $node;
}
public function leaveNode(Node $node, Environment $env): ?Node
{
if ($node instanceof ConstantExpression) {
// constants are marked safe for all
$this->setSafe($node, ['all']);
} elseif ($node instanceof BlockReferenceExpression) {
// blocks are safe by definition
$this->setSafe($node, ['all']);
} elseif ($node instanceof ParentExpression) {
// parent block is safe by definition
$this->setSafe($node, ['all']);
} elseif ($node instanceof ConditionalExpression) {
// intersect safeness of both operands
$safe = $this->intersectSafe($this->getSafe($node->getNode('expr2')), $this->getSafe($node->getNode('expr3')));
$this->setSafe($node, $safe);
} elseif ($node instanceof FilterExpression) {
// filter expression is safe when the filter is safe
$name = $node->getNode('filter')->getAttribute('value');
$args = $node->getNode('arguments');
if ($filter = $env->getFilter($name)) {
$safe = $filter->getSafe($args);
if (null === $safe) {
$safe = $this->intersectSafe($this->getSafe($node->getNode('node')), $filter->getPreservesSafety());
}
$this->setSafe($node, $safe);
} else {
$this->setSafe($node, []);
}
} elseif ($node instanceof FunctionExpression) {
// function expression is safe when the function is safe
$name = $node->getAttribute('name');
$args = $node->getNode('arguments');
if ($function = $env->getFunction($name)) {
$this->setSafe($node, $function->getSafe($args));
} else {
$this->setSafe($node, []);
}
} elseif ($node instanceof MethodCallExpression) {
if ($node->getAttribute('safe')) {
$this->setSafe($node, ['all']);
} else {
$this->setSafe($node, []);
}
} elseif ($node instanceof GetAttrExpression && $node->getNode('node') instanceof NameExpression) {
$name = $node->getNode('node')->getAttribute('name');
if (\in_array($name, $this->safeVars)) {
$this->setSafe($node, ['all']);
} else {
$this->setSafe($node, []);
}
} else {
$this->setSafe($node, []);
}
return $node;
}
private function intersectSafe(array $a = null, array $b = null): array
{
if (null === $a || null === $b) {
return [];
}
if (\in_array('all', $a)) {
return $b;
}
if (\in_array('all', $b)) {
return $a;
}
return array_intersect($a, $b);
}
public function getPriority(): int
{
return 0;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\CheckSecurityCallNode;
use Twig\Node\CheckSecurityNode;
use Twig\Node\CheckToStringNode;
use Twig\Node\Expression\Binary\ConcatBinary;
use Twig\Node\Expression\Binary\RangeBinary;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\FunctionExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\Node\SetNode;
/**
* @author Fabien Potencier <[email protected]>
*
* @internal
*/
final class SandboxNodeVisitor implements NodeVisitorInterface
{
private $inAModule = false;
private $tags;
private $filters;
private $functions;
private $needsToStringWrap = false;
public function enterNode(Node $node, Environment $env): Node
{
if ($node instanceof ModuleNode) {
$this->inAModule = true;
$this->tags = [];
$this->filters = [];
$this->functions = [];
return $node;
} elseif ($this->inAModule) {
// look for tags
if ($node->getNodeTag() && !isset($this->tags[$node->getNodeTag()])) {
$this->tags[$node->getNodeTag()] = $node;
}
// look for filters
if ($node instanceof FilterExpression && !isset($this->filters[$node->getNode('filter')->getAttribute('value')])) {
$this->filters[$node->getNode('filter')->getAttribute('value')] = $node;
}
// look for functions
if ($node instanceof FunctionExpression && !isset($this->functions[$node->getAttribute('name')])) {
$this->functions[$node->getAttribute('name')] = $node;
}
// the .. operator is equivalent to the range() function
if ($node instanceof RangeBinary && !isset($this->functions['range'])) {
$this->functions['range'] = $node;
}
if ($node instanceof PrintNode) {
$this->needsToStringWrap = true;
$this->wrapNode($node, 'expr');
}
if ($node instanceof SetNode && !$node->getAttribute('capture')) {
$this->needsToStringWrap = true;
}
// wrap outer nodes that can implicitly call __toString()
if ($this->needsToStringWrap) {
if ($node instanceof ConcatBinary) {
$this->wrapNode($node, 'left');
$this->wrapNode($node, 'right');
}
if ($node instanceof FilterExpression) {
$this->wrapNode($node, 'node');
$this->wrapArrayNode($node, 'arguments');
}
if ($node instanceof FunctionExpression) {
$this->wrapArrayNode($node, 'arguments');
}
}
}
return $node;
}
public function leaveNode(Node $node, Environment $env): ?Node
{
if ($node instanceof ModuleNode) {
$this->inAModule = false;
$node->setNode('constructor_end', new Node([new CheckSecurityCallNode(), $node->getNode('constructor_end')]));
$node->setNode('class_end', new Node([new CheckSecurityNode($this->filters, $this->tags, $this->functions), $node->getNode('class_end')]));
} elseif ($this->inAModule) {
if ($node instanceof PrintNode || $node instanceof SetNode) {
$this->needsToStringWrap = false;
}
}
return $node;
}
private function wrapNode(Node $node, string $name): void
{
$expr = $node->getNode($name);
if ($expr instanceof NameExpression || $expr instanceof GetAttrExpression) {
$node->setNode($name, new CheckToStringNode($expr));
}
}
private function wrapArrayNode(Node $node, string $name): void
{
$args = $node->getNode($name);
foreach ($args as $name => $_) {
$this->wrapNode($args, $name);
}
}
public function getPriority(): int
{
return 0;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
[PHP Simple HTML Dom v4.8.x]
0: refactor -> findOne() -> will now return always an "Blank" object if no element was found
1: "SimpleXmlDomNodeInterface" -> fix phpdocs only
2: "*NodeBlank" -> fix return type from "findOne()"
3: "innerhtmlKeep" -> added for modifying html without loosing html-hacks for e.g. svg elements
4: "HtmlDomHelper" -> added "mergeHtmlAttributes()"
5: "HtmlDomParser" -> hack for multiple root elements
[PHP Simple HTML Dom v4.7.x]
1: add "findMultiOrFalse()" + "findOneOrFalse()"
2: fix -> usage of e.g. "textContent"
3: fix -> usage of special js template tags in the dom
4: merge improvements from "ivopetkov/html5-dom-document-php -> length attribute
5: merge improvements from "ivopetkov/html5-dom-document-php -> classList support
6: add "nextNonWhitespaceSibling()"
7: fix -> usage of "outerhtml"
8: add support for "symfony/css-selector": ~5.0
9: fix -> "save()" -> will use html() insteadof of innerHtml() now
13: fix -> "val()" -> will now support hidden fields
14: fix -> keep html comments, also at the beginning of the html input
15: add "HtmlDomParser->overwriteTemplateLogicSyntaxInSpecialScriptTags()"
16: add support for "text/x-handlebars-template"
17: fix -> problem with auto-completion in e.g. PhpStorm
18: small optimizations + fix phpstan reported errors
19: add support for different special script-tags
20: fix -> invalid html (move html that is after "</html>" before "</html>")
21: fix -> internal invalid self-closing tags (e.g. <wbr>)
22: fix -> invalid html (remove content before "<!doctype.*>")
23: fix -> invalid html (remove content before "<!doctype.*>") + try to repair broken html
24: fix -> normalize the html after replacing the node
25: add support for PHP 8
26: fix -> fix "setAttribute()" -> for e.g. urls
27: fix -> "XmlDomParser" -> add option for "auto-remove-xpath-namespace"
28: fix -> allow CSS and xPath syntax for XmlDomParser
29: use github actions
30: add "previousNonWhitespaceSibling()"
31: add "SimpleHtmlDom->delete()" & "SimpleHtmlDom->getTag()" thanks @marioquartz
add support for "symfony/css-selector": ~6.0 thanks @dora38
[PHP Simple HTML Dom v4.6.x]
1: add an XmlDomParser Class + simple tests
2: add support for text/x-custom-template type
3: fix -> check result of "html5FallbackForScriptTags()"
[PHP Simple HTML Dom v4.5.x]
1: fix -> return types
2: add abstract class and interface for "Dom Elements" (SimpleHtmlDom*)
3: and abstract class and interface for "Dom Nodes" (SimpleHtmlDomNode*)
4: fix -> errors reported by phpstan (level 7)
5: fix -> error with Google AMP (<html ⚡>) & Php DomDocument
[PHP Simple HTML Dom v4.4.x]
1: add "findMulti()" method for "SimpleDomParser"
2: fix -> phpdoc improvements via phpstan
[PHP Simple HTML Dom v4.3.x]
1: add "isRemoved()" method for "SimpleHtmlDom"
2: fix -> do not remove newlines from the output
3: fix -> keep HTML closing tags in <script> tags
[PHP Simple HTML Dom v4.2.x]
1: add "val()" method for form elements
2: add simple access to DOMElement via "SimpleHtmlDom"
3: fix -> for special script tags with type="text/html"
[PHP Simple HTML Dom v4.1.x]
1: "HtmlDomParser" -> fix clone method for "document"
2: add "findOne($selector)" === "find($selector, 0)"
3: update "symfony/css-selector" (optional)
4: use LIBXML options for every html-loading task
5: fix -> for vuejs (attributes beginning with "@")
6: fix -> plaintext output
7: fix -> document.write issue from DomDocument
8: fix -> remove (auto-added) head element
[PHP Simple HTML Dom v4.0.x]
1: drop support for PHP < 7.0
2: use "strict_types"
3: "Portable UTF-8" is now optional
[PHP Simple HTML Dom v3.1.x]
1: optimize performance (use the "UTF8"-Class only if needed)
2: fix html-handling of "meta"-tags [tags in the <head>-tag]
[PHP Simple HTML Dom v3.0.x]
1: use output from "SimpleHtmlDomNode" as array instead of string
[PHP Simple HTML Dom v2.0.x]
1: Complete Re-Write (based on https://github.com/dimabdc/PHP-Fast-Simple-HTML-DOM-Parser)
2: bug-fixing / performance improvements
[PHP Simple HTML Dom v1.7.x]
1: removed old parameter: maxLen / lowercase / stripRN / defaultBRText / defaultSpanText
2: add good default settings
3: removed charset-parsing (use UTF-8)
[PHP Simple HTML Dom v1.6.x]
1: fixed code-style
2: removed debugging
3: use Composer and PSR-0
4: added UTF-8 Support (need some testing)
[PHP Simple HTML Dom version 1.5 released.]
1: Memory leak fixed!
2: Added support for detecting the source html character set. This is used to convert characters when plaintext is requested.
3: Other little fixes and features, too numerous to categorize.
4: add ability to search the "noise" array
[PHP Simple HTML DOM Parser v1.11 is released]
1. Supports xpath generated from Firebug.
2. New method "dump" of "simple_html_dom_node".
3. New attribute "xmltext" of "simple_html_dom_node".
4. remove preg_quote on selector match function: [attribute*=value];
5. Element "Comment" will treat as children.
6. Fixed the problem with <pre>.
7. Fixed bug #2207477 (does not load some pages properly).
8. Fixed bug #2315853 (Error with character after < sign).
[PHP Simple HTML DOM Parser v1.10 is released]
1. Negative indexes supports of "find" method, thanks for Vadim Voituk.
2. Constructor with automatically load contents either text or file/url, thanks for Antcs.
3. Fully supports wildcard in selectors.
4. Fixed bug of confusing by the < symbol inside the text.
5. Fixed bug of dash in selectors.
6. Fixed bug of <nobr>.
7. Fixed bug #2155883 (Nested List Parses Incorrectly).
8. Fixed bug #2155113 (error with unclosed html tags).
[PHP Simple HTML DOM Parser v1.00 is released]
1. New method "getAllAttributes" of "simple_html_dom_node".
2. Fix the bug of selector in some critical conditions.
3. Fix the bug of striping php tags.
4. Fix the bug of remove_noise().
5. Fix the bug of noise in attributes.
6. Supports full javascript string in selector: $e->find("a[onclick=alert('hello')]").
7. Change selector "*=" to case-insentive.
[PHP Simple HTML DOM Parser v0.99 is released]
1. Performance turning (boost 10%).
2. Memory requirement reduce 25%.
3. Change function name from "file_get_dom()" to "file_get_html()".
4. Change function name from "str_get_dom()" to "str_get_html()".
5. Fixed bug #2011286 (Error with unclosed html tags).
6. Fixed bug #2012551 (Error parsing divs).
7. Fixed bug #2020924 (Error for missed tag.).
8. Fixed bug (problem with <body> tag's innertext).
[PHP Simple HTML DOM Parser v0.98 is released]
1. Performance turning (boost 20%).
2. Supports "multiple class" selector feature: <div class="a b c"></div>.
3. New "callback function" feature.
4. New "multiple selectors" feature: $dom->find('p,a,b');
5. New examples.
6. Supports extract contents from HTML features: $dom->plaintext;
7. Fix the bug of $dom->clear().
8. Fix the bug of text nodes' innertext.
9. Fix the bug of comment nodes' innertext.
10. Fix the bug of decendent selector with optional tags.
11. Change simple_html_dom_node method name from "text()" to "makeup()".
[PHP Simple HTML DOM Parser v0.97 is released]
1. Important!! file and class name changed (html_dom_parser->simple_html_dom)!
2. Important!! ($dom->save_file) will not support anymore.
3. New node type "comment" (eg. $dom->find('comment')).
4. Add self-closing tags: 'base', 'spacer'.
5. Fix the bug of outertext (th).
6. Fix the bug of regular expression escaping chars ($dom->find).
7. Fix the bug while line-breaker and "\t" in tags.
8. Remove example "example_customize_parser.php".
9. New example "simple_html_dom_utility.php".
[PHP Simple HTML DOM Parser v0.96 is released]
1. (Request #1936000) New DOM operations(first_child, last_child, next_sibling, previous_sibling).
2. New method to remove attribute.
3. Add the solution while server behind proxy in FAQ (Thanks to Yousuke Shaggy).
4. Add traverse section in manual.
5. Now file_get_dom supports full file_get_contents parameters.
6. Fix the bug of self-closing tags in the end of file.
7. Fix the bug of blanks in the end of tag.
8. Add Reference section in manual.
#. Fix some typo of testcase.
[PHP Simple HTML DOM Parser v0.95 is released]
1. New attribute filters (Thanks to Yousuke Kumakura).
2. Fix the bug of optional-closing tags.
3. Fix the bug of parsing the line break next to the tag's name.
4. Supports tag name with namespace.
#. Refine structure of testcase.
[PHP Simple HTML DOM Parser v0.94 is released]
1. Stop infinity loop while tthe source content is BAD HTML.
2. Fix the bug of adding new attributes to self closing tags.
3. Fix the bug of customize parser without $dom->remove_noise();
4. Add FAQ section in manual.
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
[//]: # (AUTO-GENERATED BY "PHP README Helper": base file -> docs/api.md)
# :scroll: Simple Html Dom Parser for PHP
### DomParser API
<p id="voku-php-readme-class-methods"></p><table><tr><td><a href="#findstring-selector-intnull-idx-mixed">find</a>
</td><td><a href="#findmultistring-selector-mixed">findMulti</a>
</td><td><a href="#findmultiorfalsestring-selector-mixed">findMultiOrFalse</a>
</td><td><a href="#findonestring-selector-static">findOne</a>
</td></tr><tr><td><a href="#findoneorfalsestring-selector-mixed">findOneOrFalse</a>
</td><td><a href="#fixhtmloutputstring-content-bool-multidecodenewhtmlentity-string">fixHtmlOutput</a>
</td><td><a href="#getdocument-domdocument">getDocument</a>
</td><td><a href="#getelementbyclassstring-class-mixed">getElementByClass</a>
</td></tr><tr><td><a href="#getelementbyidstring-id-mixed">getElementById</a>
</td><td><a href="#getelementbytagnamestring-name-mixed">getElementByTagName</a>
</td><td><a href="#getelementsbyidstring-id-intnull-idx-mixed">getElementsById</a>
</td><td><a href="#getelementsbytagnamestring-name-intnull-idx-mixed">getElementsByTagName</a>
</td></tr><tr><td><a href="#htmlbool-multidecodenewhtmlentity-string">html</a>
</td><td><a href="#innerhtmlbool-multidecodenewhtmlentity-string">innerHtml</a>
</td><td><a href="#innerxmlbool-multidecodenewhtmlentity-string">innerXml</a>
</td><td><a href="#loadhtmlstring-html-intnull-libxmlextraoptions-domparserinterface">loadHtml</a>
</td></tr><tr><td><a href="#loadhtmlfilestring-filepath-intnull-libxmlextraoptions-domparserinterface">loadHtmlFile</a>
</td><td><a href="#savestring-filepath-string">save</a>
</td><td><a href="#set_callbackcallable-functionname-mixed">set_callback</a>
</td><td><a href="#textbool-multidecodenewhtmlentity-string">text</a>
</td></tr><tr><td><a href="#xmlbool-multidecodenewhtmlentity-bool-htmltoxml-bool-removexmlheader-int-options-string">xml</a>
</td></tr></table>
### SimpleHtmlDomNode (group of dom elements) API
<p id="voku-php-readme-class-methods"></p><table><tr><td><a href="#count-int">count</a>
</td><td><a href="#findstring-selector-int-idx-simplehtmldomnodesimplehtmldomnodenull">find</a>
</td><td><a href="#findmultistring-selector-simplehtmldominterfacesimplehtmldomnodeinterfacesimplehtmldominterface">findMulti</a>
</td><td><a href="#findmultiorfalsestring-selector-falsesimplehtmldominterfacesimplehtmldomnodeinterfacesimplehtmldominterface">findMultiOrFalse</a>
</td></tr><tr><td><a href="#findonestring-selector-simplehtmldomnodenull">findOne</a>
</td><td><a href="#findoneorfalsestring-selector-falsesimplehtmldomnode">findOneOrFalse</a>
</td><td><a href="#innerhtml-string">innerHtml</a>
</td><td><a href="#innertext-string">innertext</a>
</td></tr><tr><td><a href="#outertext-string">outertext</a>
</td><td><a href="#text-string">text</a>
</td></tr></table>
### SimpleHtmlDom (single dom element) API
<p id="voku-php-readme-class-methods"></p><table><tr><td><a href="#childnodesint-idx-simplehtmldominterfacesimplehtmldominterfacesimplehtmldomnodeinterfacenull">childNodes</a>
</td><td><a href="#delete-mixed">delete</a>
</td><td><a href="#findstring-selector-intnull-idx-simplehtmldominterfacesimplehtmldominterfacesimplehtmldomnodeinterfacesimplehtmldominterface">find</a>
</td><td><a href="#findmultistring-selector-simplehtmldominterfacesimplehtmldomnodeinterfacesimplehtmldominterface">findMulti</a>
</td></tr><tr><td><a href="#findmultiorfalsestring-selector-falsesimplehtmldominterfacesimplehtmldomnodeinterfacesimplehtmldominterface">findMultiOrFalse</a>
</td><td><a href="#findonestring-selector-simplehtmldominterface">findOne</a>
</td><td><a href="#findoneorfalsestring-selector-falsesimplehtmldominterface">findOneOrFalse</a>
</td><td><a href="#firstchild-simplehtmldominterfacenull">firstChild</a>
</td></tr><tr><td><a href="#getallattributes-stringnull">getAllAttributes</a>
</td><td><a href="#getattributestring-name-string">getAttribute</a>
</td><td><a href="#getelementbyclassstring-class-simplehtmldominterfacesimplehtmldomnodeinterfacesimplehtmldominterface">getElementByClass</a>
</td><td><a href="#getelementbyidstring-id-simplehtmldominterface">getElementById</a>
</td></tr><tr><td><a href="#getelementbytagnamestring-name-simplehtmldominterface">getElementByTagName</a>
</td><td><a href="#getelementsbyidstring-id-intnull-idx-simplehtmldominterfacesimplehtmldominterfacesimplehtmldomnodeinterfacesimplehtmldominterface">getElementsById</a>
</td><td><a href="#getelementsbytagnamestring-name-intnull-idx-simplehtmldominterfacesimplehtmldominterfacesimplehtmldomnodeinterfacesimplehtmldominterface">getElementsByTagName</a>
</td><td><a href="#gethtmldomparser-htmldomparser">getHtmlDomParser</a>
</td></tr><tr><td><a href="#getiterator-simplehtmldomnodeinterfacesimplehtmldominterface">getIterator</a>
</td><td><a href="#getnode-domnode">getNode</a>
</td><td><a href="#gettag-string">getTag</a>
</td><td><a href="#hasattributestring-name-bool">hasAttribute</a>
</td></tr><tr><td><a href="#htmlbool-multidecodenewhtmlentity-string">html</a>
</td><td><a href="#innerhtmlbool-multidecodenewhtmlentity-string">innerHtml</a>
</td><td><a href="#innerxmlbool-multidecodenewhtmlentity-string">innerXml</a>
</td><td><a href="#isremoved-bool">isRemoved</a>
</td></tr><tr><td><a href="#lastchild-simplehtmldominterfacenull">lastChild</a>
</td><td><a href="#nextnonwhitespacesibling-simplehtmldominterfacenull">nextNonWhitespaceSibling</a>
</td><td><a href="#nextsibling-simplehtmldominterfacenull">nextSibling</a>
</td><td><a href="#parentnode-simplehtmldominterface">parentNode</a>
</td></tr><tr><td><a href="#previousnonwhitespacesibling-simplehtmldominterfacenull">previousNonWhitespaceSibling</a>
</td><td><a href="#previoussibling-simplehtmldominterfacenull">previousSibling</a>
</td><td><a href="#removeattributestring-name-simplehtmldominterface">removeAttribute</a>
</td><td><a href="#removeattributes-simplehtmldominterface">removeAttributes</a>
</td></tr><tr><td><a href="#setattributestring-name-stringnull-value-bool-strictemptyvaluecheck-simplehtmldominterface">setAttribute</a>
</td><td><a href="#text-string">text</a>
</td><td><a href="#valstringstringnull-value-stringstringnull">val</a>
</td></tr></table>
---
## find(string $selector, int|null $idx): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Find list of nodes with a CSS selector.
**Parameters:**
- `string $selector`
- `int|null $idx`
**Return:**
- `mixed`
--------
## findMulti(string $selector): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Find nodes with a CSS selector.
**Parameters:**
- `string $selector`
**Return:**
- `mixed`
--------
## findMultiOrFalse(string $selector): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Find nodes with a CSS selector or false, if no element is found.
**Parameters:**
- `string $selector`
**Return:**
- `mixed`
--------
## findOne(string $selector): static
<a href="#voku-php-readme-class-methods">↑</a>
Find one node with a CSS selector.
**Parameters:**
- `string $selector`
**Return:**
- `static`
--------
## findOneOrFalse(string $selector): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Find one node with a CSS selector or false, if no element is found.
**Parameters:**
- `string $selector`
**Return:**
- `mixed`
--------
## fixHtmlOutput(string $content, bool $multiDecodeNewHtmlEntity): string
<a href="#voku-php-readme-class-methods">↑</a>
**Parameters:**
- `string $content`
- `bool $multiDecodeNewHtmlEntity`
**Return:**
- `string`
--------
## getDocument(): DOMDocument
<a href="#voku-php-readme-class-methods">↑</a>
**Parameters:**
__nothing__
**Return:**
- `\DOMDocument`
--------
## getElementByClass(string $class): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Return elements by ".class".
**Parameters:**
- `string $class`
**Return:**
- `mixed`
--------
## getElementById(string $id): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Return element by #id.
**Parameters:**
- `string $id`
**Return:**
- `mixed`
--------
## getElementByTagName(string $name): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Return element by tag name.
**Parameters:**
- `string $name`
**Return:**
- `mixed`
--------
## getElementsById(string $id, int|null $idx): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Returns elements by "#id".
**Parameters:**
- `string $id`
- `int|null $idx`
**Return:**
- `mixed`
--------
## getElementsByTagName(string $name, int|null $idx): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Returns elements by tag name.
**Parameters:**
- `string $name`
- `int|null $idx`
**Return:**
- `mixed`
--------
## html(bool $multiDecodeNewHtmlEntity): string
<a href="#voku-php-readme-class-methods">↑</a>
Get dom node's outer html.
**Parameters:**
- `bool $multiDecodeNewHtmlEntity`
**Return:**
- `string`
--------
## innerHtml(bool $multiDecodeNewHtmlEntity): string
<a href="#voku-php-readme-class-methods">↑</a>
Get dom node's inner html.
**Parameters:**
- `bool $multiDecodeNewHtmlEntity`
**Return:**
- `string`
--------
## innerXml(bool $multiDecodeNewHtmlEntity): string
<a href="#voku-php-readme-class-methods">↑</a>
Get dom node's inner xml.
**Parameters:**
- `bool $multiDecodeNewHtmlEntity`
**Return:**
- `string`
--------
## loadHtml(string $html, int|null $libXMLExtraOptions): DomParserInterface
<a href="#voku-php-readme-class-methods">↑</a>
Load HTML from string.
**Parameters:**
- `string $html`
- `int|null $libXMLExtraOptions`
**Return:**
- `\DomParserInterface`
--------
## loadHtmlFile(string $filePath, int|null $libXMLExtraOptions): DomParserInterface
<a href="#voku-php-readme-class-methods">↑</a>
Load HTML from file.
**Parameters:**
- `string $filePath`
- `int|null $libXMLExtraOptions`
**Return:**
- `\DomParserInterface`
--------
## save(string $filepath): string
<a href="#voku-php-readme-class-methods">↑</a>
Save the html-dom as string.
**Parameters:**
- `string $filepath`
**Return:**
- `string`
--------
## set_callback(callable $functionName): mixed
<a href="#voku-php-readme-class-methods">↑</a>
**Parameters:**
- `callable $functionName`
**Return:**
- `mixed`
--------
## text(bool $multiDecodeNewHtmlEntity): string
<a href="#voku-php-readme-class-methods">↑</a>
Get dom node's plain text.
**Parameters:**
- `bool $multiDecodeNewHtmlEntity`
**Return:**
- `string`
--------
## xml(bool $multiDecodeNewHtmlEntity, bool $htmlToXml, bool $removeXmlHeader, int $options): string
<a href="#voku-php-readme-class-methods">↑</a>
Get the HTML as XML or plain XML if needed.
**Parameters:**
- `bool $multiDecodeNewHtmlEntity`
- `bool $htmlToXml`
- `bool $removeXmlHeader`
- `int $options`
**Return:**
- `string`
--------
## count(): int
<a href="#voku-php-readme-class-methods">↑</a>
Get the number of items in this dom node.
**Parameters:**
__nothing__
**Return:**
- `int`
--------
## find(string $selector, int $idx): SimpleHtmlDomNode|\SimpleHtmlDomNode[]|null
<a href="#voku-php-readme-class-methods">↑</a>
Find list of nodes with a CSS selector.
**Parameters:**
- `string $selector`
- `int $idx`
**Return:**
- `\SimpleHtmlDomNode|\SimpleHtmlDomNode[]|null`
--------
## findMulti(string $selector): SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>
<a href="#voku-php-readme-class-methods">↑</a>
Find nodes with a CSS selector.
**Parameters:**
- `string $selector`
**Return:**
- `\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>`
--------
## findMultiOrFalse(string $selector): false|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>
<a href="#voku-php-readme-class-methods">↑</a>
Find nodes with a CSS selector or false, if no element is found.
**Parameters:**
- `string $selector`
**Return:**
- `false|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>`
--------
## findOne(string $selector): SimpleHtmlDomNode|null
<a href="#voku-php-readme-class-methods">↑</a>
Find one node with a CSS selector.
**Parameters:**
- `string $selector`
**Return:**
- `\SimpleHtmlDomNode|null`
--------
## findOneOrFalse(string $selector): false|\SimpleHtmlDomNode
<a href="#voku-php-readme-class-methods">↑</a>
Find one node with a CSS selector or false, if no element is found.
**Parameters:**
- `string $selector`
**Return:**
- `false|\SimpleHtmlDomNode`
--------
## innerHtml(): string[]
<a href="#voku-php-readme-class-methods">↑</a>
Get html of elements.
**Parameters:**
__nothing__
**Return:**
- `string[]`
--------
## innertext(): string[]
<a href="#voku-php-readme-class-methods">↑</a>
alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
**Parameters:**
__nothing__
**Return:**
- `string[]`
--------
## outertext(): string[]
<a href="#voku-php-readme-class-methods">↑</a>
alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
**Parameters:**
__nothing__
**Return:**
- `string[]`
--------
## text(): string[]
<a href="#voku-php-readme-class-methods">↑</a>
Get plain text.
**Parameters:**
__nothing__
**Return:**
- `string[]`
--------
## childNodes(int $idx): SimpleHtmlDomInterface|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface|null
<a href="#voku-php-readme-class-methods">↑</a>
Returns children of node.
**Parameters:**
- `int $idx`
**Return:**
- `\SimpleHtmlDomInterface|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface|null`
--------
## delete(): mixed
<a href="#voku-php-readme-class-methods">↑</a>
Delete
**Parameters:**
__nothing__
**Return:**
- `mixed`
--------
## find(string $selector, int|null $idx): SimpleHtmlDomInterface|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>
<a href="#voku-php-readme-class-methods">↑</a>
Find list of nodes with a CSS selector.
**Parameters:**
- `string $selector`
- `int|null $idx`
**Return:**
- `\SimpleHtmlDomInterface|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>`
--------
## findMulti(string $selector): SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>
<a href="#voku-php-readme-class-methods">↑</a>
Find nodes with a CSS selector.
**Parameters:**
- `string $selector`
**Return:**
- `\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>`
--------
## findMultiOrFalse(string $selector): false|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>
<a href="#voku-php-readme-class-methods">↑</a>
Find nodes with a CSS selector or false, if no element is found.
**Parameters:**
- `string $selector`
**Return:**
- `false|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>`
--------
## findOne(string $selector): SimpleHtmlDomInterface
<a href="#voku-php-readme-class-methods">↑</a>
Find one node with a CSS selector.
**Parameters:**
- `string $selector`
**Return:**
- `\SimpleHtmlDomInterface`
--------
## findOneOrFalse(string $selector): false|\SimpleHtmlDomInterface
<a href="#voku-php-readme-class-methods">↑</a>
Find one node with a CSS selector or false, if no element is found.
**Parameters:**
- `string $selector`
**Return:**
- `false|\SimpleHtmlDomInterface`
--------
## firstChild(): SimpleHtmlDomInterface|null
<a href="#voku-php-readme-class-methods">↑</a>
Returns the first child of node.
**Parameters:**
__nothing__
**Return:**
- `\SimpleHtmlDomInterface|null`
--------
## getAllAttributes(): string[]|null
<a href="#voku-php-readme-class-methods">↑</a>
Returns an array of attributes.
**Parameters:**
__nothing__
**Return:**
- `string[]|null`
--------
## getAttribute(string $name): string
<a href="#voku-php-readme-class-methods">↑</a>
Return attribute value.
**Parameters:**
- `string $name`
**Return:**
- `string`
--------
## getElementByClass(string $class): SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>
<a href="#voku-php-readme-class-methods">↑</a>
Return elements by ".class".
**Parameters:**
- `string $class`
**Return:**
- `\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>`
--------
## getElementById(string $id): SimpleHtmlDomInterface
<a href="#voku-php-readme-class-methods">↑</a>
Return element by "#id".
**Parameters:**
- `string $id`
**Return:**
- `\SimpleHtmlDomInterface`
--------
## getElementByTagName(string $name): SimpleHtmlDomInterface
<a href="#voku-php-readme-class-methods">↑</a>
Return element by tag name.
**Parameters:**
- `string $name`
**Return:**
- `\SimpleHtmlDomInterface`
--------
## getElementsById(string $id, int|null $idx): SimpleHtmlDomInterface|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>
<a href="#voku-php-readme-class-methods">↑</a>
Returns elements by "#id".
**Parameters:**
- `string $id`
- `int|null $idx`
**Return:**
- `\SimpleHtmlDomInterface|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>`
--------
## getElementsByTagName(string $name, int|null $idx): SimpleHtmlDomInterface|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>
<a href="#voku-php-readme-class-methods">↑</a>
Returns elements by tag name.
**Parameters:**
- `string $name`
- `int|null $idx`
**Return:**
- `\SimpleHtmlDomInterface|\SimpleHtmlDomInterface[]|\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>`
--------
## getHtmlDomParser(): HtmlDomParser
<a href="#voku-php-readme-class-methods">↑</a>
Create a new "HtmlDomParser"-object from the current context.
**Parameters:**
__nothing__
**Return:**
- `\HtmlDomParser`
--------
## getIterator(): SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface>
<a href="#voku-php-readme-class-methods">↑</a>
Retrieve an external iterator.
**Parameters:**
__nothing__
**Return:**
- `\SimpleHtmlDomNodeInterface<\SimpleHtmlDomInterface> <p>
An instance of an object implementing <b>Iterator</b> or
<b>Traversable</b>
</p>`
--------
## getNode(): DOMNode
<a href="#voku-php-readme-class-methods">↑</a>
**Parameters:**
__nothing__
**Return:**
- `\DOMNode`
--------
## getTag(): string
<a href="#voku-php-readme-class-methods">↑</a>
Return the tag of node
**Parameters:**
__nothing__
**Return:**
- `string`
--------
## hasAttribute(string $name): bool
<a href="#voku-php-readme-class-methods">↑</a>
Determine if an attribute exists on the element.
**Parameters:**
- `string $name`
**Return:**
- `bool`
--------
## html(bool $multiDecodeNewHtmlEntity): string
<a href="#voku-php-readme-class-methods">↑</a>
Get dom node's outer html.
**Parameters:**
- `bool $multiDecodeNewHtmlEntity`
**Return:**
- `string`
--------
## innerHtml(bool $multiDecodeNewHtmlEntity): string
<a href="#voku-php-readme-class-methods">↑</a>
Get dom node's inner html.
**Parameters:**
- `bool $multiDecodeNewHtmlEntity`
**Return:**
- `string`
--------
## innerXml(bool $multiDecodeNewHtmlEntity): string
<a href="#voku-php-readme-class-methods">↑</a>
Get dom node's inner html.
**Parameters:**
- `bool $multiDecodeNewHtmlEntity`
**Return:**
- `string`
--------
## isRemoved(): bool
<a href="#voku-php-readme-class-methods">↑</a>
Nodes can get partially destroyed in which they're still an
actual DOM node (such as \DOMElement) but almost their entire
body is gone, including the `nodeType` attribute.
**Parameters:**
__nothing__
**Return:**
- `bool true if node has been destroyed`
--------
## lastChild(): SimpleHtmlDomInterface|null
<a href="#voku-php-readme-class-methods">↑</a>
Returns the last child of node.
**Parameters:**
__nothing__
**Return:**
- `\SimpleHtmlDomInterface|null`
--------
## nextNonWhitespaceSibling(): SimpleHtmlDomInterface|null
<a href="#voku-php-readme-class-methods">↑</a>
Returns the next sibling of node, and it will ignore whitespace elements.
**Parameters:**
__nothing__
**Return:**
- `\SimpleHtmlDomInterface|null`
--------
## nextSibling(): SimpleHtmlDomInterface|null
<a href="#voku-php-readme-class-methods">↑</a>
Returns the next sibling of node.
**Parameters:**
__nothing__
**Return:**
- `\SimpleHtmlDomInterface|null`
--------
## parentNode(): SimpleHtmlDomInterface
<a href="#voku-php-readme-class-methods">↑</a>
Returns the parent of node.
**Parameters:**
__nothing__
**Return:**
- `\SimpleHtmlDomInterface`
--------
## previousNonWhitespaceSibling(): SimpleHtmlDomInterface|null
<a href="#voku-php-readme-class-methods">↑</a>
Returns the previous sibling of node, and it will ignore whitespace elements.
**Parameters:**
__nothing__
**Return:**
- `\SimpleHtmlDomInterface|null`
--------
## previousSibling(): SimpleHtmlDomInterface|null
<a href="#voku-php-readme-class-methods">↑</a>
Returns the previous sibling of node.
**Parameters:**
__nothing__
**Return:**
- `\SimpleHtmlDomInterface|null`
--------
## removeAttribute(string $name): SimpleHtmlDomInterface
<a href="#voku-php-readme-class-methods">↑</a>
Remove attribute.
**Parameters:**
- `string $name <p>The name of the html-attribute.</p>`
**Return:**
- `\SimpleHtmlDomInterface`
--------
## removeAttributes(): SimpleHtmlDomInterface
<a href="#voku-php-readme-class-methods">↑</a>
Remove all attributes
**Parameters:**
__nothing__
**Return:**
- `\SimpleHtmlDomInterface`
--------
## setAttribute(string $name, string|null $value, bool $strictEmptyValueCheck): SimpleHtmlDomInterface
<a href="#voku-php-readme-class-methods">↑</a>
Set attribute value.
**Parameters:**
- `string $name <p>The name of the html-attribute.</p>`
- `string|null $value <p>Set to NULL or empty string, to remove the attribute.</p>`
- `bool $strictEmptyValueCheck </p>
$value must be NULL, to remove the attribute,
so that you can set an empty string as attribute-value e.g. autofocus=""
</p>`
**Return:**
- `\SimpleHtmlDomInterface`
--------
## text(): string
<a href="#voku-php-readme-class-methods">↑</a>
Get dom node's plain text.
**Parameters:**
__nothing__
**Return:**
- `string`
--------
## val(string|string[]|null $value): string|string[]|null
<a href="#voku-php-readme-class-methods">↑</a>
**Parameters:**
- `string|string[]|null $value <p>
null === get the current input value
text === set a new input value
</p>`
**Return:**
- `string|string[]|null`
--------
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
[](https://github.com/voku/simple_html_dom/actions)
[](https://coveralls.io/github/voku/simple_html_dom?branch=master)
[](https://www.codacy.com/app/voku/simple_html_dom?utm_source=github.com&utm_medium=referral&utm_content=voku/simple_html_dom&utm_campaign=Badge_Grade)
[](https://packagist.org/packages/voku/simple_html_dom)
[](https://packagist.org/packages/voku/simple_html_dom)
[](https://packagist.org/packages/voku/simple_html_dom)
[](https://www.paypal.me/moelleken)
[](https://www.patreon.com/voku)
# What is this?
This is a fork of [voku/simple_html_dom](//github.com/voku/simple_html_dom) that simply removes LibXML autoformatting. This is designed mainly for [Rehike](//github.com/Rehike/Rehike) use, but it may be used for other purposes as well.
It is simply a one line change to correct erroneous whitespace placement.
# :scroll: Simple Html Dom Parser for PHP
A HTML DOM parser written in PHP - let you manipulate HTML in a very easy way!
This is a fork of [PHP Simple HTML DOM Parser project](http://simplehtmldom.sourceforge.net/) but instead of string manipulation we use DOMDocument and modern php classes like "Symfony CssSelector".
- PHP 7.0+ & 8.0 Support
- PHP-FIG Standard
- Composer & PSR-4 support
- PHPUnit testing via Travis CI
- PHP-Quality testing via SensioLabsInsight
- UTF-8 Support (more support via "voku/portable-utf8")
- Invalid HTML Support (partly ...)
- Find tags on an HTML page with selectors just like jQuery
- Extract contents from HTML in a single line
### Install via "composer require"
```shell
composer require yukiscoffee/simple_html_dom
composer require voku/portable-utf8 # if you need e.g. UTF-8 fixed output
```
### Quick Start
```php
use voku\helper\HtmlDomParser; // This is not a mistake, this uses the same namespaces as the original.
require_once 'composer/autoload.php';
...
$dom = HtmlDomParser::str_get_html($str);
// or
$dom = HtmlDomParser::file_get_html($file);
$element = $dom->findOne('#css-selector'); // "$element" === instance of "SimpleHtmlDomInterface"
$elements = $dom->findMulti('.css-selector'); // "$elements" === instance of SimpleHtmlDomNodeInterface<int, SimpleHtmlDomInterface>
$elementOrFalse = $dom->findOneOrFalse('#css-selector'); // "$elementOrFalse" === instance of "SimpleHtmlDomInterface" or false
$elementsOrFalse = $dom->findMultiOrFalse('.css-selector'); // "$elementsOrFalse" === instance of SimpleHtmlDomNodeInterface<int, SimpleHtmlDomInterface> or false
...
```
### Examples
[github.com/voku/simple_html_dom/tree/master/example](https://github.com/voku/simple_html_dom/tree/master/example)
### API
[github.com/voku/simple_html_dom/tree/master/README_API.md](https://github.com/voku/simple_html_dom/tree/master/README_API.md)
### Support
For support and donations please visit [Github](https://github.com/voku/simple_html_dom/) | [Issues](https://github.com/voku/simple_html_dom/issues) | [PayPal](https://paypal.me/moelleken) | [Patreon](https://www.patreon.com/voku).
For status updates and release announcements please visit [Releases](https://github.com/voku/simple_html_dom/releases) | [Twitter](https://twitter.com/suckup_de) | [Patreon](https://www.patreon.com/voku/posts).
For professional support please contact [me](https://about.me/voku).
### Thanks
- Thanks to [GitHub](https://github.com) (Microsoft) for hosting the code and a good infrastructure including Issues-Managment, etc.
- Thanks to [IntelliJ](https://www.jetbrains.com) as they make the best IDEs for PHP and they gave me an open source license for PhpStorm!
- Thanks to [Travis CI](https://travis-ci.com/) for being the most awesome, easiest continous integration tool out there!
- Thanks to [StyleCI](https://styleci.io/) for the simple but powerfull code style check.
- Thanks to [PHPStan](https://github.com/phpstan/phpstan) && [Psalm](https://github.com/vimeo/psalm) for relly great Static analysis tools and for discover bugs in the code!
### License
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fvoku%2Fsimple_html_dom?ref=badge_large)
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
# How to Contribute
## Pull Requests
1. Create your own [fork](https://help.github.com/articles/fork-a-repo) of this repo
2. Create a new branch for each feature or improvement
3. Send a pull request from each feature branch to the **master** branch
It is very important to separate new features or improvements into separate
feature branches, and to send a pull request for each branch. This allows me to
review and pull in new features or improvements individually.
## Style Guide
All pull requests must adhere to the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md).
## Unit Testing
All pull requests must be accompanied by passing PHPUnit unit tests and
complete code coverage.
[Learn about PHPUnit](https://github.com/sebastianbergmann/phpunit/) | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
#### What is this feature about (expected vs actual behaviour)?
#### How can I reproduce it?
#### Does it take minutes, hours or days to fix?
#### Any additional information? | {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
github: [voku]
patreon: voku
tidelift: "packagist/voku/simple_html_dom"
custom: https://www.paypal.me/moelleken
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
on:
push:
branches:
- master
pull_request:
branches:
- master
defaults:
run:
shell: bash
jobs:
tests:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php: [
7.0,
7.1,
7.2,
7.3,
7.4,
8.0,
8.1
]
composer: [basic]
timeout-minutes: 10
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/[email protected]
with:
php-version: ${{ matrix.php }}
coverage: xdebug
extensions: zip
tools: composer
- name: Determine composer cache directory
id: composer-cache
run: echo "::set-output name=directory::$(composer config cache-dir)"
- name: Cache composer dependencies
uses: actions/[email protected]
with:
path: ${{ steps.composer-cache.outputs.directory }}
key: ${{ matrix.php }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ matrix.php }}-composer-
- name: Install dependencies
run: |
if [[ "${{ matrix.php }}" == "7.4" ]]; then
composer require phpstan/phpstan --no-update
fi;
if [[ "${{ matrix.composer }}" == "lowest" ]]; then
composer update --prefer-dist --no-interaction --prefer-lowest --prefer-stable
fi;
if [[ "${{ matrix.composer }}" == "basic" ]]; then
composer update --prefer-dist --no-interaction
fi;
composer dump-autoload -o
- name: Run tests
run: |
mkdir -p build/logs
php vendor/bin/phpunit -c phpunit.xml --coverage-clover=build/logs/clover.xml
- name: Run phpstan
continue-on-error: true
if: ${{ matrix.php == '7.4' }}
run: |
php vendor/bin/phpstan analyse
- name: Upload coverage results to Coveralls
env:
COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
composer global require php-coveralls/php-coveralls
php-coveralls --coverage_clover=build/logs/clover.xml -v
- name: Upload coverage results to Codecov
uses: codecov/codecov-action@v1
with:
files: build/logs/clover.xml
- name: Upload coverage results to Scrutinizer
uses: sudo-bot/action-scrutinizer@latest
with:
cli-args: "--format=php-clover build/logs/clover.xml"
- name: Archive logs artifacts
if: ${{ failure() }}
uses: actions/upload-artifact@v2
with:
name: logs_composer-${{ matrix.composer }}_php-${{ matrix.php }}
path: |
build/logs
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
abstract class AbstractDomParser implements DomParserInterface
{
/**
* @var string
*/
protected static $domHtmlWrapperHelper = '____simple_html_dom__voku__html_wrapper____';
/**
* @var string
*/
protected static $domHtmlBrokenHtmlHelper = '____simple_html_dom__voku__broken_html____';
/**
* @var string
*/
protected static $domHtmlSpecialScriptHelper = '____simple_html_dom__voku__html_special_script____';
/**
* @var array
*/
protected static $domBrokenReplaceHelper = [];
/**
* @var string[][]
*/
protected static $domLinkReplaceHelper = [
'orig' => ['[', ']', '{', '}'],
'tmp' => [
'____SIMPLE_HTML_DOM__VOKU__SQUARE_BRACKET_LEFT____',
'____SIMPLE_HTML_DOM__VOKU__SQUARE_BRACKET_RIGHT____',
'____SIMPLE_HTML_DOM__VOKU__BRACKET_LEFT____',
'____SIMPLE_HTML_DOM__VOKU__BRACKET_RIGHT____',
],
];
/**
* @var string[][]
*/
protected static $domReplaceHelper = [
'orig' => ['&', '|', '+', '%', '@', '<html ⚡'],
'tmp' => [
'____SIMPLE_HTML_DOM__VOKU__AMP____',
'____SIMPLE_HTML_DOM__VOKU__PIPE____',
'____SIMPLE_HTML_DOM__VOKU__PLUS____',
'____SIMPLE_HTML_DOM__VOKU__PERCENT____',
'____SIMPLE_HTML_DOM__VOKU__AT____',
'<html ____SIMPLE_HTML_DOM__VOKU__GOOGLE_AMP____="true"',
],
];
/**
* @var callable|null
*
* @phpstan-var null|callable(\voku\helper\XmlDomParser|\voku\helper\HtmlDomParser): void
*/
protected static $callback;
/**
* @var string[]
*/
protected static $functionAliases = [];
/**
* @var \DOMDocument
*/
protected $document;
/**
* @var string
*/
protected $encoding = 'UTF-8';
/**
* @param string $name
* @param array $arguments
*
* @return bool|mixed
*/
public function __call($name, $arguments)
{
$name = \strtolower($name);
if (isset(self::$functionAliases[$name])) {
return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
}
throw new \BadMethodCallException('Method does not exist: ' . $name);
}
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
* @throws \RuntimeException
*
* @return static
*/
abstract public static function __callStatic($name, $arguments);
public function __clone()
{
$this->document = clone $this->document;
}
/**
* @param string $name
*
* @return string|null
*/
abstract public function __get($name);
/**
* @return string
*/
abstract public function __toString();
/**
* does nothing (only for api-compatibility-reasons)
*
* @return bool
*
* @deprecated
*/
public function clear(): bool
{
return true;
}
/**
* Create DOMDocument from HTML.
*
* @param string $html
* @param int|null $libXMLExtraOptions
*
* @return \DOMDocument
*/
abstract protected function createDOMDocument(string $html, $libXMLExtraOptions = null): \DOMDocument;
/**
* @param string $content
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
protected function decodeHtmlEntity(string $content, bool $multiDecodeNewHtmlEntity): string
{
if ($multiDecodeNewHtmlEntity) {
if (\class_exists('\voku\helper\UTF8')) {
$content = UTF8::rawurldecode($content, true);
} else {
do {
$content_compare = $content;
$content = \rawurldecode(
\html_entity_decode(
$content,
\ENT_QUOTES | \ENT_HTML5
)
);
} while ($content_compare !== $content);
}
} else {
/** @noinspection NestedPositiveIfStatementsInspection */
if (\class_exists('\voku\helper\UTF8')) {
$content = UTF8::rawurldecode($content, false);
} else {
$content = \rawurldecode(
\html_entity_decode(
$content,
\ENT_QUOTES | \ENT_HTML5
)
);
}
}
return $content;
}
/**
* Find list of nodes with a CSS selector.
*
* @param string $selector
* @param int|null $idx
*
* @return mixed
*/
abstract public function find(string $selector, $idx = null);
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return mixed
*/
abstract public function findMulti(string $selector);
/**
* Find nodes with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return mixed
*/
abstract public function findMultiOrFalse(string $selector);
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return mixed
*/
abstract public function findOne(string $selector);
/**
* Find one node with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return mixed
*/
abstract public function findOneOrFalse(string $selector);
/**
* @return \DOMDocument
*/
public function getDocument(): \DOMDocument
{
return $this->document;
}
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
abstract public function html(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string;
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function innerHtml(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string
{
// init
$text = '';
if ($this->document->documentElement) {
foreach ($this->document->documentElement->childNodes as $node) {
$text .= $this->document->saveHTML($node);
}
}
return $this->fixHtmlOutput($text, $multiDecodeNewHtmlEntity, $putBrokenReplacedBack);
}
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function innerXml(bool $multiDecodeNewHtmlEntity = false): string
{
// init
$text = '';
if ($this->document->documentElement) {
foreach ($this->document->documentElement->childNodes as $node) {
$text .= $this->document->saveXML($node);
}
}
return $this->fixHtmlOutput($text, $multiDecodeNewHtmlEntity);
}
/**
* Load HTML from string.
*
* @param string $html
* @param int|null $libXMLExtraOptions
*
* @return DomParserInterface
*/
abstract public function loadHtml(string $html, $libXMLExtraOptions = null): DomParserInterface;
/**
* Load HTML from file.
*
* @param string $filePath
* @param int|null $libXMLExtraOptions
*
* @throws \RuntimeException
*
* @return DomParserInterface
*/
abstract public function loadHtmlFile(string $filePath, $libXMLExtraOptions = null): DomParserInterface;
/**
* Save the html-dom as string.
*
* @param string $filepath
*
* @return string
*/
public function save(string $filepath = ''): string
{
$string = $this->html();
if ($filepath !== '') {
\file_put_contents($filepath, $string, \LOCK_EX);
}
return $string;
}
/**
* @param callable $functionName
*
* @phpstan-param callable(\voku\helper\XmlDomParser|\voku\helper\HtmlDomParser): void $functionName
*
* @return void
*/
public function set_callback($functionName)
{
static::$callback = $functionName;
}
/**
* Get dom node's plain text.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function text(bool $multiDecodeNewHtmlEntity = false): string
{
return $this->fixHtmlOutput($this->document->textContent, $multiDecodeNewHtmlEntity);
}
/**
* Get the HTML as XML or plain XML if needed.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $htmlToXml
* @param bool $removeXmlHeader
* @param int $options
*
* @return string
*/
public function xml(
bool $multiDecodeNewHtmlEntity = false,
bool $htmlToXml = true,
bool $removeXmlHeader = true,
int $options = \LIBXML_NOEMPTYTAG
): string {
$xml = $this->document->saveXML(null, $options);
if ($xml === false) {
return '';
}
if ($removeXmlHeader) {
$xml = \ltrim((string) \preg_replace('/<\?xml.*\?>/', '', $xml));
}
if ($htmlToXml) {
$return = $this->fixHtmlOutput($xml, $multiDecodeNewHtmlEntity);
} else {
$xml = $this->decodeHtmlEntity($xml, $multiDecodeNewHtmlEntity);
$return = self::putReplacedBackToPreserveHtmlEntities($xml);
}
return $return;
}
/**
* Get the encoding to use.
*
* @return string
*/
protected function getEncoding(): string
{
return $this->encoding;
}
/**
* workaround for bug: https://bugs.php.net/bug.php?id=74628
*
* @param string $html
*
* @return void
*/
protected function html5FallbackForScriptTags(string &$html)
{
// regEx for e.g.: [<script id="elements-image-2">...<script>]
/** @noinspection HtmlDeprecatedTag */
$regExSpecialScript = '/<script(?<attr>[^>]*?)>(?<content>.*)<\/script>/isU';
$htmlTmp = \preg_replace_callback(
$regExSpecialScript,
static function ($scripts) {
if (empty($scripts['content'])) {
return $scripts[0];
}
return '<script' . $scripts['attr'] . '>' . \str_replace('</', '<\/', $scripts['content']) . '</script>';
},
$html
);
if ($htmlTmp !== null) {
$html = $htmlTmp;
}
}
/**
* @param string $html
*
* @return string
*/
public static function putReplacedBackToPreserveHtmlEntities(string $html, bool $putBrokenReplacedBack = true): string
{
static $DOM_REPLACE__HELPER_CACHE = null;
if ($DOM_REPLACE__HELPER_CACHE === null) {
$DOM_REPLACE__HELPER_CACHE['tmp'] = \array_merge(
self::$domLinkReplaceHelper['tmp'],
self::$domReplaceHelper['tmp']
);
$DOM_REPLACE__HELPER_CACHE['orig'] = \array_merge(
self::$domLinkReplaceHelper['orig'],
self::$domReplaceHelper['orig']
);
$DOM_REPLACE__HELPER_CACHE['tmp']['html_wrapper__start'] = '<' . self::$domHtmlWrapperHelper . '>';
$DOM_REPLACE__HELPER_CACHE['tmp']['html_wrapper__end'] = '</' . self::$domHtmlWrapperHelper . '>';
$DOM_REPLACE__HELPER_CACHE['orig']['html_wrapper__start'] = '';
$DOM_REPLACE__HELPER_CACHE['orig']['html_wrapper__end'] = '';
$DOM_REPLACE__HELPER_CACHE['tmp']['html_special_script__start'] = '<' . self::$domHtmlSpecialScriptHelper;
$DOM_REPLACE__HELPER_CACHE['tmp']['html_special_script__end'] = '</' . self::$domHtmlSpecialScriptHelper . '>';
$DOM_REPLACE__HELPER_CACHE['orig']['html_special_script__start'] = '<script';
$DOM_REPLACE__HELPER_CACHE['orig']['html_special_script__end'] = '</script>';
}
if (
$putBrokenReplacedBack === true
&&
isset(self::$domBrokenReplaceHelper['tmp'])
&&
\count(self::$domBrokenReplaceHelper['tmp']) > 0
) {
$html = \str_ireplace(self::$domBrokenReplaceHelper['tmp'], self::$domBrokenReplaceHelper['orig'], $html);
}
return \str_ireplace($DOM_REPLACE__HELPER_CACHE['tmp'], $DOM_REPLACE__HELPER_CACHE['orig'], $html);
}
/**
* @param string $html
*
* @return string
*/
public static function replaceToPreserveHtmlEntities(string $html): string
{
// init
$linksNew = [];
$linksOld = [];
if (\strpos($html, 'http') !== false) {
// regEx for e.g.: [https://www.domain.de/foo.php?foobar=1&email=lars%40moelleken.org&guid=test1233312&{{foo}}#foo]
$regExUrl = '/(\[?\bhttps?:\/\/[^\s<>]+(?:\(\w+\)|[^[:punct:]\s]|\/|}|]))/i';
\preg_match_all($regExUrl, $html, $linksOld);
if (!empty($linksOld[1])) {
$linksOld = $linksOld[1];
foreach ((array) $linksOld as $linkKey => $linkOld) {
$linksNew[$linkKey] = \str_replace(
self::$domLinkReplaceHelper['orig'],
self::$domLinkReplaceHelper['tmp'],
$linkOld
);
}
}
}
$linksNewCount = \count($linksNew);
if ($linksNewCount > 0 && \count($linksOld) === $linksNewCount) {
$search = \array_merge($linksOld, self::$domReplaceHelper['orig']);
$replace = \array_merge($linksNew, self::$domReplaceHelper['tmp']);
} else {
$search = self::$domReplaceHelper['orig'];
$replace = self::$domReplaceHelper['tmp'];
}
return \str_replace($search, $replace, $html);
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
abstract class AbstractSimpleXmlDom
{
/**
* @var array
*/
protected static $functionAliases = [
'children' => 'childNodes',
'first_child' => 'firstChild',
'last_child' => 'lastChild',
'next_sibling' => 'nextSibling',
'prev_sibling' => 'previousSibling',
'parent' => 'parentNode',
];
/**
* @var \DOMElement|\DOMNode|null
*/
protected $node;
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
*
* @return SimpleXmlDomInterface|string|null
*/
public function __call($name, $arguments)
{
$name = \strtolower($name);
if (isset(self::$functionAliases[$name])) {
return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
}
throw new \BadMethodCallException('Method does not exist');
}
/**
* @param string $name
*
* @return array|string|null
*/
public function __get($name)
{
$nameOrig = $name;
$name = \strtolower($name);
switch ($name) {
case 'xml':
return $this->xml();
case 'plaintext':
return $this->text();
case 'tag':
return $this->node->nodeName ?? '';
case 'attr':
return $this->getAllAttributes();
default:
if ($this->node && \property_exists($this->node, $nameOrig)) {
return $this->node->{$nameOrig};
}
return $this->getAttribute($name);
}
}
/**
* @param string $selector
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function __invoke($selector, $idx = null)
{
return $this->find($selector, $idx);
}
/**
* @param string $name
*
* @return bool
*/
public function __isset($name)
{
$nameOrig = $name;
$name = \strtolower($name);
switch ($name) {
case 'outertext':
case 'outerhtml':
case 'innertext':
case 'innerhtml':
case 'innerhtmlkeep':
case 'plaintext':
case 'text':
case 'tag':
return true;
default:
if ($this->node && \property_exists($this->node, $nameOrig)) {
return isset($this->node->{$nameOrig});
}
return $this->hasAttribute($name);
}
}
/**
* @param string $name
* @param mixed $value
*
* @return SimpleXmlDomInterface|null
*/
public function __set($name, $value)
{
$nameOrig = $name;
$name = \strtolower($name);
switch ($name) {
case 'outerhtml':
case 'outertext':
return $this->replaceNodeWithString($value);
case 'innertext':
case 'innerhtml':
return $this->replaceChildWithString($value);
case 'innerhtmlkeep':
return $this->replaceChildWithString($value, false);
case 'plaintext':
return $this->replaceTextWithString($value);
default:
if ($this->node && \property_exists($this->node, $nameOrig)) {
return $this->node->{$nameOrig} = $value;
}
return $this->setAttribute($name, $value);
}
}
/**
* @return string
*/
public function __toString()
{
return $this->xml();
}
/**
* @param string $name
*
* @return void
*/
public function __unset($name)
{
/** @noinspection UnusedFunctionResultInspection */
$this->removeAttribute($name);
}
/**
* @param string $selector
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
abstract public function find(string $selector, $idx = null);
/**
* @return string[]|null
*/
abstract public function getAllAttributes();
/**
* @param string $name
*
* @return string
*/
abstract public function getAttribute(string $name): string;
/**
* @param string $name
*
* @return bool
*/
abstract public function hasAttribute(string $name): bool;
abstract public function innerXml(bool $multiDecodeNewHtmlEntity = false): string;
abstract public function removeAttribute(string $name): SimpleXmlDomInterface;
abstract protected function replaceChildWithString(string $string, bool $putBrokenReplacedBack = true): SimpleXmlDomInterface;
abstract protected function replaceNodeWithString(string $string): SimpleXmlDomInterface;
/**
* @param string $string
*
* @return SimpleXmlDomInterface
*/
abstract protected function replaceTextWithString($string): SimpleXmlDomInterface;
/**
* @param string $name
* @param string|null $value
* @param bool $strictEmptyValueCheck
*
* @return SimpleXmlDomInterface
*/
abstract public function setAttribute(string $name, $value = null, bool $strictEmptyValueCheck = false): SimpleXmlDomInterface;
abstract public function text(): string;
abstract public function xml(bool $multiDecodeNewHtmlEntity = false): string;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
abstract class AbstractSimpleHtmlDom
{
/**
* @var array
*/
protected static $functionAliases = [
'children' => 'childNodes',
'first_child' => 'firstChild',
'last_child' => 'lastChild',
'next_sibling' => 'nextSibling',
'prev_sibling' => 'previousSibling',
'parent' => 'parentNode',
'outertext' => 'html',
'outerhtml' => 'html',
'innertext' => 'innerHtml',
'innerhtml' => 'innerHtml',
'innerhtmlkeep' => 'innerHtmlKeep',
];
/**
* @var \DOMElement|\DOMNode|null
*/
protected $node;
/**
* @var SimpleHtmlAttributes|null
*/
private $classListCache;
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
*
* @return SimpleHtmlDomInterface|string|null
*/
public function __call($name, $arguments)
{
$name = \strtolower($name);
if (isset(self::$functionAliases[$name])) {
return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
}
throw new \BadMethodCallException('Method does not exist');
}
/**
* @param string $name
*
* @return SimpleHtmlAttributes|string|string[]|null
*/
public function __get($name)
{
$nameOrig = $name;
$name = \strtolower($name);
switch ($name) {
case 'outerhtml':
case 'outertext':
case 'html':
return $this->html();
case 'innerhtml':
case 'innertext':
return $this->innerHtml();
case 'innerhtmlkeep':
return $this->innerHtml(false, false);
case 'text':
case 'plaintext':
return $this->text();
case 'tag':
return $this->node->nodeName ?? '';
case 'attr':
return $this->getAllAttributes();
case 'classlist':
if ($this->classListCache === null) {
$this->classListCache = new SimpleHtmlAttributes($this->node ?? null, 'class');
}
return $this->classListCache;
default:
if ($this->node && \property_exists($this->node, $nameOrig)) {
if (\is_string($this->node->{$nameOrig})) {
return HtmlDomParser::putReplacedBackToPreserveHtmlEntities($this->node->{$nameOrig});
}
return $this->node->{$nameOrig};
}
return $this->getAttribute($name);
}
}
/**
* @param string $selector
* @param int $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function __invoke($selector, $idx = null)
{
return $this->find($selector, $idx);
}
/**
* @param string $name
*
* @return bool
*/
public function __isset($name)
{
$nameOrig = $name;
$name = \strtolower($name);
switch ($name) {
case 'outertext':
case 'outerhtml':
case 'innertext':
case 'innerhtml':
case 'innerhtmlkeep':
case 'plaintext':
case 'text':
case 'tag':
return true;
default:
if ($this->node && \property_exists($this->node, $nameOrig)) {
return isset($this->node->{$nameOrig});
}
return $this->hasAttribute($name);
}
}
/**
* @param string $name
* @param mixed $value
*
* @return SimpleHtmlDomInterface|null
*/
public function __set($name, $value)
{
$nameOrig = $name;
$name = \strtolower($name);
switch ($name) {
case 'outerhtml':
case 'outertext':
return $this->replaceNodeWithString($value);
case 'innertext':
case 'innerhtml':
return $this->replaceChildWithString($value);
case 'innerhtmlkeep':
return $this->replaceChildWithString($value, false);
case 'plaintext':
return $this->replaceTextWithString($value);
case 'classlist':
$name = 'class';
$nameOrig = 'class';
// no break
default:
if ($this->node && \property_exists($this->node, $nameOrig)) {
return $this->node->{$nameOrig} = $value;
}
return $this->setAttribute($name, $value);
}
}
/**
* @return string
*/
public function __toString()
{
return $this->html();
}
/**
* @param string $name
*
* @return void
*/
public function __unset($name)
{
/** @noinspection UnusedFunctionResultInspection */
$this->removeAttribute($name);
}
/**
* @param string $selector
* @param int|null $idx
*
* @return mixed
*/
abstract public function find(string $selector, $idx = null);
/**
* @return string[]|null
*/
abstract public function getAllAttributes();
abstract public function getAttribute(string $name): string;
abstract public function hasAttribute(string $name): bool;
abstract public function html(bool $multiDecodeNewHtmlEntity = false): string;
abstract public function innerHtml(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string;
abstract public function removeAttribute(string $name): SimpleHtmlDomInterface;
abstract protected function replaceChildWithString(string $string, bool $putBrokenReplacedBack = true): SimpleHtmlDomInterface;
abstract protected function replaceNodeWithString(string $string): SimpleHtmlDomInterface;
/**
* @param string $string
*
* @return SimpleHtmlDomInterface
*/
abstract protected function replaceTextWithString($string): SimpleHtmlDomInterface;
/**
* @param string $name
* @param string|null $value
* @param bool $strictEmptyValueCheck
*
* @return SimpleHtmlDomInterface
*/
abstract public function setAttribute(string $name, $value = null, bool $strictEmptyValueCheck = false): SimpleHtmlDomInterface;
abstract public function text(): string;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* {@inheritdoc}
*/
abstract class AbstractSimpleXmlDomNode extends \ArrayObject
{
/** @noinspection MagicMethodsValidityInspection */
/**
* @param string $name
*
* @return array|int|null
*/
public function __get($name)
{
// init
$name = \strtolower($name);
if ($name === 'length') {
return $this->count();
}
if ($this->count() > 0) {
$return = [];
foreach ($this as $node) {
if ($node instanceof SimpleXmlDomInterface) {
$return[] = $node->{$name};
}
}
return $return;
}
if ($name === 'plaintext' || $name === 'outertext') {
return [];
}
return null;
}
/**
* @param string $selector
* @param int|null $idx
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>|SimpleXmlDomNodeInterface[]|null
*/
public function __invoke($selector, $idx = null)
{
return $this->find($selector, $idx);
}
/**
* @return string
*/
public function __toString()
{
// init
$html = '';
foreach ($this as $node) {
$html .= $node->outertext;
}
return $html;
}
/**
* @param string $selector
* @param int|null $idx
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>|SimpleXmlDomNodeInterface[]|null
*/
abstract public function find(string $selector, $idx = null);
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* @property-read string $outerText
* <p>Get dom node's outer html (alias for "outerHtml").</p>
* @property-read string $outerHtml
* <p>Get dom node's outer html.</p>
* @property-read string $innerText
* <p>Get dom node's inner html (alias for "innerHtml").</p>
* @property-read string $innerHtml
* <p>Get dom node's inner html.</p>
* @property-read string $plaintext
* <p>Get dom node's plain text.</p>
*
* @method string outerText()
* <p>Get dom node's outer html (alias for "outerHtml()").</p>
* @method string outerHtml()
* <p>Get dom node's outer html.</p>
* @method string innerText()
* <p>Get dom node's inner html (alias for "innerHtml()").</p>
* @method HtmlDomParser load(string $html)
* <p>Load HTML from string.</p>
* @method HtmlDomParser load_file(string $html)
* <p>Load HTML from file.</p>
* @method static HtmlDomParser file_get_html($filePath, $libXMLExtraOptions = null)
* <p>Load HTML from file.</p>
* @method static HtmlDomParser str_get_html($html, $libXMLExtraOptions = null)
* <p>Load HTML from string.</p>
*/
class HtmlDomParser extends AbstractDomParser
{
/**
* @var callable|null
*
* @phpstan-var null|callable(string $cssSelectorString, string $xPathString, \DOMXPath, \voku\helper\HtmlDomParser): string
*/
private $callbackXPathBeforeQuery;
/**
* @var callable|null
*
* @phpstan-var null|callable(string $htmlString, \voku\helper\HtmlDomParser): string
*/
private $callbackBeforeCreateDom;
/**
* @var string[]
*/
protected static $functionAliases = [
'outertext' => 'html',
'outerhtml' => 'html',
'innertext' => 'innerHtml',
'innerhtml' => 'innerHtml',
'load' => 'loadHtml',
'load_file' => 'loadHtmlFile',
];
/**
* @var string[]
*/
protected $templateLogicSyntaxInSpecialScriptTags = [
'+',
'<%',
'{%',
'{{',
];
/**
* The properties specified for each special script tag is an array.
*
* ```php
* protected $specialScriptTags = [
* 'text/html',
* 'text/x-custom-template',
* 'text/x-handlebars-template'
* ]
* ```
*
* @var string[]
*/
protected $specialScriptTags = [
'text/html',
'text/x-custom-template',
'text/x-handlebars-template',
];
/**
* @var string[]
*/
protected $selfClosingTags = [
'area',
'base',
'br',
'col',
'command',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr',
];
/**
* @var bool
*/
protected $isDOMDocumentCreatedWithoutHtml = false;
/**
* @var bool
*/
protected $isDOMDocumentCreatedWithoutWrapper = false;
/**
* @var bool
*/
protected $isDOMDocumentCreatedWithCommentWrapper = false;
/**
* @var bool
*/
protected $isDOMDocumentCreatedWithoutHeadWrapper = false;
/**
* @var bool
*/
protected $isDOMDocumentCreatedWithoutPTagWrapper = false;
/**
* @var bool
*/
protected $isDOMDocumentCreatedWithoutHtmlWrapper = false;
/**
* @var bool
*/
protected $isDOMDocumentCreatedWithoutBodyWrapper = false;
/**
* @var bool
*/
protected $isDOMDocumentCreatedWithMultiRoot = false;
/**
* @var bool
*/
protected $isDOMDocumentCreatedWithFakeEndScript = false;
/**
* @var bool
*/
protected $keepBrokenHtml = false;
/**
* @param \DOMNode|SimpleHtmlDomInterface|string $element HTML code or SimpleHtmlDomInterface, \DOMNode
*/
public function __construct($element = null)
{
$this->document = new \DOMDocument('1.0', $this->getEncoding());
// DOMDocument settings
$this->document->preserveWhiteSpace = true;
$this->document->formatOutput = false;
if ($element instanceof SimpleHtmlDomInterface) {
$element = $element->getNode();
}
if ($element instanceof \DOMNode) {
$domNode = $this->document->importNode($element, true);
if ($domNode instanceof \DOMNode) {
$this->document->appendChild($domNode);
}
return;
}
if ($element !== null) {
$this->loadHtml($element);
}
}
/**
* @param string $name
* @param array $arguments
*
* @return bool|mixed
*/
public function __call($name, $arguments)
{
$name = \strtolower($name);
if (isset(self::$functionAliases[$name])) {
return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
}
throw new \BadMethodCallException('Method does not exist: ' . $name);
}
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
* @throws \RuntimeException
*
* @return static
*/
public static function __callStatic($name, $arguments)
{
$arguments0 = $arguments[0] ?? '';
$arguments1 = $arguments[1] ?? null;
if ($name === 'str_get_html') {
$parser = new static();
return $parser->loadHtml($arguments0, $arguments1);
}
if ($name === 'file_get_html') {
$parser = new static();
return $parser->loadHtmlFile($arguments0, $arguments1);
}
throw new \BadMethodCallException('Method does not exist');
}
/** @noinspection MagicMethodsValidityInspection */
/**
* @param string $name
*
* @return string|null
*/
public function __get($name)
{
$name = \strtolower($name);
switch ($name) {
case 'outerhtml':
case 'outertext':
return $this->html();
case 'innerhtml':
case 'innertext':
return $this->innerHtml();
case 'innerhtmlkeep':
return $this->innerHtml(false, false);
case 'text':
case 'plaintext':
return $this->text();
}
return null;
}
/**
* @return string
*/
public function __toString()
{
return $this->html();
}
/**
* does nothing (only for api-compatibility-reasons)
*
* @return bool
*
* @deprecated
*/
public function clear(): bool
{
return true;
}
/**
* Create DOMDocument from HTML.
*
* @param string $html
* @param int|null $libXMLExtraOptions
*
* @return \DOMDocument
*/
protected function createDOMDocument(string $html, $libXMLExtraOptions = null): \DOMDocument
{
if ($this->callbackBeforeCreateDom) {
$html = \call_user_func($this->callbackBeforeCreateDom, $html, $this);
}
// Remove content before <!DOCTYPE.*> because otherwise the DOMDocument can not handle the input.
$isDOMDocumentCreatedWithDoctype = false;
if (\stripos($html, '<!DOCTYPE') !== false) {
$isDOMDocumentCreatedWithDoctype = true;
if (
\preg_match('/(^.*?)<!DOCTYPE(?: [^>]*)?>/sui', $html, $matches_before_doctype)
&&
\trim($matches_before_doctype[1])
) {
$html = \str_replace($matches_before_doctype[1], '', $html);
}
}
if ($this->keepBrokenHtml) {
$html = $this->keepBrokenHtml(\trim($html));
}
if (\strpos($html, '<') === false) {
$this->isDOMDocumentCreatedWithoutHtml = true;
} elseif (\strpos(\ltrim($html), '<') !== 0) {
$this->isDOMDocumentCreatedWithoutWrapper = true;
}
if (\strpos(\ltrim($html), '<!--') === 0) {
$this->isDOMDocumentCreatedWithCommentWrapper = true;
}
/** @noinspection HtmlRequiredLangAttribute */
if (
\strpos($html, '<html ') === false
&&
\strpos($html, '<html>') === false
) {
$this->isDOMDocumentCreatedWithoutHtmlWrapper = true;
}
if (
\strpos($html, '<body ') === false
&&
\strpos($html, '<body>') === false
) {
$this->isDOMDocumentCreatedWithoutBodyWrapper = true;
}
/** @noinspection HtmlRequiredTitleElement */
if (
\strpos($html, '<head ') === false
&&
\strpos($html, '<head>') === false
) {
$this->isDOMDocumentCreatedWithoutHeadWrapper = true;
}
if (
\strpos($html, '<p ') === false
&&
\strpos($html, '<p>') === false
) {
$this->isDOMDocumentCreatedWithoutPTagWrapper = true;
}
if (
\strpos($html, '</script>') === false
&&
\strpos($html, '<\/script>') !== false
) {
$this->isDOMDocumentCreatedWithFakeEndScript = true;
}
if (\stripos($html, '</html>') !== false) {
/** @noinspection NestedPositiveIfStatementsInspection */
if (
\preg_match('/<\/html>(.*?)/suiU', $html, $matches_after_html)
&&
\trim($matches_after_html[1])
) {
$html = \str_replace($matches_after_html[0], $matches_after_html[1] . '</html>', $html);
}
}
if (\strpos($html, '<script') !== false) {
$this->html5FallbackForScriptTags($html);
foreach ($this->specialScriptTags as $tag) {
if (\strpos($html, $tag) !== false) {
$this->keepSpecialScriptTags($html);
}
}
}
if (\strpos($html, '<svg') !== false) {
$this->keepSpecialSvgTags($html);
}
if (
$this->isDOMDocumentCreatedWithoutHtmlWrapper
&&
$this->isDOMDocumentCreatedWithoutBodyWrapper
) {
if (\substr_count($html, '</') >= 2) {
$regexForMultiRootDetection = '#<(.*)>.*?</(\1)>#su';
\preg_match($regexForMultiRootDetection, $html, $matches);
if (($matches[0] ?? '') !== $html) {
$htmlTmp = \preg_replace($regexForMultiRootDetection, '', $html);
if ($htmlTmp !== null && trim($htmlTmp) === '') {
$this->isDOMDocumentCreatedWithMultiRoot = true;
}
}
}
}
$html = \str_replace(
\array_map(static function ($e) {
return '<' . $e . '>';
}, $this->selfClosingTags),
\array_map(static function ($e) {
return '<' . $e . '/>';
}, $this->selfClosingTags),
$html
);
// set error level
$internalErrors = \libxml_use_internal_errors(true);
if (\PHP_VERSION_ID < 80000) {
$disableEntityLoader = \libxml_disable_entity_loader(true);
}
\libxml_clear_errors();
$optionsXml = \LIBXML_DTDLOAD | \LIBXML_DTDATTR | \LIBXML_NONET;
if (\defined('LIBXML_BIGLINES')) {
$optionsXml |= \LIBXML_BIGLINES;
}
if (\defined('LIBXML_COMPACT')) {
$optionsXml |= \LIBXML_COMPACT;
}
if (\defined('LIBXML_HTML_NODEFDTD')) {
$optionsXml |= \LIBXML_HTML_NODEFDTD;
}
if ($libXMLExtraOptions !== null) {
$optionsXml |= $libXMLExtraOptions;
}
if (
$this->isDOMDocumentCreatedWithMultiRoot
||
$this->isDOMDocumentCreatedWithoutWrapper
||
$this->isDOMDocumentCreatedWithCommentWrapper
||
(
!$isDOMDocumentCreatedWithDoctype
&&
$this->keepBrokenHtml
)
) {
$html = '<' . self::$domHtmlWrapperHelper . '>' . $html . '</' . self::$domHtmlWrapperHelper . '>';
}
$html = self::replaceToPreserveHtmlEntities($html);
$documentFound = false;
$sxe = \simplexml_load_string($html, \SimpleXMLElement::class, $optionsXml);
if ($sxe !== false && \count(\libxml_get_errors()) === 0) {
$domElementTmp = \dom_import_simplexml($sxe);
if ($domElementTmp->ownerDocument instanceof \DOMDocument) {
$documentFound = true;
$this->document = $domElementTmp->ownerDocument;
}
}
if ($documentFound === false) {
// UTF-8 hack: http://php.net/manual/en/domdocument.loadhtml.php#95251
$xmlHackUsed = false;
if (\stripos('<?xml', $html) !== 0) {
$xmlHackUsed = true;
$html = '<?xml encoding="' . $this->getEncoding() . '" ?>' . $html;
}
if ($html !== '') {
$this->document->loadHTML($html, $optionsXml);
}
// remove the "xml-encoding" hack
if ($xmlHackUsed) {
foreach ($this->document->childNodes as $child) {
if ($child->nodeType === \XML_PI_NODE) {
$this->document->removeChild($child);
break;
}
}
}
}
// set encoding
$this->document->encoding = $this->getEncoding();
// restore lib-xml settings
\libxml_clear_errors();
\libxml_use_internal_errors($internalErrors);
if (\PHP_VERSION_ID < 80000 && isset($disableEntityLoader)) {
\libxml_disable_entity_loader($disableEntityLoader);
}
return $this->document;
}
/**
* Find list of nodes with a CSS selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function find(string $selector, $idx = null)
{
$xPathQuery = SelectorConverter::toXPath($selector);
$xPath = new \DOMXPath($this->document);
if ($this->callbackXPathBeforeQuery) {
$xPathQuery = \call_user_func($this->callbackXPathBeforeQuery, $selector, $xPathQuery, $xPath, $this);
}
$nodesList = $xPath->query($xPathQuery);
$elements = new SimpleHtmlDomNode();
if ($nodesList) {
foreach ($nodesList as $node) {
$elements[] = new SimpleHtmlDom($node);
}
}
// return all elements
if ($idx === null) {
if (\count($elements) === 0) {
return new SimpleHtmlDomNodeBlank();
}
return $elements;
}
// handle negative values
if ($idx < 0) {
$idx = \count($elements) + $idx;
}
// return one element
return $elements[$idx] ?? new SimpleHtmlDomBlank();
}
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMulti(string $selector): SimpleHtmlDomNodeInterface
{
return $this->find($selector, null);
}
/**
* Find nodes with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMultiOrFalse(string $selector)
{
$return = $this->find($selector, null);
if ($return instanceof SimpleHtmlDomNodeBlank) {
return false;
}
return $return;
}
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface
*/
public function findOne(string $selector): SimpleHtmlDomInterface
{
return $this->find($selector, 0);
}
/**
* Find one node with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleHtmlDomInterface
*/
public function findOneOrFalse(string $selector)
{
$return = $this->find($selector, 0);
if ($return instanceof SimpleHtmlDomBlank) {
return false;
}
return $return;
}
/**
* @param string $content
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function fixHtmlOutput(
string $content,
bool $multiDecodeNewHtmlEntity = false,
bool $putBrokenReplacedBack = true
): string {
// INFO: DOMDocument will encapsulate plaintext into a e.g. paragraph tag (<p>),
// so we try to remove it here again ...
if ($this->getIsDOMDocumentCreatedWithoutHtmlWrapper()) {
/** @noinspection HtmlRequiredLangAttribute */
$content = \str_replace(
[
'<html>',
'</html>',
],
'',
$content
);
}
if ($this->getIsDOMDocumentCreatedWithoutHeadWrapper()) {
/** @noinspection HtmlRequiredTitleElement */
$content = \str_replace(
[
'<head>',
'</head>',
],
'',
$content
);
}
if ($this->getIsDOMDocumentCreatedWithoutBodyWrapper()) {
$content = \str_replace(
[
'<body>',
'</body>',
],
'',
$content
);
}
if ($this->getIsDOMDocumentCreatedWithFakeEndScript()) {
$content = \str_replace(
'</script>',
'',
$content
);
}
if ($this->getIsDOMDocumentCreatedWithoutWrapper()) {
$content = (string) \preg_replace('/^<p>/', '', $content);
$content = (string) \preg_replace('/<\/p>/', '', $content);
}
if ($this->getIsDOMDocumentCreatedWithoutPTagWrapper()) {
$content = \str_replace(
[
'<p>',
'</p>',
],
'',
$content
);
}
if ($this->getIsDOMDocumentCreatedWithoutHtml()) {
$content = \str_replace(
'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">',
'',
$content
);
}
// https://bugs.php.net/bug.php?id=73175
$content = \str_replace(
\array_map(static function ($e) {
return '</' . $e . '>';
}, $this->selfClosingTags),
'',
$content
);
/** @noinspection HtmlRequiredTitleElement */
$content = \trim(
\str_replace(
[
'<simpleHtmlDomHtml>',
'</simpleHtmlDomHtml>',
'<simpleHtmlDomP>',
'</simpleHtmlDomP>',
'<head><head>',
'</head></head>',
],
[
'',
'',
'',
'',
'<head>',
'</head>',
],
$content
)
);
$content = $this->decodeHtmlEntity($content, $multiDecodeNewHtmlEntity);
return self::putReplacedBackToPreserveHtmlEntities($content, $putBrokenReplacedBack);
}
/**
* Return elements by ".class".
*
* @param string $class
*
* @return SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementByClass(string $class): SimpleHtmlDomNodeInterface
{
return $this->findMulti('.' . $class);
}
/**
* Return element by #id.
*
* @param string $id
*
* @return SimpleHtmlDomInterface
*/
public function getElementById(string $id): SimpleHtmlDomInterface
{
return $this->findOne('#' . $id);
}
/**
* Return element by tag name.
*
* @param string $name
*
* @return SimpleHtmlDomInterface
*/
public function getElementByTagName(string $name): SimpleHtmlDomInterface
{
$node = $this->document->getElementsByTagName($name)->item(0);
if ($node === null) {
return new SimpleHtmlDomBlank();
}
return new SimpleHtmlDom($node);
}
/**
* Returns elements by "#id".
*
* @param string $id
* @param int|null $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementsById(string $id, $idx = null)
{
return $this->find('#' . $id, $idx);
}
/**
* Returns elements by tag name.
*
* @param string $name
* @param int|null $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementsByTagName(string $name, $idx = null)
{
$nodesList = $this->document->getElementsByTagName($name);
$elements = new SimpleHtmlDomNode();
foreach ($nodesList as $node) {
$elements[] = new SimpleHtmlDom($node);
}
// return all elements
if ($idx === null) {
if (\count($elements) === 0) {
return new SimpleHtmlDomNodeBlank();
}
return $elements;
}
// handle negative values
if ($idx < 0) {
$idx = \count($elements) + $idx;
}
// return one element
return $elements[$idx] ?? new SimpleHtmlDomNodeBlank();
}
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function html(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string
{
if (static::$callback !== null) {
\call_user_func(static::$callback, [$this]);
}
if ($this->getIsDOMDocumentCreatedWithoutHtmlWrapper()) {
$content = $this->document->saveHTML($this->document->documentElement);
} else {
$content = $this->document->saveHTML();
}
if ($content === false) {
return '';
}
return $this->fixHtmlOutput($content, $multiDecodeNewHtmlEntity, $putBrokenReplacedBack);
}
/**
* Load HTML from string.
*
* @param string $html
* @param int|null $libXMLExtraOptions
*
* @return $this
*/
public function loadHtml(string $html, $libXMLExtraOptions = null): DomParserInterface
{
$this->document = $this->createDOMDocument($html, $libXMLExtraOptions);
return $this;
}
/**
* Load HTML from file.
*
* @param string $filePath
* @param int|null $libXMLExtraOptions
*
* @throws \RuntimeException
*
* @return $this
*/
public function loadHtmlFile(string $filePath, $libXMLExtraOptions = null): DomParserInterface
{
if (
!\preg_match("/^https?:\/\//i", $filePath)
&&
!\file_exists($filePath)
) {
throw new \RuntimeException("File " . $filePath . " not found");
}
try {
if (\class_exists('\voku\helper\UTF8')) {
$html = \voku\helper\UTF8::file_get_contents($filePath);
} else {
$html = \file_get_contents($filePath);
}
} catch (\Exception $e) {
throw new \RuntimeException("Could not load file " . $filePath);
}
if ($html === false) {
throw new \RuntimeException("Could not load file " . $filePath);
}
return $this->loadHtml($html, $libXMLExtraOptions);
}
/**
* Get the HTML as XML or plain XML if needed.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $htmlToXml
* @param bool $removeXmlHeader
* @param int $options
*
* @return string
*/
public function xml(
bool $multiDecodeNewHtmlEntity = false,
bool $htmlToXml = true,
bool $removeXmlHeader = true,
int $options = \LIBXML_NOEMPTYTAG
): string {
$xml = $this->document->saveXML(null, $options);
if ($xml === false) {
return '';
}
if ($removeXmlHeader) {
$xml = \ltrim((string) \preg_replace('/<\?xml.*\?>/', '', $xml));
}
if ($htmlToXml) {
$return = $this->fixHtmlOutput($xml, $multiDecodeNewHtmlEntity);
} else {
$xml = $this->decodeHtmlEntity($xml, $multiDecodeNewHtmlEntity);
$return = self::putReplacedBackToPreserveHtmlEntities($xml);
}
return $return;
}
/**
* @param string $selector
* @param int $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function __invoke($selector, $idx = null)
{
return $this->find($selector, $idx);
}
/**
* @return bool
*/
public function getIsDOMDocumentCreatedWithoutHeadWrapper(): bool
{
return $this->isDOMDocumentCreatedWithoutHeadWrapper;
}
/**
* @return bool
*/
public function getIsDOMDocumentCreatedWithoutPTagWrapper(): bool
{
return $this->isDOMDocumentCreatedWithoutPTagWrapper;
}
/**
* @return bool
*/
public function getIsDOMDocumentCreatedWithoutHtml(): bool
{
return $this->isDOMDocumentCreatedWithoutHtml;
}
/**
* @return bool
*/
public function getIsDOMDocumentCreatedWithoutBodyWrapper(): bool
{
return $this->isDOMDocumentCreatedWithoutBodyWrapper;
}
/**
* @return bool
*/
public function getIsDOMDocumentCreatedWithMultiRoot(): bool
{
return $this->isDOMDocumentCreatedWithMultiRoot;
}
/**
* @return bool
*/
public function getIsDOMDocumentCreatedWithoutHtmlWrapper(): bool
{
return $this->isDOMDocumentCreatedWithoutHtmlWrapper;
}
/**
* @return bool
*/
public function getIsDOMDocumentCreatedWithoutWrapper(): bool
{
return $this->isDOMDocumentCreatedWithoutWrapper;
}
/**
* @return bool
*/
public function getIsDOMDocumentCreatedWithFakeEndScript(): bool
{
return $this->isDOMDocumentCreatedWithFakeEndScript;
}
/**
* @param string $html
*
* @return string
*/
protected function keepBrokenHtml(string $html): string
{
do {
$original = $html;
$html = (string) \preg_replace_callback(
'/(?<start>.*)<(?<element_start>[a-z]+)(?<element_start_addon> [^>]*)?>(?<value>.*?)<\/(?<element_end>\2)>(?<end>.*)/sui',
static function ($matches) {
return $matches['start'] .
'°lt_simple_html_dom__voku_°' . $matches['element_start'] . $matches['element_start_addon'] . '°gt_simple_html_dom__voku_°' .
$matches['value'] .
'°lt/_simple_html_dom__voku_°' . $matches['element_end'] . '°gt_simple_html_dom__voku_°' .
$matches['end'];
},
$html
);
} while ($original !== $html);
do {
$original = $html;
$html = (string) \preg_replace_callback(
'/(?<start>[^<]*)?(?<broken>(?:<\/\w+(?:\s+\w+=\"[^"]+\")*+[^<]+>)+)(?<end>.*)/u',
static function ($matches) {
$matches['broken'] = \str_replace(
['°lt/_simple_html_dom__voku_°', '°lt_simple_html_dom__voku_°', '°gt_simple_html_dom__voku_°'],
['</', '<', '>'],
$matches['broken']
);
self::$domBrokenReplaceHelper['orig'][] = $matches['broken'];
self::$domBrokenReplaceHelper['tmp'][] = $matchesHash = self::$domHtmlBrokenHtmlHelper . \crc32($matches['broken']);
return $matches['start'] . $matchesHash . $matches['end'];
},
$html
);
} while ($original !== $html);
return \str_replace(
['°lt/_simple_html_dom__voku_°', '°lt_simple_html_dom__voku_°', '°gt_simple_html_dom__voku_°'],
['</', '<', '>'],
$html
);
}
/**
* workaround for bug: https://bugs.php.net/bug.php?id=74628
*
* @param string $html
*
* @return void
*/
protected function keepSpecialSvgTags(string &$html)
{
// regEx for e.g.: [mask-image:url('data:image/svg+xml;utf8,<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">...</svg>')]
/** @noinspection HtmlDeprecatedTag */
$regExSpecialSvg = '/\((["\'])?(?<start>data:image\/svg.*)<svg(?<attr>[^>]*?)>(?<content>.*)<\/svg>\1\)/isU';
$htmlTmp = \preg_replace_callback(
$regExSpecialSvg,
static function ($svgs) {
if (empty($svgs['content'])) {
return $svgs[0];
}
$content = '<svg' . $svgs['attr'] . '>' . $svgs['content'] . '</svg>';
self::$domBrokenReplaceHelper['orig'][] = $content;
self::$domBrokenReplaceHelper['tmp'][] = $matchesHash = self::$domHtmlBrokenHtmlHelper . \crc32($content);
return '(' . $svgs[1] . $svgs['start'] . $matchesHash . $svgs[1] . ')';
},
$html
);
if ($htmlTmp !== null) {
$html = $htmlTmp;
}
}
/**
* @param string $html
*
* @return void
*/
protected function keepSpecialScriptTags(string &$html)
{
// regEx for e.g.: [<script id="elements-image-1" type="text/html">...</script>]
$tags = \implode('|', \array_map(
static function ($value) {
return \preg_quote($value, '/');
},
$this->specialScriptTags
));
$html = (string) \preg_replace_callback(
'/(?<start>(<script [^>]*type=["\']?(?:' . $tags . ')+[^>]*>))(?<innerContent>.*)(?<end><\/script>)/isU',
function ($matches) {
// Check for logic in special script tags, like [<% _.each(tierPrices, function(item, key) { %>],
// because often this looks like non-valid html in the template itself.
foreach ($this->templateLogicSyntaxInSpecialScriptTags as $logicSyntaxInSpecialScriptTag) {
if (\strpos($matches['innerContent'], $logicSyntaxInSpecialScriptTag) !== false) {
// remove the html5 fallback
$matches['innerContent'] = \str_replace('<\/', '</', $matches['innerContent']);
self::$domBrokenReplaceHelper['orig'][] = $matches['innerContent'];
self::$domBrokenReplaceHelper['tmp'][] = $matchesHash = self::$domHtmlBrokenHtmlHelper . \crc32($matches['innerContent']);
return $matches['start'] . $matchesHash . $matches['end'];
}
}
// remove the html5 fallback
$matches[0] = \str_replace('<\/', '</', $matches[0]);
$specialNonScript = '<' . self::$domHtmlSpecialScriptHelper . \substr($matches[0], \strlen('<script'));
return \substr($specialNonScript, 0, -\strlen('</script>')) . '</' . self::$domHtmlSpecialScriptHelper . '>';
},
$html
);
}
/**
* @param bool $keepBrokenHtml
*
* @return $this
*/
public function useKeepBrokenHtml(bool $keepBrokenHtml): DomParserInterface
{
$this->keepBrokenHtml = $keepBrokenHtml;
return $this;
}
/**
* @param string[] $templateLogicSyntaxInSpecialScriptTags
*
* @return $this
*/
public function overwriteTemplateLogicSyntaxInSpecialScriptTags(array $templateLogicSyntaxInSpecialScriptTags): DomParserInterface
{
foreach ($templateLogicSyntaxInSpecialScriptTags as $tmp) {
if (!\is_string($tmp)) {
throw new \InvalidArgumentException('setTemplateLogicSyntaxInSpecialScriptTags only allows string[]');
}
}
$this->templateLogicSyntaxInSpecialScriptTags = $templateLogicSyntaxInSpecialScriptTags;
return $this;
}
/**
* @param string[] $specialScriptTags
*
* @return $this
*/
public function overwriteSpecialScriptTags(array $specialScriptTags): DomParserInterface
{
foreach ($specialScriptTags as $tag) {
if (!\is_string($tag)) {
throw new \InvalidArgumentException('SpecialScriptTags only allows string[]');
}
}
$this->specialScriptTags = $specialScriptTags;
return $this;
}
/**
* @param callable $callbackXPathBeforeQuery
*
* @phpstan-param callable(string $cssSelectorString, string $xPathString,\DOMXPath,\voku\helper\HtmlDomParser): string $callbackXPathBeforeQuery
*
* @return $this
*/
public function setCallbackXPathBeforeQuery(callable $callbackXPathBeforeQuery): self
{
$this->callbackXPathBeforeQuery = $callbackXPathBeforeQuery;
return $this;
}
/**
* @param callable $callbackBeforeCreateDom
*
* @phpstan-param callable(string $htmlString, \voku\helper\HtmlDomParser): string $callbackBeforeCreateDom
*
* @return $this
*/
public function setCallbackBeforeCreateDom(callable $callbackBeforeCreateDom): self
{
$this->callbackBeforeCreateDom = $callbackBeforeCreateDom;
return $this;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* {@inheritdoc}
*/
class SimpleXmlDomNodeBlank extends AbstractSimpleXmlDomNode implements SimpleXmlDomNodeInterface
{
/**
* @param string $selector
* @param int|null $idx
*
* @return null
*/
public function find(string $selector, $idx = null)
{
return null;
}
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMulti(string $selector): SimpleXmlDomNodeInterface
{
return new self();
}
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return false
*/
public function findMultiOrFalse(string $selector)
{
return false;
}
/**
* Find one node with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface
*/
public function findOne(string $selector)
{
return new SimpleXmlDomBlank();
}
/**
* @param string $selector
*
* @return false
*/
public function findOneOrFalse(string $selector)
{
return false;
}
/**
* @return string[]
*/
public function innerHtml(): array
{
return [];
}
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function innertext()
{
return [];
}
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function outertext()
{
return [];
}
/**
* @return string[]
*/
public function text(): array
{
return [];
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace voku\helper;
interface DomParserInterface
{
/**
* Find list of nodes with a CSS selector.
*
* @param string $selector
* @param int|null $idx
*
* @return mixed
*/
public function find(string $selector, $idx = null);
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return mixed
*/
public function findMulti(string $selector);
/**
* Find nodes with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return mixed
*/
public function findMultiOrFalse(string $selector);
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return static
*/
public function findOne(string $selector);
/**
* Find one node with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return mixed
*/
public function findOneOrFalse(string $selector);
/**
* @param string $content
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function fixHtmlOutput(string $content, bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string;
/**
* @return \DOMDocument
*/
public function getDocument(): \DOMDocument;
/**
* Return elements by ".class".
*
* @param string $class
*
* @return mixed
*/
public function getElementByClass(string $class);
/**
* Return element by #id.
*
* @param string $id
*
* @return mixed
*/
public function getElementById(string $id);
/**
* Return element by tag name.
*
* @param string $name
*
* @return mixed
*/
public function getElementByTagName(string $name);
/**
* Returns elements by "#id".
*
* @param string $id
* @param int|null $idx
*
* @return mixed
*/
public function getElementsById(string $id, $idx = null);
/**
* Returns elements by tag name.
*
* @param string $name
* @param int|null $idx
*
* @return mixed
*/
public function getElementsByTagName(string $name, $idx = null);
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function html(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string;
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function innerHtml(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string;
/**
* Get dom node's inner xml.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function innerXml(bool $multiDecodeNewHtmlEntity = false): string;
/**
* Load HTML from string.
*
* @param string $html
* @param int|null $libXMLExtraOptions
*
* @return DomParserInterface
*/
public function loadHtml(string $html, $libXMLExtraOptions = null): self;
/**
* Load HTML from file.
*
* @param string $filePath
* @param int|null $libXMLExtraOptions
*
* @throws \RuntimeException
*
* @return DomParserInterface
*/
public function loadHtmlFile(string $filePath, $libXMLExtraOptions = null): self;
/**
* Save the html-dom as string.
*
* @param string $filepath
*
* @return string
*/
public function save(string $filepath = ''): string;
/**
* @param callable $functionName
*
* @return mixed
*/
public function set_callback($functionName);
/**
* Get dom node's plain text.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function text(bool $multiDecodeNewHtmlEntity = false): string;
/**
* Get the HTML as XML or plain XML if needed.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $htmlToXml
* @param bool $removeXmlHeader
* @param int $options
*
* @return string
*/
public function xml(bool $multiDecodeNewHtmlEntity = false, bool $htmlToXml = true, bool $removeXmlHeader = true, int $options = \LIBXML_NOEMPTYTAG): string;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* @property-read string $plaintext
* <p>Get dom node's plain text.</p>
*
* @method static XmlDomParser file_get_xml($xml, $libXMLExtraOptions = null)
* <p>Load XML from file.</p>
* @method static XmlDomParser str_get_xml($xml, $libXMLExtraOptions = null)
* <p>Load XML from string.</p>
*/
class XmlDomParser extends AbstractDomParser
{
/**
* @var callable|null
*
* @phpstan-var null|callable(string $cssSelectorString, string $xPathString, \DOMXPath, \voku\helper\XmlDomParser): string
*/
private $callbackXPathBeforeQuery;
/**
* @var callable|null
*
* @phpstan-var null|callable(string $xmlString, \voku\helper\XmlDomParser): string
*/
private $callbackBeforeCreateDom;
/**
* @var bool
*/
private $autoRemoveXPathNamespaces = false;
/**
* @var bool
*/
private $autoRegisterXPathNamespaces = false;
/**
* @var bool
*/
private $reportXmlErrorsAsException = false;
/**
* @var string[]
*
* @phpstan-var array<string, string>
*/
private $xPathNamespaces = [];
/**
* @param \DOMNode|SimpleXmlDomInterface|string $element HTML code or SimpleXmlDomInterface, \DOMNode
*/
public function __construct($element = null)
{
$this->document = new \DOMDocument('1.0', $this->getEncoding());
// DOMDocument settings
$this->document->preserveWhiteSpace = true;
$this->document->formatOutput = true;
if ($element instanceof SimpleXmlDomInterface) {
$element = $element->getNode();
}
if ($element instanceof \DOMNode) {
$domNode = $this->document->importNode($element, true);
if ($domNode instanceof \DOMNode) {
/** @noinspection UnusedFunctionResultInspection */
$this->document->appendChild($domNode);
}
return;
}
if ($element !== null) {
$this->loadXml($element);
}
}
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
* @throws \RuntimeException
*
* @return static
*/
public static function __callStatic($name, $arguments)
{
$arguments0 = $arguments[0] ?? '';
$arguments1 = $arguments[1] ?? null;
if ($name === 'str_get_xml') {
$parser = new static();
return $parser->loadXml($arguments0, $arguments1);
}
if ($name === 'file_get_xml') {
$parser = new static();
return $parser->loadXmlFile($arguments0, $arguments1);
}
throw new \BadMethodCallException('Method does not exist');
}
/** @noinspection MagicMethodsValidityInspection */
/**
* @param string $name
*
* @return string|null
*/
public function __get($name)
{
$name = \strtolower($name);
if ($name === 'plaintext') {
return $this->text();
}
return null;
}
/**
* @return string
*/
public function __toString()
{
return $this->xml(false, false, true, 0);
}
/**
* Create DOMDocument from XML.
*
* @param string $xml
* @param int|null $libXMLExtraOptions
*
* @return \DOMDocument
*/
protected function createDOMDocument(string $xml, $libXMLExtraOptions = null): \DOMDocument
{
if ($this->callbackBeforeCreateDom) {
$xml = \call_user_func($this->callbackBeforeCreateDom, $xml, $this);
}
// set error level
$internalErrors = \libxml_use_internal_errors(true);
if (\PHP_VERSION_ID < 80000) {
$disableEntityLoader = \libxml_disable_entity_loader(true);
}
\libxml_clear_errors();
$optionsXml = \LIBXML_DTDLOAD | \LIBXML_DTDATTR | \LIBXML_NONET;
if (\defined('LIBXML_BIGLINES')) {
$optionsXml |= \LIBXML_BIGLINES;
}
if (\defined('LIBXML_COMPACT')) {
$optionsXml |= \LIBXML_COMPACT;
}
if ($libXMLExtraOptions !== null) {
$optionsXml |= $libXMLExtraOptions;
}
$this->xPathNamespaces = []; // reset
$matches = [];
\preg_match_all('#xmlns:(?<namespaceKey>.*)=(["\'])(?<namespaceValue>.*)\\2#Ui', $xml, $matches);
foreach ($matches['namespaceKey'] ?? [] as $index => $key) {
if ($key) {
$this->xPathNamespaces[\trim($key, ':')] = $matches['namespaceValue'][$index];
}
}
if ($this->autoRemoveXPathNamespaces) {
$xml = $this->removeXPathNamespaces($xml);
}
$xml = self::replaceToPreserveHtmlEntities($xml);
$documentFound = false;
$sxe = \simplexml_load_string($xml, \SimpleXMLElement::class, $optionsXml);
$xmlErrors = \libxml_get_errors();
if ($sxe !== false && \count($xmlErrors) === 0) {
$domElementTmp = \dom_import_simplexml($sxe);
if ($domElementTmp->ownerDocument instanceof \DOMDocument) {
$documentFound = true;
$this->document = $domElementTmp->ownerDocument;
}
}
if ($documentFound === false) {
// UTF-8 hack: http://php.net/manual/en/domdocument.loadhtml.php#95251
$xmlHackUsed = false;
/** @noinspection StringFragmentMisplacedInspection */
if (\stripos('<?xml', $xml) !== 0) {
$xmlHackUsed = true;
$xml = '<?xml encoding="' . $this->getEncoding() . '" ?>' . $xml;
}
$documentFound = $this->document->loadXML($xml, $optionsXml);
// remove the "xml-encoding" hack
if ($xmlHackUsed) {
foreach ($this->document->childNodes as $child) {
if ($child->nodeType === \XML_PI_NODE) {
/** @noinspection UnusedFunctionResultInspection */
$this->document->removeChild($child);
break;
}
}
}
}
if (
$documentFound === false
&&
\count($xmlErrors) > 0
) {
$errorStr = 'XML-Errors: ' . \print_r($xmlErrors, true) . ' in ' . \print_r($xml, true);
if (!$this->reportXmlErrorsAsException) {
\trigger_error($errorStr, \E_USER_WARNING);
} else {
throw new \InvalidArgumentException($errorStr);
}
}
// set encoding
$this->document->encoding = $this->getEncoding();
// restore lib-xml settings
\libxml_clear_errors();
\libxml_use_internal_errors($internalErrors);
if (\PHP_VERSION_ID < 80000 && isset($disableEntityLoader)) {
\libxml_disable_entity_loader($disableEntityLoader);
}
return $this->document;
}
/**
* Find list of nodes with a CSS or xPath selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function find(string $selector, $idx = null)
{
$xPathQuery = SelectorConverter::toXPath($selector, true, false);
$xPath = new \DOMXPath($this->document);
if ($this->autoRegisterXPathNamespaces) {
foreach ($this->xPathNamespaces as $key => $value) {
$xPath->registerNamespace($key, $value);
}
}
if ($this->callbackXPathBeforeQuery) {
$xPathQuery = \call_user_func($this->callbackXPathBeforeQuery, $selector, $xPathQuery, $xPath, $this);
}
$nodesList = $xPath->query($xPathQuery);
$elements = new SimpleXmlDomNode();
if ($nodesList) {
foreach ($nodesList as $node) {
$elements[] = new SimpleXmlDom($node);
}
}
// return all elements
if ($idx === null) {
if (\count($elements) === 0) {
return new SimpleXmlDomNodeBlank();
}
return $elements;
}
// handle negative values
if ($idx < 0) {
$idx = \count($elements) + $idx;
}
// return one element
return $elements[$idx] ?? new SimpleXmlDomBlank();
}
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMulti(string $selector): SimpleXmlDomNodeInterface
{
return $this->find($selector, null);
}
/**
* Find nodes with a CSS or xPath selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMultiOrFalse(string $selector)
{
$return = $this->find($selector, null);
if ($return instanceof SimpleXmlDomNodeBlank) {
return false;
}
return $return;
}
/**
* Find one node with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface
*/
public function findOne(string $selector): SimpleXmlDomInterface
{
return $this->find($selector, 0);
}
/**
* Find one node with a CSS or xPath selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleXmlDomInterface
*/
public function findOneOrFalse(string $selector)
{
$return = $this->find($selector, 0);
if ($return instanceof SimpleXmlDomBlank) {
return false;
}
return $return;
}
/**
* @param string $content
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function fixHtmlOutput(
string $content,
bool $multiDecodeNewHtmlEntity = false,
bool $putBrokenReplacedBack = true
): string {
$content = $this->decodeHtmlEntity($content, $multiDecodeNewHtmlEntity);
return self::putReplacedBackToPreserveHtmlEntities($content, $putBrokenReplacedBack);
}
/**
* Return elements by ".class".
*
* @param string $class
*
* @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementByClass(string $class): SimpleXmlDomNodeInterface
{
return $this->findMulti(".${class}");
}
/**
* Return element by #id.
*
* @param string $id
*
* @return SimpleXmlDomInterface
*/
public function getElementById(string $id): SimpleXmlDomInterface
{
return $this->findOne("#${id}");
}
/**
* Return element by tag name.
*
* @param string $name
*
* @return SimpleXmlDomInterface
*/
public function getElementByTagName(string $name): SimpleXmlDomInterface
{
$node = $this->document->getElementsByTagName($name)->item(0);
if ($node === null) {
return new SimpleXmlDomBlank();
}
return new SimpleXmlDom($node);
}
/**
* Returns elements by "#id".
*
* @param string $id
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementsById(string $id, $idx = null)
{
return $this->find("#${id}", $idx);
}
/**
* Returns elements by tag name.
*
* @param string $name
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementsByTagName(string $name, $idx = null)
{
$nodesList = $this->document->getElementsByTagName($name);
$elements = new SimpleXmlDomNode();
foreach ($nodesList as $node) {
$elements[] = new SimpleXmlDom($node);
}
// return all elements
if ($idx === null) {
if (\count($elements) === 0) {
return new SimpleXmlDomNodeBlank();
}
return $elements;
}
// handle negative values
if ($idx < 0) {
$idx = \count($elements) + $idx;
}
// return one element
return $elements[$idx] ?? new SimpleXmlDomNodeBlank();
}
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function html(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string
{
if (static::$callback !== null) {
\call_user_func(static::$callback, [$this]);
}
$content = $this->document->saveHTML();
if ($content === false) {
return '';
}
return $this->fixHtmlOutput($content, $multiDecodeNewHtmlEntity, $putBrokenReplacedBack);
}
/**
* Load HTML from string.
*
* @param string $html
* @param int|null $libXMLExtraOptions
*
* @return $this
*/
public function loadHtml(string $html, $libXMLExtraOptions = null): DomParserInterface
{
$this->document = $this->createDOMDocument($html, $libXMLExtraOptions);
return $this;
}
/**
* Load HTML from file.
*
* @param string $filePath
* @param int|null $libXMLExtraOptions
*
* @throws \RuntimeException
*
* @return $this
*/
public function loadHtmlFile(string $filePath, $libXMLExtraOptions = null): DomParserInterface
{
if (
!\preg_match("/^https?:\/\//i", $filePath)
&&
!\file_exists($filePath)
) {
throw new \RuntimeException("File ${filePath} not found");
}
try {
if (\class_exists('\voku\helper\UTF8')) {
$html = \voku\helper\UTF8::file_get_contents($filePath);
} else {
$html = \file_get_contents($filePath);
}
} catch (\Exception $e) {
throw new \RuntimeException("Could not load file ${filePath}");
}
if ($html === false) {
throw new \RuntimeException("Could not load file ${filePath}");
}
return $this->loadHtml($html, $libXMLExtraOptions);
}
/**
* @param string $selector
* @param int $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function __invoke($selector, $idx = null)
{
return $this->find($selector, $idx);
}
/**
* @param string $xml
*
* @return string
*/
private function removeXPathNamespaces(string $xml): string
{
foreach ($this->xPathNamespaces as $key => $value) {
$xml = \str_replace($key . ':', '', $xml);
}
return (string) \preg_replace('#xmlns:?.*=(["\'])(?:.*)\\1#Ui', '', $xml);
}
/**
* Load XML from string.
*
* @param string $xml
* @param int|null $libXMLExtraOptions
*
* @return $this
*/
public function loadXml(string $xml, $libXMLExtraOptions = null): self
{
$this->document = $this->createDOMDocument($xml, $libXMLExtraOptions);
return $this;
}
/**
* Load XML from file.
*
* @param string $filePath
* @param int|null $libXMLExtraOptions
*
* @throws \RuntimeException
*
* @return $this
*/
public function loadXmlFile(string $filePath, $libXMLExtraOptions = null): self
{
if (
!\preg_match("/^https?:\/\//i", $filePath)
&&
!\file_exists($filePath)
) {
throw new \RuntimeException("File ${filePath} not found");
}
try {
if (\class_exists('\voku\helper\UTF8')) {
$xml = \voku\helper\UTF8::file_get_contents($filePath);
} else {
$xml = \file_get_contents($filePath);
}
} catch (\Exception $e) {
throw new \RuntimeException("Could not load file ${filePath}");
}
if ($xml === false) {
throw new \RuntimeException("Could not load file ${filePath}");
}
return $this->loadXml($xml, $libXMLExtraOptions);
}
/**
* @param callable $callback
* @param \DOMNode|null $domNode
*
* @return void
*/
public function replaceTextWithCallback($callback, \DOMNode $domNode = null)
{
if ($domNode === null) {
$domNode = $this->document;
}
if ($domNode->hasChildNodes()) {
$children = [];
// since looping through a DOM being modified is a bad idea we prepare an array:
foreach ($domNode->childNodes as $child) {
$children[] = $child;
}
foreach ($children as $child) {
if ($child->nodeType === \XML_TEXT_NODE) {
/** @noinspection PhpSillyAssignmentInspection */
/** @var \DOMText $child */
$child = $child;
$oldText = self::putReplacedBackToPreserveHtmlEntities($child->wholeText);
$newText = $callback($oldText);
if ($domNode->ownerDocument) {
$newTextNode = $domNode->ownerDocument->createTextNode(self::replaceToPreserveHtmlEntities($newText));
$domNode->replaceChild($newTextNode, $child);
}
} else {
$this->replaceTextWithCallback($callback, $child);
}
}
}
}
/**
* @param bool $autoRemoveXPathNamespaces
*
* @return $this
*/
public function autoRemoveXPathNamespaces(bool $autoRemoveXPathNamespaces = true): self
{
$this->autoRemoveXPathNamespaces = $autoRemoveXPathNamespaces;
return $this;
}
/**
* @param bool $autoRegisterXPathNamespaces
*
* @return $this
*/
public function autoRegisterXPathNamespaces(bool $autoRegisterXPathNamespaces = true): self
{
$this->autoRegisterXPathNamespaces = $autoRegisterXPathNamespaces;
return $this;
}
/**
* @param callable $callbackXPathBeforeQuery
*
* @phpstan-param callable(string $cssSelectorString, string $xPathString, \DOMXPath, \voku\helper\XmlDomParser): string $callbackXPathBeforeQuery
*
* @return $this
*/
public function setCallbackXPathBeforeQuery(callable $callbackXPathBeforeQuery): self
{
$this->callbackXPathBeforeQuery = $callbackXPathBeforeQuery;
return $this;
}
/**
* @param callable $callbackBeforeCreateDom
*
* @phpstan-param callable(string $xmlString, \voku\helper\XmlDomParser): string $callbackBeforeCreateDom
*
* @return $this
*/
public function setCallbackBeforeCreateDom(callable $callbackBeforeCreateDom): self
{
$this->callbackBeforeCreateDom = $callbackBeforeCreateDom;
return $this;
}
/**
* @param bool $reportXmlErrorsAsException
*
* @return $this
*/
public function reportXmlErrorsAsException(bool $reportXmlErrorsAsException = true): self
{
$this->reportXmlErrorsAsException = $reportXmlErrorsAsException;
return $this;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* {@inheritdoc}
*/
class SimpleHtmlAttributes implements SimpleHtmlAttributesInterface
{
/**
* @var string
*/
private $attributeName;
/**
* @var \DOMElement|null
*/
private $element;
/**
* @var string[]
*
* @psalm-var list<string>
*/
private $tokens = [];
/**
* @var string|null
*/
private $previousValue;
/**
* Creates a list of space-separated tokens based on the attribute value of an element.
*
* @param \DOMElement|null $element
* <p>The DOM element.</p>
* @param string $attributeName
* <p>The name of the attribute.</p>
*/
public function __construct($element, string $attributeName)
{
$this->element = $element;
$this->attributeName = $attributeName;
$this->tokenize();
}
/** @noinspection MagicMethodsValidityInspection */
/**
* Returns the value for the property specified.
*
* @param string $name The name of the property
*
* @return int|string The value of the property specified
*/
public function __get(string $name)
{
if ($name === 'length') {
$this->tokenize();
return \count($this->tokens);
}
if ($name === 'value') {
return (string) $this;
}
throw new \InvalidArgumentException('Undefined property: $' . $name);
}
/**
* @return string
*/
public function __toString(): string
{
$this->tokenize();
return \implode(' ', $this->tokens);
}
/**
* {@inheritdoc}
*/
public function add(string ...$tokens)
{
if (\count($tokens) === 0) {
return null;
}
foreach ($tokens as $t) {
if (\in_array($t, $this->tokens, true)) {
continue;
}
$this->tokens[] = $t;
}
return $this->setAttributeValue();
}
/**
* {@inheritdoc}
*/
public function contains(string $token): bool
{
$this->tokenize();
return \in_array($token, $this->tokens, true);
}
/**
* {@inheritdoc}
*/
public function entries(): \ArrayIterator
{
$this->tokenize();
return new \ArrayIterator($this->tokens);
}
public function item(int $index)
{
$this->tokenize();
if ($index >= \count($this->tokens)) {
return null;
}
return $this->tokens[$index];
}
/**
* {@inheritdoc}
*/
public function remove(string ...$tokens)
{
if (\count($tokens) === 0) {
return null;
}
if (\count($this->tokens) === 0) {
return null;
}
foreach ($tokens as $t) {
$i = \array_search($t, $this->tokens, true);
if ($i === false) {
continue;
}
\array_splice($this->tokens, $i, 1);
}
return $this->setAttributeValue();
}
/**
* {@inheritdoc}
*/
public function replace(string $old, string $new)
{
if ($old === $new) {
return null;
}
$this->tokenize();
$i = \array_search($old, $this->tokens, true);
if ($i !== false) {
$j = \array_search($new, $this->tokens, true);
if ($j === false) {
$this->tokens[$i] = $new;
} else {
\array_splice($this->tokens, $i, 1);
}
return $this->setAttributeValue();
}
return null;
}
/**
* {@inheritdoc}
*/
public function toggle(string $token, bool $force = null): bool
{
// init
$this->tokenize();
$isThereAfter = false;
$i = \array_search($token, $this->tokens, true);
if ($force === null) {
if ($i === false) {
$this->tokens[] = $token;
$isThereAfter = true;
} else {
\array_splice($this->tokens, $i, 1);
}
} elseif ($force) {
if ($i === false) {
$this->tokens[] = $token;
}
$isThereAfter = true;
} else {
/** @noinspection NestedPositiveIfStatementsInspection */
if ($i !== false) {
\array_splice($this->tokens, $i, 1);
}
}
/** @noinspection UnusedFunctionResultInspection */
$this->setAttributeValue();
return $isThereAfter;
}
/**
* @return \DOMAttr|false|null
*/
private function setAttributeValue()
{
if ($this->element === null) {
return false;
}
$value = \implode(' ', $this->tokens);
if ($this->previousValue === $value) {
return null;
}
$this->previousValue = $value;
return $this->element->setAttribute($this->attributeName, $value);
}
/**
* @return void
*/
private function tokenize()
{
if ($this->element === null) {
return;
}
$current = $this->element->getAttribute($this->attributeName);
if ($this->previousValue === $current) {
return;
}
$this->previousValue = $current;
$tokens = \explode(' ', $current);
$finals = [];
foreach ($tokens as $token) {
if ($token === '') {
continue;
}
if (\in_array($token, $finals, true)) {
continue;
}
$finals[] = $token;
}
$this->tokens = $finals;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace voku\helper;
/**
* Represents a set of space-separated attributes of an element attribute.
*
* @property-read int $length The number of tokens.
* @property-read string $value A space-separated list of the tokens.
*/
interface SimpleHtmlAttributesInterface
{
/**
* Adds the given tokens to the list.
*
* @param string ...$tokens
* <p>The tokens you want to add to the list.</p>
*
* @return \DOMAttr|false|null
*/
public function add(string ...$tokens);
/**
* Returns true if the list contains the given token, otherwise false.
*
* @param string $token the token you want to check for the existence of in the list
*
* @return bool true if the list contains the given token, otherwise false
*/
public function contains(string $token): bool;
/**
* Returns an iterator allowing you to go through all tokens contained in the list.
*
* @return \ArrayIterator
*/
public function entries(): \ArrayIterator;
/**
* Returns an item in the list by its index (returns null if the number is greater than or equal to the length of
* the list).
*
* @param int $index the zero-based index of the item you want to return
*
* @return string|null
*/
public function item(int $index);
/**
* Removes the specified tokens from the list. If the string does not exist in the list, no error is thrown.
*
* @param string ...$tokens
* <p>The token you want to remove from the list.</>
*
* @return \DOMAttr|false|null
*/
public function remove(string ...$tokens);
/**
* Replaces an existing token with a new token.
*
* @param string $old the token you want to replace
* @param string $new the token you want to replace $old with
*
* @return \DOMAttr|false|null
*/
public function replace(string $old, string $new);
/**
* Removes a given token from the list and returns false. If token doesn't exist it's added and the function
* returns true.
*
* @param string $token the token you want to toggle
* @param bool $force A Boolean that, if included, turns the toggle into a one way-only operation. If set to
* false, the token will only be removed but not added again. If set to true, the token will
* only be added but not removed again.
*
* @return bool false if the token is not in the list after the call, or true if the token is in the list after the
* call
*/
public function toggle(string $token, bool $force = null): bool;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace voku\helper;
/**
* @property-read int $length
* <p>The list items count.</p>
* @property-read string[] $outertext
* <p>Get dom node's outer html.</p>
* @property-read string[] $plaintext
* <p>Get dom node's plain text.</p>
*
* @extends \IteratorAggregate<int, SimpleXmlDomInterface>
*/
interface SimpleXmlDomNodeInterface extends \IteratorAggregate
{
/**
* @param string $name
*
* @return array|null
*/
public function __get($name);
/**
* @param string $selector
* @param int $idx
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>|SimpleXmlDomNodeInterface[]|null
*/
public function __invoke($selector, $idx = null);
/**
* @return string
*/
public function __toString();
/**
* Get the number of items in this dom node.
*
* @return int
*/
public function count();
/**
* Find list of nodes with a CSS or xPath selector.
*
* @param string $selector
* @param int $idx
*
* @return SimpleXmlDomNode|SimpleXmlDomNode[]|null
*/
public function find(string $selector, $idx = null);
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMulti(string $selector): self;
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return false|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMultiOrFalse(string $selector);
/**
* Find one node with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface
*/
public function findOne(string $selector);
/**
* Find one node with a CSS or xPath selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleXmlDomInterface
*/
public function findOneOrFalse(string $selector);
/**
* Get html of elements.
*
* @return string[]
*/
public function innerHtml(): array;
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function innertext();
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function outertext();
/**
* Get plain text.
*
* @return string[]
*/
public function text(): array;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
final class HtmlDomHelper {
/**
* @param string $html
* @param string $optionStr
* @param string $htmlCssSelector
*
* @return string
*/
static function mergeHtmlAttributes(
string $html,
string $optionStr,
string $htmlCssSelector
): string {
if (!$optionStr) {
return $html;
}
$dom = \voku\helper\HtmlDomParser::str_get_html($html);
$domNew = \voku\helper\HtmlDomParser::str_get_html('<textarea ' . $optionStr . '></textarea>');
$domElement = $dom->findOneOrFalse($htmlCssSelector);
if ($domElement === false) {
return $html;
}
$attributes = $domElement->getAllAttributes();
if (!$attributes) {
return $html;
}
$domElementNew = $domNew->findOneOrFalse('textarea');
if ($domElementNew === false) {
return $html;
}
$attributesNew = $domElementNew->getAllAttributes();
if (!$attributesNew) {
return $html;
}
foreach ($attributesNew as $attributeNameNew => $attributeValueNew) {
$attributeNameNew = \strtolower($attributeNameNew);
if (
$attributeNameNew === 'class'
||
$attributeNameNew === 'style'
||
\strpos($attributeNameNew, 'on') === 0 // e.g. onClick, ...
) {
if (isset($attributes[$attributeNameNew])) {
$attributes[$attributeNameNew] .= ' ' . $attributeValueNew;
} else {
$attributes[$attributeNameNew] = $attributeValueNew;
}
} else {
$attributes[$attributeNameNew] = $attributeValueNew;
}
}
foreach ($attributes as $attributeName => $attributeValue) {
$domElement->setAttribute($attributeName, $attributeValue);
}
return $domElement->html();
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* {@inheritdoc}
*/
abstract class AbstractSimpleHtmlDomNode extends \ArrayObject
{
/** @noinspection MagicMethodsValidityInspection */
/**
* @param string $name
*
* @return array|int|null
*/
public function __get($name)
{
// init
$name = \strtolower($name);
if ($name === 'length') {
return $this->count();
}
if ($this->count() > 0) {
$return = [];
foreach ($this as $node) {
if ($node instanceof SimpleHtmlDomInterface) {
$return[] = $node->{$name};
}
}
return $return;
}
if ($name === 'plaintext' || $name === 'outertext') {
return [];
}
return null;
}
/**
* @param string $selector
* @param int|null $idx
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>|SimpleHtmlDomNodeInterface[]|null
*/
public function __invoke($selector, $idx = null)
{
return $this->find($selector, $idx);
}
/**
* @return string
*/
public function __toString()
{
// init
$html = '';
foreach ($this as $node) {
$html .= $node->outertext;
}
return $html;
}
/**
* @param string $selector
* @param int|null $idx
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>|SimpleHtmlDomNodeInterface[]|null
*/
abstract public function find(string $selector, $idx = null);
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
use Symfony\Component\CssSelector\CssSelectorConverter;
class SelectorConverter
{
/**
* @var string[]
*
* @phpstan-var array<string,string>
*/
protected static $compiled = [];
/**
* @param string $selector
* @param bool $ignoreCssSelectorErrors
* <p>
* Ignore css selector errors and use the $selector as it is on error,
* so that you can also use xPath selectors.
* </p>
* @param bool $isForHtml
*
* @return string
*/
public static function toXPath(string $selector, bool $ignoreCssSelectorErrors = false, bool $isForHtml = true)
{
if (isset(self::$compiled[$selector])) {
return self::$compiled[$selector];
}
// Select DOMText
if ($selector === 'text') {
return '//text()';
}
// Select DOMComment
if ($selector === 'comment') {
return '//comment()';
}
if (\strpos($selector, '//') === 0) {
return $selector;
}
if (!\class_exists(CssSelectorConverter::class)) {
throw new \RuntimeException('Unable to filter with a CSS selector as the Symfony CssSelector 2.8+ is not installed (you can use filterXPath instead).');
}
$converterKey = '-' . $isForHtml . '-' . $ignoreCssSelectorErrors . '-';
static $converterArray = [];
if (!isset($converterArray[$converterKey])) {
$converterArray[$converterKey] = new CssSelectorConverter($isForHtml);
}
$converter = $converterArray[$converterKey];
assert($converter instanceof CssSelectorConverter);
if ($ignoreCssSelectorErrors) {
try {
$xPathQuery = $converter->toXPath($selector);
} catch (\Exception $e) {
$xPathQuery = $selector;
}
} else {
$xPathQuery = $converter->toXPath($selector);
}
self::$compiled[$selector] = $xPathQuery;
return $xPathQuery;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* {@inheritdoc}
*/
class SimpleHtmlDomNodeBlank extends AbstractSimpleHtmlDomNode implements SimpleHtmlDomNodeInterface
{
/**
* @param string $selector
* @param int|null $idx
*
* @return null
*/
public function find(string $selector, $idx = null)
{
return null;
}
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMulti(string $selector): SimpleHtmlDomNodeInterface
{
return new self();
}
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return false
*/
public function findMultiOrFalse(string $selector)
{
return false;
}
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface
*/
public function findOne(string $selector)
{
return new SimpleHtmlDomBlank();
}
/**
* Find one node with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false
*/
public function findOneOrFalse(string $selector)
{
return false;
}
/**
* @return string[]
*/
public function innerHtml(): array
{
return [];
}
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function innertext()
{
return [];
}
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function outertext()
{
return [];
}
/**
* @return string[]
*/
public function text(): array
{
return [];
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace voku\helper;
/**
* @property string $outertext
* <p>Get dom node's outer html (alias for "outerHtml").</p>
* @property string $outerhtml
* <p>Get dom node's outer html.</p>
* @property string $innertext
* <p>Get dom node's inner html (alias for "innerHtml").</p>
* @property string $innerhtml
* <p>Get dom node's inner html.</p>
* @property string $plaintext
* <p>Get dom node's plain text.</p>
* @property-read string $tag
* <p>Get dom node name.</p>
* @property-read string $attr
* <p>Get dom node attributes.</p>
* @property-read string $text
* <p>Get dom node name.</p>
* @property-read string $html
* <p>Get dom node's outer html.</p>
*
* @method SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>|null children() children($idx = -1)
* <p>Returns children of node.</p>
* @method SimpleXmlDomInterface|null first_child()
* <p>Returns the first child of node.</p>
* @method SimpleXmlDomInterface|null last_child()
* <p>Returns the last child of node.</p>
* @method SimpleXmlDomInterface|null next_sibling()
* <p>Returns the next sibling of node.</p>
* @method SimpleXmlDomInterface|null prev_sibling()
* <p>Returns the previous sibling of node.</p>
* @method SimpleXmlDomInterface|null parent()
* <p>Returns the parent of node.</p>
* @method string outerText()
* <p>Get dom node's outer html (alias for "outerHtml()").</p>
* @method string outerHtml()
* <p>Get dom node's outer html.</p>
* @method string innerText()
* <p>Get dom node's inner html (alias for "innerHtml()").</p>
*
* @extends \IteratorAggregate<int, \DOMNode>
*/
interface SimpleXmlDomInterface extends \IteratorAggregate
{
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
*
* @return SimpleXmlDomInterface|string|null
*/
public function __call($name, $arguments);
/**
* @param string $name
*
* @return array|string|null
*/
public function __get($name);
/**
* @param string $selector
* @param int $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function __invoke($selector, $idx = null);
/**
* @param string $name
*
* @return bool
*/
public function __isset($name);
/**
* @return string
*/
public function __toString();
/**
* Returns children of node.
*
* @param int $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>|null
*/
public function childNodes(int $idx = -1);
/**
* Find list of nodes with a CSS or xPath selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function find(string $selector, $idx = null);
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMulti(string $selector): SimpleXmlDomNodeInterface;
/**
* Find nodes with a CSS or xPath selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMultiOrFalse(string $selector);
/**
* Find one node with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface
*/
public function findOne(string $selector): self;
/**
* Find one node with a CSS or xPath selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleXmlDomInterface
*/
public function findOneOrFalse(string $selector);
/**
* Returns the first child of node.
*
* @return SimpleXmlDomInterface|null
*/
public function firstChild();
/**
* Returns an array of attributes.
*
* @return string[]|null
*/
public function getAllAttributes();
/**
* @return bool
*/
public function hasAttributes(): bool;
/**
* Return attribute value.
*
* @param string $name
*
* @return string
*/
public function getAttribute(string $name): string;
/**
* Return elements by ".class".
*
* @param string $class
*
* @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementByClass(string $class);
/**
* Return element by "#id".
*
* @param string $id
*
* @return SimpleXmlDomInterface
*/
public function getElementById(string $id): self;
/**
* Return element by tag name.
*
* @param string $name
*
* @return SimpleXmlDomInterface
*/
public function getElementByTagName(string $name): self;
/**
* Returns elements by "#id".
*
* @param string $id
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementsById(string $id, $idx = null);
/**
* Returns elements by tag name.
*
* @param string $name
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementsByTagName(string $name, $idx = null);
/**
* Retrieve an external iterator.
*
* @see http://php.net/manual/en/iteratoraggregate.getiterator.php
*
* @return SimpleXmlDomNodeInterface<int, \DOMNode>
* <p>
* An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
* </p>
*/
public function getIterator(): SimpleXmlDomNodeInterface;
/**
* @return \DOMNode
*/
public function getNode(): \DOMNode;
/**
* Create a new "XmlDomParser"-object from the current context.
*
* @return XmlDomParser
*/
public function getXmlDomParser(): XmlDomParser;
/**
* Determine if an attribute exists on the element.
*
* @param string $name
*
* @return bool
*/
public function hasAttribute(string $name): bool;
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function innerHtml(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string;
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function innerXml(bool $multiDecodeNewHtmlEntity = false): string;
/**
* Nodes can get partially destroyed in which they're still an
* actual DOM node (such as \DOMElement) but almost their entire
* body is gone, including the `nodeType` attribute.
*
* @return bool true if node has been destroyed
*/
public function isRemoved(): bool;
/**
* Returns the last child of node.
*
* @return SimpleXmlDomInterface|null
*/
public function lastChild();
/**
* Returns the next sibling of node.
*
* @return SimpleXmlDomInterface|null
*/
public function nextSibling();
/**
* Returns the next sibling of node.
*
* @return SimpleXmlDomInterface|null
*/
public function nextNonWhitespaceSibling();
/**
* Returns the parent of node.
*
* @return SimpleXmlDomInterface
*/
public function parentNode(): self;
/**
* Returns the previous sibling of node.
*
* @return SimpleXmlDomInterface|null
*/
public function previousSibling();
/**
* Returns the previous sibling of node.
*
* @return SimpleXmlDomInterface|null
*/
public function previousNonWhitespaceSibling();
/**
* Remove attribute.
*
* @param string $name <p>The name of the html-attribute.</p>
*
* @return SimpleXmlDomInterface
*/
public function removeAttribute(string $name): self;
/**
* Set attribute value.
*
* @param string $name <p>The name of the html-attribute.</p>
* @param string|null $value <p>Set to NULL or empty string, to remove the attribute.</p>
* @param bool $strictEmptyValueCheck </p>
* $value must be NULL, to remove the attribute,
* so that you can set an empty string as attribute-value e.g. autofocus=""
* </p>
*
* @return SimpleXmlDomInterface
*/
public function setAttribute(string $name, $value = null, bool $strictEmptyValueCheck = false): self;
/**
* Get dom node's plain text.
*
* @return string
*/
public function text(): string;
/**
* @param string|string[]|null $value <p>
* null === get the current input value
* text === set a new input value
* </p>
*
* @return string|string[]|null
*/
public function val($value = null);
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function xml(bool $multiDecodeNewHtmlEntity = false): string;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* @noinspection PhpHierarchyChecksInspection
*
* {@inheritdoc}
*
* @implements \IteratorAggregate<int, \DOMNode>
*/
class SimpleHtmlDom extends AbstractSimpleHtmlDom implements \IteratorAggregate, SimpleHtmlDomInterface
{
/**
* @param \DOMElement|\DOMNode $node
*/
public function __construct(\DOMNode $node)
{
$this->node = $node;
}
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
*
* @return SimpleHtmlDomInterface|string|null
*/
public function __call($name, $arguments)
{
$name = \strtolower($name);
if (isset(self::$functionAliases[$name])) {
return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
}
throw new \BadMethodCallException('Method does not exist');
}
/**
* Find list of nodes with a CSS selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function find(string $selector, $idx = null)
{
return $this->getHtmlDomParser()->find($selector, $idx);
}
public function getTag(): string
{
return $this->tag;
}
/**
* Returns an array of attributes.
*
* @return string[]|null
*/
public function getAllAttributes()
{
if (
$this->node
&&
$this->node->hasAttributes()
) {
$attributes = [];
foreach ($this->node->attributes ?? [] as $attr) {
$attributes[$attr->name] = HtmlDomParser::putReplacedBackToPreserveHtmlEntities($attr->value);
}
return $attributes;
}
return null;
}
/**
* @return bool
*/
public function hasAttributes(): bool
{
return $this->node && $this->node->hasAttributes();
}
/**
* Return attribute value.
*
* @param string $name
*
* @return string
*/
public function getAttribute(string $name): string
{
if ($this->node instanceof \DOMElement) {
return HtmlDomParser::putReplacedBackToPreserveHtmlEntities(
$this->node->getAttribute($name)
);
}
return '';
}
/**
* Determine if an attribute exists on the element.
*
* @param string $name
*
* @return bool
*/
public function hasAttribute(string $name): bool
{
if (!$this->node instanceof \DOMElement) {
return false;
}
return $this->node->hasAttribute($name);
}
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function html(bool $multiDecodeNewHtmlEntity = false): string
{
return $this->getHtmlDomParser()->html($multiDecodeNewHtmlEntity);
}
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function innerHtml(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string
{
return $this->getHtmlDomParser()->innerHtml($multiDecodeNewHtmlEntity, $putBrokenReplacedBack);
}
/**
* Remove attribute.
*
* @param string $name <p>The name of the html-attribute.</p>
*
* @return SimpleHtmlDomInterface
*/
public function removeAttribute(string $name): SimpleHtmlDomInterface
{
if (\method_exists($this->node, 'removeAttribute')) {
$this->node->removeAttribute($name);
}
return $this;
}
/**
* Remove all attributes
*
* @return SimpleHtmlDomInterface
*/
public function removeAttributes(): SimpleHtmlDomInterface
{
if ($this->hasAttributes()) {
foreach (array_keys((array)$this->getAllAttributes()) as $attribute) {
$this->removeAttribute($attribute);
}
}
return $this;
}
/**
* Replace child node.
*
* @param string $string
* @param bool $putBrokenReplacedBack
*
* @return SimpleHtmlDomInterface
*/
protected function replaceChildWithString(string $string, bool $putBrokenReplacedBack = true): SimpleHtmlDomInterface
{
if (!empty($string)) {
$newDocument = new HtmlDomParser($string);
$tmpDomString = $this->normalizeStringForComparison($newDocument);
$tmpStr = $this->normalizeStringForComparison($string);
if ($tmpDomString !== $tmpStr) {
throw new \RuntimeException(
'Not valid HTML fragment!' . "\n" .
$tmpDomString . "\n" .
$tmpStr
);
}
}
/** @var \DOMNode[] $remove_nodes */
$remove_nodes = [];
if ($this->node->childNodes->length > 0) {
// INFO: We need to fetch the nodes first, before we can delete them, because of missing references in the dom,
// if we delete the elements on the fly.
foreach ($this->node->childNodes as $node) {
$remove_nodes[] = $node;
}
}
foreach ($remove_nodes as $remove_node) {
$this->node->removeChild($remove_node);
}
if (!empty($newDocument)) {
$newDocument = $this->cleanHtmlWrapper($newDocument);
$ownerDocument = $this->node->ownerDocument;
if (
$ownerDocument
&&
$newDocument->getDocument()->documentElement
) {
$newNode = $ownerDocument->importNode($newDocument->getDocument()->documentElement, true);
$this->node->appendChild($newNode);
}
}
return $this;
}
/**
* Replace this node.
*
* @param string $string
*
* @return SimpleHtmlDomInterface
*/
protected function replaceNodeWithString(string $string): SimpleHtmlDomInterface
{
if (empty($string)) {
if ($this->node->parentNode) {
$this->node->parentNode->removeChild($this->node);
}
$this->node = new \DOMText();
return $this;
}
$newDocument = new HtmlDomParser($string);
$tmpDomOuterTextString = $this->normalizeStringForComparison($newDocument);
$tmpStr = $this->normalizeStringForComparison($string);
if ($tmpDomOuterTextString !== $tmpStr) {
throw new \RuntimeException(
'Not valid HTML fragment!' . "\n"
. $tmpDomOuterTextString . "\n" .
$tmpStr
);
}
$newDocument = $this->cleanHtmlWrapper($newDocument, true);
$ownerDocument = $this->node->ownerDocument;
if (
$ownerDocument === null
||
$newDocument->getDocument()->documentElement === null
) {
return $this;
}
$newNode = $ownerDocument->importNode($newDocument->getDocument()->documentElement, true);
$this->node->parentNode->replaceChild($newNode, $this->node);
$this->node = $newNode;
// Remove head element, preserving child nodes. (again)
if (
$this->node->parentNode instanceof \DOMElement
&&
$newDocument->getIsDOMDocumentCreatedWithoutHeadWrapper()
) {
$html = $this->node->parentNode->getElementsByTagName('head')[0];
if (
$html !== null
&&
$this->node->parentNode->ownerDocument
) {
$fragment = $this->node->parentNode->ownerDocument->createDocumentFragment();
/** @var \DOMNode $html */
while ($html->childNodes->length > 0) {
$tmpNode = $html->childNodes->item(0);
if ($tmpNode !== null) {
/** @noinspection UnusedFunctionResultInspection */
$fragment->appendChild($tmpNode);
}
}
$html->parentNode->replaceChild($fragment, $html);
}
}
return $this;
}
/**
* Replace this node with text
*
* @param string $string
*
* @return SimpleHtmlDomInterface
*/
protected function replaceTextWithString($string): SimpleHtmlDomInterface
{
if (empty($string)) {
if ($this->node->parentNode) {
$this->node->parentNode->removeChild($this->node);
}
$this->node = new \DOMText();
return $this;
}
$ownerDocument = $this->node->ownerDocument;
if ($ownerDocument) {
$newElement = $ownerDocument->createTextNode($string);
$newNode = $ownerDocument->importNode($newElement, true);
$this->node->parentNode->replaceChild($newNode, $this->node);
$this->node = $newNode;
}
return $this;
}
/**
* Set attribute value.
*
* @param string $name <p>The name of the html-attribute.</p>
* @param string|null $value <p>Set to NULL or empty string, to remove the attribute.</p>
* @param bool $strictEmptyValueCheck <p>
* $value must be NULL, to remove the attribute,
* so that you can set an empty string as attribute-value e.g. autofocus=""
* </p>
*
* @return SimpleHtmlDomInterface
*/
public function setAttribute(string $name, $value = null, bool $strictEmptyValueCheck = false): SimpleHtmlDomInterface
{
if (
($strictEmptyValueCheck && $value === null)
||
(!$strictEmptyValueCheck && empty($value))
) {
/** @noinspection UnusedFunctionResultInspection */
$this->removeAttribute($name);
} elseif (\method_exists($this->node, 'setAttribute')) {
/** @noinspection UnusedFunctionResultInspection */
$this->node->setAttribute($name, HtmlDomParser::replaceToPreserveHtmlEntities((string) $value));
}
return $this;
}
/**
* Get dom node's plain text.
*
* @return string
*/
public function text(): string
{
return $this->getHtmlDomParser()->fixHtmlOutput($this->node->textContent);
}
/**
* Change the name of a tag in a "DOMNode".
*
* @param \DOMNode $node
* @param string $name
*
* @return \DOMElement|false
* <p>DOMElement a new instance of class DOMElement or false
* if an error occurred.</p>
*/
protected function changeElementName(\DOMNode $node, string $name)
{
$ownerDocument = $node->ownerDocument;
if (!$ownerDocument) {
return false;
}
$newNode = $ownerDocument->createElement($name);
foreach ($node->childNodes as $child) {
$child = $ownerDocument->importNode($child, true);
$newNode->appendChild($child);
}
foreach ($node->attributes ?? [] as $attrName => $attrNode) {
/** @noinspection UnusedFunctionResultInspection */
$newNode->setAttribute($attrName, $attrNode);
}
if ($newNode->ownerDocument) {
/** @noinspection UnusedFunctionResultInspection */
$newNode->ownerDocument->replaceChild($newNode, $node);
}
return $newNode;
}
/**
* Returns children of node.
*
* @param int $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface|null
*/
public function childNodes(int $idx = -1)
{
$nodeList = $this->getIterator();
if ($idx === -1) {
return $nodeList;
}
return $nodeList[$idx] ?? null;
}
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMulti(string $selector): SimpleHtmlDomNodeInterface
{
return $this->getHtmlDomParser()->findMulti($selector);
}
/**
* Find nodes with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMultiOrFalse(string $selector)
{
return $this->getHtmlDomParser()->findMultiOrFalse($selector);
}
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface
*/
public function findOne(string $selector): SimpleHtmlDomInterface
{
return $this->getHtmlDomParser()->findOne($selector);
}
/**
* Find one node with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleHtmlDomInterface
*/
public function findOneOrFalse(string $selector)
{
return $this->getHtmlDomParser()->findOneOrFalse($selector);
}
/**
* Returns the first child of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function firstChild()
{
/** @var \DOMNode|null $node */
$node = $this->node->firstChild;
if ($node === null) {
return null;
}
return new static($node);
}
/**
* Return elements by ".class".
*
* @param string $class
*
* @return SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementByClass(string $class): SimpleHtmlDomNodeInterface
{
return $this->findMulti(".${class}");
}
/**
* Return element by #id.
*
* @param string $id
*
* @return SimpleHtmlDomInterface
*/
public function getElementById(string $id): SimpleHtmlDomInterface
{
return $this->findOne("#${id}");
}
/**
* Return element by tag name.
*
* @param string $name
*
* @return SimpleHtmlDomInterface
*/
public function getElementByTagName(string $name): SimpleHtmlDomInterface
{
if ($this->node instanceof \DOMElement) {
$node = $this->node->getElementsByTagName($name)->item(0);
} else {
$node = null;
}
if ($node === null) {
return new SimpleHtmlDomBlank();
}
return new static($node);
}
/**
* Returns elements by "#id".
*
* @param string $id
* @param int|null $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementsById(string $id, $idx = null)
{
return $this->find("#${id}", $idx);
}
/**
* Returns elements by tag name.
*
* @param string $name
* @param int|null $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementsByTagName(string $name, $idx = null)
{
if ($this->node instanceof \DOMElement) {
$nodesList = $this->node->getElementsByTagName($name);
} else {
$nodesList = [];
}
$elements = new SimpleHtmlDomNode();
foreach ($nodesList as $node) {
$elements[] = new static($node);
}
// return all elements
if ($idx === null) {
if (\count($elements) === 0) {
return new SimpleHtmlDomNodeBlank();
}
return $elements;
}
// handle negative values
if ($idx < 0) {
$idx = \count($elements) + $idx;
}
// return one element
return $elements[$idx] ?? new SimpleHtmlDomBlank();
}
/**
* Create a new "HtmlDomParser"-object from the current context.
*
* @return HtmlDomParser
*/
public function getHtmlDomParser(): HtmlDomParser
{
return new HtmlDomParser($this);
}
/**
* @return \DOMNode
*/
public function getNode(): \DOMNode
{
return $this->node;
}
/**
* Nodes can get partially destroyed in which they're still an
* actual DOM node (such as \DOMElement) but almost their entire
* body is gone, including the `nodeType` attribute.
*
* @return bool true if node has been destroyed
*/
public function isRemoved(): bool
{
return !isset($this->node->nodeType);
}
/**
* Returns the last child of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function lastChild()
{
/** @var \DOMNode|null $node */
$node = $this->node->lastChild;
if ($node === null) {
return null;
}
return new static($node);
}
/**
* Returns the next sibling of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function nextSibling()
{
/** @var \DOMNode|null $node */
$node = $this->node->nextSibling;
if ($node === null) {
return null;
}
return new static($node);
}
/**
* Returns the next sibling of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function nextNonWhitespaceSibling()
{
/** @var \DOMNode|null $node */
$node = $this->node->nextSibling;
while ($node && !\trim($node->textContent)) {
/** @var \DOMNode|null $node */
$node = $node->nextSibling;
}
if ($node === null) {
return null;
}
return new static($node);
}
/**
* Returns the parent of node.
*
* @return SimpleHtmlDomInterface
*/
public function parentNode(): SimpleHtmlDomInterface
{
return new static($this->node->parentNode);
}
/**
* Returns the previous sibling of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function previousSibling()
{
/** @var \DOMNode|null $node */
$node = $this->node->previousSibling;
if ($node === null) {
return null;
}
return new static($node);
}
/**
* Returns the previous sibling of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function previousNonWhitespaceSibling()
{
/** @var \DOMNode|null $node */
$node = $this->node->previousSibling;
while ($node && !\trim($node->textContent)) {
/** @var \DOMNode|null $node */
$node = $node->previousSibling;
}
if ($node === null) {
return null;
}
return new static($node);
}
/**
* @param string|string[]|null $value <p>
* null === get the current input value
* text === set a new input value
* </p>
*
* @return string|string[]|null
*/
public function val($value = null)
{
if ($value === null) {
if (
$this->tag === 'input'
&&
(
$this->getAttribute('type') === 'hidden'
||
$this->getAttribute('type') === 'text'
||
!$this->hasAttribute('type')
)
) {
return $this->getAttribute('value');
}
if (
$this->hasAttribute('checked')
&&
\in_array($this->getAttribute('type'), ['checkbox', 'radio'], true)
) {
return $this->getAttribute('value');
}
if ($this->node->nodeName === 'select') {
$valuesFromDom = [];
$options = $this->getElementsByTagName('option');
if ($options instanceof SimpleHtmlDomNode) {
foreach ($options as $option) {
if ($this->hasAttribute('checked')) {
$valuesFromDom[] = (string) $option->getAttribute('value');
}
}
}
if (\count($valuesFromDom) === 0) {
return null;
}
return $valuesFromDom;
}
if ($this->node->nodeName === 'textarea') {
return $this->node->nodeValue;
}
} else {
/** @noinspection NestedPositiveIfStatementsInspection */
if (\in_array($this->getAttribute('type'), ['checkbox', 'radio'], true)) {
if ($value === $this->getAttribute('value')) {
/** @noinspection UnusedFunctionResultInspection */
$this->setAttribute('checked', 'checked');
} else {
/** @noinspection UnusedFunctionResultInspection */
$this->removeAttribute('checked');
}
} elseif ($this->node instanceof \DOMElement && $this->node->nodeName === 'select') {
foreach ($this->node->getElementsByTagName('option') as $option) {
/** @var \DOMElement $option */
if ($value === $option->getAttribute('value')) {
/** @noinspection UnusedFunctionResultInspection */
$option->setAttribute('selected', 'selected');
} else {
$option->removeAttribute('selected');
}
}
} elseif ($this->node->nodeName === 'input' && \is_string($value)) {
// Set value for input elements
/** @noinspection UnusedFunctionResultInspection */
$this->setAttribute('value', $value);
} elseif ($this->node->nodeName === 'textarea' && \is_string($value)) {
$this->node->nodeValue = $value;
}
}
return null;
}
/**
* @param HtmlDomParser $newDocument
* @param bool $removeExtraHeadTag
*
* @return HtmlDomParser
*/
protected function cleanHtmlWrapper(
HtmlDomParser $newDocument,
$removeExtraHeadTag = false
): HtmlDomParser {
if (
$newDocument->getIsDOMDocumentCreatedWithoutHtml()
||
$newDocument->getIsDOMDocumentCreatedWithoutHtmlWrapper()
) {
// Remove doc-type node.
if ($newDocument->getDocument()->doctype !== null) {
$newDocument->getDocument()->doctype->parentNode->removeChild($newDocument->getDocument()->doctype);
}
// Replace html element, preserving child nodes -> but keep the html wrapper, otherwise we got other problems ...
// so we replace it with "<simpleHtmlDomHtml>" and delete this at the ending.
$item = $newDocument->getDocument()->getElementsByTagName('html')->item(0);
if ($item !== null) {
/** @noinspection UnusedFunctionResultInspection */
$this->changeElementName($item, 'simpleHtmlDomHtml');
}
if ($newDocument->getIsDOMDocumentCreatedWithoutPTagWrapper()) {
// Remove <p>-element, preserving child nodes.
$pElement = $newDocument->getDocument()->getElementsByTagName('p')->item(0);
if ($pElement instanceof \DOMElement) {
$fragment = $newDocument->getDocument()->createDocumentFragment();
while ($pElement->childNodes->length > 0) {
$tmpNode = $pElement->childNodes->item(0);
if ($tmpNode !== null) {
/** @noinspection UnusedFunctionResultInspection */
$fragment->appendChild($tmpNode);
}
}
if ($pElement->parentNode !== null) {
$pElement->parentNode->replaceChild($fragment, $pElement);
}
}
}
// Remove <body>-element, preserving child nodes.
$body = $newDocument->getDocument()->getElementsByTagName('body')->item(0);
if ($body instanceof \DOMElement) {
$fragment = $newDocument->getDocument()->createDocumentFragment();
while ($body->childNodes->length > 0) {
$tmpNode = $body->childNodes->item(0);
if ($tmpNode !== null) {
/** @noinspection UnusedFunctionResultInspection */
$fragment->appendChild($tmpNode);
}
}
if ($body->parentNode !== null) {
$body->parentNode->replaceChild($fragment, $body);
}
}
}
// Remove head element, preserving child nodes.
if (
$removeExtraHeadTag
&&
$this->node->parentNode instanceof \DOMElement
&&
$newDocument->getIsDOMDocumentCreatedWithoutHeadWrapper()
) {
$html = $this->node->parentNode->getElementsByTagName('head')[0] ?? null;
if (
$html !== null
&&
$this->node->parentNode->ownerDocument
) {
$fragment = $this->node->parentNode->ownerDocument->createDocumentFragment();
/** @var \DOMNode $html */
while ($html->childNodes->length > 0) {
$tmpNode = $html->childNodes->item(0);
if ($tmpNode !== null) {
/** @noinspection UnusedFunctionResultInspection */
$fragment->appendChild($tmpNode);
}
}
$html->parentNode->replaceChild($fragment, $html);
}
}
return $newDocument;
}
/**
* Retrieve an external iterator.
*
* @see http://php.net/manual/en/iteratoraggregate.getiterator.php
*
* @return SimpleHtmlDomNode
* <p>
* An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
* </p>
*/
public function getIterator(): SimpleHtmlDomNodeInterface
{
$elements = new SimpleHtmlDomNode();
if ($this->node->hasChildNodes()) {
foreach ($this->node->childNodes as $node) {
$elements[] = new static($node);
}
}
return $elements;
}
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function innerXml(bool $multiDecodeNewHtmlEntity = false): string
{
return $this->getHtmlDomParser()->innerXml($multiDecodeNewHtmlEntity);
}
/**
* Normalize the given input for comparison.
*
* @param HtmlDomParser|string $input
*
* @return string
*/
private function normalizeStringForComparison($input): string
{
if ($input instanceof HtmlDomParser) {
$string = $input->html(false, false);
if ($input->getIsDOMDocumentCreatedWithoutHeadWrapper()) {
/** @noinspection HtmlRequiredTitleElement */
$string = \str_replace(['<head>', '</head>'], '', $string);
}
} else {
$string = (string) $input;
}
return
\urlencode(
\urldecode(
\trim(
\str_replace(
[
' ',
"\n",
"\r",
'/>',
],
[
'',
'',
'',
'>',
],
\strtolower($string)
)
)
)
);
}
/**
* Delete
*
* @return void
*/
public function delete()
{
$this->outertext = '';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace voku\helper;
/**
* @property string $outertext
* <p>Get dom node's outer html (alias for "outerHtml").</p>
* @property string $outerhtml
* <p>Get dom node's outer html.</p>
* @property string $innertext
* <p>Get dom node's inner html (alias for "innerHtml").</p>
* @property string $innerhtml
* <p>Get dom node's inner html.</p>
* @property string $innerhtmlKeep
* <p>Get dom node's inner html + keep fix for broken html.</p>
* @property string $plaintext
* <p>Get dom node's plain text.</p>
* @property string $class
* <p>Get dom node's class attribute.</p>
* @property string $id
* <p>Get dom node's id attribute.</p>
* @property SimpleHtmlAttributes $classList
* <p>Get dom node attributes.</p>
* @property-read string $tag
* <p>Get dom node name.</p>
* @property-read string $attr
* <p>Get dom node attributes.</p>
* @property-read string $text
* <p>Get dom node name.</p>
* @property-read string $html
* <p>Get dom node's outer html.</p>
*
* @method SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface|null children() children($idx = -1)
* <p>Returns children of node.</p>
* @method SimpleHtmlDomInterface|null first_child()
* <p>Returns the first child of node.</p>
* @method SimpleHtmlDomInterface|null last_child()
* <p>Returns the last child of node.</p>
* @method SimpleHtmlDomInterface|null next_sibling()
* <p>Returns the next sibling of node.</p>
* @method SimpleHtmlDomInterface|null prev_sibling()
* <p>Returns the previous sibling of node.</p>
* @method SimpleHtmlDomInterface|null parent()
* <p>Returns the parent of node.</p>
* @method string outerText()
* <p>Get dom node's outer html (alias for "outerHtml()").</p>
* @method string outerHtml()
* <p>Get dom node's outer html.</p>
* @method string innerText()
* <p>Get dom node's inner html (alias for "innerHtml()").</p>
*
* @extends \IteratorAggregate<int, \DOMNode>
*/
interface SimpleHtmlDomInterface extends \IteratorAggregate
{
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
*
* @return SimpleHtmlDomInterface|string|null
*/
public function __call($name, $arguments);
/**
* @param string $name
*
* @return array|string|null
*/
public function __get($name);
/**
* @param string $selector
* @param int $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function __invoke($selector, $idx = null);
/**
* @param string $name
*
* @return bool
*/
public function __isset($name);
/**
* @return string
*/
public function __toString();
/**
* Return the tag of node
*
* @return string
*/
public function getTag():string;
/**
* Returns children of node.
*
* @param int $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface|null
*/
public function childNodes(int $idx = -1);
/**
* Find list of nodes with a CSS selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function find(string $selector, $idx = null);
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMulti(string $selector): SimpleHtmlDomNodeInterface;
/**
* Find nodes with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMultiOrFalse(string $selector);
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface
*/
public function findOne(string $selector): self;
/**
* Find one node with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleHtmlDomInterface
*/
public function findOneOrFalse(string $selector);
/**
* Returns the first child of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function firstChild();
/**
* Returns an array of attributes.
*
* @return string[]|null
*/
public function getAllAttributes();
/**
* Return attribute value.
*
* @param string $name
*
* @return string
*/
public function getAttribute(string $name): string;
/**
* Return elements by ".class".
*
* @param string $class
*
* @return SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementByClass(string $class);
/**
* Return element by "#id".
*
* @param string $id
*
* @return SimpleHtmlDomInterface
*/
public function getElementById(string $id): self;
/**
* Return element by tag name.
*
* @param string $name
*
* @return SimpleHtmlDomInterface
*/
public function getElementByTagName(string $name): self;
/**
* Returns elements by "#id".
*
* @param string $id
* @param int|null $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementsById(string $id, $idx = null);
/**
* Returns elements by tag name.
*
* @param string $name
* @param int|null $idx
*
* @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementsByTagName(string $name, $idx = null);
/**
* Create a new "HtmlDomParser"-object from the current context.
*
* @return HtmlDomParser
*/
public function getHtmlDomParser(): HtmlDomParser;
/**
* Retrieve an external iterator.
*
* @see http://php.net/manual/en/iteratoraggregate.getiterator.php
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
* <p>
* An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
* </p>
*/
public function getIterator(): SimpleHtmlDomNodeInterface;
/**
* @return \DOMNode
*/
public function getNode(): \DOMNode;
/**
* Determine if an attribute exists on the element.
*
* @param string $name
*
* @return bool
*/
public function hasAttribute(string $name): bool;
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function html(bool $multiDecodeNewHtmlEntity = false): string;
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function innerHtml(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string;
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function innerXml(bool $multiDecodeNewHtmlEntity = false): string;
/**
* Nodes can get partially destroyed in which they're still an
* actual DOM node (such as \DOMElement) but almost their entire
* body is gone, including the `nodeType` attribute.
*
* @return bool true if node has been destroyed
*/
public function isRemoved(): bool;
/**
* Returns the last child of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function lastChild();
/**
* Returns the next sibling of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function nextSibling();
/**
* Returns the next sibling of node, and it will ignore whitespace elements.
*
* @return SimpleHtmlDomInterface|null
*/
public function nextNonWhitespaceSibling();
/**
* Returns the previous sibling of node, and it will ignore whitespace elements.
*
* @return SimpleHtmlDomInterface|null
*/
public function previousNonWhitespaceSibling();
/**
* Returns the parent of node.
*
* @return SimpleHtmlDomInterface
*/
public function parentNode(): self;
/**
* Returns the previous sibling of node.
*
* @return SimpleHtmlDomInterface|null
*/
public function previousSibling();
/**
* Remove attribute.
*
* @param string $name <p>The name of the html-attribute.</p>
*
* @return SimpleHtmlDomInterface
*/
public function removeAttribute(string $name): self;
/**
* Set attribute value.
*
* @param string $name <p>The name of the html-attribute.</p>
* @param string|null $value <p>Set to NULL or empty string, to remove the attribute.</p>
* @param bool $strictEmptyValueCheck </p>
* $value must be NULL, to remove the attribute,
* so that you can set an empty string as attribute-value e.g. autofocus=""
* </p>
*
* @return SimpleHtmlDomInterface
*/
public function setAttribute(string $name, $value = null, bool $strictEmptyValueCheck = false): self;
/**
* Remove all attributes
*
* @return SimpleHtmlDomInterface
*/
public function removeAttributes(): self;
/**
* Get dom node's plain text.
*
* @return string
*/
public function text(): string;
/**
* @param string|string[]|null $value <p>
* null === get the current input value
* text === set a new input value
* </p>
*
* @return string|string[]|null
*/
public function val($value = null);
/**
* Delete
*
* @return mixed
*/
public function delete();
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* @noinspection PhpHierarchyChecksInspection
*
* {@inheritdoc}
*
* @implements \IteratorAggregate<int, \DOMNode>
*/
class SimpleXmlDomBlank extends AbstractSimpleXmlDom implements \IteratorAggregate, SimpleXmlDomInterface
{
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
*
* @return SimpleXmlDomInterface|string|null
*/
public function __call($name, $arguments)
{
$name = \strtolower($name);
if (isset(self::$functionAliases[$name])) {
return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
}
throw new \BadMethodCallException('Method does not exist');
}
/**
* Find list of nodes with a CSS or xPath selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function find(string $selector, $idx = null)
{
return new SimpleXmlDomNodeBlank();
}
/**
* Returns an array of attributes.
*
* @return null
*/
public function getAllAttributes()
{
return null;
}
/**
* @return bool
*/
public function hasAttributes(): bool
{
return false;
}
/**
* Return attribute value.
*
* @param string $name
*
* @return string
*/
public function getAttribute(string $name): string
{
return '';
}
/**
* Determine if an attribute exists on the element.
*
* @param string $name
*
* @return bool
*/
public function hasAttribute(string $name): bool
{
return false;
}
/**
* Get dom node's inner xml.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function innerXml(bool $multiDecodeNewHtmlEntity = false): string
{
return '';
}
/**
* Remove attribute.
*
* @param string $name <p>The name of the html-attribute.</p>
*
* @return SimpleXmlDomInterface
*/
public function removeAttribute(string $name): SimpleXmlDomInterface
{
return $this;
}
/**
* @param string $string
* @param bool $putBrokenReplacedBack
*
* @return SimpleXmlDomInterface
*/
protected function replaceChildWithString(string $string, bool $putBrokenReplacedBack = true): SimpleXmlDomInterface
{
return new static();
}
/**
* @param string $string
*
* @return SimpleXmlDomInterface
*/
protected function replaceNodeWithString(string $string): SimpleXmlDomInterface
{
return new static();
}
/**
* @param string $string
*
* @return SimpleXmlDomInterface
*/
protected function replaceTextWithString($string): SimpleXmlDomInterface
{
return new static();
}
/**
* Set attribute value.
*
* @param string $name <p>The name of the html-attribute.</p>
* @param string|null $value <p>Set to NULL or empty string, to remove the attribute.</p>
* @param bool $strictEmptyValueCheck </p>
* $value must be NULL, to remove the attribute,
* so that you can set an empty string as attribute-value e.g. autofocus=""
* </p>
*
* @return SimpleXmlDomInterface
*/
public function setAttribute(string $name, $value = null, bool $strictEmptyValueCheck = false): SimpleXmlDomInterface
{
return $this;
}
/**
* Get dom node's plain text.
*
* @return string
*/
public function text(): string
{
return '';
}
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function xml(bool $multiDecodeNewHtmlEntity = false): string
{
return '';
}
/**
* Returns children of node.
*
* @param int $idx
*
* @return null
*/
public function childNodes(int $idx = -1)
{
return null;
}
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMulti(string $selector): SimpleXmlDomNodeInterface
{
return new SimpleXmlDomNodeBlank();
}
/**
* Find nodes with a CSS or xPath selector or false, if no element is found.
*
* @param string $selector
*
* @return false
*/
public function findMultiOrFalse(string $selector)
{
return false;
}
/**
* Find one node with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface
*/
public function findOne(string $selector): SimpleXmlDomInterface
{
return new static();
}
/**
* Find one node with a CSS or xPath selector or false, if no element is found.
*
* @param string $selector
*
* @return false
*/
public function findOneOrFalse(string $selector)
{
return false;
}
/**
* Returns the first child of node.
*
* @return null
*/
public function firstChild()
{
return null;
}
/**
* Return elements by ".class".
*
* @param string $class
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementByClass(string $class): SimpleXmlDomNodeInterface
{
return new SimpleXmlDomNodeBlank();
}
/**
* Return element by #id.
*
* @param string $id
*
* @return SimpleXmlDomInterface
*/
public function getElementById(string $id): SimpleXmlDomInterface
{
return new static();
}
/**
* Return element by tag name.
*
* @param string $name
*
* @return SimpleXmlDomInterface
*/
public function getElementByTagName(string $name): SimpleXmlDomInterface
{
return new static();
}
/**
* Returns elements by "#id".
*
* @param string $id
* @param int|null $idx
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementsById(string $id, $idx = null)
{
return new SimpleXmlDomNodeBlank();
}
/**
* Returns elements by tag name.
*
* @param string $name
* @param int|null $idx
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementsByTagName(string $name, $idx = null)
{
return new SimpleXmlDomNodeBlank();
}
/**
* @return \DOMNode
*/
public function getNode(): \DOMNode
{
return new \DOMNode();
}
/**
* Create a new "XmlDomParser"-object from the current context.
*
* @return XmlDomParser
*/
public function getXmlDomParser(): XmlDomParser
{
return new XmlDomParser($this);
}
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function innerHtml(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string
{
return '';
}
/**
* Nodes can get partially destroyed in which they're still an
* actual DOM node (such as \DOMElement) but almost their entire
* body is gone, including the `nodeType` attribute.
*
* @return bool true if node has been destroyed
*/
public function isRemoved(): bool
{
return true;
}
/**
* Returns the last child of node.
*
* @return null
*/
public function lastChild()
{
return null;
}
/**
* Returns the next sibling of node.
*
* @return null
*/
public function nextSibling()
{
return null;
}
/**
* Returns the next sibling of node.
*
* @return null
*/
public function nextNonWhitespaceSibling()
{
return null;
}
/**
* Returns the parent of node.
*
* @return SimpleXmlDomInterface
*/
public function parentNode(): SimpleXmlDomInterface
{
return new static();
}
/**
* Returns the previous sibling of node.
*
* @return null
*/
public function previousSibling()
{
return null;
}
/**
* Returns the previous sibling of node.
*
* @return null
*/
public function previousNonWhitespaceSibling()
{
return null;
}
/**
* @param string|string[]|null $value <p>
* null === get the current input value
* text === set a new input value
* </p>
*
* @return string|string[]|null
*/
public function val($value = null)
{
return null;
}
/**
* Retrieve an external iterator.
*
* @see http://php.net/manual/en/iteratoraggregate.getiterator.php
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
* <p>
* An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
* </p>
*/
public function getIterator(): SimpleXmlDomNodeInterface
{
return new SimpleXmlDomNodeBlank();
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* @noinspection PhpHierarchyChecksInspection
*
* {@inheritdoc}
*
* @implements \IteratorAggregate<int, \DOMNode>
*/
class SimpleXmlDom extends AbstractSimpleXmlDom implements \IteratorAggregate, SimpleXmlDomInterface
{
/**
* @param \DOMElement|\DOMNode $node
*/
public function __construct(\DOMNode $node)
{
$this->node = $node;
}
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
*
* @return SimpleXmlDomInterface|string|null
*/
public function __call($name, $arguments)
{
$name = \strtolower($name);
if (isset(self::$functionAliases[$name])) {
return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
}
throw new \BadMethodCallException('Method does not exist');
}
/**
* Find list of nodes with a CSS or xPath selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function find(string $selector, $idx = null)
{
return $this->getXmlDomParser()->find($selector, $idx);
}
/**
* Returns an array of attributes.
*
* @return string[]|null
*/
public function getAllAttributes()
{
if (
$this->node
&&
$this->node->hasAttributes()
) {
$attributes = [];
foreach ($this->node->attributes ?? [] as $attr) {
$attributes[$attr->name] = XmlDomParser::putReplacedBackToPreserveHtmlEntities($attr->value);
}
return $attributes;
}
return null;
}
/**
* @return bool
*/
public function hasAttributes(): bool
{
return $this->node->hasAttributes();
}
/**
* Return attribute value.
*
* @param string $name
*
* @return string
*/
public function getAttribute(string $name): string
{
if ($this->node instanceof \DOMElement) {
return XmlDomParser::putReplacedBackToPreserveHtmlEntities(
$this->node->getAttribute($name)
);
}
return '';
}
/**
* Determine if an attribute exists on the element.
*
* @param string $name
*
* @return bool
*/
public function hasAttribute(string $name): bool
{
if (!$this->node instanceof \DOMElement) {
return false;
}
return $this->node->hasAttribute($name);
}
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function innerXml(bool $multiDecodeNewHtmlEntity = false): string
{
return $this->getXmlDomParser()->innerXml($multiDecodeNewHtmlEntity);
}
/**
* Remove attribute.
*
* @param string $name <p>The name of the html-attribute.</p>
*
* @return SimpleXmlDomInterface
*/
public function removeAttribute(string $name): SimpleXmlDomInterface
{
if (\method_exists($this->node, 'removeAttribute')) {
$this->node->removeAttribute($name);
}
return $this;
}
/**
* Replace child node.
*
* @param string $string
* @param bool $putBrokenReplacedBack
*
* @return SimpleXmlDomInterface
*/
protected function replaceChildWithString(string $string, bool $putBrokenReplacedBack = true): SimpleXmlDomInterface
{
if (!empty($string)) {
$newDocument = new XmlDomParser($string);
$tmpDomString = $this->normalizeStringForComparision($newDocument);
$tmpStr = $this->normalizeStringForComparision($string);
if ($tmpDomString !== $tmpStr) {
throw new \RuntimeException(
'Not valid XML fragment!' . "\n" .
$tmpDomString . "\n" .
$tmpStr
);
}
}
/** @var \DOMNode[] $remove_nodes */
$remove_nodes = [];
if ($this->node->childNodes->length > 0) {
// INFO: We need to fetch the nodes first, before we can delete them, because of missing references in the dom,
// if we delete the elements on the fly.
foreach ($this->node->childNodes as $node) {
$remove_nodes[] = $node;
}
}
foreach ($remove_nodes as $remove_node) {
$this->node->removeChild($remove_node);
}
if (!empty($newDocument)) {
$ownerDocument = $this->node->ownerDocument;
if (
$ownerDocument
&&
$newDocument->getDocument()->documentElement
) {
$newNode = $ownerDocument->importNode($newDocument->getDocument()->documentElement, true);
/** @noinspection UnusedFunctionResultInspection */
$this->node->appendChild($newNode);
}
}
return $this;
}
/**
* Replace this node.
*
* @param string $string
*
* @return SimpleXmlDomInterface
*/
protected function replaceNodeWithString(string $string): SimpleXmlDomInterface
{
if (empty($string)) {
if ($this->node->parentNode) {
$this->node->parentNode->removeChild($this->node);
}
return $this;
}
$newDocument = new XmlDomParser($string);
$tmpDomOuterTextString = $this->normalizeStringForComparision($newDocument);
$tmpStr = $this->normalizeStringForComparision($string);
if ($tmpDomOuterTextString !== $tmpStr) {
throw new \RuntimeException(
'Not valid XML fragment!' . "\n"
. $tmpDomOuterTextString . "\n" .
$tmpStr
);
}
$ownerDocument = $this->node->ownerDocument;
if (
$ownerDocument === null
||
$newDocument->getDocument()->documentElement === null
) {
return $this;
}
$newNode = $ownerDocument->importNode($newDocument->getDocument()->documentElement, true);
$this->node->parentNode->replaceChild($newNode, $this->node);
$this->node = $newNode;
return $this;
}
/**
* Replace this node with text
*
* @param string $string
*
* @return SimpleXmlDomInterface
*/
protected function replaceTextWithString($string): SimpleXmlDomInterface
{
if (empty($string)) {
if ($this->node->parentNode) {
$this->node->parentNode->removeChild($this->node);
}
return $this;
}
$ownerDocument = $this->node->ownerDocument;
if ($ownerDocument) {
$newElement = $ownerDocument->createTextNode($string);
$newNode = $ownerDocument->importNode($newElement, true);
$this->node->parentNode->replaceChild($newNode, $this->node);
$this->node = $newNode;
}
return $this;
}
/**
* Set attribute value.
*
* @param string $name <p>The name of the html-attribute.</p>
* @param string|null $value <p>Set to NULL or empty string, to remove the attribute.</p>
* @param bool $strictEmptyValueCheck </p>
* $value must be NULL, to remove the attribute,
* so that you can set an empty string as attribute-value e.g. autofocus=""
* </p>
*
* @return SimpleXmlDomInterface
*/
public function setAttribute(string $name, $value = null, bool $strictEmptyValueCheck = false): SimpleXmlDomInterface
{
if (
($strictEmptyValueCheck && $value === null)
||
(!$strictEmptyValueCheck && empty($value))
) {
/** @noinspection UnusedFunctionResultInspection */
$this->removeAttribute($name);
} elseif (\method_exists($this->node, 'setAttribute')) {
/** @noinspection UnusedFunctionResultInspection */
$this->node->setAttribute($name, HtmlDomParser::replaceToPreserveHtmlEntities((string) $value));
}
return $this;
}
/**
* Get dom node's plain text.
*
* @return string
*/
public function text(): string
{
return $this->getXmlDomParser()->fixHtmlOutput($this->node->textContent);
}
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function xml(bool $multiDecodeNewHtmlEntity = false): string
{
return $this->getXmlDomParser()->xml($multiDecodeNewHtmlEntity, false);
}
/**
* Change the name of a tag in a "DOMNode".
*
* @param \DOMNode $node
* @param string $name
*
* @return \DOMElement|false
* <p>DOMElement a new instance of class DOMElement or false
* if an error occured.</p>
*/
protected function changeElementName(\DOMNode $node, string $name)
{
$ownerDocument = $node->ownerDocument;
if (!$ownerDocument) {
return false;
}
$newNode = $ownerDocument->createElement($name);
foreach ($node->childNodes as $child) {
$child = $ownerDocument->importNode($child, true);
$newNode->appendChild($child);
}
foreach ($node->attributes ?? [] as $attrName => $attrNode) {
/** @noinspection UnusedFunctionResultInspection */
$newNode->setAttribute($attrName, $attrNode);
}
if ($newNode->ownerDocument) {
/** @noinspection UnusedFunctionResultInspection */
$newNode->ownerDocument->replaceChild($newNode, $node);
}
return $newNode;
}
/**
* Returns children of node.
*
* @param int $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>|null
*/
public function childNodes(int $idx = -1)
{
$nodeList = $this->getIterator();
if ($idx === -1) {
return $nodeList;
}
return $nodeList[$idx] ?? null;
}
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMulti(string $selector): SimpleXmlDomNodeInterface
{
return $this->getXmlDomParser()->findMulti($selector);
}
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return false|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMultiOrFalse(string $selector)
{
return $this->getXmlDomParser()->findMultiOrFalse($selector);
}
/**
* Find one node with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface
*/
public function findOne(string $selector): SimpleXmlDomInterface
{
return $this->getXmlDomParser()->findOne($selector);
}
/**
* Find one node with a CSS or xPath selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleXmlDomInterface
*/
public function findOneOrFalse(string $selector)
{
return $this->getXmlDomParser()->findOneOrFalse($selector);
}
/**
* Returns the first child of node.
*
* @return SimpleXmlDomInterface|null
*/
public function firstChild()
{
/** @var \DOMNode|null $node */
$node = $this->node->firstChild;
if ($node === null) {
return null;
}
return new static($node);
}
/**
* Return elements by ".class".
*
* @param string $class
*
* @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementByClass(string $class): SimpleXmlDomNodeInterface
{
return $this->findMulti(".${class}");
}
/**
* Return element by #id.
*
* @param string $id
*
* @return SimpleXmlDomInterface
*/
public function getElementById(string $id): SimpleXmlDomInterface
{
return $this->findOne("#${id}");
}
/**
* Return element by tag name.
*
* @param string $name
*
* @return SimpleXmlDomInterface
*/
public function getElementByTagName(string $name): SimpleXmlDomInterface
{
if ($this->node instanceof \DOMElement) {
$node = $this->node->getElementsByTagName($name)->item(0);
} else {
$node = null;
}
if ($node === null) {
return new SimpleXmlDomBlank();
}
return new static($node);
}
/**
* Returns elements by "#id".
*
* @param string $id
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementsById(string $id, $idx = null)
{
return $this->find("#${id}", $idx);
}
/**
* Returns elements by tag name.
*
* @param string $name
* @param int|null $idx
*
* @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function getElementsByTagName(string $name, $idx = null)
{
if ($this->node instanceof \DOMElement) {
$nodesList = $this->node->getElementsByTagName($name);
} else {
$nodesList = [];
}
$elements = new SimpleXmlDomNode();
foreach ($nodesList as $node) {
$elements[] = new static($node);
}
// return all elements
if ($idx === null) {
if (\count($elements) === 0) {
return new SimpleXmlDomNodeBlank();
}
return $elements;
}
// handle negative values
if ($idx < 0) {
$idx = \count($elements) + $idx;
}
// return one element
return $elements[$idx] ?? new SimpleXmlDomBlank();
}
/**
* @return \DOMNode
*/
public function getNode(): \DOMNode
{
return $this->node;
}
/**
* Create a new "XmlDomParser"-object from the current context.
*
* @return XmlDomParser
*/
public function getXmlDomParser(): XmlDomParser
{
return new XmlDomParser($this);
}
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function innerHtml(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string
{
return $this->getXmlDomParser()->innerHtml($multiDecodeNewHtmlEntity, $putBrokenReplacedBack);
}
/**
* Nodes can get partially destroyed in which they're still an
* actual DOM node (such as \DOMElement) but almost their entire
* body is gone, including the `nodeType` attribute.
*
* @return bool true if node has been destroyed
*/
public function isRemoved(): bool
{
return !isset($this->node->nodeType);
}
/**
* Returns the last child of node.
*
* @return SimpleXmlDomInterface|null
*/
public function lastChild()
{
/** @var \DOMNode|null $node */
$node = $this->node->lastChild;
if ($node === null) {
return null;
}
return new static($node);
}
/**
* Returns the next sibling of node.
*
* @return SimpleXmlDomInterface|null
*/
public function nextSibling()
{
/** @var \DOMNode|null $node */
$node = $this->node->nextSibling;
if ($node === null) {
return null;
}
return new static($node);
}
/**
* Returns the next sibling of node.
*
* @return SimpleXmlDomInterface|null
*/
public function nextNonWhitespaceSibling()
{
/** @var \DOMNode|null $node */
$node = $this->node->nextSibling;
if ($node === null) {
return null;
}
while ($node && !\trim($node->textContent)) {
/** @var \DOMNode|null $node */
$node = $node->nextSibling;
}
return new static($node);
}
/**
* Returns the parent of node.
*
* @return SimpleXmlDomInterface
*/
public function parentNode(): SimpleXmlDomInterface
{
return new static($this->node->parentNode);
}
/**
* Returns the previous sibling of node.
*
* @return SimpleXmlDomInterface|null
*/
public function previousSibling()
{
/** @var \DOMNode|null $node */
$node = $this->node->previousSibling;
if ($node === null) {
return null;
}
return new static($node);
}
/**
* Returns the previous sibling of node.
*
* @return SimpleXmlDomInterface|null
*/
public function previousNonWhitespaceSibling()
{
/** @var \DOMNode|null $node */
$node = $this->node->previousSibling;
while ($node && !\trim($node->textContent)) {
/** @var \DOMNode|null $node */
$node = $node->previousSibling;
}
if ($node === null) {
return null;
}
return new static($node);
}
/**
* @param string|string[]|null $value <p>
* null === get the current input value
* text === set a new input value
* </p>
*
* @return string|string[]|null
*/
public function val($value = null)
{
if ($value === null) {
if (
$this->tag === 'input'
&&
(
$this->getAttribute('type') === 'hidden'
||
$this->getAttribute('type') === 'text'
||
!$this->hasAttribute('type')
)
) {
return $this->getAttribute('value');
}
if (
$this->hasAttribute('checked')
&&
\in_array($this->getAttribute('type'), ['checkbox', 'radio'], true)
) {
return $this->getAttribute('value');
}
if ($this->node->nodeName === 'select') {
$valuesFromDom = [];
$options = $this->getElementsByTagName('option');
if ($options instanceof SimpleXmlDomNode) {
foreach ($options as $option) {
if ($this->hasAttribute('checked')) {
$valuesFromDom[] = (string) $option->getAttribute('value');
}
}
}
if (\count($valuesFromDom) === 0) {
return null;
}
return $valuesFromDom;
}
if ($this->node->nodeName === 'textarea') {
return $this->node->nodeValue;
}
} else {
/** @noinspection NestedPositiveIfStatementsInspection */
if (\in_array($this->getAttribute('type'), ['checkbox', 'radio'], true)) {
if ($value === $this->getAttribute('value')) {
/** @noinspection UnusedFunctionResultInspection */
$this->setAttribute('checked', 'checked');
} else {
/** @noinspection UnusedFunctionResultInspection */
$this->removeAttribute('checked');
}
} elseif ($this->node instanceof \DOMElement && $this->node->nodeName === 'select') {
foreach ($this->node->getElementsByTagName('option') as $option) {
/** @var \DOMElement $option */
if ($value === $option->getAttribute('value')) {
/** @noinspection UnusedFunctionResultInspection */
$option->setAttribute('selected', 'selected');
} else {
$option->removeAttribute('selected');
}
}
} elseif ($this->node->nodeName === 'input' && \is_string($value)) {
// Set value for input elements
/** @noinspection UnusedFunctionResultInspection */
$this->setAttribute('value', $value);
} elseif ($this->node->nodeName === 'textarea' && \is_string($value)) {
$this->node->nodeValue = $value;
}
}
return null;
}
/**
* Retrieve an external iterator.
*
* @see http://php.net/manual/en/iteratoraggregate.getiterator.php
*
* @return SimpleXmlDomNode
* <p>
* An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
* </p>
*/
public function getIterator(): SimpleXmlDomNodeInterface
{
$elements = new SimpleXmlDomNode();
if ($this->node->hasChildNodes()) {
foreach ($this->node->childNodes as $node) {
$elements[] = new static($node);
}
}
return $elements;
}
/**
* Normalize the given input for comparision.
*
* @param string|XmlDomParser $input
*
* @return string
*/
private function normalizeStringForComparision($input): string
{
if ($input instanceof XmlDomParser) {
$string = $input->html(false, false);
} else {
$string = (string) $input;
}
return
\urlencode(
\urldecode(
\trim(
\str_replace(
[
' ',
"\n",
"\r",
'/>',
],
[
'',
'',
'',
'>',
],
\strtolower($string)
)
)
)
);
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* @noinspection PhpHierarchyChecksInspection
*
* {@inheritdoc}
*
* @implements \IteratorAggregate<int, \DOMNode>
*/
class SimpleHtmlDomBlank extends AbstractSimpleHtmlDom implements \IteratorAggregate, SimpleHtmlDomInterface
{
/**
* @param string $name
* @param array $arguments
*
* @throws \BadMethodCallException
*
* @return SimpleHtmlDomInterface|string|null
*/
public function __call($name, $arguments)
{
$name = \strtolower($name);
if (isset(self::$functionAliases[$name])) {
return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
}
throw new \BadMethodCallException('Method does not exist');
}
/**
* Find list of nodes with a CSS selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function find(string $selector, $idx = null)
{
return new SimpleHtmlDomNodeBlank();
}
public function getTag(): string
{
return '';
}
/**
* Returns an array of attributes.
*
* @return null
*/
public function getAllAttributes()
{
return null;
}
/**
* @return bool
*/
public function hasAttributes(): bool
{
return false;
}
/**
* Return attribute value.
*
* @param string $name
*
* @return string
*/
public function getAttribute(string $name): string
{
return '';
}
/**
* Determine if an attribute exists on the element.
*
* @param string $name
*
* @return bool
*/
public function hasAttribute(string $name): bool
{
return false;
}
/**
* Get dom node's outer html.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function html(bool $multiDecodeNewHtmlEntity = false): string
{
return '';
}
/**
* Get dom node's inner html.
*
* @param bool $multiDecodeNewHtmlEntity
* @param bool $putBrokenReplacedBack
*
* @return string
*/
public function innerHtml(bool $multiDecodeNewHtmlEntity = false, bool $putBrokenReplacedBack = true): string
{
return '';
}
/**
* Remove attribute.
*
* @param string $name <p>The name of the html-attribute.</p>
*
* @return SimpleHtmlDomInterface
*/
public function removeAttribute(string $name): SimpleHtmlDomInterface
{
return $this;
}
/**
* Remove all attributes
*
* @return SimpleHtmlDomBlank
*/
public function removeAttributes(): SimpleHtmlDomInterface
{
return $this;
}
/**
* @param string $string
* @param bool $putBrokenReplacedBack
*
* @return SimpleHtmlDomInterface
*/
protected function replaceChildWithString(string $string, bool $putBrokenReplacedBack = true): SimpleHtmlDomInterface
{
return new static();
}
/**
* @param string $string
*
* @return SimpleHtmlDomInterface
*/
protected function replaceNodeWithString(string $string): SimpleHtmlDomInterface
{
return new static();
}
/**
* @param string $string
*
* @return SimpleHtmlDomInterface
*/
protected function replaceTextWithString($string): SimpleHtmlDomInterface
{
return new static();
}
/**
* Set attribute value.
*
* @param string $name <p>The name of the html-attribute.</p>
* @param string|null $value <p>Set to NULL or empty string, to remove the attribute.</p>
* @param bool $strictEmptyValueCheck </p>
* $value must be NULL, to remove the attribute,
* so that you can set an empty string as attribute-value e.g. autofocus=""
* </p>
*
* @return SimpleHtmlDomInterface
*/
public function setAttribute(string $name, $value = null, bool $strictEmptyValueCheck = false): SimpleHtmlDomInterface
{
return $this;
}
/**
* Get dom node's plain text.
*
* @return string
*/
public function text(): string
{
return '';
}
/**
* Returns children of node.
*
* @param int $idx
*
* @return null
*/
public function childNodes(int $idx = -1)
{
return null;
}
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMulti(string $selector): SimpleHtmlDomNodeInterface
{
return new SimpleHtmlDomNodeBlank();
}
/**
* Find nodes with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false
*/
public function findMultiOrFalse(string $selector)
{
return false;
}
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface
*/
public function findOne(string $selector): SimpleHtmlDomInterface
{
return new static();
}
/**
* Find one node with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false
*/
public function findOneOrFalse(string $selector)
{
return false;
}
/**
* Returns the first child of node.
*
* @return null
*/
public function firstChild()
{
return null;
}
/**
* Return elements by ".class".
*
* @param string $class
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementByClass(string $class): SimpleHtmlDomNodeInterface
{
return new SimpleHtmlDomNodeBlank();
}
/**
* Return element by #id.
*
* @param string $id
*
* @return SimpleHtmlDomInterface
*/
public function getElementById(string $id): SimpleHtmlDomInterface
{
return new static();
}
/**
* Return element by tag name.
*
* @param string $name
*
* @return SimpleHtmlDomInterface
*/
public function getElementByTagName(string $name): SimpleHtmlDomInterface
{
return new static();
}
/**
* Returns elements by "#id".
*
* @param string $id
* @param int|null $idx
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementsById(string $id, $idx = null)
{
return new SimpleHtmlDomNodeBlank();
}
/**
* Returns elements by tag name.
*
* @param string $name
* @param int|null $idx
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function getElementsByTagName(string $name, $idx = null)
{
return new SimpleHtmlDomNodeBlank();
}
/**
* Create a new "HtmlDomParser"-object from the current context.
*
* @return HtmlDomParser
*/
public function getHtmlDomParser(): HtmlDomParser
{
return new HtmlDomParser($this);
}
/**
* @return \DOMNode
*/
public function getNode(): \DOMNode
{
return new \DOMNode();
}
/**
* Nodes can get partially destroyed in which they're still an
* actual DOM node (such as \DOMElement) but almost their entire
* body is gone, including the `nodeType` attribute.
*
* @return bool true if node has been destroyed
*/
public function isRemoved(): bool
{
return true;
}
/**
* Returns the last child of node.
*
* @return null
*/
public function lastChild()
{
return null;
}
/**
* Returns the next sibling of node.
*
* @return null
*/
public function nextSibling()
{
return null;
}
/**
* Returns the next sibling of node.
*
* @return null
*/
public function nextNonWhitespaceSibling()
{
return null;
}
/**
* Returns the previous sibling of node.
*
* @return null
*/
public function previousNonWhitespaceSibling()
{
return null;
}
/**
* Returns the parent of node.
*
* @return SimpleHtmlDomInterface
*/
public function parentNode(): SimpleHtmlDomInterface
{
return new static();
}
/**
* Returns the previous sibling of node.
*
* @return null
*/
public function previousSibling()
{
return null;
}
/**
* @param string|string[]|null $value <p>
* null === get the current input value
* text === set a new input value
* </p>
*
* @return string|string[]|null
*/
public function val($value = null)
{
return null;
}
/**
* Retrieve an external iterator.
*
* @see http://php.net/manual/en/iteratoraggregate.getiterator.php
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
* <p>
* An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
* </p>
*/
public function getIterator(): SimpleHtmlDomNodeInterface
{
return new SimpleHtmlDomNodeBlank();
}
/**
* Get dom node's inner xml.
*
* @param bool $multiDecodeNewHtmlEntity
*
* @return string
*/
public function innerXml(bool $multiDecodeNewHtmlEntity = false): string
{
return '';
}
/**
* Delete
*
* @return void
*/
public function delete()
{
$this->outertext='';
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* {@inheritdoc}
*/
class SimpleHtmlDomNode extends AbstractSimpleHtmlDomNode implements SimpleHtmlDomNodeInterface
{
/**
* Find list of nodes with a CSS selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>|SimpleHtmlDomNodeInterface[]|null
*/
public function find(string $selector, $idx = null)
{
// init
$elements = new static();
foreach ($this as $node) {
\assert($node instanceof SimpleHtmlDomInterface);
foreach ($node->find($selector) as $res) {
$elements[] = $res;
}
}
// return all elements
if ($idx === null) {
if (\count($elements) === 0) {
return new SimpleHtmlDomNodeBlank();
}
return $elements;
}
// handle negative values
if ($idx < 0) {
$idx = \count($elements) + $idx;
}
// return one element
return $elements[$idx] ?? null;
}
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMulti(string $selector): SimpleHtmlDomNodeInterface
{
return $this->find($selector, null);
}
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return false|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMultiOrFalse(string $selector)
{
$return = $this->find($selector, null);
if ($return instanceof SimpleHtmlDomNodeBlank) {
return false;
}
return $return;
}
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findOne(string $selector)
{
$return = $this->find($selector, 0);
return $return ?? new SimpleHtmlDomNodeBlank();
}
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return false|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findOneOrFalse(string $selector)
{
$return = $this->find($selector, 0);
return $return ?? false;
}
/**
* Get html of elements.
*
* @return string[]
*/
public function innerHtml(): array
{
// init
$html = [];
foreach ($this as $node) {
$html[] = $node->outertext;
}
return $html;
}
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function innertext()
{
return $this->innerHtml();
}
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function outertext()
{
return $this->innerHtml();
}
/**
* Get plain text.
*
* @return string[]
*/
public function text(): array
{
// init
$text = [];
foreach ($this as $node) {
$text[] = $node->plaintext;
}
return $text;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
declare(strict_types=1);
namespace voku\helper;
/**
* {@inheritdoc}
*/
class SimpleXmlDomNode extends AbstractSimpleXmlDomNode implements SimpleXmlDomNodeInterface
{
/**
* Find list of nodes with a CSS or xPath selector.
*
* @param string $selector
* @param int|null $idx
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>|SimpleXmlDomNodeInterface[]|null
*/
public function find(string $selector, $idx = null)
{
// init
$elements = new static();
foreach ($this as $node) {
\assert($node instanceof SimpleXmlDomInterface);
foreach ($node->find($selector) as $res) {
$elements->append($res);
}
}
// return all elements
if ($idx === null) {
if (\count($elements) === 0) {
return new SimpleXmlDomNodeBlank();
}
return $elements;
}
// handle negative values
if ($idx < 0) {
$idx = \count($elements) + $idx;
}
// return one element
return $elements[$idx] ?? null;
}
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMulti(string $selector): SimpleXmlDomNodeInterface
{
return $this->find($selector, null);
}
/**
* Find nodes with a CSS or xPath selector.
*
* @param string $selector
*
* @return false|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findMultiOrFalse(string $selector)
{
$return = $this->find($selector, null);
if ($return instanceof SimpleXmlDomNodeBlank) {
return false;
}
return $return;
}
/**
* Find one node with a CSS or xPath selector.
*
* @param string $selector
*
* @return SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findOne(string $selector)
{
$return = $this->find($selector, 0);
return $return ?? new SimpleXmlDomNodeBlank();
}
/**
* Find one node with a CSS or xPath selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleXmlDomNodeInterface<SimpleXmlDomInterface>
*/
public function findOneOrFalse(string $selector)
{
$return = $this->find($selector, 0);
return $return ?? false;
}
/**
* Get html of elements.
*
* @return string[]
*/
public function innerHtml(): array
{
// init
$html = [];
foreach ($this as $node) {
$html[] = $node->outertext;
}
return $html;
}
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function innertext()
{
return $this->innerHtml();
}
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function outertext()
{
return $this->innerHtml();
}
/**
* Get plain text.
*
* @return string[]
*/
public function text(): array
{
// init
$text = [];
foreach ($this as $node) {
$text[] = $node->plaintext;
}
return $text;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
namespace voku\helper;
/**
* @property-read int $length
* <p>The list items count.</p>
* @property-read string[] $outertext
* <p>Get dom node's outer html.</p>
* @property-read string[] $plaintext
* <p>Get dom node's plain text.</p>
*
* @extends \IteratorAggregate<int, SimpleHtmlDomInterface>
*/
interface SimpleHtmlDomNodeInterface extends \IteratorAggregate
{
/**
* @param string $name
*
* @return array|null
*/
public function __get($name);
/**
* @param string $selector
* @param int $idx
*
* @return SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>|SimpleHtmlDomNodeInterface[]|null
*/
public function __invoke($selector, $idx = null);
/**
* @return string
*/
public function __toString();
/**
* Get the number of items in this dom node.
*
* @return int
*/
public function count();
/**
* Find list of nodes with a CSS selector.
*
* @param string $selector
* @param int $idx
*
* @return SimpleHtmlDomNode|SimpleHtmlDomNode[]|null
*/
public function find(string $selector, $idx = null);
/**
* Find nodes with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMulti(string $selector): self;
/**
* Find nodes with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface<SimpleHtmlDomInterface>
*/
public function findMultiOrFalse(string $selector);
/**
* Find one node with a CSS selector.
*
* @param string $selector
*
* @return SimpleHtmlDomNodeInterface
*/
public function findOne(string $selector);
/**
* Find one node with a CSS selector or false, if no element is found.
*
* @param string $selector
*
* @return false|SimpleHtmlDomNodeInterface
*/
public function findOneOrFalse(string $selector);
/**
* Get html of elements.
*
* @return string[]
*/
public function innerHtml(): array;
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function innertext();
/**
* alias for "$this->innerHtml()" (added for compatibly-reasons with v1.x)
*
* @return string[]
*/
public function outertext();
/**
* Get plain text.
*
* @return string[]
*/
public function text(): array;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/vendor/autoload.php';
$readmeText = (new \voku\PhpReadmeHelper\GenerateApi())->generate(
__DIR__ . '/../src/',
__DIR__ . '/docs/api.md',
[
\voku\helper\DomParserInterface::class,
\voku\helper\SimpleHtmlDomNodeInterface::class,
\voku\helper\SimpleHtmlDomInterface::class
]
);
file_put_contents(__DIR__ . '/../README_API.md', $readmeText);
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
# :scroll: Simple Html Dom Parser for PHP
### DomParser API
%__functions_index__voku\helper\DomParserInterface__%
### SimpleHtmlDomNode (group of dom elements) API
%__functions_index__voku\helper\SimpleHtmlDomNodeInterface__%
### SimpleHtmlDom (single dom element) API
%__functions_index__voku\helper\SimpleHtmlDomInterface__%
---
%__functions_list__voku\helper\DomParserInterface__%
%__functions_list__voku\helper\SimpleHtmlDomNodeInterface__%
%__functions_list__voku\helper\SimpleHtmlDomInterface__%
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php return array(
'root' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => '6804d07fa55219cf34683a7d22cbd1c727592b87',
'name' => '__root__',
'dev' => true,
),
'versions' => array(
'__root__' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => '6804d07fa55219cf34683a7d22cbd1c727592b87',
'dev_requirement' => false,
),
'google/protobuf' => array(
'pretty_version' => 'v3.21.11',
'version' => '3.21.11.0',
'type' => 'library',
'install_path' => __DIR__ . '/../google/protobuf',
'aliases' => array(),
'reference' => '8f8dc48540aed2c96eb3febcc4816f1321f66b85',
'dev_requirement' => false,
),
'rehike/spfphp' => array(
'pretty_version' => '1.0.5',
'version' => '1.0.5.0',
'type' => 'library',
'install_path' => __DIR__ . '/../rehike/spfphp',
'aliases' => array(),
'reference' => '3959d0cb24a123da3b223f5df0cb339b3d46aa93',
'dev_requirement' => false,
),
'symfony/css-selector' => array(
'pretty_version' => 'v5.4.3',
'version' => '5.4.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/css-selector',
'aliases' => array(),
'reference' => 'b0a190285cd95cb019237851205b8140ef6e368e',
'dev_requirement' => false,
),
'symfony/polyfill-ctype' => array(
'pretty_version' => 'v1.26.0',
'version' => '1.26.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-ctype',
'aliases' => array(),
'reference' => '6fd1b9a79f6e3cf65f9e679b23af304cd9e010d4',
'dev_requirement' => false,
),
'symfony/polyfill-mbstring' => array(
'pretty_version' => 'v1.26.0',
'version' => '1.26.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-mbstring',
'aliases' => array(),
'reference' => '9344f9cb97f3b19424af1a21a3b0e75b0a7d8d7e',
'dev_requirement' => false,
),
'symfony/polyfill-php80' => array(
'pretty_version' => 'v1.26.0',
'version' => '1.26.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-php80',
'aliases' => array(),
'reference' => 'cfa0ae98841b9e461207c13ab093d76b0fa7bace',
'dev_requirement' => false,
),
'twig/twig' => array(
'pretty_version' => 'v3.4.3',
'version' => '3.4.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../twig/twig',
'aliases' => array(),
'reference' => 'c38fd6b0b7f370c198db91ffd02e23b517426b58',
'dev_requirement' => false,
),
'yukiscoffee/simple_html_dom' => array(
'pretty_version' => '4.8.9',
'version' => '4.8.9.0',
'type' => 'library',
'install_path' => __DIR__ . '/../yukiscoffee/simple_html_dom',
'aliases' => array(),
'reference' => 'cb6ec2e501f359be70af9c02148aff4e6705763e',
'dev_requirement' => false,
),
),
);
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <[email protected]>
* Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*/
class InstalledVersions
{
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}|array{}|null
*/
private static $installed;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']);
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints($constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
$installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = require __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
$installed[] = self::$installed;
return $installed;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
);
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 70205)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.5". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
trigger_error(
'Composer detected issues in your platform: ' . implode(' ', $issues),
E_USER_ERROR
);
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit14befcaebdd16793d803391aa69e5f63
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInit14befcaebdd16793d803391aa69e5f63', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(\dirname(__FILE__)));
spl_autoload_unregister(array('ComposerAutoloaderInit14befcaebdd16793d803391aa69e5f63', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit14befcaebdd16793d803391aa69e5f63::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit14befcaebdd16793d803391aa69e5f63::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire14befcaebdd16793d803391aa69e5f63($fileIdentifier, $file);
}
return $loader;
}
}
/**
* @param string $fileIdentifier
* @param string $file
* @return void
*/
function composerRequire14befcaebdd16793d803391aa69e5f63($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
require $file;
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <[email protected]>
* Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <[email protected]>
* @author Jordi Boggiano <[email protected]>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var ?string */
private $vendorDir;
// PSR-4
/**
* @var array[]
* @psalm-var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, array<int, string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* @var array[]
* @psalm-var array<string, array<string, string[]>>
*/
private $prefixesPsr0 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var string[]
* @psalm-var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var bool[]
* @psalm-var array<string, bool>
*/
private $missingClasses = array();
/** @var ?string */
private $apcuPrefix;
/**
* @var self[]
*/
private static $registeredLoaders = array();
/**
* @param ?string $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
}
/**
* @return string[]
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array[]
* @psalm-return array<string, array<int, string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return string[] Array of classname => path
* @psalm-return array<string, string>
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param string[] $classMap Class to filename map
* @psalm-param array<string, string> $classMap
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param string[]|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param string[]|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param string[]|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param string[]|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders indexed by their corresponding vendor directories.
*
* @return self[]
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
* @private
*/
function includeFile($file)
{
include $file;
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit14befcaebdd16793d803391aa69e5f63
{
public static $files = array (
'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
);
public static $prefixLengthsPsr4 = array (
'v' =>
array (
'voku\\helper\\' => 12,
),
'T' =>
array (
'Twig\\' => 5,
),
'S' =>
array (
'Symfony\\Polyfill\\Php80\\' => 23,
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Polyfill\\Ctype\\' => 23,
'Symfony\\Component\\CssSelector\\' => 30,
'SpfPhp\\' => 7,
),
'G' =>
array (
'Google\\Protobuf\\' => 16,
'GPBMetadata\\Google\\Protobuf\\' => 28,
),
);
public static $prefixDirsPsr4 = array (
'voku\\helper\\' =>
array (
0 => __DIR__ . '/..' . '/yukiscoffee/simple_html_dom/src/voku/helper',
),
'Twig\\' =>
array (
0 => __DIR__ . '/..' . '/twig/twig/src',
),
'Symfony\\Polyfill\\Php80\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-php80',
),
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Polyfill\\Ctype\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
),
'Symfony\\Component\\CssSelector\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/css-selector',
),
'SpfPhp\\' =>
array (
0 => __DIR__ . '/..' . '/rehike/spfphp/src',
),
'Google\\Protobuf\\' =>
array (
0 => __DIR__ . '/..' . '/google/protobuf/src/Google/Protobuf',
),
'GPBMetadata\\Google\\Protobuf\\' =>
array (
0 => __DIR__ . '/..' . '/google/protobuf/src/GPBMetadata/Google/Protobuf',
),
);
public static $classMap = array (
'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit14befcaebdd16793d803391aa69e5f63::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit14befcaebdd16793d803391aa69e5f63::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit14befcaebdd16793d803391aa69e5f63::$classMap;
}, null, ClassLoader::class);
}
}
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'voku\\helper\\' => array($vendorDir . '/yukiscoffee/simple_html_dom/src/voku/helper'),
'Twig\\' => array($vendorDir . '/twig/twig/src'),
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'Symfony\\Component\\CssSelector\\' => array($vendorDir . '/symfony/css-selector'),
'SpfPhp\\' => array($vendorDir . '/rehike/spfphp/src'),
'Google\\Protobuf\\' => array($vendorDir . '/google/protobuf/src/Google/Protobuf'),
'GPBMetadata\\Google\\Protobuf\\' => array($vendorDir . '/google/protobuf/src/GPBMetadata/Google/Protobuf'),
);
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
# protobuf-php
This repository contains only PHP files to support Composer installation. This repository is a mirror of [protobuf](https://github.com/protocolbuffers/protobuf). Any support requests, bug reports, or development contributions should be directed to that project. To install protobuf for PHP, please see https://github.com/protocolbuffers/protobuf/tree/master/php
| {
"repo_name": "Rehike/Rehike",
"stars": "81",
"repo_language": "PHP",
"file_name": "config.php",
"mime_type": "text/x-php"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.