Skip to content

Commit

Permalink
[CS] Optimize sprintf calls for PHP 8.4
Browse files Browse the repository at this point in the history
  • Loading branch information
smnandre authored and kbond committed Jun 26, 2024
1 parent fed00e2 commit eab7db5
Show file tree
Hide file tree
Showing 106 changed files with 295 additions and 290 deletions.
3 changes: 3 additions & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@
EOF;

return (new PhpCsFixer\Config())
->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect())
->setRules([
'@PHPUnit75Migration:risky' => true,
'@Symfony' => true,
'@Symfony:risky' => true,
'header_comment' => ['header' => $fileHeaderComment],
// TODO: Remove once the "compiler_optimized" set includes "sprintf"
'native_function_invocation' => ['include' => ['@compiler_optimized', 'sprintf'], 'scope' => 'namespaced', 'strict' => true],
'trailing_comma_in_multiline' => ['elements' => ['arrays', 'match', 'parameters']],
])
->setRiskyAllowed(true)
Expand Down
2 changes: 1 addition & 1 deletion src/Autocomplete/src/AutocompleteResultsExecutor.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public function fetchResults(EntityAutocompleterInterface $autocompleter, string
}

if (!\is_callable($groupBy)) {
throw new \InvalidArgumentException(sprintf('Option "group_by" must be callable, "%s" given.', get_debug_type($groupBy)));
throw new \InvalidArgumentException(\sprintf('Option "group_by" must be callable, "%s" given.', get_debug_type($groupBy)));
}

