Skip to content

Commit

Permalink
minor #3934 Use PHP 8 features (fabpot)
Browse files Browse the repository at this point in the history
This PR was squashed before being merged into the 4.x branch.

Discussion
----------

Use PHP 8 features

Commits
-------

be67e96 Use str_* when possible
0668be9 Use arrow function
06d9fc6 Use is_countable()
89d37cd Use get_debug_type()
308aa5b Remove usage of list()
a42eba6 Use match instead of switch
fed8dd1 Use ::class
  • Loading branch information
fabpot committed Dec 9, 2023
2 parents 67c8798 + be67e96 commit aa4b59c
Show file tree
Hide file tree
Showing 25 changed files with 100 additions and 158 deletions.
2 changes: 1 addition & 1 deletion extra/html-extra/HtmlExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public function dataUri(string $data, string $mime = null, array $parameters = [
$repr .= ';'.$key.'='.rawurlencode($value);
}

if (0 === strpos($mime, 'text/')) {
if (str_starts_with($mime, 'text/')) {
$repr .= ','.rawurlencode($data);
} else {
$repr .= ';base64,'.base64_encode($data);
Expand Down
4 changes: 2 additions & 2 deletions src/Error/Error.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,11 @@ private function guessTemplateInfo(): void
$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']);
$currentClass = $trace['object']::class;
$isEmbedContainer = null === $templateClass ? false : str_starts_with($templateClass, $currentClass);
if (null === $this->name || ($this->name == $trace['object']->getTemplateName() && !$isEmbedContainer)) {
$template = $trace['object'];
$templateClass = \get_class($trace['object']);
$templateClass = $trace['object']::class;
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/ExpressionParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,7 @@ public function parseArguments($namedArguments = false, $definition = false, $al
$name = null;
if ($namedArguments && $token = $stream->nextIf(/* Token::OPERATOR_TYPE */ 8, '=')) {
if (!$value instanceof NameExpression) {
throw new SyntaxError(sprintf('A parameter name must be a string, "%s" given.', \get_class($value)), $token->getLine(), $stream->getSourceContext());
throw new SyntaxError(sprintf('A parameter name must be a string, "%s" given.', $value::class), $token->getLine(), $stream->getSourceContext());
}
$name = $value->getAttribute('name');

Expand Down Expand Up @@ -704,7 +704,7 @@ private function parseNotTestExpression(Node $node): NotUnary
private function parseTestExpression(Node $node): TestExpression
{
$stream = $this->parser->getStream();
list($name, $test) = $this->getTest($node->getTemplateLine());
[$name, $test] = $this->getTest($node->getTemplateLine());

$class = $this->getTestNodeClass($test);
$arguments = null;
Expand Down
40 changes: 18 additions & 22 deletions src/Extension/CoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ function twig_date_converter(Environment $env, $date = null, $timezone = null)
function twig_replace_filter($str, $from)
{
if (!is_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)));
throw new RuntimeError(sprintf('The "replace" filter expects an array or "Traversable" as replace values, got "%s".', get_debug_type($from)));
}

return strtr($str ?? '', twig_to_array($from));
Expand Down Expand Up @@ -1054,16 +1054,12 @@ function twig_trim_filter($string, $characterMask = null, $side = 'both')
$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".');
}
return match ($side) {
'both' => trim($string ?? '', $characterMask),
'left' => ltrim($string ?? '', $characterMask),
'right' => rtrim($string ?? '', $characterMask),
default => throw new RuntimeError('Trimming side must be "left", "right" or "both".'),
};
}

/**
Expand Down Expand Up @@ -1123,7 +1119,7 @@ function twig_length_filter(Environment $env, $thing)
return mb_strlen($thing, $env->getCharset());
}

if ($thing instanceof \Countable || \is_array($thing) || $thing instanceof \SimpleXMLElement) {
if (is_countable($thing) || $thing instanceof \SimpleXMLElement) {
return \count($thing);
}

Expand Down Expand Up @@ -1384,10 +1380,10 @@ function twig_constant($constant, $object = null)
{
if (null !== $object) {
if ('class' === $constant) {
return \get_class($object);
return $object::class;
}

$constant = \get_class($object).'::'.$constant;
$constant = $object::class.'::'.$constant;
}

if (!\defined($constant)) {
Expand All @@ -1412,7 +1408,7 @@ function twig_constant_is_defined($constant, $object = null)
return true;
}

$constant = \get_class($object).'::'.$constant;
$constant = $object::class.'::'.$constant;
}

return \defined($constant);
Expand All @@ -1430,7 +1426,7 @@ function twig_constant_is_defined($constant, $object = null)
function twig_array_batch($items, $size, $fill = null, $preserveKeys = true)
{
if (!is_iterable($items)) {
throw new RuntimeError(sprintf('The "batch" filter expects an array or "Traversable", got "%s".', \is_object($items) ? \get_class($items) : \gettype($items)));
throw new RuntimeError(sprintf('The "batch" filter expects an array or "Traversable", got "%s".', get_debug_type($items)));
}

$size = ceil($size);
Expand Down Expand Up @@ -1492,9 +1488,9 @@ function twig_get_attribute(Environment $env, Source $source, $object, $item, ar
}

if ($object instanceof ArrayAccess) {
$message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.', $arrayItem, \get_class($object));
$message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.', $arrayItem, $object::class);
} 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));
$message = sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.', $item, $object::class);
} elseif (\is_array($object)) {
if (empty($object)) {
$message = sprintf('Key "%s" does not exist as the array is empty.', $arrayItem);
Expand Down Expand Up @@ -1558,14 +1554,14 @@ function twig_get_attribute(Environment $env, Source $source, $object, $item, ar

static $cache = [];

$class = \get_class($object);
$class = $object::class;

// 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);
$lcMethods = array_map(fn($value) => strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), $methods);
$classCache = [];
foreach ($methods as $i => $method) {
$classCache[$method] = $method;
Expand Down Expand Up @@ -1674,7 +1670,7 @@ function twig_array_column($array, $name, $index = null): array
function twig_array_filter(Environment $env, $array, $arrow)
{
if (!is_iterable($array)) {
throw new RuntimeError(sprintf('The "filter" filter expects an array or "Traversable", got "%s".', \is_object($array) ? \get_class($array) : \gettype($array)));
throw new RuntimeError(sprintf('The "filter" filter expects an array or "Traversable", got "%s".', get_debug_type($array)));
}

twig_check_arrow_in_sandbox($env, $arrow, 'filter', 'filter');
Expand Down Expand Up @@ -1743,7 +1739,7 @@ function twig_array_every(Environment $env, $array, $arrow)

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()) {
if (!$arrow instanceof Closure && $env->hasExtension(\Twig\Extension\SandboxExtension::class) && $env->getExtension(\Twig\Extension\SandboxExtension::class)->isSandboxed()) {
throw new RuntimeError(sprintf('The callable passed to the "%s" %s must be a Closure in sandbox mode.', $thing, $type));
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Extension/EscaperExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ function twig_escape_filter(Environment $env, $string, $strategy = 'html', $char
if (!\is_string($string)) {
if (\is_object($string) && method_exists($string, '__toString')) {
if ($autoescape) {
$c = \get_class($string);
$c = $string::class;
$ext = $env->getExtension(EscaperExtension::class);
if (!isset($ext->safeClasses[$c])) {
$ext->safeClasses[$c] = [];
Expand Down
8 changes: 4 additions & 4 deletions src/ExtensionSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public function getLastModified(): int

public function addExtension(ExtensionInterface $extension): void
{
$class = \get_class($extension);
$class = $extension::class;

if ($this->initialized) {
throw new \LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $class));
Expand Down Expand Up @@ -330,7 +330,7 @@ public function getGlobals(): array

$extGlobals = $extension->getGlobals();
if (!\is_array($extGlobals)) {
throw new \UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', \get_class($extension)));
throw new \UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', $extension::class));
}

$globals = array_merge($globals, $extGlobals);
Expand Down Expand Up @@ -466,11 +466,11 @@ private function initExtension(ExtensionInterface $extension): void
// operators
if ($operators = $extension->getOperators()) {
if (!\is_array($operators)) {
throw new \InvalidArgumentException(sprintf('"%s::getOperators()" must return an array with operators, got "%s".', \get_class($extension), \is_object($operators) ? \get_class($operators) : \gettype($operators).(\is_resource($operators) ? '' : '#'.$operators)));
throw new \InvalidArgumentException(sprintf('"%s::getOperators()" must return an array with operators, got "%s".', $extension::class, \is_object($operators) ? $operators::class : \gettype($operators).(\is_resource($operators) ? '' : '#'.$operators)));
}

if (2 !== \count($operators)) {
throw new \InvalidArgumentException(sprintf('"%s::getOperators()" must return an array of 2 elements, got %d.', \get_class($extension), \count($operators)));
throw new \InvalidArgumentException(sprintf('"%s::getOperators()" must return an array of 2 elements, got %d.', $extension::class, \count($operators)));
}

$this->unaryOperators = array_merge($this->unaryOperators, $operators[0]);
Expand Down
19 changes: 6 additions & 13 deletions src/FileExtensionEscapingStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,11 @@ public static function guess(string $name)

$extension = pathinfo($name, \PATHINFO_EXTENSION);

switch ($extension) {
case 'js':
return 'js';

case 'css':
return 'css';

case 'txt':
return false;

default:
return 'html';
}
return match ($extension) {
'js' => 'js',
'css' => 'css',
'txt' => false,
default => 'html',
};
}
}
6 changes: 3 additions & 3 deletions src/Lexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public function tokenize(Source $source): TokenStream
$this->pushToken(/* Token::EOF_TYPE */ -1);

if (!empty($this->brackets)) {
list($expect, $lineno) = array_pop($this->brackets);
[$expect, $lineno] = array_pop($this->brackets);
throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source);
}

Expand Down Expand Up @@ -355,7 +355,7 @@ private function lexExpression(): void
throw new SyntaxError(sprintf('Unexpected "%s".', $this->code[$this->cursor]), $this->lineno, $this->source);
}

