Skip to content

Commit

Permalink
minor #4108 Optimize sprintf() calls for PHP 8.4 (fabpot)
Browse files Browse the repository at this point in the history
This PR was merged into the 3.x branch.

Discussion
----------

Optimize sprintf() calls for PHP 8.4

Commits
-------

b63bde3 Optimize sprintf() calls for PHP 8.4
  • Loading branch information
fabpot committed Jun 21, 2024
2 parents ca39534 + b63bde3 commit 1d8458d
Show file tree
Hide file tree
Showing 59 changed files with 239 additions and 238 deletions.
5 changes: 3 additions & 2 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
'heredoc_to_nowdoc' => false,
'ordered_imports' => true,
'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'],
'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'all'],
])
// TODO: Remove once the "compiler_optimized" set includes "sprintf"
'native_function_invocation' => ['include' => ['@compiler_optimized', 'sprintf'], 'scope' => 'all'],
])
->setRiskyAllowed(true)
->setFinder((new PhpCsFixer\Finder())->in(__DIR__))
;
4 changes: 2 additions & 2 deletions doc/_build/build.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@
file_put_contents($htmlFilePath, str_replace('href="assets/', 'href="/assets/', $htmlContents));
}

$io->success(sprintf('The Twig docs were successfully built at %s', realpath($outputDir)));
$io->success(\sprintf('The Twig docs were successfully built at %s', realpath($outputDir)));
} else {
$io->error(sprintf("There were some errors while building the docs:\n\n%s\n", $result->getErrorTrace()));
$io->error(\sprintf("There were some errors while building the docs:\n\n%s\n", $result->getErrorTrace()));
$io->newLine();
$io->comment('Tip: you can add the -v, -vv or -vvv flags to this command to get debug information.');

Expand Down
6 changes: 3 additions & 3 deletions extra/cache-extra/TokenParser/CacheTokenParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,18 @@ public function parse(Token $token): Node
switch ($k) {
case 'ttl':
if (1 !== \count($args)) {
throw new SyntaxError(sprintf('The "ttl" modifier takes exactly one argument (%d given).', \count($args)), $stream->getCurrent()->getLine(), $stream->getSourceContext());
throw new SyntaxError(\sprintf('The "ttl" modifier takes exactly one argument (%d given).', \count($args)), $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$ttl = $args->getNode('0');
break;
case 'tags':
if (1 !== \count($args)) {
throw new SyntaxError(sprintf('The "tags" modifier takes exactly one argument (%d given).', \count($args)), $stream->getCurrent()->getLine(), $stream->getSourceContext());
throw new SyntaxError(\sprintf('The "tags" modifier takes exactly one argument (%d given).', \count($args)), $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$tags = $args->getNode('0');
break;
default:
throw new SyntaxError(sprintf('Unknown "%s" configuration.', $k), $stream->getCurrent()->getLine(), $stream->getSourceContext());
throw new SyntaxError(\sprintf('Unknown "%s" configuration.', $k), $stream->getCurrent()->getLine(), $stream->getSourceContext());
}
}

Expand Down
4 changes: 2 additions & 2 deletions extra/html-extra/HtmlExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,15 @@ public static function htmlClasses(...$args): string
} elseif (\is_array($arg)) {
foreach ($arg as $class => $condition) {
if (!\is_string($class)) {
throw new RuntimeError(sprintf('The html_classes function argument %d (key %d) should be a string, got "%s".', $i, $class, \gettype($class)));
throw new RuntimeError(\sprintf('The html_classes function argument %d (key %d) should be a string, got "%s".', $i, $class, \gettype($class)));
}
if (!$condition) {
continue;
}
$classes[] = $class;
}
} else {
throw new RuntimeError(sprintf('The html_classes function argument %d should be either a string or an array, got "%s".', $i, \gettype($arg)));
throw new RuntimeError(\sprintf('The html_classes function argument %d should be either a string or an array, got "%s".', $i, \gettype($arg)));
}
}

Expand Down
14 changes: 7 additions & 7 deletions extra/intl-extra/IntlExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ public function formatCurrency($amount, string $currency, array $attrs = [], ?st
public function formatNumber($number, array $attrs = [], string $style = 'decimal', string $type = 'default', ?string $locale = null): string
{
if (!isset(self::NUMBER_TYPES[$type])) {
throw new RuntimeError(sprintf('The type "%s" does not exist, known types are: "%s".', $type, implode('", "', array_keys(self::NUMBER_TYPES))));
throw new RuntimeError(\sprintf('The type "%s" does not exist, known types are: "%s".', $type, implode('", "', array_keys(self::NUMBER_TYPES))));
}

$formatter = $this->createNumberFormatter($locale, $style, $attrs);
Expand Down Expand Up @@ -409,11 +409,11 @@ private function createDateFormatter(?string $locale, ?string $dateFormat, ?stri
$dateFormats = self::availableDateFormats();

if (null !== $dateFormat && !isset($dateFormats[$dateFormat])) {
throw new RuntimeError(sprintf('The date format "%s" does not exist, known formats are: "%s".', $dateFormat, implode('", "', array_keys($dateFormats))));
throw new RuntimeError(\sprintf('The date format "%s" does not exist, known formats are: "%s".', $dateFormat, implode('", "', array_keys($dateFormats))));
}

if (null !== $timeFormat && !isset(self::TIME_FORMATS[$timeFormat])) {
throw new RuntimeError(sprintf('The time format "%s" does not exist, known formats are: "%s".', $timeFormat, implode('", "', array_keys(self::TIME_FORMATS))));
throw new RuntimeError(\sprintf('The time format "%s" does not exist, known formats are: "%s".', $timeFormat, implode('", "', array_keys(self::TIME_FORMATS))));
}

if (null === $locale) {
Expand Down Expand Up @@ -450,7 +450,7 @@ private function createDateFormatter(?string $locale, ?string $dateFormat, ?stri
private function createNumberFormatter(?string $locale, string $style, array $attrs = []): \NumberFormatter
{
if (!isset(self::NUMBER_STYLES[$style])) {
throw new RuntimeError(sprintf('The style "%s" does not exist, known styles are: "%s".', $style, implode('", "', array_keys(self::NUMBER_STYLES))));
throw new RuntimeError(\sprintf('The style "%s" does not exist, known styles are: "%s".', $style, implode('", "', array_keys(self::NUMBER_STYLES))));
}

if (null === $locale) {
Expand Down Expand Up @@ -492,18 +492,18 @@ private function createNumberFormatter(?string $locale, string $style, array $at

foreach ($attrs as $name => $value) {
if (!isset(self::NUMBER_ATTRIBUTES[$name])) {
throw new RuntimeError(sprintf('The number formatter attribute "%s" does not exist, known attributes are: "%s".', $name, implode('", "', array_keys(self::NUMBER_ATTRIBUTES))));
throw new RuntimeError(\sprintf('The number formatter attribute "%s" does not exist, known attributes are: "%s".', $name, implode('", "', array_keys(self::NUMBER_ATTRIBUTES))));
}

if ('rounding_mode' === $name) {
if (!isset(self::NUMBER_ROUNDING_ATTRIBUTES[$value])) {
throw new RuntimeError(sprintf('The number formatter rounding mode "%s" does not exist, known modes are: "%s".', $value, implode('", "', array_keys(self::NUMBER_ROUNDING_ATTRIBUTES))));
throw new RuntimeError(\sprintf('The number formatter rounding mode "%s" does not exist, known modes are: "%s".', $value, implode('", "', array_keys(self::NUMBER_ROUNDING_ATTRIBUTES))));
}

$value = self::NUMBER_ROUNDING_ATTRIBUTES[$value];
} elseif ('padding_position' === $name) {
if (!isset(self::NUMBER_PADDING_ATTRIBUTES[$value])) {
throw new RuntimeError(sprintf('The number formatter padding position "%s" does not exist, known positions are: "%s".', $value, implode('", "', array_keys(self::NUMBER_PADDING_ATTRIBUTES))));
throw new RuntimeError(\sprintf('The number formatter padding position "%s" does not exist, known positions are: "%s".', $value, implode('", "', array_keys(self::NUMBER_PADDING_ATTRIBUTES))));
}

$value = self::NUMBER_PADDING_ATTRIBUTES[$value];
Expand Down
6 changes: 3 additions & 3 deletions extra/twig-extra-bundle/MissingExtensionSuggestor.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ final class MissingExtensionSuggestor
public function suggestFilter(string $name): bool
{
if ($filter = Extensions::getFilter($name)) {
throw new SyntaxError(sprintf('The "%s" filter is part of the %s, which is not installed/enabled; try running "composer require %s".', $name, $filter[0], $filter[1]));
throw new SyntaxError(\sprintf('The "%s" filter is part of the %s, which is not installed/enabled; try running "composer require %s".', $name, $filter[0], $filter[1]));
}

return false;
Expand All @@ -27,7 +27,7 @@ public function suggestFilter(string $name): bool
public function suggestFunction(string $name): bool
{
if ($function = Extensions::getFunction($name)) {
throw new SyntaxError(sprintf('The "%s" function is part of the %s, which is not installed/enabled; try running "composer require %s".', $name, $function[0], $function[1]));
throw new SyntaxError(\sprintf('The "%s" function is part of the %s, which is not installed/enabled; try running "composer require %s".', $name, $function[0], $function[1]));
}

return false;
Expand All @@ -36,7 +36,7 @@ public function suggestFunction(string $name): bool
public function suggestTag(string $name): bool
{
if ($function = Extensions::getTag($name)) {
throw new SyntaxError(sprintf('The "%s" tag is part of the %s, which is not installed/enabled; try running "composer require %s".', $name, $function[0], $function[1]));
throw new SyntaxError(\sprintf('The "%s" tag is part of the %s, which is not installed/enabled; try running "composer require %s".', $name, $function[0], $function[1]));
}

return false;
Expand Down
6 changes: 3 additions & 3 deletions src/Cache/FilesystemCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ public function write(string $key, string $content): void
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));
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));
throw new \RuntimeException(\sprintf('Unable to write in the cache directory (%s).', $dir));
}

$tmpFile = tempnam($dir, basename($key));
Expand All @@ -73,7 +73,7 @@ public function write(string $key, string $content): void
return;
}

throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $key));
throw new \RuntimeException(\sprintf('Failed to write cache file "%s".', $key));
}

public function getTimestamp(string $key): int
Expand Down
6 changes: 3 additions & 3 deletions src/Compiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public function write(...$strings)
*/
public function string(string $value)
{
$this->source .= sprintf('"%s"', addcslashes($value, "\0\t\"\$\\"));
$this->source .= \sprintf('"%s"', addcslashes($value, "\0\t\"\$\\"));

return $this;
}
Expand Down Expand Up @@ -196,7 +196,7 @@ public function repr($value)
public function addDebugInfo(Node $node)
{
if ($node->getTemplateLine() != $this->lastLine) {
$this->write(sprintf("// line %d\n", $node->getTemplateLine()));
$this->write(\sprintf("// line %d\n", $node->getTemplateLine()));

$this->sourceLine += substr_count($this->source, "\n", $this->sourceOffset);
$this->sourceOffset = \strlen($this->source);
Expand Down Expand Up @@ -244,7 +244,7 @@ public function outdent(int $step = 1)

public function getVarName(): string
{
return sprintf('__internal_compile_%d', $this->varNameSalt++);
return \sprintf('__internal_compile_%d', $this->varNameSalt++);
}

private function checkForEcho(string $string): void
Expand Down
14 changes: 7 additions & 7 deletions src/Environment.php
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ public function loadTemplate(string $cls, string $name, ?int $index = null): Tem
}

if (!class_exists($cls, false)) {
throw new RuntimeError(sprintf('Failed to load Twig template "%s", index "%s": cache might be corrupted.', $name, $index), -1, $source);
throw new RuntimeError(\sprintf('Failed to load Twig template "%s", index "%s": cache might be corrupted.', $name, $index), -1, $source);
}
}
}
Expand All @@ -418,9 +418,9 @@ public function createTemplate(string $template, ?string $name = null): Template
{
$hash = hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $template, false);
if (null !== $name) {
$name = sprintf('%s (string template %s)', $name, $hash);
$name = \sprintf('%s (string template %s)', $name, $hash);
} else {
$name = sprintf('__string_template__%s', $hash);
$name = \sprintf('__string_template__%s', $hash);
}

$loader = new ChainLoader([
Expand Down Expand Up @@ -485,7 +485,7 @@ public function resolveTemplate($names): TemplateWrapper
return $this->load($name);
}

throw new LoaderError(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
throw new LoaderError(\sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
}

public function setLexer(Lexer $lexer)
Expand Down Expand Up @@ -554,7 +554,7 @@ public function compileSource(Source $source): string
$e->setSourceContext($source);
throw $e;
} catch (\Exception $e) {
throw new SyntaxError(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e);
throw new SyntaxError(\sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e);
}
}

Expand Down Expand Up @@ -632,7 +632,7 @@ public function getRuntime(string $class)
return $this->runtimes[$class] = $runtime;
}

throw new RuntimeError(sprintf('Unable to load the "%s" runtime.', $class));
throw new RuntimeError(\sprintf('Unable to load the "%s" runtime.', $class));
}

public function addExtension(ExtensionInterface $extension)
Expand Down Expand Up @@ -803,7 +803,7 @@ public function getFunctions(): array
public function addGlobal(string $name, $value)
{
if ($this->extensionSet->isInitialized() && !\array_key_exists($name, $this->getGlobals())) {
throw new \LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name));
throw new \LogicException(\sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name));
}

if (null !== $this->resolvedGlobals) {
Expand Down
6 changes: 3 additions & 3 deletions src/Error/Error.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,15 +143,15 @@ private function updateRepr(): void

if ($this->name) {
if (\is_string($this->name) || (\is_object($this->name) && method_exists($this->name, '__toString'))) {
$name = sprintf('"%s"', $this->name);
$name = \sprintf('"%s"', $this->name);
} else {
$name = json_encode($this->name);
}
$this->message .= sprintf(' in %s', $name);
$this->message .= \sprintf(' in %s', $name);
}

if ($this->lineno && $this->lineno >= 0) {
$this->message .= sprintf(' at line %d', $this->lineno);
$this->message .= \sprintf(' at line %d', $this->lineno);
}

if ($dot) {
Expand Down
2 changes: 1 addition & 1 deletion src/Error/SyntaxError.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,6 @@ public function addSuggestions(string $name, array $items): void

asort($alternatives);

$this->appendMessage(sprintf(' Did you mean "%s"?', implode('", "', array_keys($alternatives))));
$this->appendMessage(\sprintf(' Did you mean "%s"?', implode('", "', array_keys($alternatives))));
}
}
Loading

0 comments on commit 1d8458d

Please sign in to comment.