$optgroupLabels = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function __invoke(string $alias, Request $request): Response
{
$autocompleter = $this->autocompleteFieldRegistry->getAutocompleter($alias);
if (!$autocompleter) {
throw new NotFoundHttpException(sprintf('No autocompleter found for "%s". Available autocompleters are: (%s)', $alias, implode(', ', $this->autocompleteFieldRegistry->getAutocompleterNames())));
throw new NotFoundHttpException(\sprintf('No autocompleter found for "%s". Available autocompleters are: (%s)', $alias, implode(', ', $this->autocompleteFieldRegistry->getAutocompleterNames())));
}

if ($autocompleter instanceof OptionsAwareEntityAutocompleterInterface) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ private function processEntityAutocompleteFieldTag(ContainerBuilder $container)
foreach ($container->findTaggedServiceIds(self::ENTITY_AUTOCOMPLETE_FIELD_TAG, true) as $serviceId => $tag) {
$serviceDefinition = $container->getDefinition($serviceId);
if (!$serviceDefinition->hasTag('form.type')) {
throw new \LogicException(sprintf('Service "%s" has the "%s" tag, but is not tagged with "form.type". Did you add the "%s" attribute to a class that is not a form type?', $serviceId, self::ENTITY_AUTOCOMPLETE_FIELD_TAG, AsEntityAutocompleteField::class));
throw new \LogicException(\sprintf('Service "%s" has the "%s" tag, but is not tagged with "form.type". Did you add the "%s" attribute to a class that is not a form type?', $serviceId, self::ENTITY_AUTOCOMPLETE_FIELD_TAG, AsEntityAutocompleteField::class));
}
$alias = $this->getAlias($serviceId, $serviceDefinition, $tag);

Expand All @@ -61,7 +61,7 @@ private function getAlias(string $serviceId, Definition $serviceDefinition, arra
$class = $serviceDefinition->getClass();
$attribute = AsEntityAutocompleteField::getInstance($class);
if (null === $attribute) {
throw new \LogicException(sprintf('The service "%s" either needs to have the #[%s] attribute above its class or its "%s" tag needs an "alias" key.', $serviceId, self::ENTITY_AUTOCOMPLETE_FIELD_TAG, AsEntityAutocompleteField::class));
throw new \LogicException(\sprintf('The service "%s" either needs to have the #[%s] attribute above its class or its "%s" tag needs an "alias" key.', $serviceId, self::ENTITY_AUTOCOMPLETE_FIELD_TAG, AsEntityAutocompleteField::class));
}

return $attribute->getAlias() ?: AsEntityAutocompleteField::shortName($class);
Expand All @@ -72,7 +72,7 @@ private function processEntityAutocompleterTag(ContainerBuilder $container)
$servicesMap = [];
foreach ($container->findTaggedServiceIds(self::ENTITY_AUTOCOMPLETER_TAG, true) as $serviceId => $tag) {
if (!isset($tag[0]['alias'])) {
throw new \LogicException(sprintf('The "%s" tag of the "%s" service needs "alias" key.', self::ENTITY_AUTOCOMPLETER_TAG, $serviceId));
throw new \LogicException(\sprintf('The "%s" tag of the "%s" service needs "alias" key.', self::ENTITY_AUTOCOMPLETER_TAG, $serviceId));
}

$servicesMap[$tag[0]['alias']] = new Reference($serviceId);
Expand Down
4 changes: 2 additions & 2 deletions src/Autocomplete/src/Doctrine/EntityMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public function getFieldMetadata(string $propertyName): array
return (array) $this->metadata->fieldMappings[$propertyName];
}

throw new \InvalidArgumentException(sprintf('The "%s" field does not exist in the "%s" entity.', $propertyName, $this->metadata->getName()));
throw new \InvalidArgumentException(\sprintf('The "%s" field does not exist in the "%s" entity.', $propertyName, $this->metadata->getName()));
}

/**
Expand All @@ -86,7 +86,7 @@ public function getAssociationMetadata(string $propertyName): array
return $associationMapping;
}

throw new \InvalidArgumentException(sprintf('The "%s" field does not exist in the "%s" entity.', $propertyName, $this->metadata->getName()));
throw new \InvalidArgumentException(\sprintf('The "%s" field does not exist in the "%s" entity.', $propertyName, $this->metadata->getName()));
}

public function getPropertyDataType(string $propertyName): string
Expand Down
4 changes: 2 additions & 2 deletions src/Autocomplete/src/Doctrine/EntityMetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ private function getEntityMetadata(string $entityFqcn): ClassMetadata
$entityMetadata = $entityManager->getClassMetadata($entityFqcn);

if (1 !== \count($entityMetadata->getIdentifierFieldNames())) {
throw new \RuntimeException(sprintf('Autocomplete does not support Doctrine entities with composite primary keys (such as the ones used in the "%s" entity).', $entityFqcn));
throw new \RuntimeException(\sprintf('Autocomplete does not support Doctrine entities with composite primary keys (such as the ones used in the "%s" entity).', $entityFqcn));
}

return $entityMetadata;
Expand All @@ -46,7 +46,7 @@ private function getEntityMetadata(string $entityFqcn): ClassMetadata
private function getEntityManager(string $entityFqcn): ObjectManager
{
if (null === $entityManager = $this->doctrine->getManagerForClass($entityFqcn)) {
throw new \RuntimeException(sprintf('There is no Doctrine Entity Manager defined for the "%s" class', $entityFqcn));
throw new \RuntimeException(\sprintf('There is no Doctrine Entity Manager defined for the "%s" class', $entityFqcn));
}

return $entityManager;
Expand Down
12 changes: 6 additions & 6 deletions src/Autocomplete/src/Doctrine/EntitySearchUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function addSearchClause(QueryBuilder $queryBuilder, string $query, strin
$numAssociatedProperties = \count($associatedProperties);

if (1 === $numAssociatedProperties) {
throw new \InvalidArgumentException(sprintf('The "%s" property included in the setSearchFields() method is not a valid search field. When using associated properties in search, you must also define the exact field used in the search (e.g. \'%s.id\', \'%s.name\', etc.)', $propertyName, $propertyName, $propertyName));
throw new \InvalidArgumentException(\sprintf('The "%s" property included in the setSearchFields() method is not a valid search field. When using associated properties in search, you must also define the exact field used in the search (e.g. \'%s.id\', \'%s.name\', etc.)', $propertyName, $propertyName, $propertyName));
}

$originalPropertyName = $associatedProperties[0];
Expand Down Expand Up @@ -102,19 +102,19 @@ public function addSearchClause(QueryBuilder $queryBuilder, string $query, strin
|| ($isIntegerProperty && $isIntegerQuery)
|| ($isNumericProperty && $isNumericQuery)
) {
$expressions[] = $queryBuilder->expr()->eq(sprintf('%s.%s', $entityName, $propertyName), ':query_for_numbers');
$expressions[] = $queryBuilder->expr()->eq(\sprintf('%s.%s', $entityName, $propertyName), ':query_for_numbers');
$queryBuilder->setParameter('query_for_numbers', $dqlParameters['numeric_query']);
} elseif ($isGuidProperty && $isUuidQuery) {
$expressions[] = $queryBuilder->expr()->eq(sprintf('%s.%s', $entityName, $propertyName), ':query_for_uuids');
$expressions[] = $queryBuilder->expr()->eq(\sprintf('%s.%s', $entityName, $propertyName), ':query_for_uuids');
$queryBuilder->setParameter('query_for_uuids', $dqlParameters['uuid_query'], 'uuid' === $propertyDataType ? 'uuid' : null);
} elseif ($isUlidProperty && $isUlidQuery) {
$expressions[] = $queryBuilder->expr()->eq(sprintf('%s.%s', $entityName, $propertyName), ':query_for_uuids');
$expressions[] = $queryBuilder->expr()->eq(\sprintf('%s.%s', $entityName, $propertyName), ':query_for_uuids');
$queryBuilder->setParameter('query_for_uuids', $dqlParameters['uuid_query'], 'ulid');
} elseif ($isTextProperty) {
$expressions[] = $queryBuilder->expr()->like(sprintf('LOWER(%s.%s)', $entityName, $propertyName), ':query_for_text');
$expressions[] = $queryBuilder->expr()->like(\sprintf('LOWER(%s.%s)', $entityName, $propertyName), ':query_for_text');
$queryBuilder->setParameter('query_for_text', $dqlParameters['text_query']);

$expressions[] = $queryBuilder->expr()->in(sprintf('LOWER(%s.%s)', $entityName, $propertyName), ':query_as_words');
$expressions[] = $queryBuilder->expr()->in(\sprintf('LOWER(%s.%s)', $entityName, $propertyName), ':query_as_words');
$queryBuilder->setParameter('query_as_words', $dqlParameters['words_query']);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Autocomplete/src/Form/AutocompleteChoiceTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ private function getUrlWithExtraOptions(string $url, array $extraOptions): strin
$extraOptions[self::CHECKSUM_KEY] = $this->checksumCalculator->calculateForArray($extraOptions);
$extraOptions = base64_encode(json_encode($extraOptions));

return sprintf(
return \sprintf(
'%s%s%s',
$url,
$this->hasUrlParameters($url) ? '&' : '?',
Expand All @@ -127,7 +127,7 @@ private function validateExtraOptions(array $extraOptions): void
{
foreach ($extraOptions as $optionKey => $option) {
if (!\is_scalar($option) && !\is_array($option) && null !== $option) {
throw new \InvalidArgumentException(sprintf('Extra option with key "%s" must be a scalar value, an array or null. Got "%s".', $optionKey, get_debug_type($option)));
throw new \InvalidArgumentException(\sprintf('Extra option with key "%s" must be a scalar value, an array or null. Got "%s".', $optionKey, get_debug_type($option)));
}

if (\is_array($option)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
*
* @internal
*
* @deprecated since 2.13
* @deprecated since UX 2.13
*/
final class AutocompleteEntityTypeSubscriber implements EventSubscriberInterface
{
Expand Down Expand Up @@ -77,7 +77,7 @@ public function preSubmit(FormEvent $event)

if ($params) {
$queryBuilder
->andWhere(sprintf("$rootAlias.$idField IN (%s)", implode(', ', array_keys($params))))
->andWhere(\sprintf("$rootAlias.$idField IN (%s)", implode(', ', array_keys($params))))
;
foreach ($params as $key => $param) {
$queryBuilder->setParameter($key, $param[0], $param[1]);
Expand Down
2 changes: 1 addition & 1 deletion src/Autocomplete/src/Form/BaseEntityAutocompleteType.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ private function getAutocompleteUrl(FormBuilderInterface $builder, array $option
$attribute = AsEntityAutocompleteField::getInstance($formType::class);

if (!$attribute) {
throw new \LogicException(sprintf('You must either provide your own autocomplete_url, or add #[AsEntityAutocompleteField] attribute to %s.', $formType::class));
throw new \LogicException(\sprintf('You must either provide your own autocomplete_url, or add #[AsEntityAutocompleteField] attribute to "%s".', $formType::class));
}

return $this->urlGenerator->generate($attribute->getRoute(), [
Expand Down
4 changes: 2 additions & 2 deletions src/Autocomplete/src/Form/ParentEntityAutocompleteType.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
/**
* All form types that want to expose autocomplete functionality should use this for its getParent().
*
* @deprecated since 2.13, use "Symfony\UX\Autocomplete\Form\BaseEntityAutocompleteType" instead
* @deprecated since UX 2.13, use "Symfony\UX\Autocomplete\Form\BaseEntityAutocompleteType" instead
*/
final class ParentEntityAutocompleteType extends AbstractType implements DataMapperInterface
{
Expand All @@ -39,7 +39,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
$attribute = AsEntityAutocompleteField::getInstance($formType::class);

if (!$attribute && empty($options['autocomplete_url'])) {
throw new \LogicException(sprintf('You must either provide your own autocomplete_url, or add #[AsEntityAutocompleteField] attribute to %s.', $formType::class));
throw new \LogicException(\sprintf('You must either provide your own autocomplete_url, or add #[AsEntityAutocompleteField] attribute to "%s".', $formType::class));
}

// Use the provided URL, or auto-generate from the provided alias
Expand Down
6 changes: 3 additions & 3 deletions src/Autocomplete/src/Maker/MakeAutocompleteField.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma

$this->entityClass = $io->askQuestion($question);

$defaultClass = Str::asClassName(sprintf('%s AutocompleteField', $this->entityClass));
$defaultClass = Str::asClassName(\sprintf('%s AutocompleteField', $this->entityClass));
$this->className = $io->ask(
sprintf('Choose a name for your entity field class (e.g. <fg=yellow>%s</>)', $defaultClass),
\sprintf('Choose a name for your entity field class (e.g. <fg=yellow>%s</>)', $defaultClass),
$defaultClass
);
}
Expand Down Expand Up @@ -146,7 +146,7 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
'',
' <comment>$builder</comment>',
' <comment>// ...</comment>',
sprintf(' <comment>->add(\'%s\', %s::class)</comment>', Str::asLowerCamelCase($entityClassDetails->getShortName()), $classDetails->getShortName()),
\sprintf(' <comment>->add(\'%s\', %s::class)</comment>', Str::asLowerCamelCase($entityClassDetails->getShortName()), $classDetails->getShortName()),
' <comment>;</>',
]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,11 +164,11 @@ public function testItReturnsErrorWhenSendingMalformedExtraOptions(): void
$extraOptionsWithValidChecksum = $this->encodeData(['foo' => 'bar', '@checksum' => 'O2nYjcGr/l8GmUuYUSfE52hoyEL0NtDhBzUbn17KVHQ=']);

$this->browser()
->post(sprintf('/test/autocomplete/category_autocomplete_type?extra_options=%s', $extraOptionsWithoutChecksum))
->post(\sprintf('/test/autocomplete/category_autocomplete_type?extra_options=%s', $extraOptionsWithoutChecksum))
->assertStatus(400)
->post(sprintf('/test/autocomplete/category_autocomplete_type?extra_options=%s', $extraOptionsWithInvalidChecksum))
->post(\sprintf('/test/autocomplete/category_autocomplete_type?extra_options=%s', $extraOptionsWithInvalidChecksum))
->assertStatus(400)
->post(sprintf('/test/autocomplete/category_autocomplete_type?extra_options=%s', $extraOptionsWithValidChecksum))
->post(\sprintf('/test/autocomplete/category_autocomplete_type?extra_options=%s', $extraOptionsWithValidChecksum))
->assertStatus(200)
;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Chartjs/src/Twig/ChartExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,6 @@ public function renderChart(Chart $chart, array $attributes = []): string
}
}

return sprintf('<canvas %s></canvas>', $stimulusAttributes);
return \sprintf('<canvas %s></canvas>', $stimulusAttributes);
}
}
8 changes: 4 additions & 4 deletions src/Icons/src/Command/ImportIconCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ protected function execute(InputInterface $input, OutputInterface $output): int

foreach ($names as $name) {
if (!preg_match('#^([\w-]+):([\w-]+)$#', $name, $matches)) {
$io->error(sprintf('Invalid icon name "%s".', $name));
$io->error(\sprintf('Invalid icon name "%s".', $name));
$result = Command::FAILURE;

continue;
}

[$fullName, $prefix, $name] = $matches;

$io->comment(sprintf('Importing %s...', $fullName));
$io->comment(\sprintf('Importing %s...', $fullName));

try {
$svg = $this->iconify->fetchSvg($prefix, $name);
Expand All @@ -79,11 +79,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$cursor = new Cursor($output);
$cursor->moveUp(2);

$this->registry->add(sprintf('%s/%s', $prefix, $name), $svg);
$this->registry->add(\sprintf('%s/%s', $prefix, $name), $svg);

$license = $this->iconify->metadataFor($prefix)['license'];

$io->text(sprintf(
$io->text(\sprintf(
" <fg=bright-green;options=bold>✓</> Imported <fg=bright-white;bg=black>%s:</><fg=bright-magenta;bg=black;options>%s</> (License: <href=%s>%s</>). Render with: <comment>{{ ux_icon('%s') }}</comment>",
$prefix,
$name,
Expand Down
6 changes: 3 additions & 3 deletions src/Icons/src/Command/LockIconsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int
continue;
}

$this->registry->add(sprintf('%s/%s', $prefix, $name), $svg);
$this->registry->add(\sprintf('%s/%s', $prefix, $name), $svg);

$license = $this->iconify->metadataFor($prefix)['license'];
++$count;

$io->text(sprintf(
$io->text(\sprintf(
" <fg=bright-green;options=bold>✓</> Imported <fg=bright-white;bg=black>%s:</><fg=bright-magenta;bg=black;options>%s</> (License: <href=%s>%s</>). Render with: <comment>{{ ux_icon('%s') }}</comment>",
$prefix,
$name,
Expand All @@ -94,7 +94,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
));
}

$io->success(sprintf('Imported %d icons.', $count));
$io->success(\sprintf('Imported %d icons.', $count));

return Command::SUCCESS;
}
Expand Down
Loading

0 comments on commit eab7db5

Please sign in to comment.