list($expect, $lineno) = array_pop($this->brackets);
[$expect, $lineno] = array_pop($this->brackets);
if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) {
throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source);
}
Expand Down Expand Up @@ -425,7 +425,7 @@ private function lexString(): void
$this->pushToken(/* Token::STRING_TYPE */ 7, stripcslashes($match[0]));
$this->moveCursor($match[0]);
} elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) {
list($expect, $lineno) = array_pop($this->brackets);
[$expect, $lineno] = array_pop($this->brackets);
if ('"' != $this->code[$this->cursor]) {
throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Loader/ChainLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public function getCacheKey(string $name): string
try {
return $loader->getCacheKey($name);
} catch (LoaderError $e) {
$exceptions[] = \get_class($loader).': '.$e->getMessage();
$exceptions[] = $loader::class.': '.$e->getMessage();
}
}

Expand All @@ -110,7 +110,7 @@ public function isFresh(string $name, int $time): bool
try {
return $loader->isFresh($name, $time);
} catch (LoaderError $e) {
$exceptions[] = \get_class($loader).': '.$e->getMessage();
$exceptions[] = $loader::class.': '.$e->getMessage();
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Loader/FilesystemLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ protected function findTemplate(string $name, bool $throw = true)
}

try {
list($namespace, $shortname) = $this->parseName($name);
[$namespace, $shortname] = $this->parseName($name);

$this->validateName($shortname);
} catch (LoaderError $e) {
Expand Down
4 changes: 2 additions & 2 deletions src/Node/Expression/CallExpression.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ protected function compileCallable(Compiler $compiler)
$compiler->raw(sprintf('$this->env->getRuntime(\'%s\')->%s', $callable[0], $callable[1]));
}
} elseif (\is_array($callable) && $callable[0] instanceof ExtensionInterface) {
$class = \get_class($callable[0]);
$class = $callable[0]::class;
if (!$compiler->getEnvironment()->hasExtension($class)) {
// Compile a non-optimized call to trigger a \Twig\Error\RuntimeError, which cannot be a compile-time error
$compiler->raw(sprintf('$this->env->getExtension(\'%s\')', $class));
Expand Down Expand Up @@ -140,7 +140,7 @@ protected function getArguments($callable, $arguments)
throw new \LogicException($message);
}

list($callableParameters, $isPhpVariadic) = $this->getCallableParameters($callable, $isVariadic);
[$callableParameters, $isPhpVariadic] = $this->getCallableParameters($callable, $isVariadic);
$arguments = [];
$names = [];
$missingArguments = [];
Expand Down
2 changes: 1 addition & 1 deletion src/Node/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function __construct(array $nodes = [], array $attributes = [], int $line
{
foreach ($nodes as $name => $node) {
if (!$node instanceof self) {
throw new \InvalidArgumentException(sprintf('Using "%s" for the value of node "%s" of "%s" is not supported. You must pass a \Twig\Node\Node instance.', \is_object($node) ? \get_class($node) : (null === $node ? 'null' : \gettype($node)), $name, static::class));
throw new \InvalidArgumentException(sprintf('Using "%s" for the value of node "%s" of "%s" is not supported. You must pass a \Twig\Node\Node instance.', \is_object($node) ? $node::class : (null === $node ? 'null' : \gettype($node)), $name, static::class));
}
}
$this->nodes = $nodes;
Expand Down
2 changes: 1 addition & 1 deletion src/NodeVisitor/EscaperNodeVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ private function escapePrintNode(PrintNode $node, Environment $env, string $type
return $node;
}

$class = \get_class($node);
$class = $node::class;

return new $class($this->getEscaperFilter($type, $expression), $node->getTemplateLine());
}
Expand Down
2 changes: 1 addition & 1 deletion src/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ private function filterBodyNodes(Node $node, bool $nested = false): ?Node

// here, $nested means "being at the root level of a child template"
// we need to discard the wrapping "Node" for the "body" node
$nested = $nested || Node::class !== \get_class($node);
$nested = $nested || Node::class !== $node::class;
foreach ($node as $k => $n) {
if (null !== $n && null === $this->filterBodyNodes($n, $nested)) {
$node->removeNode($k);
Expand Down
2 changes: 1 addition & 1 deletion src/Profiler/Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,6 @@ public function __serialize(): array
*/
public function __unserialize(array $data): void
{
list($this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles) = $data;
[$this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles] = $data;
}
}
6 changes: 3 additions & 3 deletions src/Sandbox/SecurityPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function setAllowedMethods(array $methods): void
{
$this->allowedMethods = [];
foreach ($methods as $class => $m) {
$this->allowedMethods[$class] = array_map(function ($value) { return strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); }, \is_array($m) ? $m : [$m]);
$this->allowedMethods[$class] = array_map(fn($value) => strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), \is_array($m) ? $m : [$m]);
}
}

Expand Down Expand Up @@ -101,7 +101,7 @@ public function checkMethodAllowed($obj, $method): void
}

if (!$allowed) {
$class = \get_class($obj);
$class = $obj::class;
throw new SecurityNotAllowedMethodError(sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, $class), $class, $method);
}
}
Expand All @@ -117,7 +117,7 @@ public function checkPropertyAllowed($obj, $property): void
}

if (!$allowed) {
$class = \get_class($obj);
$class = $obj::class;
throw new SecurityNotAllowedPropertyError(sprintf('Calling "%s" property on a "%s" object is not allowed.', $property, $class), $class, $property);
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/Template.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ public function renderParentBlock($name, array $context, array $blocks = [])
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
ob_start(fn() => '');
}
$this->displayParentBlock($name, $context, $blocks);

Expand All @@ -238,7 +238,7 @@ public function renderBlock($name, array $context, array $blocks = [], $useBlock
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
ob_start(fn() => '');
}
$this->displayBlock($name, $context, $blocks, $useBlocks);

Expand Down Expand Up @@ -373,7 +373,7 @@ public function render(array $context)
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
ob_start(fn() => '');
}
try {
$this->display($context);
Expand Down
2 changes: 1 addition & 1 deletion src/TemplateWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public function renderBlock(string $name, array $context = []): string
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
ob_start(fn() => '');
}
try {
$this->template->displayBlock($name, $context);
Expand Down
Loading

0 comments on commit aa4b59c

Please sign in to comment.